Pages

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:

Friday, September 21, 2012

JavaFx 2.2 – Webservice - Oracle DB example




This short example demonstrates us, how javafx works as a client, in an application having a client-server arhitecture. The tutorial uses the following softwares and tools, and if you wish to try it, you should have installed, these on your computer:
-         Oracle Database Express Edition 11g Release
-         Java SE Development Kit 7
JavaFX SDK is now included in the JDK 7 for Windows, Mac OS X, and Linux x86/x64.
-         Netbeans 7.2 Development IDE
(http://netbeans.org/downloads/index.html). Download the Java EE or the full version of Netbeans. This setup will install to your computer the Apache Tomcat and also the Glassfish Server if you check these options. In this tutorial we use just the Tomcat Apache Server 7.0.27.
-         JDBC Driver to the Oracle Database Express Edition 11g

Web services are Web based applications that use open, XML-based standards and transport protocols to exchange data with clients. Web services are developed using Java Technology APIs and tools provided by an integrated Web Services Stack called Metro. The Metro library package is also installed on your computer by Netbeans
JavaFX is the next step in the evolution of Java as a rich client platform. It is designed to provide a lightweight, hardware-accelerated Java UI platform for enterprise business applications. With JavaFX, developers can preserve existing investments by reusing Java libraries in their applications. They can even access native system capabilities, or seamlessly connect to server-based middleware applications.


FYI:
You can use also your favorite IDE instead of Netbeans, but you must ensure that the additional packages(Tomcat, Metro), are also installed.
 After having installed all the software and tools, we will have 3 more steps to do, first database operations, then creating the web service in Netbeans, and finally the client part programming, javafx.

1.    Database tasks

The example is about storing information about books, read by me, and retrieving information from database by a given book id, and presenting them by javafx client, through a webservice. In the database we will have a book table, with the fields: Id, Title and Writer. To increment the primary key at every new record, in the book table, we use triggers and sequences in Oracle. You should use, the free SQLDeveloper tool. (http://www.oracle.com/technetwork/developer-tools/sql-developer/downloads/index.html). The sql code for creating a login user, the table, sequence, and trigger, are the following:

Login user

-- Create the user
create user TESTER
  identified by ""
  default tablespace SYSTEM
  temporary tablespace TEMP
  profile DEFAULT
  password expire;
-- Grant/Revoke role privileges
grant dba to TESTER;
-- Grant/Revoke system privileges
grant unlimited tablespace to TESTER;

Create table

-- Create table
create table BOOK
(
  ID     NUMBER not null,
  TITLE  NVARCHAR2(50) not null,
  WRITER NVARCHAR2(100)
)
tablespace SYSTEM
  pctfree 10
  pctused 40
  initrans 1
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );
-- Add comments to the table
comment on table BOOK
  is 'Testing javafx and webservice';
-- Add comments to the columns
comment on column BOOK.ID
  is 'Primary key';
comment on column BOOK.TITLE
  is 'Title of the book';
comment on column BOOK.WRITER
  is 'Writer of the book';
-- Create/Recreate primary, unique and foreign key constraints
alter table BOOK
  add constraint PK_ID primary key (ID)
  using index
  tablespace SYSTEM
  pctfree 10
  initrans 2
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );

Create sequence

-- Create sequence
create sequence SEQ_BOOK
minvalue 1
maxvalue 9999999999999999999999999999
start with 1
increment by 1
cache 20;

Create trigger

create or replace trigger TRG_BOOK
  before insert on book 
  for each row
declare
  -- local variables here
begin
   IF INSERTING THEN
  IF :NEW.ID IS NULL THEN
   SELECT SEQ_BOOK.NEXTVAL INTO :NEW.ID FROM DUAL;
  END IF;
 END IF;
end TRG_BOOK;
/

2.    Creating the Webservice

Using the Netbeans IDE, to create a webservice, is very easy. First you create a Web Application, by doing: File-New Web Application in Netbeans' Menu. In this demo, we use the Apache Tomcat 7.0.27. as a webserver for our web application. Netbeans 7.2 IDE allows you to choose this webserver, when you create the web application. After the first step we easyly create the webservice, just right clicking on project source and saying, create webservice. Name your webservice(class), WebServcieForJavaFx. Then Netbeans will create you, also a simple “hello” example method, that we will change to the method GetBookInfo. The GetBookInfo() function will retrieve the informations, book title and writer from database, by an ID. The ID will be an input parameter to this method, and the return type of this function will be a special type, created by us: RecordType. Because the program works with Oracle database you must also add the oracle jdbc driver to this project. Right click at the project and at the Properties you can add the ojdbc6.jar file.
First let’s see the special return type, the RecordType java class file, how it looks:

