Pages

Google+ Followers

Friday, October 26, 2012

MGWT – Reading data from XML file on mobile phones


MGWT stands for making GWT(google web toolkit) work with mobile.
Mgwt works on all kind of mobile devices that support webkit (like iPhone, iPad, iPod, Android, Blackberry, ...) and is invented by Daniel Kurka. You can find more information and you can download this java library on http://www.m-gwt.com/

In a short presentation I would like you to show you, how can we read data from client side xml file using the java programming language.

First of all, I created a simple GWT web project and I added the Mgwt library to it. In all the GWT projects, we have a configuration file, where we must list the additional libraries and components of the project. 

Here you can see that I declared 4 package, each of them having its purpose. The first one, user.User stands for gwt libraries, mgwt.MGWT shows us that it is a porject for mobile phone that supports webkit, the xml.XML works with xml file, and 4th. one stands for date and time functions. The gwt date and time library can be downloaded from http://code.google.com/p/gwt-time/ which I also added to my project, to show you how can we use date and time functions in our mgwt project.

The content of the xml file which we will use in our project, to read data from, is looks like:
 
Reading from an xml file with the gwt/mgwt project, can be resolved on client side, that means, there is no need to any web application server, all the project runs in offline mode too. If you would like to write back data to an xml file, then you need a web application server, like Tomcat or any other to implement the server side tehchnology using GWT-RPC(remote procedure call) technology. I wouldn’t like to enter now in details, regarding server side programming, because this short presentation is just about reading offline data.

I am going to present now some lines of code form the main java file. The whole project can be downloaded from my file server, http://siposlehel.atw.hu

  1. Loading the xml file:
        try {
            RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET,"content.xml");                                                               
            requestBuilder.sendRequest(null, new RequestCallback() {
                public void onError(Request request, Throwable exception) { 
                    System.out.println(exception.getMessage());
                }
                public void onResponseReceived(Request request, Response response){             
                    renderXML(response.getText());                   
                }
            });
        }
        catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

  1. Work with xml file – getting data from xml
    private void renderXML(String xmlText) {       
        try {
            Document messageDom = null;           
            messageDom = XMLParser.parse(xmlText);            
            NodeList entries = messageDom.getDocumentElement().getElementsByTagName("student");       
            for (int intI = 0 ; intI < entries.getLength(); intI++) {           
                Element entry = (Element) entries.item(intI);                                                
                String keyValue = entry.getElementsByTagName("id").item(0).getFirstChild().getNodeValue();               
                //Getting the record from xml with an id=1(strId)
                if (keyValue.equals(strId)) {
                    //getting the the field <name> from the xml               
                    strName = entry.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();                   
                    //getting the the field <begin> from the xml               
                    strDate = entry.getElementsByTagName("begin").item(0).getFirstChild().getNodeValue();                                                            
                }   
            }
        }
        catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }

  1. using date and time utilities in our MGWT project
            DateTime dateToday = new DateTime();
            int year = dateToday.getYear();
            int month = dateToday.getMonthOfYear();
            int day = dateToday.getDayOfMonth();
            strToday = String.valueOf(year)+"."+String.valueOf(month)+"."+String.valueOf(day);                               

The running application looks like this:

Thursday, October 18, 2012

GWT Animation – GWT FX




Google Web Toolkit (GWT) is a development toolkit for building and optimizing complex browser-based applications. https://developers.google.com/web-toolkit/

You write your code in Java language and the GWT compiler will produce to you the client side javascript(/ajax) and html files.
There are lot of additional java libraries which you can use to improve your GWT application for free:

For example to do animations, you can use the custom gwt animation tool and components, but there is also a java package named gwt-fx, reachable from the list above mentioned.
With gwt-fx you have additional animation possibilities:

I write a short application to demonstrate some animation functionalities using the gwt-fx package and the custom gwt animation component. This application is running on the free Google Application Engine server:

Using the custom GWT animation component, a short example demonstrates us, a function of moving widgets:  




class CustomAnimation extends Animation {
    private int centerX = 120;
    private int centerY = 120;
    private int radius = 100;

    @Override
    protected void onComplete() {
      super.onComplete();
      //write code here, what to do after the animation stops
    }
    @Override
    protected void onStart() {
      super.onStart();
     //write code here, what to do before the animation starts
    }


    @Override
    protected void onUpdate(double progress) {
      double radian = 2 * Math.PI * progress;
      updatePosition(your_gwt_widget1, radian, 0);
      updatePosition(your_gwt_widget2, radian, 0.5 * Math.PI);
      updatePosition(your_gwt_widget3, radian, Math.PI);
      updatePosition(your_gwt_widget4, radian, 1.5 * Math.PI);
    }
    private void updatePosition(Widget w, double radian, double offset) {
      radian += offset;
      double x = radius * Math.cos(radian) + centerX;
      double y = radius * Math.sin(radian) + centerY;
      YourPanelContainingTheWidgets.setWidgetPosition(w, (int) x, (int) y);
    }
  }
 




