Pages

Friday, March 22, 2013

SmartGWT.Mobile

Mobile world and web approach solutions – SmartGWT.Mobile


As the demands increase for applications to mobile phones, tablets and smart phones I would like to, go through at existing web solutions for mobiles, among native applications, and analyzing a little bit, and emphasizing one of them, the SmartGWT.Mobile product.


The first thing that comes in my mind, of course is html, javascript, css3, html5. The mobile web is growing up quickly, and tons of great HTML5 features are already supported on modern mobile browsers. Web developers can use the same set of technologies they know and love to build rich web applications that work across different device types. HTML5 allows us to use efficiently local storage, multimedia introducing new audio-video types like: MP4, WebM, Ogg and offers a canvas for graphics. Supports mouse and touch together.


If you are not satisfied with simple web pages or applications, you might think forward using technologies, that offers us, server side communications too. HTML5 can be paired with server side solutions like PHP or JSP. And then, you can enter into Java world, because there are plenty of possibilities which says that you can write all the code, the server side and even the client side program, all in java. When you are ready with programming, you just translate or compile your program to javascript and html5. And more, because your output will be a more efficient html5 and ajax code, than one written manually. You don't have to worry about browser's compatibility and of course the server side code will run on a java web server. Thanks for GWT-GoogleWebToolkit, such solutions are the following, let's see a few of them:


MGWT; GWT-Phonegap
mgwt is a library for developing mobile apps and mobile websites with GWT from one code base. mgwt provides native looking widgets for many platforms, animations and many other things that are needed for writing mobile apps. gwt-phonegap enables GWT apps to use Phonegap. With Phonegap HTML5 apps can access the same device features that native apps can use from Javascript, such as the file system or contacts.
With mgwt and gwt-phonegap you can deploy your GWT apps into any app store or let your users use them as a website.
Both projects are available under apache 2.0 license from maven central.
mgwt provides mobile widgets that are compatible with UIBinder and the Editor Framework. mgwt integrates touch events and animation events with its own DOM implementation and provides gesture recognizers on top of that.
There are themes for iPhone, iPad, android phones, android tablets and blackberry. For going offline there is an automatically generated HTML5 offline manifest.
In dev mode gwt-phonegap can emulate the Phonegap API so that developing of Phonegap apps can happen inside GWT dev mode.
gwt-phonegap also provides utilities to make GWT RPC work in a Phonegap environment. Personally, I think that the one disadvantage of this solution, is that for GWT PRC server side communications, you must use the GWT-Phonegap library too, among the mgwt package.


Emitrom products:
emitrom – comes with a set of product for different kind of applications like: Flash4J, Lienzo, Titanium4JMobile, Touch4J. They are very modern and interesting, is worthy to see and try. Develop slick mobile web apps that will look and feel like native iOS, Android and BlackBerry using the Secha Touch API but do it in the language you know with the tools you already know in Java. So sounds good, but one thing brothers me a little bit, for the functionality, you have to add additional packages to your emitrom project, like Sencha Touch Javascript library, or Phonegap.


SmartGWT.Mobile:
The smartclient  platform makes is simple to build powerful, high-productivity web applications on pure web standards. SmartGWT is coding in java, and getting the power of the SmartClient framework.
Smart GWT combines the industry's richest set of GWT UI components with a Java server framework to provide an end-to-end solution for building business web applications. Provides all the power of true Ajax, deep server integration, rich enterprise ui components, and mobile support without a rewrite. Even if you know nothing about mobile development, your Smart GWT application supports mobile. Finger taps and gestures arrive as normal mouse events, so your event handlers just work — users can even trigger context menus and hovers via touch-and-hold, and drag and drop via finger slides. Device-aware components automatically switch appearance and behavior to mimic typical mobile UIs.
Want more control? Gesture & orientation change events, as well as native functions like phone dialing are all there to let you fully tune the mobile experience.
In plus, SmartGWT offers us a new product family named SmartGWT.Mobile.
When should I use SmartGWT.mobile vs Smart GWT?

In a nutshell, if your application:
1. primarily targets phones and tablets: use SmartGWT.mobile only
2. primarily targets desktops and tablets: use Smart GWT only
3. targets desktops, tablets and phones: consider using both; however, depending on devices and requirements you may use just one or the other.


I would like to present a short application written in java with SmartGWT.Mobile which has a server side RPC communication, getting data from a server, and showing into a TableView mobile component. There is no need of additional packages like, phonegap or sencha to run this program. I put this running code on a free java server to demonstrate the functionality. If you test this in a desktop pc, you should us the google chrome explorer, because this explorer handles dialog boxes for mobiles. Google Application Engine offers us a web server for java applications, and it has also a free but limited storage.
You can find the link of my mobile applications on my site


My personal conclusion is that, you may use any of these technologies, if you want a web solution on your mobile, and as you see, these technologies are making effort also, to achieve a native appearance or sometimes even native functionalities too. It is ok! but for example, I don't consider a server side communication, being just a native functionality, it is also a web programming pretension
Web pages, I think, never will transform to real, true native applications. And don't have to. At the end you will always deal with javascript and html as a result of your work. Is not a problem, it is in order.  And again, my personal opinion, is that, for a real native application use the right tool or programming language, because there are also many solutions, even in java, like Codename One. For web pages, sites and web applications the above mentioned technologies are the best :) 



Saturday, March 9, 2013

Java swing with JavaFx

Enhance a Java swing frame with JavaFx componets or functionality


My purpose with this short blog to present a very simple example of how I was understood the use Java swing components together with Javafx components on a Java Frame form. So, I just was curios to see how can I improve a swing form with the new modern JavaFx componets or technology. Having this idea in my mind I have looked for technical documents at oracle javafx blog site, and I found the following 2 interesting articles:


More about javafx on: Oracle's site


Firs let me show you to picture about my running application, that tells you all, about my short example.

Image 1:





Image 2:


Now as you see above, just a short demonstration of how can we use together a javafx and a swing button on a JFrame form. With Netbeans IDE, the steps are easy primitve, but of course you can use your favorite IDE to try this also. I packed all the application in a zip file, so you can even download for free, if you want to look over.


First I created an empty, new JavaFx project, called javafxswingapplication1. Then you may wonder, but I created a new java file, not a javafx unit. This was an empty JFrame form, and I just put on it a swing button, a swing text field and also a JPanel swing container. The JPanel will hold the javafx components, designed on a JFXPanel. The “birdge” between the swing and javafx, is the JFXPanel javafx container, which can be added to the JPanel. The swing part of the form was designed with the swing designer from the Netbeans IDE, and the javafx code I added manually to the form.


All the javafx code is wrapped into a single method and is called from the constructor of the Jframe form, after the call of initcomponents() swing initialization method. The javafx project is set to start this frame at running the application. This can be done at project properties, run – main class.


So the key point is the javafx method, let's see how does it look. I was called this method: createSceneAndAddToSwing


private void createSceneAndAddToSwing() {
PlatformImpl.startup(new Runnable() {
public void run() {
jfxPanel = new JFXPanel();
Group mainPanel = new Group();
Scene scene = new Scene(mainPanel,300,150);
Button btn = new Button();
btn.setText("From JavaFX");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
jTextField1.setText("It was pushed a JavaFX button!");
}
});
mainPanel.getChildren().add(btn);
btn.setLayoutX(50);
btn.setLayoutY(100);
jfxPanel.setScene(scene);


//add this "javafx" to the swing jframe's jpanel
jPanel1.setLayout(new BorderLayout());
jfxPanel.setPreferredSize(new Dimension(PANEL_WIDTH_INT, PANEL_HEIGHT_INT));
jPanel1.add(jfxPanel, BorderLayout.CENTER);
jPanel1.revalidate();
jPanel1.repaint();
}
});
}
So that's it, for a more complex javafx functionality in a swing frame, I would firstly create a standalone javafx project to wirte and test the desired javafx and then to embed it onto a jpanel container using the JFXPanel as a bridge.

Tuesday, March 5, 2013

NetBeans 7.3 Contribution


Today I got this response to my NetBeans 7.3 contribution. I am very happy now :)

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: