Showing posts with label GWT. Show all posts

GWT (Google Web Toolkit) review

GWT(Google Web Toolkit) project started by Google back in 2005 - 2006. Its an open source set of tools that allows web developers to build Javascript front-end applications in Java. It is licensed under the Apache License version 2.0. Now its enough talk about its history. Today will give review of GWT from level of programmer.

What drives me to write good part of GWT?
The only things I observed for good part of Google Web Toolkit. If there is something do comment for other viewer.

  • It converts whole front-end website in complex JavaScript code. Thats the best part of Google Web Toolkit. It create bunch of complex JavaScript code that event hard for you to understand. 
  • Provide table, tree structure and other stuff by just writing 30-40 lines of code. 

What drives me to write bad part of GWT?
Yeah, I'm eagerly waiting for this part to write. Only by converting front-end website into JavaScript doesn't mean its good for develop small or large application.

Web security
Converting front-end website into JavaScript not only thing provide security to website. Security always depends on quality code. Properly handled validation leads to secure website.

Hard to understand (Time Consumption Factor)
Its very hard for new developer to understand its flow. You need to train your developer for Google Web Toolkit. Can't find help on Google also.

Pain for developer (Time Consumption Factor)
Its my personal experience that sometime just for CSS change you've to compile whole code.

- You can't access localhost website running in eclipse from other machine. You need to compile and create war and have to up in server. [In JSP, Servlet, Struts, etc... you can access localhost website running in eclipse from other system directly. Not required to compile and up it in server]

- You can't use all java package at client level. Check link to see which class supported by Google Web Toolkit http://www.gwtproject.org/doc/latest/RefJreEmulation.html#Package_java_io

- In some case GWT store cache in browser and website stops working and throws unexpected errors. You need to clean history of browser to let it work.

- To use some library you have to configure tons of thing in it. To use simple JSON library you have to waste more than 2-3 hours. Sometime works and sometime compilation error for just JSON. So you can imagine how hard to use external libraries.

- Last but not least. You can't use jQuery directly.


Conclusion
I would recommend not to use Google Web Toolkit at all. Even Google is not using GWT for their wide range of products. You may find very rare companies working on GWT.

@Developer: Don't do Job or Work for GWT.
@Manager, @Company: Just throw GWT and start working on other technologies. That may save your time and can work on other features for your product.

gwtupload custom package with example/sample application

Uploading file(s) on the server is always important part of any web application. Today we are talking about uploading file(s) in GWT application along with the progress bar. Before we begin lets have look at the source of this plugin.


gwtupload
Its originally coded by "Manolo Carrasco". I made few changes regarding maximum upload size in original source code. The plugin works fine but when you want dynamic upload size for your each uploader. This facility not provided in current version. By using my custom gwtupload plugin you'll have that flexibility.

Prerequisites (Available in sample application)
1. gwtupload-custom.jar
2. commons-fileupload-1.2.2.jar
3. commons-io-2.3.jar
4. log4j-1.2.15.jar

I attached sample project at the end of the article. Lets have look at the important snippet of code...

GwtuploadSample.java
package com.javaquery.client;

import gwtupload.client.IFileInput.FileInputType;
import gwtupload.client.IUploadStatus.Status;
import gwtupload.client.IUploader;
import gwtupload.client.IUploader.OnChangeUploaderHandler;
import gwtupload.client.IUploader.OnFinishUploaderHandler;
import gwtupload.client.IUploader.OnStartUploaderHandler;
import gwtupload.client.MultiUploader;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define onModuleLoad().
 */
public class GwtuploadSample implements EntryPoint {
 /**
  * This is the entry point method.
  */
 public void onModuleLoad() {
  final Label responseLabel = new Label();
  
  MultiUploader multiUploader = new MultiUploader(FileInputType.BUTTON);
  multiUploader.setAutoSubmit(true);
  multiUploader.setEnabled(true);
  multiUploader.avoidRepeatFiles(false);
  multiUploader.addOnChangeUploadHandler(new OnChangeUploaderHandler() {
   @Override
   public void onChange(IUploader uploader) {
    if(uploader.getStatus() == Status.CHANGED){
     System.out.println("File input changed, can be handled before upload begin");
     /**
      * If you want to validate something at your side before upload.  
      * Check it here and you can cancel uploading.
      * Uncomment below line if you need it.
      * /
      
     /* uploader.cancel(); */
    }
   }
  });
  multiUploader.addOnStartUploadHandler(new OnStartUploaderHandler() {
   @Override
   public void onStart(IUploader uploader) {
    /**
     * This is where you can pass the hidden value to servlet.
     */
    uploader.add(new Hidden("param1", "value"));
    uploader.add(new Hidden("param2", "value"));
   }
  });
  multiUploader.addOnFinishUploadHandler(new OnFinishUploaderHandler() {
   @Override
   public void onFinish(IUploader uploader) {
    /**
     * Before processing output check the status of upload.
     */
    if(uploader.getStatus() == Status.SUCCESS){
     /**
      * If you passed details in JSONObject. You have to use subtring function of String to get your JSON String.
      */
     System.out.println(uploader.getServerResponse());
     responseLabel.setText(uploader.getServerRawResponse());
    }else{
     System.out.println(uploader.getStatus());
    }
   }
  });  
  //10485760 = 10 MB x 1024 x 1024
  multiUploader.setServletPath(GWT.getModuleBaseURL()+"upServlet?maxUpload=10485760");
  
  // Add the nameField and sendButton to the RootPanel
  // Use RootPanel.get() to get the entire body element
  RootPanel.get("MultiUpload").add(multiUploader);
  RootPanel.get("infoLabel").add(responseLabel);
 }
}

uploadServlet.java
package com.javaquery.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;

import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;

public class uploadServlet extends UploadAction{
 private static final long serialVersionUID = -4035393951562844790L;

 @Override
 public String executeAction(HttpServletRequest request, List sessionFiles) throws UploadActionException {
  String response = "";
  for (FileItem item : sessionFiles) {
   if (false == item.isFormField()) {
    String fileNameWithExt = item.getName();
    String fileName = fileNameWithExt.substring(0, fileNameWithExt.lastIndexOf("."));
    String fileExt = fileNameWithExt.substring(fileNameWithExt.lastIndexOf("."), fileNameWithExt.length());
    String uploadDir = getServletContext().getRealPath("/") + "gwtuploadFiles" + File.separatorChar;
    try {
     /**
      * Creating temporary file at "C:\Users\javaQuery\AppData\Local\Temp"
      * File.createTempFile(arg1,arg2)
      * arg1 : prefix you want to set. 
      *      Why "_projectName" used?
      *      - Say if filename length is 2 character then it'll throws error. 
      *        So for safe side we added "_projectName" to ensure that it must be long name.
      * arg2 : postfix you want to set. Whether its and extension or anything you like
      */
     File tempFile = File.createTempFile(fileName+"_projectName", ".bin");
     item.write(tempFile);

     /**
      * Before writing file to server folder you can scan temporary file (with antivirus on server) if you want.
      * Write it to server at your desired location. 
      */
     File createDir = new File(uploadDir);
     if (!createDir.exists()) {
      createDir.mkdir();
     }
     File saveOnserver = new File(uploadDir + File.separatorChar + item.getName());
     /**
      * Copy temporary file to original file.
      */
     FileInputStream inStream = new FileInputStream(tempFile);
     FileOutputStream outStream = new FileOutputStream(saveOnserver);
     byte[] buffer = new byte[1024];
     int length;
     while ((length = inStream.read(buffer)) > 0) {
      outStream.write(buffer, 0, length);
     }
     inStream.close();
     outStream.close();
     
     /**
      * Set response message you want at client side.
      * Say if you want extended details of your upload. Create JSON object, put values in it and pass it as String.
      */
     response += "File saved as " + saveOnserver.getAbsolutePath();
    } catch (Exception e) {
     throw new UploadActionException(e);
    }
   }else{
    /**
     * You can get the other parameter of your request here.
     */
    String hiddenFieldName = item.getFieldName();
    String hiddenFieldValue = item.getString();
    System.out.println("{param: "+hiddenFieldName+"; value: "+hiddenFieldValue+"}");
   }
  }

  // Remove files from session because we have a copy of them
  removeSessionFileItems(request);

  // Send your customized message to the client.
  return response;
 }
}

web.xml
<web-app version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee 
              http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
  <servlet>
    <servlet-name>uploadServlet</servlet-name>
    <servlet-class>com.javaquery.server.uploadServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>uploadServlet</servlet-name>
    <url-pattern>/gwtuploadsample/upServlet</url-pattern>
  </servlet-mapping>
  
  <!-- Default page to serve -->
  <welcome-file-list>
    <welcome-file>GwtuploadSample.html</welcome-file>
  </welcome-file-list>

</web-app>

Now you are good to go for multiple file upload in GWT with progress bar. Don't forget to check official project website. For any queries and latest updates.

Download Sample Application