package utils;

/**
 *
 * @author Sipos Lehel
 */
public class RecordType {
    private String Title;
    private String Writer;
   
    RecordType() {
       
    }

    public String getTitle() {
        return Title;
    }
    public void setTitle(String Title) {
        this.Title = Title;
    }
    public String getWriter() {
        return Writer;
    }
    public void setWriter(String Writer) {
        this.Writer = Writer;
    }
   
}

And then the webservice main class will be the following:
package server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import utils.*;

/**
 *
 * @author Sipos Lehel
 */
@WebService(serviceName = "WebServiceForJavaFx")
public class WebServiceForJavaFx {

    @WebMethod(operationName = "GetBookInfo")
    public RecordType GetBookInfo(@WebParam(name = "strID") String strID) {
        RecordType answer = new RecordType();
        answer.setTitle("empty");
        answer.setWriter("empty");
       
        try {            
            Class.forName("oracle.jdbc.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "tester", "tester");           
            ResultSet rs = null;
            Statement stmt =  con.createStatement();
            rs=stmt.executeQuery("select * from book where ID="+strID);           
            if (rs!=null) {
                rs.next();
                answer.setTitle(rs.getString("TITLE"));
                answer.setWriter(rs.getString("WRITER"));                                         
                rs.close();
            }
            stmt.close();           
        } catch (Exception ex) {
            answer.setTitle(ex.getMessage());
            answer.setWriter("Error occured!");           
        }                                        
        return answer;
    }

}

A webservice publishes it’s method through a WSDL file, and therefore right click in Netbeans, at webservice and say generate WSDL file. Start your webservice, by running this application. You can test the web service information by also, right clicking in Netbeans:



3.    Programming JavaFx – webservice client

To create a javafx application in Netbeans, just simply say, File-New Project-JavaFx-Create JavaFx Application. Call your java main file in this project: WebClientJavaFx.
Creating a webservice client at the second step, is also very easy, just right click your source in the Projects window and say create web service client. Creating your webservice client you will need to point the WSDL location, which you can do by specifying its URL:
In the java source file you can call the Web Service Operation in your start method, by right clicking in the netbeans source editor, and saying Insert Code and then Call Web Service Operation.
We will have 3 components to work with, a button to call the webservice, a label to see the answer, and a field component to bypass the ID input parameter to the webservice method.
Your WebClientJavaFx java file, after programming should look like this:

package webclientjavafx;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import webclientjavafx.webclient.RecordType;

/**
 *
 * @author Sipos Lehel
 */
public class WebClientJavaFx extends Application {
    Label lbl = new Label("Lehel Sipos read: ");
    TextField fld = new TextField("2");  
    RecordType answ;
   
    @Override
    public void start(Stage primaryStage) {       
        answ = getBookInfo("2");               
        Button btn = new Button();
        btn.setText("Get a book from the shelf");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                answ = getBookInfo(fld.getText());
                lbl.setText("Lehel Sipos read: "+answ.getTitle()+" "+answ.getWriter());
            }
        });               
        Group root = new Group();       
        root.getChildren().add(0,lbl);        
        root.getChildren().add(1,fld);
        root.getChildren().add(2,btn);
        root.getChildren().get(0).setLayoutX(50);               
        root.getChildren().get(0).setLayoutY(10);       
        root.getChildren().get(1).setLayoutX(50);       
        root.getChildren().get(1).setLayoutY(40);       
        root.getChildren().get(2).setLayoutX(50);       
        root.getChildren().get(2).setLayoutY(100);                             
        Scene scene = new Scene(root, 600, 250);       
        primaryStage.setTitle("JavaFx-Webservice example");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
   
    public static void main(String[] args) {
        launch(args);
    }
   
    private static RecordType getBookInfo(java.lang.String strID) {
        webclientjavafx.webclient.WebServiceForJavaFx_Service service = new webclientjavafx.webclient.WebServiceForJavaFx_Service();
        webclientjavafx.webclient.WebServiceForJavaFx port = service.getWebServiceForJavaFxPort();
        return port.getBookInfo(strID);
    }
}

This application can be run also from browsers, if the javafx applet will be a signed jar file, or maybe you change your java.policy security file by adding the following lines to the …jre7\lib\security\java.policy
grant { 
 permission java.security.AllPermission;
};
The running program is showed in the following pictures: