Pages

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.

Thursday, June 14, 2012

Wednesday, June 6, 2012

JavaFx - CHART example

We would like to have a chart of the imported fruits. 
Let' see in JavaFx the PieChart diagram:

public class JavaFXApplication1 extends Application {

    public static void main(String[] args) {
        launch(args);
    }
   
    @Override
    public void start(Stage primaryStage) {
       
      primaryStage.setTitle("Chart example");
      ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList(
                new PieChart.Data("Grapefruit", 13),
                new PieChart.Data("Oranges", 25),
                new PieChart.Data("Plums", 10),
                new PieChart.Data("Pears", 22),
                new PieChart.Data("Apples", 30));
        PieChart chart = new PieChart(pieChartData);
        chart.setTitle("Imported Fruits");       
       
        StackPane root = new StackPane();
        root.getChildren().add(chart);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
               
    }
}

Java - read from console, dos prompt

The JAVA file is the following, for an example of reading input values from console:

package javaapplication1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class JavaApplication1 {

    public static void main(String[] args) throws IOException {
       
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
       
        String prompt = "";       
        System.out.println("Enter your name: ");
        prompt = reader.readLine();
        if (prompt.equals("\t"))
            System.out.println("You entered a TAB from your keyboard.");
        else
            System.out.println("Your name is: "+prompt);
       
    }
}

Friday, June 1, 2012

Java - sorting strings with Hungarian characters

        Let's sort some Hungarian strings in alphabetical order:

        String[] words = {"Bruce","Géza","Ákos"};

        Collator c = Collator.getInstance(new Locale("hu"));      
        Arrays.sort(words, c);


        for(int m=0; m<words.length; m++)
            System.out.print(words[m]+", ");

Tuesday, May 29, 2012

Java - Enumerated types

To enumerate some constant values, and/or associate to them methods or values, we can use enum in java. Enum types in Java are considered like classes, they can have constructors too, can implement interfaces, but can have no descendants. Let see, how we work with enum in java, through an example that classifies programming languages.
Create your own test class, and then test the following code:

    private enum prog_language {
        //enumerated constants
        java(true), c(true), basic(true), php(true), delphi(true), csharp(false), cplus(false);
       
        //fields to associate with the enum types
        private int position;
        private boolean usedbyme;
       
        //constructor
        prog_language(boolean bUsedByMe) {
            usedbyme = bUsedByMe;
        }           
        //getters and setters of the fields
        public int getPosition() {
            return position;
        }
        public void setPosition(int position) {
            this.position = position;
        }          
        public boolean isUsedbyme() {
            return usedbyme;
        }       
    };

.......................................       
        int i = 0;
        for (prog_language p : prog_language.values()) {
            i++;
            p.setPosition(i);
        }                              
        System.out.print(prog_language.valueOf("java").name());      
        System.out.println(" - at position: "+prog_language.valueOf("java").getPosition());
        System.out.println("I am using this language: "+prog_language.valueOf("java").isUsedbyme());

   
 
Enum types can also participate in switch-case statements too.

Thursday, May 24, 2012

Java - Data Structures

Data Structure       Advantages                Disadvantages



Array
Quick insertion
(very fast access if index known.)
Slow search, 
Slow deletion, 
fixed size.
Ordered Array
Quicker search
Slow insertion,
Slow deletion,
fixed size. 
Stack
Provides last-in, first-out access
Slow access to other items
Queue
Provides first-in, first-out access
Slow access to other items
Linked list
Quick insertion, quick deletion
Slow search
       ArrayList           
(is same as a Vector. Vectors are
synchronized, can be thread safe, but
slower)
Binary Search, Sort
Slow insertion, deletion
Binary tree
Quick insertion, deletion (if tree remains balanced), and search.
Deletion algorithm is complex
Red-black tree
Quick insertion, deletion (this tree is always balanced), and search.
Complex
2-3-4 tree
Quick insertion, deletion (this tree is always balanced, is good for disk storage progr.), and search.
Complex
Hash table (~arrays)
Very fast access if key known. Fast insertion
Slow deletion, access slow if key not known, inefficient memory usage.
Heap (~LinkedList)
Fast insertion, deletion, access to largest item.
Slow access to other items
Graph
Models real-world situations.
Slow and complex.