Pages

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:





Wednesday, August 8, 2012

MGWT - A very simple example - click the button

MGWT

MGWT stands for developing mobile applications with GWT and mgwt.
Mgwt works on all kind of mobile devices that support webkit (like iPhone, iPad, iPod, Android, Blackberry, ...)
  • Native support for touchevent the GWT Way
  • Animations built in with GWT MVP
  • lots and lots of widgets
  • specific theme for each plattform (iOS, Android, ...)

 Let' se a simple example starting from a Google Web Toolkit(GWT) project:

1. Create a GWT project
2. In your gwt xml file add this line:
   <inherits name='com.googlecode.mgwt.MGWT'/>

3. Add the MGWT library to your project
(It can be downloaded from: http://www.m-gwt.com/ )

4. And your EntryPoint will be this:


public class mobileEntryPoint implements EntryPoint {

    //global variables
    int countI;
    MTextBox lbl;
   
    public void onModuleLoad() {
                //initialization
                lbl = new MTextBox();
                countI=0;
       
                //set viewport and other settings for mobile
                MGWT.applySettings(MGWTSettings.getAppSetting());
                //build animation helper and attach it
                AnimationHelper animationHelper = new AnimationHelper();
                RootPanel.get().add(animationHelper);

                //build some UI
                LayoutPanel layoutPanel = new LayoutPanel();
                Button button = new Button("Hello User!");               
                //for click event
                button.addTapHandler(new TapHandler() {
                    @Override
                    public void onTap(TapEvent event) {
                        countI++;                                               
                        lbl.setText("You clicked: "+countI+" times");
                    }                   
                }) ;                                                                                             
                layoutPanel.add(button);
                layoutPanel.add(lbl);

                //animate at click
                animationHelper.goTo(layoutPanel, Animation.SLIDE);              
    }
}

By using gwt-phonegap and mgwt you can write applications that can be deployed into the app store or the market place with GWT.