At your button click event you can use the following code to start and stop this custom gwt animation:
CustomAnimation animation;
…..
animation.run(4000);
animation.cancel(); 




Monday, October 15, 2012

GWT - Getting Started with Chart Tools

For using chart tools in your GWT web application project you need to download the gwt-visualization API(gwt-visualization.jar) from the web page of the Official Google Api Libraries for Google Web Toolkit:
http://code.google.com/p/gwt-google-apis/downloads/list

In the next step, inherit com.google.gwt.visualizatio in the module XML definition file, of your gwt web project.
<inherits name='com.google.gwt.visualization.Visualization'/>


You may try a sample code, using the chart libraries:

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.visualizations.*;
import com.google.gwt.visualization.client.visualizations.PieChart.Options;

/**
 * Main entry point.
 *
 * @author  Lehel Sipos
 */
public class gwtchartEntryPoint implements EntryPoint {

  public void onModuleLoad() {     
    // Create a callback to be called when the visualization API
    // has been loaded.
    Runnable onLoadCallback = new Runnable() {
      public void run() {
        Panel panel = RootPanel.get();
        // Create a pie chart visualization.
        PieChart pie = new PieChart(createDataTable(), createOptions());       
        panel.add(pie);
      }
    };
    // Load the visualization api, passing the onLoadCallback to be called
    // when loading is done.
    VisualizationUtils.loadVisualizationApi(onLoadCallback, PieChart.PACKAGE);
  }

  private DataTable createDataTable() {
    /* create a datatable */
    DataTable data = DataTable.create();
    data.addColumn(ColumnType.STRING, "Prog. Language");
    data.addColumn(ColumnType.NUMBER, "Popularity");
    data.addRows(5);
    data.setValue(0, 0, "C");
    data.setValue(0, 1, 11);   
    data.setValue(1, 0, "Visual Basic");
    data.setValue(1, 1, 2);   
    data.setValue(2, 0, "Delphi");
    data.setValue(2, 1, 2);  
    data.setValue(3, 0, "PHP");
    data.setValue(3, 1, 2);   
    data.setValue(4, 0, "Java");
    data.setValue(4, 1, 10);
    return data;
  }   
 
  private Options createOptions() {
    /* create pie chart */  
    Options options = Options.create();
    options.setWidth(450);
    options.setHeight(300);
    options.set3D(true);
    options.setTitle("Programming Languages");
    return options; 
  } 
 }


This java code will be translated by the GWT compiler to html and javascript code, runnable in your browser:



 

Thursday, October 11, 2012

Vaadin – using html template files as a layout in a vaadin application



While it is possible in a Vaadin application to create almost any typical layout with the standard layout components, it is sometimes best to separate the layout completely from code.

With the CustomLayout vaadin component, you can write your layout as a template in XHTML separately, and this html file will contain div elements with the location attribute, to provide locations of any contained vaadin widget in it.

The layout template html is included in a theme directory in your web directory.
..\web\VAADIN\themes\sampletheme\layouts\examplecustomlayout.html

This separation allows the layout to be designed separately from code, for example using WYSIWYG web designer tools such as Adobe Dreamweaver.
Vaadin requires that the templates layout must use UTF-8 charset

Let’ look how does it look such a HTML template layout file, that holds place for vaadin widgets:

<table>
  <tbody>
    <tr>
      <td colspan="2">
      <h1 style="margin-top: 0pt;" align="center">Belépés a banki rendszerbe</h1>
      </td>
       <td> </td>
    </tr>
    <tr>
      <td align="right">Felhasználó:</td>
      <td>
      <div location="username"></div>
      </td>
    </tr>
    <tr>
      <td align="right">Jelszó:</td>
      <td>
      <div location="password"></div>
      </td>
    </tr>
    <tr>
      <td colspan="2" align="right">
      <div location="okbutton" style="padding: 10px;"></div>
      </td>
    </tr>
    <tr>
      <td colspan="2" style="padding: 7px; background-color: rgb(255, 172, 132);">
      <img src="examplecustomlayout_elemei/icon_info.gif" align="absbottom">Kérem adja meg a belépési adatait.
      </td>
      <td> </td>
    </tr>
  </tbody>
</table>
The whole template html should look like this at design view:



Now let’s have the java code which will use this template above, in a vaadin application:
First the we work with the main starting java file:

import com.vaadin.Application;
import com.vaadin.ui.*;
import com.vaadin.data.*;

/**
 *
 * @author Sipos Lehel
 * @version 1.0.0.0
 */

public class MyApplication extends Application {

    @Override
    public void init() {
        //create the directory for your own Theme
        //web\VAADIN\themes\lehel\styles.css
        setTheme("lehel");
       
        Window mainWindow = new Window("HTML TEMPLATE EXAMPLE");
        mainWindow.setName("main");
        //instantiating the java class working with the HTML layout templat
        CustomLayoutsExample template = new CustomLayoutsExample();
        mainWindow.addComponent(template);
        setMainWindow(mainWindow);
    }
}

Then let’ see the class which will hold the html template file:

import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.*;
import javax.management.Notification;

@SuppressWarnings("serial")
public class CustomLayoutsExample extends VerticalLayout {
    //vaadin widget that we will place on the layout
    Button ok;
    TextField username;
    PasswordField password;

    public CustomLayoutsExample() {
        setMargin(true);

        // Create the custom layout html file, and set it as a component in
        // the current vaadin layout
        //d:\Programming\JavaVaadin\Vaadin1\web\VAADIN\themes\lehel\layouts\examplecustomlayout.html
        CustomLayout custom = new CustomLayout("examplecustomlayout");      
        addComponent(custom);

        // Create components and bind them to the location tags
        // in the custom layout html template                             
        username = new TextField();
        custom.addComponent(username, "username");
       
        password = new PasswordField();
        custom.addComponent(password, "password");
       
        ok = new Button("Belépés");
        custom.addComponent(ok, "okbutton");
       
        ok.addListener(new Button.ClickListener() {
            @Override
            public void buttonClick(ClickEvent event) {               
                //verifying that the fields are filled or not
                if (!username.getValue().toString().equals("") && !password.getValue().toString().equals(""))
                    ok.getApplication().getWindow("main").showNotification("Figyelem!", "A belépés folyamatban");
                else
                    ok.getApplication().getWindow("main").showNotification("Figyelem!", "Töltse ki a mezőket");                   
            }
        });       
    }
}

After running the vaadin application that uses the html template file the result will be:





Friday, October 5, 2012

MGWT – using GWT Map widget on mobile phone with mgwt




I am going to demonstrate with this short presentation the use of gwt-maps library with MGWT technology, and this is about how to develop a mobile application under Netbeans IDE, for all the mobile phones that supports webkit. The application will have a simple button component that the user clicks, a map appears on the screen, positioned to Satu Mare city, where I live.

If you have the Netbeans IDE ver 7.2 installed on your computer, or any other java editor, just follow the steps:
  1. download and install(unzip) to your computer the GWT  SDK(google web toolkit)

  1. if you have Netbeans IDE, download the latest GWT plugin for Netbeans, and install it from Tools->Plugins->Downloaded

  1. download and install(unzip) the latest version of MGWT sdk library(making gwt work with mobile)

  1. download and install(unzip) the gwt map library, version 1.1


After these steps just create a web application with Netbeans and use for example the Tomcat Apache web server for running the program. Creating the application with Netbeans wizard, you will have the option to add to your project, the GWT sdk, at the end of the wizard, by checking it.
After creating your project, right click on project properties window, and add the library of MGWT(mgwt-1.1.1.jar) too and also the library of gwt-map(gwt-maps.jar).

In your project, find the *.gwt.xml file, open it, and add the following lines to the existing code:
    <inherits name="com.google.gwt.user.User"/>
    <inherits name='com.googlecode.mgwt.MGWT'/>
    <inherits name='com.google.gwt.maps.GoogleMaps'/>

//if you use firefox
<set-property name="user.agent" value="gecko1_8"/>
//or for example chrome
<set-property name="user.agent" value="safari"/>  

One more step.... :) add the following java code to onModuleLoad() procedure in your EntryPoint java file:
    public void onModuleLoad() {      
        //build some UI
        layoutPanel = new LayoutPanel();
        Button button = new Button("View the MAP!");               
        layoutPanel.add(button);
        //for click event
        button.addTapHandler(new TapHandler() {
        @Override
        public void onTap(TapEvent event) {
           Maps.loadMapsApi("", "2", false, new Runnable() {
              public void run() {
                // Open a map centered on Satu Mare, Romania
                LatLng SatuMareCity = LatLng.newInstance(47.792091, 22.885189);

                final MapWidget map = new MapWidget(SatuMareCity, 2);
                map.setSize("100%", "100%");
                // Add some controls for the zoom level
                map.addControl(new LargeMapControl());

                // Add a marker
                map.addOverlay(new Marker(SatuMareCity));

                // Add an info window to highlight a point of interest
                map.getInfoWindow().open(map.getCenter(),
                    new InfoWindowContent("The River Somes is here in Satu Mare"));

                final DockLayoutPanel dock = new DockLayoutPanel(Unit.PX);
                dock.addNorth(map, 500);

                // Add the map to the HTML host page
                layoutPanel.add(dock);
              }
            });
        }                   
        }) ;                                                                                                             
        RootPanel.get().add(layoutPanel);               
    }

Where the compoent layoutPanel is a global variable defined in the main class file, that implements EntryPoint, and where also the method above is situated.
LayoutPanel layoutPanel;

You can test your application under your browser,  but there are also emulators on the web which you can use to test mobile applicatons:

If you run, the application above should look like: