Pages

Monday, February 25, 2013

Reusable GWT components in java library packages


Using the Google Web Toolkit technology we have a set of widgets for enhance our web client interface. You can find the list of these java ui components with a short description on Gwt’s website: GWT widgets
In this blog I would like to present an easy way of developing new reusable widgets to our gwt web application. The new gwt widget can be packed into a java library package, in this way making it reusable for other web projects too. During my work, I use the Netbeans IDE but you are free to follow the steps in your favorite java editor.
I advice to plan always your web application with a multi-tier architecture, having separate modules for servers and client side programming.
In first step I will show you, how to create GWT widget library and then how to use it in a test web project.

  1. Creating a reusable gwt widget library
    In Netbeans Ide just choose File-New Project and Java-Java Class Library. Name your project for example: GwtComponents
    In project properties we must add the google web toolkit sdk library GWT2.5.0, which should contain at least the gwt-user.jar file
    Structure your library project to have 3 folders:
  • a directory for the gwt.xml file: gwtcomponents
  • a directory for java files, where we place the new gwt component: gwtcomponents.client
  • a directory for resource files, like css, image files: gwtcomponents.public

So, we almost are ready, but let's see how to create a new component. First we need an xml file, because this package, will be a gwt reusable library package. Create an xml file and name it, Main.gwt.xml and put it, into your main directory, gwtcomponents. Your xml file should contain the following lines:
<?xml version="1.0" encoding="UTF-8"?>
<module>
<!-- including the gwt module into the library -->
<inherits name="com.google.gwt.user.User"/>
<!-- declaring css file for styling our widget components -->
<stylesheet src="mystyle.css"/>
<!-- folder which contains the widget component -->
<source path="client"/>
</module>

To create a gwt widget, just create a java file that extends a gwt existing component. In my example I extend my java file with a HorizontalPanel, and I put on it a gwt label and an edit component. In this way, I will call my new gwt widget, LabeledEdit. Let's see how does it look:
package gwtcomponents.client;
/**
*
* GWT component: LabeledEdit - in constructor gets the argument for the text of the label
*
*/
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;

public class LabeledEdit extends HorizontalPanel {
public TextBox txtField;
public Label lblField;
public LabeledEdit(String label) {
//base horizontal panel settings:
setStyleName("comp1-hpanel");
//the label
lblField = new Label(label);
lblField.setStyleName("comp1-label");
add(lblField);
//the field
txtField = new TextBox();
add(txtField);
}
}

My stylesheet file under the public directory, is the follwing:
/*
LabeledEdit
*/
.comp1-hpanel {
background-color: #C3D9FF;
border: 1px solid blue;
}
.comp1-label {
border: 1px solid black;
background-color: orange;
font-weight: bold;
text-align: center;
}
So, that's it, in the next step, after building and creating the jar file from this project, I will test it in a gwt web project:
  1. Using the newly created gwt library
      In my gwt web project I just added the jar file – GwtComponents.jar - created above to my gwt web application. The main gwt.xml file of the web project must contain the following line to use the library in the test project:
      <inherits name="gwtcomponents.Main"/>
         And your main module:
LabeledEdit labelwithedit;
public void onModuleLoad() {
  labelwithedit = new LabeledEdit("Reuseable GWT library: ");
  //you can also redesign your gwt component here, if you want
  //labelwithedit.setStyleName("newstyle_in_this_project");
  RootPanel.get().add(labelwithedit);
}


These are all the necessary steps to do, for creating your own gwt reusable package. You can download my gwt library for free, it is written under Netbeans.
And also you will find a link there, to test a running web project which use this library.

Friday, December 7, 2012

Codename One – accesing java servlets with mobile phones



  Using java, there are lot of ways to access a database server which is not local, is not on your phone. You can have java servlets, webservices, or using for exampe the java server pages(jsp) technology, we can retrieve data from database servers.
Unfortunately Codename One, till now, does not support the webservice wsdl technology, but of course you can have servlets or jsp.
An acceptable arhitecture could be, when from client side Codename One, you achieve a servlet, which servlet connects to the database. For having this method, we have to have, two main java Object in Codename One:
NetworkManager
ConnectionRequest

A simple servlet code, accessing a db server, should look like this:
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
        String ID;
        String answer = "no answer";      
        ID = request.getParameter("Id");
        if (ID!=null) {
            //register driver
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            //get the database connection
            Connection con = DriverManager.getConnection ("jdbc:mysql://localhost/test", "user", "password");
            // Create statement
            Statement stmt = con.createStatement ();
            ResultSet rs = stmt.executeQuery ("select * from test where ID="+ID);
            rs.first();           
            answer=rs.getString("Name");                  
         }
        //this is an answer to the client – Codename one          
        out.print(answer);                        
        } finally {           
            out.close();
        }
    }
So, on client side, from mobile phones with Codename One we may have the following code to access the servlet above(the following proecedure is a button click):

D:\Programming\JavaCodenameOne\CodenameOne_2\src\userclasses\StateMachine.java
39     protected void onMain_ButtonAction(Component c, ActionEvent event) {
40         response = "empty";
41         try {          
42              //the NetworkManager object
43              NetworkManager networkManager = NetworkManager.getInstance();
44              networkManager.start();
45              networkManager.addErrorListener(new ActionListener() {
46              public void actionPerformed(ActionEvent evt) {
47                  NetworkEvent n = (NetworkEvent) evt;
48                  n.getError().printStackTrace();                       
49              }});
50              //ConnectionRequest object  
51              ConnectionRequest request = new ConnectionRequest() {
52                  int chr;
53                  StringBuffer sb = new StringBuffer();                  
54                  protected void readResponse(InputStream input) throws IOException {
55                       //reading the answer                     
56                       while ((chr = input.read()) != -1){
57                             sb.append((char) chr);
58                         }
59                       response = sb.toString();                                          
60                       response = response.trim();
61                  } 
62                  protected void handleException(Exception err) {
63                       //An error occured - show a message:
64              Dialog.show("Yikes!!", "Are you connected to the internet? Check your connection", "Ok", null);
65                  }
66              };
67              request.setUrl("http://localhost:8084/WebServicePhone/start"); //servlet calling
68              request.setPost(false);
69              request.addArgument("Id", "1"); //sending a the parameter Id to the servlet                                 
70              networkManager.addToQueue(request);          
71         } catch (Exception e) {
72             System.out.println(e.getMessage());
73         }               
74         while(response.equals("empty")) {
75             //waiting for the answer from the serlvet or jsp server
76         }
77         //set the label with the information from the server
78         findLabel().setText(response);
79         Dialog.show("Hi World", "Getting Data From JSP - MYSQL database", "OK" ,null);               
80     }

Tuesday, November 6, 2012

J2ME – RMS local database

RmsDb.java
The Mobile Information Device Profile -- the platform for mobile Java applications -- provides a mechanism for MIDP applications to persistently store data locally, across multiple invocations and retrieve it later.

This persistent storage mechanism can be viewed as a simple record-oriented database model and is called the record management system (RMS).

The javax.microedition.rms.RecordStore class represents a RMS record store, called otherwise a database table. It provides several methods to manage as well as insert, update, and delete records in a record store.
The record store is created in platform-dependent locations, like nonvolatile device memory.

I implemented a simple java class working with RMS, that we can use in our j2me application:

D:\Programming\Java2ME\MobileApplicationDB\src\mobileapplicationdb\RmsDb.java

 1 package mobileapplicationdb;
 2 
 3 import javax.microedition.rms.RecordStore;
 4 
 5 public class RmsDb {
 6   private RecordStore rmsDb = null;
 7   static final String LOCAL_DB_NAME = "rms_db_example";
 8 
 9   public RmsDb() {
10   }
11 
12   public void openRecStore() {
13     try {
14       // The second parameter indicates that the record store
15       // should be created if it does not exist
16       rmsDb = RecordStore.openRecordStore(LOCAL_DB_NAME, true );
17     }
18     catch (Exception e) {
19         System.out.println(e.toString());        
20     }
21   }    
22   
23   public void closeRecStore() {
24     try {
25       rmsDb.closeRecordStore();
26     }
27     catch (Exception e) {
28       System.out.println(e.toString());        
29     }
30   }
31 
32   public void deleteRecStore() {
33     if (RecordStore.listRecordStores() != null) {
34       try {
35         RecordStore.deleteRecordStore(LOCAL_DB_NAME);
36       }
37       catch (Exception e) {
38         System.out.println(e.toString());        
39       }
40     }      
41   }
42 
43   public void writeRecord(String str) {
44     byte[] record = str.getBytes();
45     try {
46       rmsDb.addRecord(record, 0, record.length);      
47     }
48     catch (Exception e) {
49       System.out.println(e.toString());        
50     }
51   }
52 
53   public String readRecords() {
54     String res = "";            
55     StringBuffer buf = new StringBuffer();                
56     try {
57       byte[] recData = null;
58       int intLen;
59 
60       for (int i = 1; i <= rmsDb.getNumRecords(); i++) {        
61           recData = new byte[rmsDb.getRecordSize(i)];       
62           intLen = rmsDb.getRecord(i, recData, 0);
63           res = "Record no." + i + ": " + new String(recData, 0, intLen)+"\n";       
64           buf.append(res);        
65       }
66       res = buf.toString();
67     }
68     catch (Exception e) {
69       System.out.println(e.toString());        
70     }
71     return res;
72   }
73 
74 }
-->

Mobile phones with Codename One – Getting/Storing data from/into xml file



Today I found a short description on wikipedia about how many technologies are in mobile application development area.

You can choose your programming language that you prefer to use, and you will find which mobile platform you can address with it.

The Codename One  technology uses the java language and enables Java Developers to build true native applications for all mobile/tablet platforms. Sounds quite interesting and it is. However, for the J2ME enabled phones, personally I prefer to use the j2me language and environment with the Netbeans IDE.

But let see through a short example, what is Codename One. It declares that you have just 5 easy steps for app development:
-         downloading the codename one plugin for free (eclipse or netbeans)
-         write your code in java
-         you have a designer for the GUI
-         and you have an embedded simulator to test your app
-         Generate a native mobile application for the desired device, sending to the build server, your code to be build. (you can do this from your IDE)

You can have more information at http://www.codenameone.com/


Now, let’ see a short example code, how to read and write xml file with codename one.
After you create a codename one project in your ide, just put a button and a label onto your form using the designer.
I used the following xml file for this example:

You must import packages like:
import com.codename1.io.*;
import com.codename1.ui.*;
import com.codename1.ui.events.*;
import com.codename1.xml.*;
//import java.io.InputStreamReader;
At the button’s onclick event I associated the following code for reading XML files, and also you will see the "xml write" in commented lines:
    protected void onMain_BtnDataAction(Component c, ActionEvent event) {                    
        String fromXml = "empty";
        try {
            //open the xml file for reading
            BufferedInputStream file = new BufferedInputStream(
                    FileSystemStorage.getInstance().openInputStream("example.xml"));
            InputStreamReader reader = new InputStreamReader(file);         
           
            //processing the xml
            XMLParser parser = new XMLParser();           
            Element elem;    
            elem = parser.parse(reader);   
            fromXml = elem.getChildAt(0).getChildAt(0).getChildAt(0).getText();            
/*elem.getChildAt(0).getChildAt(0).getChildAt(0).setText("writebackintoxmlfile"); FileSystemStorage.getInstance().openOutputStream("example.xml").write(elem.toString().getBytes());*/
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }       
        //label component - setting it's text from the XML
        findLblData().setText("XML: "+fromXml);       
        Dialog.show("Hello world","Success reading XML","OK",null);               
    }

The result, running your program:

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: