Search This Blog

Saturday, July 30, 2011

GWT - communicating with PHP via JSON

  Finally something useful :) I'll show you my implementations of JSON communication. Of course it took some time before I found out how to do everything myself.
  Note that this works only if your application is on the same domain and port with the server you are talking with. See my previous post http://coders-tutorials.blogspot.com/2011/07/thinking-ahead-gwt-server-side-java-or.html . Otherwise you have to use JSONP.

  Creating POST parameters
  When you want to post parameters, a String according to standard has to be created. I implemented a class that does it for me:
 
public class PostParameters {
 public String parameters = "";  //String with all parameters

 public PostParameters() { 
 }

 public void addParameter(String name, String value){
   parameters+=URL.encode(name);
   parameters+="=";
   parameters+=URL.encode(value);
   parameters+="&";
 }
}

 

All parameters have to be URL encoded. Usage can be seen in Making request topic.

  Making request

public void login(){    
  PostParameters params = new PostParameters();  //the class containing post parameters
  params.addParameter("name", nameTxtBox.getText());
  RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, "php/login.php");
  builder.setHeader("Content-Type","application/x-www-form-urlencoded");
  builder.setTimeoutMillis(20000);
     try {
       Request request = builder.sendRequest(params.parameters, new RequestCallback() {
         public void onError(Request request, Throwable exception) {
          Window.alert(exception.getMessage());
         }        
         public void onResponseReceived(Request request, Response response) {
           if (200 == response.getStatusCode()) {
            handleLogin(response.getText());  //this function is called when everything ok
           } else {
            Window.alert(response.getStatusText());
           }
         }
       });     
     } catch (RequestException e) {
      Window.alert(e.getMessage());
     }    
}
In handleLogin() function is response parsing process, which is explained further.

  My JSON syntax

  All my responses have text "results:"...you can do without it...I don't know why I started using it, but that's how my server does :)
  For simple info you can send something like this (this comes from server):
  {'results': {'successfulLogin': 'true'}}
Or something like this:


{
"results": {
        "receivedSentData": [
            {
                "uuid": "10f6a663-2840-41b9-b726-91359ec7cf95",
                "regNr": "11-XXX",
                "regDate": "2011-07-11",
                "correspondent": "Mr John",
                "howReceieved": "e-document"
            },
            
        ],
        "files": [
            
        ],
        "folders": [
            {
                "author": "okmAdmin",
                "created": "2011-07-29T08:53:42.845+03:00",
                "hasChilds": false,
                "path": "\/okm:root\/LIETVDS_VDC\/2011\/IEN\/11-XXX",
                "permissions": 15,
                "subscribed": false,
                "uuid": "10f6a663-2840-41b9-b726-91359ec7cf95"
            },
            
        ],
        "totalRows": 1,
        "startRow": 0,
        "endRow": 1
    }
}



This is an example of data which I receive when populating a table. In receivedSentData I have info from database, in files and folders I have info about documents from document system. Doesn't matter...now I'll show how to parse them in GWT.


How it works
GWT has some great classes for JSON parsing, but firstly you have to use JavaScript's native function eval() which just executes received JSON data and that way you can get data object.
Personally I created a static class which parses all server responses.
public class MyParser {
 public static native JavaScriptObject parseJson(String responseString) /*-{
   return eval('('+responseString+')');
 }-*/;
}

And then it's very easy to use this parser for every response:
JSONObject json = new JSONObject(MyParser.parseJson(responseString)) \\;

Now JSONObject has the received data and can be easily parsed out. For example this is how I get all the "results" data.
JSONObject ary = json.get("results").isObject(); 

Then I can get receivedSentData array or any other object with just providing keyword:
JSONArray dataArray = ary.get("receivedSentData").isArray();

And then from array:
dataArray.get(i).isObject().get("regNr").isString().stringValue();

You can add all this parsing code in try catch blocks, so when server responds with an invalid JSON that can't be parsed, an exception occurs and you can show it.

GWT - Creating new project and removing unnecessary stuff

  This is an easy step, but as always there are some secrets - what to do better...at least what was better for me.
  1. Create new web application

   2. Insert project name, package name. As you can see I am putting my projects in Apache's public folder (read my last post for reasons).  Uncheck Google App Engine, because when I started using GWT, didn't understand why my project doesn't work when there is no Internet connection...this was the reason...GWT was communicating with some kind App Engine's API online. And leave sample code checkbox enabled.

  3. Then you can delete unnecessary files ...

  4. You can delete everything in projectName.css. Have to delete heading and table tags in projectName.html. And web.xml has descriptions of servlets. Hopefully servlets were deleted, when you deleted files, but if they still are there just remove them, or else it won't be possible to compile project.
  5.You could have left projectName.java file undeleted and just removed unnecessary code, but it's easier to delete and just create a new one like this....
6. Now you can choose design mode, add a button and add click event to it....easy. At first I was confused when didn't see the Design tab. When it happens you just have to right click your file and choose
 Open With -> GWT Designer.

  When everything is ready right click project, choose Debug As -> Web Application (running on external server)... choose this option if your project is in Apache directory as I told in previous post. Otherwise choose just Web Application. Click the link, install browsers plugin, and  there you have...your project is running. :)
  After that if changes are made to source code, only browser has to be reloaded. No need of restarting applications debug mode. And when application is ready, choose Compile Project. Then everything in war folder can be put on server and your web application is ready.

Thinking ahead - GWT server side : Java or PHP

   I think this is very important topic, because I struggled many times with server communication, because it wasn't well explained in documentation.
   Working with my project, I had to decide what will be used on server side. As it was recommended on GWT web page to use Java, I thought to give it a try (but changed later to PHP). GWT has great interface for using Java on server side. http://code.google.com/webtoolkit/doc/latest/tutorial/RPC.html You just have to write server side classes on the same project...and that's all. Then it is very easy to use these functions...because you don't have to worry about data sending types, names, response parsing... it is just like calling simple function. BUT, because I am not a Java guy I couldn't do many things that had to be accomplish on server (e.g. file uploading with JumpLoader, sessions). And of course there is the problem with Java servers JBoss, GlassFish a.o. --- I just think they are hard to configure. So then I decided to use PHP with Apache...easy and proven value.
 
   Application development - debug mode


   Before I continue, something has to be explained - how application development works.
   When you are writing code and want to test it, you have to do it in Debug mode - because the compilation to JavaScript takes some time. There are two ways how you can launch the debug mode :

  •  normal Web application - then some kind of GWT's Java server (named Jetty) is started and server side code is executed on it - great if you are developing with Java server code. And can be used if there is no communication with server, just a static web page with widgets or something else. I guess Jetty server doesn't support PHP.
  • Web application (running on external server) - then Jetty isn't launched, and you don't need one, because the communication is done with PHP via JSON or XML (recommend JSON). BUT then arises one big problem I struggled with for many hours.... 
    If you put project in default Eclipse workspace path and launch normal Web application mode, then 1)you have to use full url for server requests (e.g. http://localhost/ManagementSystem/php/login.php) 2)You can't make normal AJAX requests, because browsers implement SOP (Same Origin Policy). In short - browsers forbid to use data from different host or port (in our case Jetty and Apache ports are different). 
  There are workarounds explained here http://code.google.com/webtoolkit/doc/latest/tutorial/Xsite.html , but they are just confusing everything. At the beginning of project I used JSONP requests and everything worked, but the code was complicated and that way you can send data only with GET method. I think IE has some restrictions with url (GET) length. There are situations when you really need to do such a request, i.e. for some kind of a Yahoo service, but that wasn't my case. I will later write an article about how to implement this JSONP with some source code.... the one on GWT's web page is missing something.  

Installing GWT - Tutorial

   First thing you need to do is install GWT on your computer. It's very simple if you are going to use Eclipse - it's possible to download SDK separately, but I don't think it's necessary. Only once when there was an error in newest GWT plugin update, I downloaded SDK and configured Eclipse to use it.. but that was only for a while.

Installation steps:


  1. Download Eclipse  http://www.eclipse.org/downloads/ if you don't have it already installed
  2. Install GWT SDK plugin 
    And insert link from this site http://code.google.com/eclipse/docs/download.html according to your Eclipse version. There are detailed instructions if you need. If you don't know your Eclipse version here is a good description how to find it out - http://www.thinkplexx.com/learn/howto/ide/eclipse/find-out-exact-eclipse-version
     3. Install Designer plugin, so you will be able to drag and drop widgets just like in normal desktop application development. Use the same steps from previous plugin installation and insert link according to your  Eclipse version - http://code.google.com/webtoolkit/tools/download-gwtdesigner.html

  Now you don't have to worry about anything, because the newest versions will be downloaded automatically, so you will have the newest framework and features.

Thursday, July 28, 2011

GWT - What is it and how I use it in my project - Tutorials

   Now I am working on a document system project. Requirements - web interface, desktop alike application, document upload, viewing, editing, security and so on. So I needed a framework, which could satisfy those requirements. Of course everything can be made in pure PHP and javascript, but the web is developing, so I decided to use some kind of a new technology. Gmail is created with GWT, and maybe even this blogging site.


   In short about GWT - It's Google's project, where you can write Web application in Java and then it is compiled to pure JavaScript. 
                                     http://code.google.com/webtoolkit/overview.html
               Advantages:
      • Use (Eclipse or NetBeans) IDE - syntax check, auto complete, debugging, compile time error checking.
      • Source code is compiled as small as possible (with variables a, aa...).
      • JavaScript is compiled for each browser separately, so you don't have to worry about that. And the code is using each browser's specific functions, so it is faster.
      • Page (application) is loaded only once, everything else - pure Ajax
      • JUnit testing (haven't used it myself)
      • Can work without JavaScript knowledge
      • Can include third party libraries (I am using SmartGWT), jQuery is possible
      • Server side can be Java, PHP or other
      • Use of designer (drag and drop Widgets)
      • ...............
                Disadvantages:
        • Not so straightforward including pure JavaScript (at first)
        • GWT default Widgets lack of richness - must implement yourself (or use extra library)
       In other words, I highly recommend using GWT in your projects...maybe because I haven't used other frameworks...but why should I, if I'm not disappointed :)

    Losing virginity

         Hi, all my readers ( I hope at least my girlfriend will read this) :). This is my first post and first blog and first public  using of English language, so please don't judge me... I guess first posts will get some help from Google Translate ;)


       Little about this blog - first I thought I should make two blogs - one with geeky technical stuff and other for mortals, who can read and understand something. But as I gave a little thought, understood that no one is going to be interested in the normal stuff, because .... well who cares. There is Twitter now where everyone can follow and get the newest information...no point of going to my page and read everyday stuff.
        So this is going to be my TUTORIAL blog. Most of it will contain information about technical stuff (programming, computer science), but I will try to include other interesting stuff too - e.g. last year I began learning guitar for my self, so now I think I could make some kind of a tutorial or progress - how, where to find information, where to start. If I knew that stuff earlier, it would be great, that's why I've always wanted to contribute my knowledge, so no one should struggle with these stuff.

      Are you asking, what is going to be the technical stuff? If you are not, then...I will tell anyway. In short - I am IT specialist (not a big one - learning now to get Masters degree) and I've worked for some projects where I encountered many new stuff that was very interesting, but lacked of more documentation. So I thought -  tutorial blog it is. hell yeah. My project experience - C#, PostgreSQL, MySQL, PHP, HTML, JavaScript, Qt and now GWT (Java , SmartGWT). There is good amount of information about C#, PHP bla bla, but Qt and GWT aren't so widespread that's why I will write some info about those technologies, mostly about GWT while I am on a project using this framework.

      I will try of course to add posts about technical stuff that can be understood by someone who is using computer just for fun. If any friend is going to read my blog, maybe I can post some tutorial about...don't know emmm.. general information - what is Linux and why aren't you using it :)

      C ya.