martes, 4 de diciembre de 2012

Guidelines for writing GWT Overlay types

Guidelines for writing GWT Overlay types

This post is related with an older post Eclipse templates for overlay types about the same topic. You can find eclipse java code templates for code proposed here in that section. Now, that I have my ideas more clear and tested this is a summary.

When writing overlay types we have to take in consideration two main ideas:

  • we are writing a Java class that will be used by Java users
  • we are overlaying a JavaScript object with an API designed to be used in JavaScript

The following presents some guidelines learned and adopted in my GWT libraries porting javascript libraries like YUI and raphaël to GWT using 100% overlay types for a zero overhead Java API implementation.

Constructor

Use a static method with a simple name like create() or newInstance() that return an empty object or an object with some desired initialization state. Example:

public class MyOverlay extends JavaScriptObject {
 protected MyOverlay(){}
 public static native final create()/*-{
  return {}; 
 }-*/;
}

Properties

In Java we use the Bean convention for accessing obejct attributes / properties with getters and setters methods:

public class MyOverlay extends JavaScriptObject {
 protected MyOverlay(){}
 public static native final create()/*-{
  return {}; 
 }-*/;
 public native final String getColor()/*-{
  return this.color; 
 }-*/;
 public native final void setColor(String color)/*-{
  this.color=color; 
 }-*/;
}
End User example code:
MyOverlay o = MyOverlay.create(); 
o.setColor("red"); 
aController.method1(o);

Nevertheless, we must remember that "we are overlaying a JavaScript object with an API designed to be used in JavaScript". In JavaScript we normally are able to define an entire object in a single statement. For accomplish this in Java we need our setters methods to return the this object so we can perform method chaning. Also, but not so important, se omit the prefixes get/set for there methods

public class MyOverlay extends JavaScriptObject {
 protected MyOverlay(){}
 public static native final create()/*-{
  return {}; 
 }-*/;
 public native final String color()/*-{
  return this["color"]; 
 }-*/;
 public native final MyOverlay color(String color)/*-{
  this["color"]=color; 
  return this; 
 }-*/;
}

End User example code:

aController.method1(MyOverlay.create().color("red")); 

Much more similar to its JavaScript common counterpart aController.method1({color: "red"}), don't you think ?

Some notes:

  • We use setters and getters without the prefixes "get" or "set", so our method names are the same as the property name. This make it easy to use IDE tools like eclipse Java Code templates for generating the getter/setter code automatically.
  • In JSNI code we use string literals this["color"] instead variable names like this.color so the closure compiler (available optionally in GWT > 2.5) don't mess up JavaScript Object property names.

For those Java convention lovers I think it wouldnt cost too much to have "normal" java bean getters and setters AND this kind of shorter accessor methods for those who like to define object more "a la" javascript.

About Performance

Unfortunately the proposed code style here adds some overhead to the JavaScript code output produced by the GWT compiler. In the following example, I have created 2 JSOs, one called NormalBean that follows the Java Bean getter/setter conventions and other one called JsFriendlyBean that uses the solution proposed here with setters that return 'this' for method chaining. Then I use them both and compared the resulting JavaScript output code by GWT compiler using -style PRETTY and -optimize 9 compiler options. This is the result:

Java Sources:

NormalBean normalBean = NormalBean.create();
normalBean.setColor("turttlered1");
normalBean.setAge(13);

JsFriendlyBeam jsFriendlyBeam = JsFriendlyBeam.create()
 .color("turttlered2").age(14); 

Window.alert(normalBean + " - " + jsFriendlyBeam);

JavaScript output:

normalBean = {};
normalBean['color'] = 'turttlered1';
normalBean['age'] = 13;
jsFriendlyBeam = $age($color({}, 'turttlered2'), 14);
$wnd.alert(normalBean + ' - ' + jsFriendlyBeam);
...
function $color(this$static, val){
  this$static['color'] = val;
  return this$static;
}
function $age(this$static, val){
  this$static['age'] = val;
  return this$static;
}

As you can see, the setters of the NormalBean are inlined in JavaScript with zero-overhead while the setters of JsFriendlyBean are not. In the later, JavaScript functions $age() and $color() are created and called and that adds little but some overhead.

I cannot find a workaround for this. Tried with single JSNI statements like the followings but the result is the same:

public native final JsFriendlyBeam age(int val) /*-{
 return (this["age"]=val, this); 
}-*/;
and
public native final JsFriendlyBeam age(int val) /*-{
 return (this["age"] = val || true) ? this : null;
}-*/;

If anybody has an idea about how this setters can be written so they are inlined in JavaScritp output, pleas share it with me :)

martes, 27 de noviembre de 2012

HTML to valid XML code using tidy.

Sometimes you copy HTML source code from a web page that is not valid. Some tools, like mine htmlminimizator requires valid XML fragments to work. In this case we need to transform HTML sources to valid XML. I'm doing it fine with the tidy utility like this.

First I suppose you have your HTML code fragment in a file called test1.html, then I perform :

tidy -asxml -ashtml -utf8 test1.html 

Hope that can be of help to others in a similar situation.

miércoles, 31 de octubre de 2012

Using YUI in GWT UIBinder

About this document 

This document try to document a new feature of the toolkit YUIGWT for using YUI markup in GWT UIBinder.  It will no try to teach you how to use neither YUI or YUIGWT or GWT UIBinder (the user is supposed to know the basics of these technologies).

Online tests


YUIGWT example gallery contains the first tests related to using YUIGWT and UIBinder. The examples are:
  • uibinder test 1 - contains some yui widgets and GWT widgets mixed - layouting using YUI cssgrids.
  • just one, making more for the 1001 usescase... stay in touch....

Introduction

In GWT applications it is common to use UIBinder to separate the markup and style (design) from Java code (behavior).

And YUI proposes a very similar thing. All YUI widgets can be created from a markup structure. This markup structure is defined by each YUI widget. Some simple widgets like Y.Button only requires you to give a <button> element, but other more complicated YUI widgets like tabview, treeview, etc need you to provide a more complex markup (example).  This is somehow related to yui philosophy's of "Progressive Enhancement" @see http://yuilibrary.com/yui/docs/tutorials/gbs/

UIBinder users can mix both GWT Widgets markup and plain HTML Markup in their UI. Also the user is able to bind some of these markup elements to actual Java Objects fields in its Java code where the behavior, controller and modeling of the application is written.

In this document we will discuss how to use YUI Widgets proposed markup together with GWT UIBinder for rendering YUI components using UIBinder in a YUIGWT application.

Solution Summary

In general, the solution proposed here is the user to write YUI plain HTML markup for its YUI widgets in the UIBinder ui.xml, and mark them with an special class name for indicating the framework that that HTML element is a YUI widget and must be "post rendered". Then the user binds these widget elements in the UIBinder java's and after creating the UIBinder main Widget, ask the framework to render all the YUI elements. Later in the code, the user can ask the framework to return the appropiate YUIGWT Widget java class from a certain html element for work with the widget in Java. Hope this can be cleared in the following:

Example

In the following UIBinder example we use YUI cssgrids for layouting, create a yui tabview with some mixed YUI and GWT buttons inside:We commented each YUI element introduced in the markup:

<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
 xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:y="urn:import:org.sgx.yuigwt.ui">

<ui:style>
</ui:style>


<g:HTMLPanel>

 <!-- yui cssgrids -->
 <div class="yui3-g">
  <div class="yui3-u-5-24">
   <!-- yui button -->
   <button ui:field="yuiButton1" class="yui-button">the first YUI Button</button>

   <p>lak sjdlkaj slkdj alk sdlkaj slkdj lak sk djla sd</p>
   <p>lak sjdlkaj slkdj alk sdlkaj slkdj lak sk djla sd</p>

  </div>
  <div class="yui3-u-19-24">

   <!-- YUI tabview -->
   <div ui:field="tabView1" class="yui-tabview">
    <ul>
     <li>
      <a href="#foo">foo</a>
     </li>
     <li>
      <a href="#bar">bar</a>
     </li>
     <li>
      <a href="#baz">baz</a>
     </li>
    </ul>
    <div>
     <div id="foo">

      Some content with two buttons - one yui's and other GWT's<br />
      
      <!-- a YUI button -->
      <button ui:field="yuiButton2" class="yui-button">another yui button</button>
      
      <!-- a gwt button -->
      <g:Button ui:field="gwtButton2">..aGWTButton..</g:Button>

     </div>
     <div id="bar">
      a single GWT button:
      
      <g:Button text="GWT button1" ui:field="gwtButton1"></g:Button>
     </div>
     <div id="baz">baz content</div>
    </div>
   </div>

  </div>
 </div>

</g:HTMLPanel>
</ui:UiBinder>


Two important things to notice here:
  • For YUI Widgets we are writing using the same markup as expected and documented by YUI Widgets. For example, we give a plain html element <button> for creating a YUI Button, and give the markup documented in TabView Documentation - Minimal markup required.
  • We want to bind with GWT UIBinder the html elements corresponding to a YUI Widget, so we annotate them with ui:field="myfield".
  • Each html element corresponding to a YUI Widget must be annotated with an special class name corresponding to the aforementioned Widget. For example we annotate indicate it is a YUI Button using class="yui-button". This is how we indicate "this element must be rendered as a YUI Button"



And now the Java Sources corresponding to the UIBinder Composite definition I hope it is self documented:

package org.sgx.yuigwt.ui.test;

import org.sgx.yuigwt.ui.YUIBinder;
import org.sgx.yuigwt.ui.YUIBinderListener;
import org.sgx.yuigwt.yui.YuiContext;
import org.sgx.yuigwt.yui.event.EventCallback;
import org.sgx.yuigwt.yui.widget.button.Button;
import org.sgx.yuigwt.yui.widget.button.ButtonEvent;
import org.sgx.yuigwt.yui.widget.tabview.TabView;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;

/**
 * this is a common UIBinder Composite class. Notes:
 * 
 * < p>
 * 1) for YUI, we are binding plain HTML Elements, like @UiField Element
 * tabViewEl1;
 * < /p>
 * 
 * < p>
 * 2) then in the constructor, after this GWT widget is initialized with
 * initWidget(uiBinder.createAndBindUi(this));, we call YUIBinder.bindYUI
 * passing this Element UIFields corresponding to YUI stuff and register myself
 * as a listener to be notified when YUI binding is done to start working.
 * < /p>
 * 
 * < p>
 * 3) in yuiBinded() callback we ask for YUI Widgets and start working with
 * them.
 * < /p>
 * 
 * @author sg
 * 
 */
public class YUIInUiBinderTest2 extends Composite implements YUIBinderListener {

 interface MyUiBinder extends UiBinder< Widget, YUIInUiBinderTest2> {
 }

 private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

 @UiField
 Element tabViewEl1;

 @UiField
 com.google.gwt.user.client.ui.Button gwtButton1, gwtButton2;

 @UiField
 Element yuiButtonEl1;

 @UiField
 Element yuiButtonEl2;

 private YUIBinder binderUtil;

 private Button yuiButton1;

 private TabView tabView;

 public YUIInUiBinderTest2(YuiContext y) {

  initWidget(uiBinder.createAndBindUi(this));

  binderUtil = new YUIBinder();

  /*
   * bind YUI stuff manually passing this Element UIFields corresponding
   * to YUI stuff and register myself as a listener to be notified when
   * YUI binding is done
   */

  binderUtil.bindYUI(y, this, new Element[] { tabViewEl1, yuiButtonEl1, yuiButtonEl2 }, this);

  /*
   * the gwt widgets can be used right away, but for using YUI widgets we
   * need to wait until binding is finished, see method yuiBindede() below
   */
  gwtButton2.addClickHandler(new ClickHandler() {
   @Override
   public void onClick(ClickEvent event) {
    Window.alert("gwtbutton1clicked");
    tabView.selectChild(2);
   }
  });
 }

 @Override
 public void yuiBinded() {
  /*
   * all YUI stuff is ready and rendered, we obtain the YUI widgets and
   * work directly in java:
   */
  yuiButton1 = binderUtil.getWidget(yuiButtonEl1).cast();
  tabView = binderUtil.getWidget(tabViewEl1).cast();

  yuiButton1.on("click", new EventCallback< ButtonEvent>() {
   @Override
   public void call(ButtonEvent e) {
    tabView.selectChild(1);
   }
  });
 }

}

Interesting stuff here:

  • Unlike GWT widgets, for work with YUI Widgets we will bind plain HTML Element (com.google.gwt.dom.client.Element).
  • We need to manually call our "YUIBinder", passing all the @UIField Elements correspondiing to YUI widgets and later, when the binding is dont, we can obtain the YUIGWT Widget classes to work with them in Java.

Known Issues

  • Some GWT Widgets are not designed to contain any HTML content only other GWT widets, so it is possiblt that including YUI Widgets there cannot behave well.
  • Putting a GWT Button inside a YUI TabView will make the GWT button to loose click handlers... ?

How this works and some decisions.

lunes, 15 de octubre de 2012

Testing GWT Service Classes synchronously using syncproxy

Testing GWT Service Classes synchronously using syncproxy


Why ?


In GWT applications that use RPC for client-server comunication, RPC "Services" classes bring a Web API to our business logic core in the server. For example, an RPC service class may be responsible of managing a certain model class (its CRUD operations, etc). It is important for us to write automated tests for ensuring a certain degree of quality of those RPC services, automatically.

In a common - not GWT application we just write Junit serverside tests that will use our services classes asynchronically. For example, a service for a managing Apples, could be easily tested with the code:

Apple a1 = new Apple(); 
a1.setId("a1"); 
a1.setColor("red"); 

appleService.addApple(a1); 
Apple a2 = appleService.getAppleByName("a1"); 
assertEquals("red", a2.getColor()); 

appleService.removeApple(a1); 
a2 = appleService.getAppleByName("a1"); 
assertTrue(a2 == null); 

Unfortunately, GWT RPC service class methods, are called asyncrhonously, so it is very hard to write the same test case, because, we need to"continue the next test " inside the (async) callback. So for writing  the last example using RPC async calls, we will end up with code that contains 4 or 5 anidated code blocks, like:

appleService.addApple(a1, new AsyncCallback<Void>() {

 @Override
 public void onSuccess(Void result) {

  appleService.getAppleByName("", new AsyncCallback<Apple>() {

   @Override
   public void onSuccess(Apple result) {
    assertTrue(result.getColor().equals("red"));

    // :( ... test folows here ... :(
   }

   @Override
   public void onFailure(Throwable caught) {
   }
  });
 }

 @Override
 public void onFailure(Throwable caught) {
 }
});

On a first thought I tried to remedy this using a datastructure I called SyncQueue, for putting each service method call in a queue and at the end, ask the sync queue to run each task synch. But as this example shows, this is also a not so productive and readable way of writing tests.

How to ? 


Thinking this for some time get me to the conclusion that I really need to write JUnit test calling my RPC service methods synchronously (like the first code example). The project syncproxy seemed what I wanted but it wasn't so trivial to getting started with, mainly because documentation seems a little outdated.

So these are my instructions for making synch tests of your RPC services, using eclipse and google eclipse  plugin.

A summary of the entire procedure:
  1. create a new GWT Application project using eclipse New Application project wizard code template that comes with an example RPC service to test against to. This will be our "target" GWT application which we want to test.
  2. create a (second) eclipse Java Project, add syncproxy.jar and previous "target" GWT project to its build path. 
  3. create a JUnit  TestCase class in the test project that calls the target service class synchronously. The test app is a java client that tests against the "target" running GWT application.

First of all, I suppose you already have a GWT application which GWT services you wish to write tests for. If you don't just create a new GWT Web Applicaiton project with asking the wizard to create the template project that contains an already running RPC service for testing. That is what we will use in this example, so

Step 1 (optional): create a GWT project with a RPC service to test. 

Go to File -> New -> Other... -> Google -> Web Application Proje. Unselect Support for appengine and make sure "Generate sample code" is checked: 




Press Finnish and test the new application if you want. In my case I named it "Gwtrpcapp1" so I right click the file /war/Gwtrpcapp1.html -> Debug as .. -> Web Application . After is loaded, open the url http://127.0.0.1:8888/Gwtrpcapp1.html?gwt.codesvr=127.0.0.1:9997 in your browser.

This project cointains a RPC service called "greet". The data that we need from this RPC service are its module base url ("http://127.0.0.1:8888/gwtrpcapp1/") and the name of the service that we wish to test ("greet"). I found these values using Firefox's Firebug extension for examining HTTP request of our app:


Step 2: Create your test project


We will create a second project containing our junit tests. We choose a second project but if you are familiar with the tools you should not have major problems for putting these tests inside the same GWT project. In this case go to File -> New -> Java -> Java Project and create one. In my case I named it "Gwtrpcapp1Test1".

Now let's configure it a little this new project, first of all add the our target GWT project to its java class path. Right click project "Gwtrpcapp1Test1" -> Build Path -> Configure build Path -> Projects -> Add.. and choose our  target in my case "Gwtrpcapp1".

Also download syncproxy.jar from http://code.google.com/p/gwt-syncproxy/downloads/list,. copy syncproxy.jar file inside project "Gwtrpcapp1Test1", and add it to its class path.

Also you will need to add gwt-servlet.jar to your test project build path. Just go to Configure build path -> Libraries -> Add jars and choose the file  gwtrpcapp1/war/WEB-INF/lib/gwt-servlet.jar.


Now create some java package to work and create a Junit Test right clicking the package -> New .. -> Other -> Java -> JUnit -> JUnit Test Case. Eclipse will ask permission for adding JUnit library in your project. Complete some simple test there:

package org.sgx.gwtrpcapp1.test;

import static org.junit.Assert.*;

import org.junit.Test;
import org.sgx.gwtrpcapp1.client.GreetingService;

import com.gdevelop.gwt.syncrpc.SyncProxy;
/**
 * test for GreetingService - url : http://127.0.0.1:8888/gwtrpcapp1/greet 
 * @author sg
 *
 */
public class GreetingServiceTest1 {
 private static final String MODULE_BASE_URL = "http://127.0.0.1:8888/gwtrpcapp1/";
 private static final String SERVICE_NAME = "greet"; 
  
 private static GreetingService greetingService = (GreetingService) SyncProxy
  .newProxyInstance(GreetingService.class, MODULE_BASE_URL, SERVICE_NAME);

 @Test
 public void test() {
  System.out.println(greetingService.greetServer("Sebastian"));
  assertTrue(greetingService.greetServer("Sebastian").startsWith("Hello, Sebastian!"));    
 }
}

Important:  For this to work, all the classes that you want to pass / return from RPC methods must implement the com.google.gwt.user.client.rpc.IsSerializable interface.

 Run the test


If everything was fine, first run the target GWT Application like I told you before, and after its loads complete, run the our JUnit test. For that just right click GreetingServiceTest1 file -> Run as -> JUnit Test Voila! Hope this can be helpful to others in a similar situation.

Google AppEngine DataStore

If you are testing RPC services that perform some CRUD operations in Google Appengine DataStore these few tips could be helpful. Also this apply for frameworks that run on top of appengine datastore, like objectify.

The datastore it self is not synchronically: it takes some seconds to really impact changes to the datastore. So for example, if in our synchronous JUnit tests we save an entity it could not be available yet in the next data query. The same for deletion, it takes aprox 5 seconds to the datastore to really impact the entity deletion.

This is bad for our synchronous JUnit tests where we want the changes to impact synchronously. Fortunately, it is easy to configure the appengine in devmode for the datastore to behave synchronously. Just go to your appengine project launch configuration -> Appengine and edit the "unapplied job percentage" value to a very small number like 0.001:

Now your datastore will behave synchronously (at least almost all the time).

Also, I successfully run this test against my application deployed on appspot.com. I thought the test will fail because the weak consistence nature of the datastore, but surprisely, the test finnish without errors. Coud this be because of my slow intenret connection. Or, more worry, could this be because my eclipse application launcher configuration is somehow deplyed also ? ... mmm will have to investigate...

miércoles, 10 de octubre de 2012

Developing a vaadin application for Google appengine in eclipse.

Developing a vaadin application for Google appengine in eclipse. 


This is a step by step tutorial about making a vaadin application that runs on top of google appengine.

vaadin supports google appengine as a server backend as it is documented in the vaadin book. Also the vaadin eclipse plugin comes with a eclipse project wizard for building a web application based on vaadin and GAE. However, the resulting application do not support the GAE runtime and as a result, the GAE developemtn mode cannot be used (for testing the GAE application locally before deploying it to the web).

In this tutorial, we will generate such an application and change it for supporting GAE runtime and so being able of testing the app locally. The idea is to do agile development (save a file change, and only need to refresh the web page for reflecting the changes, no server restart)

So let's begin, we will use eclipse 4.2, java 1.6, Google appengine (GAE) 1.7.1, vaadin 6.8.4. OS: linux . Also this has been tested on eclipse 3.7.

1) Install Google Plugin for Eclipse. You can use eclipse marketplace at Help -> Marketplace for easy find and install this plugin.

2) Install Vaadin Plugin for Eclipse. You can use eclipse marketplace at Help -> Marketplace for easy find and install this plugin.

3) Create a new vaadin project. Just go to File -> New -> Other -> Vaadin -> Vaadin project. Make sure you set "Deployment configuration" to "Google App Engine servlet". You can leave all the other options to their default values. For this example, we left "Create project template" checked because we want something to test right away.

Also notice that we leave the target runtime empty: we don't want to run this application on tomcat or some other Java container but using the GAE runtime. In this example we named the project "vaadingaetest".  This project is ready for being deployed on GAE, but we cannot use the GAE runtime locally for testing and working, that is what the following steps are for.





4) Edit the project's .project file. You may need to go to eclipse's Navigator view for locating it because it is hidden in most other views. Once you have opened it, we need to add the XML element com.google.appengine.eclipse.core.gaeNature inside the element. you should end with something like this:
<natures>
 <nature>com.google.appengine.eclipse.core.gaeNature</nature>
 <nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
 <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
 <nature>org.eclipse.wst.common.project.facet.core.nature</nature>
 <nature>org.eclipse.jdt.core.javanature</nature>
 <nature>com.vaadin.integration.eclipse.widgetsetNature</nature>
 <nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>


5) Enable the GAE runtime in the project. This is simply a matter of adding the GAE library to the project. Right click on the project name in the project explorer -> Build Path -> Add Libraries and there choose "google app engine" and use the default SDK. If you have not an GAE SDK installed, install it (you can ask eclipse to download it for you). Also you may need to give the GAE library more preference than other libraries. Just right click the project -> Build path -> Configure build path -> Order and export and there select the "appengine SDK" entry on the list and press the Up button for increasing the priority of this library like showed on the following image:



6) Fix the file war/WEB-INF/appengine-web.xml adding the following element inside. For some reason this geerated file won't work without that line.

true

And that's all the configuration needed! Now let's run our vaading application using the GAE runtime locally.

7) Run our vaadin application on GAE runtime. For this, make sure you have refreshed the project and then right click the project name -> Debug As -> Web Application. Note: if there is no Web Application option this means you have done something wrong in steps 4 or 5. Try to refresh your project and make sure you are working in Java Porject Explorer eclipse view.

8) Test your application, open http://localhost:8888/?restartApplication in your browser and you should see your vaadin app. Now, let's modify something on file /vaadingaetest/src/com/example/vaadingaetest/VaadingaetestApplication.java, for example, change the label value like:

Label label = new Label("Hello Vaadin eclipse and appengine user!");

Save the java file and you should see your changes reflected just refreshing your browser window with F5 key.

A little explanation: In a vaadin application we do not have jsps or html pages, but servlets that are responsible for render our app. Because in the project creation wizard we left "Create project template" checked, the wizard has created a sample application for us that we can run and in our case this servlet class is com.example.vaadingaetest.VaadingaetestApplication. Also looking at the created web descriptor (file /war/WEB-INF/web.xml) we can see that the servlet is mapped to the URL pattern "/*", this means accessing http://localhost:8888/anythinghere will render our vaading application (a servlet).

Also, notice that I used the ?restartApplication http parameter. This tells vaadin framework to automatically apply changes in the java code without having to restart the container something very appreciated when developing.


Well, hope this can serve others eclipse vaading and google app engine users to getting started with these technologies.

jueves, 9 de agosto de 2012

YUIGWT

YUIGWT

 A Java GWT API for the great JavaScript YUI lirary

Project home page: http://code.google.com/p/yuigwt/ 

Example Gallery with online Java sources : http://cancerbero.vacau.com/yuigwt/

The project is very very new, but a general pattern for migrating all the YUI JavaScript API to Java was found, using 100% GWT Overlay types for a zero overhead Java API. A lot of components are already ready to be used, check the example gallery that will reflect current progress.

viernes, 20 de julio de 2012

Eclipse Java Code Templates for GWT related code automation

I often develop GWT libraries that port an existing javascript library like for example the raphael4gwt project that ports the javascript drawing library raphael to GWT / Java. I uses a lot of GWT Overlay types for dealing with native javascript objects from Java code.
GWT overlay types are not common java objects, in fact, at runtime, they "overlay" a native javascript object created outside GWT for example a DOM node. In my libraries I discovered that a good way to work with overlay types from java is like the following code.
Suppose I need to overlay a simple javascript object like the following in a java overlay type:
{
  color: "#ededed", 
  dashStyle: "none"
}
(this is an example taken from a real javascript library, YUI 3 - http://yuilibrary.com/yui/docs/api/classes/Circle.html#attr_stroke)
Now wuppose I want to create a GWT overlay type for this Stroke objects. In my experience I would like to define the overlay type, so I can create the same previous javascript object using the following java :
Stroke stroke1 = Stroke.create().
  color("#ededed").
  dashStyle("none");
The overlay type must be something like the following java class:
package org.sgx.yui4gwt.yui.graphic;

import com.google.gwt.core.client.JavaScriptObject;

/**GWT Overlay type for yui graphic stroke objects - 
 * http://yuilibrary.com/yui/docs/api/classes/Circle.html#attr_stroke
 * @author sg
 */
public class Stroke extends JavaScriptObject {

 protected Stroke() {}

 public static final String LINECAP_BUTT = "butt",
   LINECAP_SQUARE = "square", LINECAP_ROUND = "round";
 
 public static final String DASHSTYPE_NONE = "none",
   DASHSTYPE_TODO = "..."; 

 /** static constructor */
 public static final native Stroke create()/*-{
  return {}; 
 }-*/;
 
 /**
  * The color of the stroke.
  * 
  * @return
  */
 public native final String color() /*-{
  return this.color;
 }-*/;

 /**
  * The color of the stroke.
  * 
  * @param val
  * @return this - for setter chaining
  */
 public native final Stroke color(String val) /*-{
  this.color = val;
  return this;
 }-*/;

 /**
  * Number that indicates the width of the stroke.
  * 
  * @return
  */
 public native final double weight() /*-{
  return this.weight;
 }-*/;

 /**
  * Number that indicates the width of the stroke.
  * 
  * @param val
  * @return this - for setter chaining
  */
 public native final Stroke weight(double val) /*-{
  this.weight = val;
  return this;
 }-*/;

 /**
  * Number between 0 and 1 that indicates the opacity of the stroke. The
  * default value is 1.
  * 
  * @return
  */
 public native final double opacity() /*-{
  return this.opacity;
 }-*/;

 /**
  * 
  * @param val
  * @return this - for setter chaining
  */
 public native final Stroke opacity(double val) /*-{
  this.opacity = val;
  return this;
 }-*/;

 /**
  * 
  * @return
  */
 public native final String dashStyle() /*-{
  return this.dashStyle;
 }-*/;

 /**
  * 
  * @param val
  * @return this - for setter chaining
  */
 public native final Stroke dashStyle(String val) /*-{
  this.dashStyle = val; 
  return this; 
 }-*/;
}
And now the fun part. Writing more and more of this kind of overlay types I discovered that I can automate the work with eclipse java code templates. Just create an eclipse java code template going to Preferences->Java->Editor->Templates, and create a new template called "gwtOverlay1" with the following body:
/**
 * 
 * @return
 */
public native final ${attributeType} ${attributeName}() /*-{
 return this.${attributeName}; 
}-*/;
/**
 * 
 * @param val
 * @return this - for setter chaining
 */
public native final ${enclosing_type} ${attributeName}(${attributeType} val) /*-{
 this.${attributeName} = val; 
 return this; 
}-*/;
this way, when you need editing your overlay types in the eclipse java editor, to add another property to your overlay type, just use this template. type "gwt" and press ctrl+space. Choose "gwtOverlay1" and press enter. The template code will generated, and you can refactor the property type and property name.

yuigwt java code templates

In http://code.google.com/p/yuigwt/, where I work 100% with these kind of overlay types, I'm automatizing the Java definition of YUI attributes using getters/setters methods created with Java code templates. This is the template for those cases.
/**
 * 
 * @return
 */
public native final ${type} ${name}() /*-{
return this.get("${name}"); 
}-*/;

/**
 * 
 * @param val
 * @return this - for method chaining
 */
public native final ${enclosing_type} ${name}(${type} val) /*-{
this.set("${name}", val); 
return this; 
}-*/;

UIBinder @UIFactory

When writing YUIGWT with UIBinder (as documented in TODO LINK), if we reference a "YUIBinded" in another "YUIBinded" because "YUIBinded" required to pass a YUIContext as a constructor parameter, it is useful to autogenerate the @UIFactory method. This is a very personal note since I dot think anybody is working with this tech besides me. This is the template:

/**
 * Will be used for creating ${T} instances of this UIBinder widget. 
 * @return a new ${T}
 */
@UiFactory 
public ${T} make${T}() {
 return new ${T}(y); 
}

HTML Minimizator

I had to develop my own HTML code minimization application for my own specific needs, and here I would like to share the experience with the public.I called HTML minimizator and it is available online at htmlminimizator online web page.

A little background - while developing javascvript toolkits porting to Java GWT or to Java2Script frameworks I often need to copy javascript documentation to my javadocs classes comments for documenting java methods or classes that correspond to some javascript function or object.

For this I can copy the HTML sources of the javascript toolkit's documentation,
and paste it directly into the javadoc and it will look the same in generated html javadocs. This is really usefull and let me copy directly from the javascript toolkit documentation htmls.

For this, I want the javadoc size to be the minimun as possible and also I need to erase ALL html attributes like ids, hrefs, etc. Also I would like to eliminate any empty elements

That is what this little application HTML Minimizator try to do. It is a small GWT appilcation that let you paste XML valid code fragment, configure a little options and then get the minimified HTML.

I know there are a lot of HTML minimizators on the web, but none of them do an acceptable work for me, most of all because they won't eliminate attributes.

The project is hosted at https://code.google.com/p/gwteditors/ svn, since it uses my project gwteditors and it is very little for its own project.

For example, for default configuration, an html code like this:

< p>< code>Shape< /code> has the following implementations based on browser capability.< /p>

< ul id="yui_3_5_1_1_1342815626205_173">
    < li>< a href="SVGShape.html">< code>SVGShape< /code>< /a>< /li>
    < li id="yui_3_5_1_1_1342815626205_172">< a id="yui_3_5_1_1_1342815626205_171" href="VMLShape.html">< code>VMLShape< /code>< /a>< /li>
    < li>< a href="CanvasShape.html">< code>CanvasShape< /code>< /a>< /li>
< /ul>
will be minimized to the following html code:
< p>< code>Shape< /code> has the following implementations based on browser capability.< /p>< ul>< li>< a>< 
code>SVGShape< /code>< /a>< /li>< li>< a>< code>VMLShape< /code>< /a>< /li>< li>< a><
 code>CanvasShape< /code>< /a>< /li>< /ul>

lunes, 2 de julio de 2012

Disable all but one html element with jquery

They asked me to be able to disable all the html document but a single html element. Have done this with jquery like the following html snippet. The idea is to add 4 absolute positioned boxed "around" the given element, with big z-index with some transparency:

< !doctype html>
< html lang="es-UY">

< head>
< title>test< /title>
< script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript">< /script>
< /head>
< body>

< script>
/**
 * disablingFocus - disable all the document instead a single element - put 4 masks around the given element
 so it appear that all except that element is disabled. */
var lib = {
 maskStyle: { 
  zIndex: 9998, 
  position: "absolute", 
  display: "block", 
  opacity: 0.5, 
  backgroundColor: "#111111" 
 },  
 mask: null, 
 disableAllBut: function(el) {
  if(!lib.masks) {
   lib.masks=[]; 
   for(var i = 0; i< 4; i++) {
    var maskEl = document.createElement("div"); 
    document.body.appendChild(maskEl); 
    $(maskEl).attr({id: "disableAllButMask"+i});
    $(maskEl).css(lib.maskStyle); 
    lib.masks.push(maskEl)
   }
  }
  var x = $(el).offset().left, 
   y = $(el).offset().top, 
   w = $(el).width(), 
   h = $(el).height(); 
  var maxWidth = 3333, //$(document.body).offset().width, 
   maxHeight = 3333; //$(document.body).offset().height; 
  $(lib.masks[0]).css({
   "left": "0px", "top": "0px", "height": y+"px", "width": maxWidth+"px"
  });
  $(lib.masks[1]).css({
   "left": "0px", "top": (y+h)+"px", "height": maxHeight+"px", "width": maxWidth+"px"
  }); 
  $(lib.masks[2]).css({
   "left": 0+"px", "top": (y)+"px", "height": h+"px", "width": x+"px"
  }); 
  $(lib.masks[3]).css({
   "left": (x+w)+"px", "top": (y)+"px", "height": h+"px", "width": maxWidth+"px"
  })
 }, 
 "":""
}; 
window.disabler=lib; 
window.disableAllBut=lib.disableAllBut; 
< /script>
< style type="text/css">
< /style>

< div class="apagado">
 hola 1
 < table>
  < tr>< td>hola hola< /td>
      < td>
   < div class="prendido">
   hola 2< p>hhhhh< a href="">hshshs< /a>< /p>
   < /div>
      < /td>
  < /tr>
  < tr>
   < div id='div3'>
   hola 3 asd < span id="div4">asd< /span> as d
   < /div>
  < /tr>
 < /table>
< /div>

< button onclick="disableAllBut(document.getElementById('div4'))">click me for the disabling< /button>



< /html>

viernes, 29 de junio de 2012

Disable HTML elements programatically

They asked me to disable / disable some html elements in the client side with javascript so the user cannot interact with cerrtain parts of an html document at some point. My sollution, based on jquery, is to put an html element in front of each elments we want to disable. This mask should be transparent and positioned absolutely with a big z-index. The following is an HTML document that demonstrates the problem and contains a simple implementation of a sollution. Hope it can be usefull to somebody needing something similar.


< !doctype html>
< html lang="es-UY">

< head>
< script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript">< /script>
< title>test< /title>
< /head>

< script type="text/javascript">
var lib = {
idCounter: 0, 
disablers: [], 
/**
 * disable the given html elements by putting a mask html element with the same bounds in front of each given element. use disablers.enable for enabling them programatically. 
 * @param el - a reference to the elements to disable. For example, ".c1" will disable all elements of CSS class c1, "#el1" will disable the element id el1.
 * @param maskCSS - optional - an object with extra CSS value for the mask, for example: {"background-color": "red", opacity: 0.2}
 * @return the masks elements (array of jquery object) created
 */
disable: function(el, maskCSS) {
 var masks = []; 
 $(el).each(function(){
  masks.push(lib.disableOne(el, maskCSS)); 
 });
 return masks; 
}, 
/**
 * the same as disable, but treat the given object as a single element 
 */
disableOne: function(el, maskCSS) {
 var id = $(el).attr("id"); 
 if(!id) {
  lib.idCounter++;
  id="disabler_"+lib.idCounter; 
  $(el).attr({"id": id}); 
 }
 if(!lib.disablers[id]) {
  var dis = document.createElement("div"); 
  document.body.appendChild(dis); 
  lib.disablers[id]=$(dis); 
 }
 var dis = lib.disablers[id];
 $(dis).css({
  "position": "absolute", "z-index": 99999, "display": 
  "block", "left": $(el).offset().left, "top": $(el).offset().top, 
  "width": $(el).width(), "height": $(el).height(), "opacity": 0.4, "background-color": "black"
 });  
 $(dis).show(); 
 if(maskCSS)
  $(dis).css(maskCSS); 
 return dis; 
},
enable: function(el) {
 if($(el).attr("id") & & lib.disablers[$(el).attr("id")]) {
  var dis = lib.disablers[$(el).attr("id")]; 
  dis.hide(); 
 }
}
}; 
window.disabler=lib; 
< /script>

< p>The following table contains a disabled element< /p>

< table>
< tr>< td id="el1">< button>hello< /button>< /td>< td>< p>alskjdlaksjd< /p>< /td>< /tr>
< tr>< td>< button onclick="window.disabler.enable('#el1')">click me for enable < /button>< /td>< td>< p>als< a href="">kjdlaksj< /a>d< /p>< /td>< /tr>
< /table>

< script type="text/javascript">
//examples: 

//disable a single element with id "el1"
disabler.disable("#el1"); 

//disable all < a> elements: 
disabler.disable("a"); 
< /script>


< /body>


< /html>

domingo, 10 de junio de 2012

JavaScript function inBetween

JavaScript function inBetween - be notified when a javascript function is called N times in between a time lapsus of T milliseconds.

This idea borned when reading the work of Ben Alman for function throttle : http://benalman.com/projects/jquery-throttle-debounce-plugin/

In that case the problem is to execute a function no more than once every T milliseconds. This is very helpful when you want to control how much an event handler is called back. I put a common example for events that are called intensively, like mousemove, or drag in my raphaël tutorial: http://cancerbero.vacau.com/raphaeltut/index.html#sec-events-function-throttle   There I explain very usefull cases of function throttle.

The thing is that function throttle made me think on the opposite problem: being notified when a function is called N times in a time lapsus of T milliseconds. This can be useful for registering double, triple, cuadruple clicks, and in general nth-clicks events.I call this, function inBetween (don't have a better name, suggestions accepted). See for example, how I would use inBetween with jquery for neing notified when a triple click occurs in between 1000 ms:

function click3Hendler(evt) {
    alert(this.clickCount+" clicks detected. last click xcoord: "+evt.clientX);
};
$("#someElement").click(inBetween(3, 1000, cb, {clickCount: 3}));

This is a complete working example: http://jsfiddle.net/RP7mW/11/.

Also there is a section in my raphaël tutorial for registering nth-click listeners to raphaël shapes using inBetween(). Link: http://cancerbero.vacau.com/raphaeltut/index.html#sec-events-inbetween

And this is the inBetween function code:
        
/**
 * inBetween resolves the problem of being notified when a function is called N times in in between a time lapsus of T ms.
 * @param n the amount of times.
 * @param t the time lapsus in ms
 * @param callback - the function to be called when the returned fcuntion is called at least n times in a lapsus of n ms.
 * @return a new function - when that function is called n times in a lapsus
 of t ms, then callback function will be called using the context object as
 the callback context.
 */
function inBetween(n, t, callback, context) {    
    var sb = [];
    sb.push("var that = arguments.callee; ")
    sb.push("var thisTime = new Date().getTime(); ")
    sb.push("var arr = that['ARR'];");
    sb.push("if(!arr){");
    sb.push("    arr = []; ");
    sb.push("    for(var i = 0; i < that['N']; i++) arr.push(thisTime); ");
    sb.push("    that['ARR'] = arr;");
    sb.push("    that['COUNT']=0");
    sb.push("}");
    
    sb.push("that['COUNT']++; ");;
    sb.push("arr.push(thisTime);");
    sb.push("var lastTime = arr.shift();");
        
    sb.push("if(that['COUNT'] >= that['N']) {");
    sb.push("    that['COUNT']=1; ");
    sb.push("    for(var i = 0; i < that['N']; i++) arr[i] = thisTime; ");
    sb.push("    if(thisTime-lastTime < that['T']) ");          
    sb.push("        that['CB'].apply(that['CTX'], arguments); ");
    sb.push("}");
        
    var fn = new Function(sb.join(""));    
    fn['N']=n;
    fn['T']=t;
    fn['CB']=callback;
    fn['CTX']=context;
    return fn;        
}; 

Hope this can be of some use for those who need some advance event - function stuff like this.

jueves, 17 de mayo de 2012

raphaelJs tutorial

I'm working on a raphaeljs tutorial. The tutorial is available here.

I made it in pure html and css, with a little javascript based on jquery.

It has nice dynamic features like

  • references-links, this is links that opens in an iframe showing an anchor iframes with a method or property documentation of raphaeljs reference .
  • code examples that can be runned online. A dialog with a raphal paper will be open with the example inside. The javascript code is prettyfied very using code-google-pretify
  • auto creation of a table of content from h1, h2, h3, etc. HTML elements.
  • auto creation of an index of terms, using class="index" in those html elements which contents I want to use as an index term.
While this is now a very attractive document for those begginers and not so raphaeljs users, it isi still a work in progress, but spect lots of improvements soon. If you have comments, please make them in raphaeljs users group.

viernes, 9 de marzo de 2012

RaphaelMarkup - XML syntax for great drawing Javascript API

My new pet project is http://code.google.com/p/raphaelmarkup/, let me present it to you:


Some links:

feature examples: http://cancerbero.vacau.com/raphaelmarkup/src/doc/examples.html

different ways of including raphael XML in HTML documents:
http://cancerbero.vacau.com/raphaelmarkup/src/doc/usage.html

documented raphael XML document definition in XML Schema:
http://cancerbero.vacau.com/raphaelmarkup/src/raphael.xsd




resume:

Write and validate your raphael drawings in xml, stylize with CSS like
syntax. Access any raphael paper instances in an XML DOM using jquery.
Use CSS 3 selectors for locating your shapes in the raphael DOM.

long description:

raphaël javascript library has a portable and nice API for drawing
vector graphics with javascript. This project, RaphaelMarkup, try to
bring declarative parts of raphaël API to XML so you can draw with XML
and CSS. Some important things that raphaelmarkup supports:

* RaphaelMarkup define a XML document type for writing raphaël in
XML. A XML Schema document definition is provided so users can
validate their xml drawings.
* It contains a javascript renderer for easily render xml drawings
in your HTML documents.
Provides several ways of including XML drawings in HTML documents,
like embedding code, ajax, XSL stylesheets, etc.
* Creates an XML DOM that can be manipulated programatically with
tools like jquery. and then easily update the drawing with the changes
in the DOM
* CSS like syntax for raphaël shapes attributes. Raphael elements
support id and class attributes, and CSS3 selectors are supported.
Note that this is not CSS, some cascading rules are different and
raphael attributes are not valid CSS.
* Easy scripting for rendered documents.
* Utilities for easy export any raphael paper to XML drawing code.

RaphaelMarkup depends on raphael and jquery libraries. jquery is used
for XML parsing and XML DOM Manipulation.

The project just started, many things still need revision and some
parts of raphaeljs api still need works. Expect improvements soon! I'm
announcing it here for feedback so please if you have any suggestions.
Expect project inprovements soon!

jQuery: accessing XML doms created with $.parseXML and problems with append(string)

In the project raphaelmarkup I'm exploiting jquery API for loading and manipulating XML. First I parse the XML sources and then I can use jquery API for accessing and manipulating it. A documented example:

//some xml string example. the XML must not have any <!doctype definition
var xmlStr = '<p><o><b></b></o><b></b></p>';

//create a jquery dom object for that xml document.
var xmldoc1 = $.parseXML(xmlStr); //the native XMLDocument object
var dom = $(xmldoc1); //the jquery DOM object that we will use fopr accessing

//finds some element and sets attributes using the jquery API
dom.find("p>o").attr("attr1", "val1");


This has some advantages: its uses the internal XML browser parser, the jquery API is a portable way of accessing the XML DOM.

Now I want to document a problem that I had with this using jquery's append(String) method.
In the previous example, dom.find("p").append("hello) won't work. This is mainly because append(String) method will create the new elements using the global html document (the global "document variable) instead or using our XML document object. So we must do the following for appending an element :


var g1 = $(xmldoc1.createElement("g"));
dom.find("p>o").append(g1);
g1.test("hello");


the complete example based on qunit (ok() is an assertEquals()) :

var xmlStr = '

'
var dom = $($.parseXML(xmlStr));

ok(dom.find("b").size()==2, "jquery xml dom 1"); //OK

//set attribute and check -
dom.find("p").attr("attr1", "val1");
ok(dom.find("p").attr("attr1")=="val1", "jquery xml dom 12");
ok($("p", dom).size()==1, "13");//OK

/* a bug, using dom.find("p").append('<d>hello</d>') won't work. it seems
jquery won't let creation of non HTML valid code. */

dom.find("p").append('<d>hello</d>'); //this doesn't work
ok(dom.find("d").size()==1, "jquery xml dom 2"); //FAIL!

/* but this way works. Don't use append(string) but create the element
manually, and pass the dom object to append() */

var c1 = $(dom.get(0).createElement("c")); //make sure new el is created in our xml doc
dom.find("p").append(c1);
ok($("c", dom).size()==1, "14"); //OK



A function for creation of arbitrary xml elements :




/**
* create a new element in raphael XML dom
* @param parent an html dom or jquery selector or object
* where to append the created child.
* @return the created jquery dom element
*/
createElement: function(parent, tagName, attrs) {
parent=$(parent);
var xmldoc = null;
//if they send us a document, we append it on the documentElement

if(rm.isDocument(parent)) {
parent=$(parent.prop("documentElement"));
}
xmldoc=parent.prop("ownerDocument");

var e = $(xmldoc.createElement(tagName));
if(attrs)
e.attr(attrs);

parent.append(e);

return e;
},


Being a great tool for parsing and accessing xml documents in xhtml documents, It is a shame that jquery don't let to use arbitrary xml markup strings in methods like append, prepend, etc. :( But it seems that it is a thing we can live without

jueves, 8 de marzo de 2012

Advance gnome configuration with gconf

In gnome you can configure a lot of advanced stuff using gconf that are not available in GUI programs like gnome-control-center. For example, in default gnomes it is common that new application windows steal the focus of current window. In my case, I launch eclipse (that takes some time to show the window) and a console. While writing on the console, when the eclipse window appears it steals the focus to the console and this is very annoying.

There is no option in visual tools like gnome-control-center for configuring this, but using the gconftool command line program we can check the state of the configuration property that controls the "new windows focus", like this:

gconftool-2 --get /apps/metacity/general/focus_new_windows

or can change its value to "strict" that will prevent focus stealing:

gconftool-2 --set /apps/metacity/general/focus_new_windows --type string strict

More, using the application gconf-editor one can inspect all available properties and edit them. Note that "metacity" is just another gnome application, in this case the window manager (the program that administer windows). The new windows focus policy is a responsability of metacity.