Thursday, 12 January 2012

GWT calling Flex and Flex calling GWT


Can GWT and Flex speak together?
Yes,  Flex can communicate with GWT client side very well, as they both can speak the same language (JavaScript).
How?
It is very easy, GWT can call Flex methods through native functions, and Flex can call GWT methods through external interface
Hello World example (as usual) ,
GWT calling Flex Methods:
1. Initialize Flex application (Flexy):
In “creationComplete” event add this line of code

ExternalInterface.addCallback( “sayHello”, sayHello);
“sayHello” is the java script function to call from outside flex.
sayHello is the flex function to call when someone call sayHello from outside .
2.  Create sayHello Flex function :

Function void sayHello(hello:String):void {
Alert.show(hello);
}

then compile and add Flexy.swf file in the public folder of GWT project.
3. Add SWF file to GWT Panel:
Create new panel inside your application to hold the swf file “Flexy.swf”,

Panel  swfHolder = new Panel();
swfHolder.setWidth(400);
swfHolder.setHeight(400);
swfHolder.setHtml(
"<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'"+
"id='flexy' width='100%' height='100%'"+
"codebase='http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab'>"+
"<param name='movie' value=' Flexy.swf' />"+
"<param name='quality' value='high' />"+
"<param name='bgcolor' value='#ffffff' />"+
"<param name='allowScriptAccess' value='sameDomain' />"+
"<embed src=' Flexy.swf' quality='high' bgcolor='#ffffff'"+
"width='100%' height='100%' name='flexy' align='middle'"+
"play='true'"+
"loop='false'"+
"quality='high'"+
"allowScriptAccess='sameDomain'"+
"type='application/x-shockwave-flash'"+
"pluginspage='http://www.adobe.com/go/getflashplayer'>"+
"</embed>"+
"</object>");

4.  GWT call Flex Methods:
In your main java file add a new native method

Private native void helloFlex(String  hello)/*-{
function getFlexApp(appName) {
if (navigator.appName.indexOf ("Microsoft") !=-1) {
return $wnd[appName];
} else {
return $doc[appName];
}
};
getFlexApp('Flexy').sayHello(hello);
}-*/;

Now you can call helloFlex(“hello World”) from GWT client code and it will call the flex function and show the message box inside Flex.
Flex calling GWT functions:
1. Create GWT function:

Private void helloGwt(String hello)
{
MessageBox.alert(hello);
}

2. Publish the method so Flex can call it:
The problem is that GWT converts the java code to java script so all the function names will change
We can override this by creating definition method,

Private native void defHelloGwt(Panel holderPanel)/*-{
$wnd.sayHello = function(hello){
holderPanel.@{your package name}.{class name}::helloGwt(Ljava/lang/String;)(hello);
};
}-*/;

Now we can call sayHello from flex.
3. Flex call GWT method :
From flex app we can use

ExternalInterface.call(“sayHello”,”hello world”);

And a message box in GWT will show with text “hello World” .

Monday, 3 October 2011

Fetch system time using gwt


SYSTEM TIME

package com.client;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import com.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class systemtime implements EntryPoint {
 
 
  private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);

  /**
   * This is the entry point method.
   */
  public void onModuleLoad() {

     
      Date date = new Date();
      int Month = date.getMonth();
      int Day = date.getDate();
      int Year = date.getYear();
      int Hour = date.getHours();
      int min = date.getMinutes();
      int sec = date.getSeconds();
      int tz = date.getTimezoneOffset();
      int UnixTimeStamp = (int) (date.getTime() * .001);

      //get unix time stamp example (seconds)
      Long lTimeStamp = date.getTime(); //time in milleseconds since the epoch
      int iTimeStamp = (int) (lTimeStamp * .001); //(Cast) to Int from Long, Seconds since epoch
      String sTimeStamp = Integer.toString(iTimeStamp); //seconds to string

      //get the gmt date - will show tz offset in string in browser, not eclipse debug window
      String TheDate = date.toString();

      //render date to root panel in gwt
      Label label = new Label(TheDate);
      RootPanel.get().add(label);
     
     
  }
}

Wednesday, 27 July 2011

Creating chemistry toolbar and fetch image

tlbrbtnChemisrty = new ToolbarButton("CHEMISRTY DIAGRAMS\r\n");
       tlbrbtnChemisrty.addListener(new ButtonListenerAdapter() {
            @Override
            public void onClick(com.gwtext.client.widgets.Button button, EventObject e) {
           
                chem=new Toolbar();
               
               
                chem.setAutoWidth(false);
                absolutePanel_1.add(chem, 15, 132);
               
                chem.setSize("850px", "35px");
               
               
               

            
               

                 textBoxchem = new TextBox();
                    absolutePanel.add(textBoxchem, 74, 128);
                 periodic=new ToolbarButton();
               
                 periodic.setText("View Periodic Table");
                 periodic.setTooltip("Periodic Table");
                 periodic.setCls("a");
                 periodic.setToggleGroup("");
                 periodic.setIcon("");
                    chem.addButton(periodic);
                    periodic.setSize("34px", "35px");
                    periodic.addListener(new ButtonListenerAdapter() {
                        @Override
                        public void onClick(com.gwtext.client.widgets.Button button, EventObject e) {
                       
                             funperiodic();
                           
                           
                       
                        }
                    });


                    insertimage=new ToolbarButton();
                    insertimage.setText("Insert image");
                    insertimage.setTooltip("insert image");
                    insertimage.setToggleGroup("");
                    insertimage.setIcon("");

                    chem.addButton(insertimage);
                    insertimage.setCls("italic:hover");
                    insertimage.addListener(new ButtonListenerAdapter() {
                        @Override
                        public void onClick(com.gwtext.client.widgets.Button button, EventObject e) {
                       
                       
                            sschem=textBoxchem.getText();
                            System.out.println(sschem);
                           
                       
                           
                         s1chem=richTextArea.getText();
                         fun(sschem);
                       
                                flagchem=true;

                     

                      
                           
                       
                        }
                    });
                   
                   
                   

                    getimage=new ToolbarButton();
                    getimage.setText("Get image");
                    getimage.setTooltip("Get image");
                    getimage.setToggleGroup("");
                    getimage.setIcon("");
                    chem.addButton(getimage);
                    getimage.setCls("under:hover");
               
                   
                   
                    getimage.addListener(new ButtonListenerAdapter() {
                        @Override
                        public void onClick(com.gwtext.client.widgets.Button button, EventObject e) {
                       
                            if(flagchem==true)
                             {


                                 richTextArea.getExtendedFormatter().insertImage("http://localhost:8082/image2.php?name="+sschem+"");
                       
                             }
                           
                           
                       
                        }
                    });

                   
                   
                   
                   
                   
                   
                    panel.add(absolutePanel,84,267);
            }
        });
       
       
       
       
       
       
   
       
       
       
       
       
       
       
       
       
        toolbar.addButton(tlbrbtnChemisrty);
        toolbar.addSeparator();
       
       

Converting Text into array and creating Combined image(Text + image)


            public String path(String text,String id) {
               
               
                String query;


                BufferedImage image;
                OutputStream targetFile1;
                //Image image1;
                byte[] buf=new byte[1024];


                byte[] fileBytes;
                ResultSet rs;
                int i;
                char a[]=text.toCharArray(); 
                int t= text.length();
                System.out.println("i is"+t);
                float x=t/40;
                double value=Math.ceil(x);
                int val=(int)value;
                String [] str=new String[val+1];
                int len=0;
                int k=0,j;
                char [] temp={' '};
                StringBuffer strbuf;
               
               
               
                for( i=1;i<=val;i++)
                {
                    //System.out.println("print value"+i);
                   for(j=40*(i-1);j<t;j++)
                   {
               
                if(j==40*i)
                {
                    for( k=40*i;k>40*(i-1);k--)
                    {
                       
                       
                       
                        if(a[k]==(char)(32))
                        {
                           
                            //System.out.println("k is"+k);
                           
                            break;
                        }
                    }
                    //System.out.println("len  is........"+len);
                    strbuf =new StringBuffer();
                    for(int l=len;l<k;l++)
                    {
                       


                        //System.out.println("print"+a[l]);
                       
                       
                          strbuf.append(a[l]);
                         
                       
                    }
                    //System.out.println("a39 is..."+a[39]);
                    //System.out.println("a39 is"+a[40]);
                    //System.out.println("print stringbuffer"+strbuf);
                      
                len=k;
               
               
                       String s=new String();
                    s=strbuf.toString();
                       //System.out.println("print karo"+s);
                        str[i-1]=s;
                        //System.out.println(str[i-1]+"check");
                   
                    strbuf=null;
                    break;
                   
               
                }
           
               
               
                   }  
                  
                //System.out.println(j+"welcome to all");
                }
               
               
               strbuf =new StringBuffer();
                System.out.println("what is val-1"+val);
                for(int last=k;last<t;last++)
                {
                    strbuf.append(a[last]);
                    //System.out.print("ye h ........"+a[last]);
                }

                   String s=new String();
                s=strbuf.toString();
                   System.out.println("print karo"+s);
                    str[val]=s;
                   
                    //System.out.println(str[i-1]+"check");
               
                strbuf=null;
               
              
               
                for(int extra=0;extra<=val;extra++)
                {
                    System.out.println("hello ji kya hua "+str[extra]+"\n");
                }
               
                try
                {
                   
                   
                   
                    connect();
                        query = "select image from save1";


                        rs= st.executeQuery(query);
                        if (rs.next())
                       {
                            System.out.println("hello");
                                 fileBytes = rs.getBytes("image");
                                 OutputStream targetFile= 
                                 new FileOutputStream(
                                      "d://flex.JPG");

                                 targetFile.write(fileBytes);
                                 targetFile.close();
                       }       
                      
                }
                catch (Exception e)
                {
                        e.printStackTrace();
                }


        //String totallen=text;


                try
                {

                   
                   
                   
                   

                   
                    BufferedImage imagefinal = ImageIO.read(new File("d://flex.jpg"));
                               
                //    int w = Math.max(image.getWidth(), overlay.getWidth());
                    //int h = Math.max(image.getHeight(), overlay.getHeight());
                   
                    BufferedImage combined = new BufferedImage(500, 800, BufferedImage.TYPE_INT_ARGB);
                   
                   
                    //combined.setRGB(40,30,30);
                   
                   
                    Graphics g = combined.getGraphics();
                   
                    Font font = new Font("Serif", Font.PLAIN, 24);
                       g.setFont(font);
                       g.setColor(Color.black);
                      
                       g.drawImage(imagefinal, 20, 20, null);
                       int faltu=20;
                for(int m=0;m<=val;m++)
                {

                    g.drawString(str[m], 20, 150+m*faltu);

                   
                }
                   
                    //g.drawImage(overlay, 40, 40, null);// Save as

                   ImageIO.write(combined, "PNG", new File("d://final.jpg"));

                   


                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }

               
                         int len1;
                    String query1;
                 
                    PreparedStatement pstmt;
                    try
                  
                    {
                        connect();
                            File file = new File("d://final.jpg");
                            FileInputStream fis = new FileInputStream(file);
                          
                            len1 = (int)file.length();

                            query1 = ("insert into last VALUES(?,?)");
                            pstmt = con.prepareStatement(query1);
                            pstmt.setString(1,id);
                           
                            // Method used to insert a stream of bytes
                            pstmt.setBinaryStream(2, fis, len1);
                            pstmt.executeUpdate();

                    }


                  
                    catch (Exception e)
                    {
                            e.printStackTrace();
                    }
          
                  //sending
              
                 int len1;
                    String query1;
                 
                    PreparedStatement pstmt;
                    try
                  
                    {
                        connect();
                            File file = new File("d://final.jpg");
                            FileInputStream fis = new FileInputStream(file);
                          
                            len1 = (int)file.length();

                            query1 = ("insert into last VALUES(?,?)");
                            pstmt = con.prepareStatement(query1);
                            pstmt.setString(1,id);
                           
                            // Method used to insert a stream of bytes
                            pstmt.setBinaryStream(2, fis, len1);
                            pstmt.executeUpdate();

                    }


                  
                    catch (Exception e)
                    {
                            e.printStackTrace();
                    }
          
              
              
              
              
              
              
              
              
              
              
              
              
              
              
              
              
                return null;
              
              
              
            }



 
              
       
               

Monday, 25 July 2011

Open file selection dialog programatically for hidden UploadItem

package com.client;

import com.shared.FieldVerifier;


public class FileUploadsmart implements EntryPoint {
    //FormPanel formPanel ;
    //TextField textField1;


 
  private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
  VLayout layout;
 
  public void onModuleLoad() {
     
      RootPanel p=RootPanel.get();
    
      VLayout layout = new VLayout();
      layout.setSize("100px", "44px");
    
      final DynamicForm uploadForm = new DynamicForm();      
      uploadForm.setSize("54px", "147px");
      uploadForm.setEncoding(Encoding.MULTIPART);
    
    
     //  UploadItem fileItem = new UploadItem("image");
      
       HTML q =new HTML();
       q.setHTML("<"+"div style='display: block; width: 100px; height: 20px; overflow: hidden;'"+">"
      
                      +  "<"+"button style='width: 110px; height: 30px; position: relative; top: -5px; left: -5px;'"+">"+ "<a href=  'javascript: void(0)'>upload file</a>"+"</button>"
              
              +"<"+"input type='file' id='upload_input' name='upload' style='font-size: 50px; width: 120px; opacity: 0; filter:alpha(opacity: 0); position: relative; top: -40px; left: -20px'"+"/>" +
              
              "</div>" );
     
     
     
     
      uploadForm.setAction(GWT.getModuleBaseURL()+"upload");
   
      IButton uploadButton = new IButton("Attachment");
      uploadButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler()
      {
          @Override
          public void onClick(
                  com.smartgwt.client.widgets.events.ClickEvent event) {
              // TODO Auto-generated method stub
           
              
              uploadForm.submitForm();
          }
      });
      uploadForm.addChild(q);  
  ///uploadForm.setItems(fileItem);

      layout.setMembers(uploadForm, uploadButton);

    
    
    
      RootPanel.get().add(layout, 2, 2);

      
      

       
       
    }
}

Thursday, 21 July 2011

Upload file using widget in gwt ext

CLIENT CODE

 example.java
package com.client;

import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.gwtext.client.widgets.Window;

public class example implements EntryPoint {

    public void onModuleLoad() {
    RootPanel rootPanel = RootPanel.get();
    Button clickMeButton = new Button();
    rootPanel.add(clickMeButton);
    clickMeButton.setText("Click me!");
    clickMeButton.addClickHandler(new ClickHandler(){
    public void onClick(ClickEvent event) {
       
        FileUploadWindow window = new FileUploadWindow();
        window.setVisible(true);
    }
    });
   
    }
    }



FileUploadWindow.java
package com.client;

import com.google.gwt.core.client.GWT;

import com.gwtext.client.core.Connection;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.data.XmlReader;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.Form;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.TextField;
import com.gwtext.client.widgets.form.event.FormListenerAdapter;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Image;

public class FileUploadWindow extends Window {
FormPanel formPanel = new FormPanel();
Grid grid = new Grid(1,1);
public FileUploadWindow() {
super("Photo Upload");
setSize("500px", "400px");
formPanel.setFileUpload(true);
//setup error reader to process from submit response from server
RecordDef errorRecordDef = new RecordDef(new FieldDef[]{
new StringFieldDef("id"),
new StringFieldDef("msg")
});
XmlReader errorReader = new XmlReader("field", errorRecordDef);
errorReader.setSuccess("@success");
formPanel.setErrorReader(errorReader);

final TextField textField = new TextField("Photo", "file");
textField.setInputType("file");
textField.setSize("334px", "28px");
formPanel.add(textField);
this.add(formPanel);
this.addButton(new Button("Submit",new ButtonListenerAdapter() {
public void onClick(Button button, EventObject e) {
MessageBox.confirm("Confirm", "Do you want to submit?",
new MessageBox.ConfirmCallback() {
public void execute(String btnID) {
if (btnID.equals("yes")) {
formPanel.getForm().submit(GWT.getModuleBaseURL()+"upload", null, Connection.POST, "Saving Data...", true);
}
}
});
}
}));
formPanel.addFormListener(new FormListenerAdapter(){
public boolean doBeforeAction(Form form) {return true;}
public void onActionComplete(Form form, int httpStatus, java.lang.String responseText){
Image image = new Image("img/"+responseText);
image.setSize("300px", "300px");
grid.setWidget(0, 0, image);
}
public void onActionFailed(Form form, int httpStatus, java.lang.String responseText){
com.google.gwt.user.client.Window.alert("File upload is failed.");
}
});
this.add(grid);
}

}


SERVER CODE

XmlServlet.java

package com.server;


import java.io.*;

import java.sql.*;
import java.util.*;
import java.text.*;
import java.util.regex.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import org.mortbay.jetty.Response;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;  
import java.sql.*;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.ServletInputStream.*;  
import java.io.PrintWriter;  
 
public class XmlServlet extends HttpServlet {  
 
public void doPost(HttpServletRequest req,HttpServletResponse res)  
{
    File uploadedFile;
 
   
    System.out.print("on server");
try{  
 
Class.forName("com.mysql.jdbc.Driver");  
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/image","root","enggheads"); 

PrintWriter out=res.getWriter();  
 
//out.println("<br>Content type is :: " +contentType);  
//to get the content type information from JSP Request Header  
String contentType = req.getContentType();  
int flag=0;  
FileInputStream fis=null;  
FileOutputStream fileOut=null;  
//here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0  
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))  
{  
DataInputStream in = new DataInputStream(req.getInputStream());  
//we are taking the length of Content type data  
int formDataLength = req.getContentLength();  
byte dataBytes[] = new byte[formDataLength];  
int byteRead = 0;  
int totalBytesRead = 0;  
 
//this loop converting the uploaded file into byte code  
while (totalBytesRead < formDataLength) {  
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);  
totalBytesRead += byteRead;  
}  
 
String file = new String(dataBytes);  
//for saving the file name  
String saveFile = file.substring(file.indexOf("filename=\"") + 10);  
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));  
out.println("savefiledddd"+saveFile);  
int extension_save=saveFile.lastIndexOf("\"");  
String extension_saveName=saveFile.substring(extension_save);  
 
//Here we are invoking the absolute path out of the encrypted data  
 
saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));  
int lastIndex = contentType.lastIndexOf("=");  
String boundary = contentType.substring(lastIndex + 1,contentType.length());  
int pos;  
 
//extracting the index of file  
pos = file.indexOf("filename=\"");  
pos = file.indexOf("\n", pos) + 1;  
pos = file.indexOf("\n", pos) + 1;  
pos = file.indexOf("\n", pos) + 1;  
int boundaryLocation = file.indexOf(boundary, pos) - 4;  
int startPos = ((file.substring(0, pos)).getBytes()).length;  
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;  
 
out.println("savefile"+saveFile);  
 
int file_No=22; 

 uploadedFile=new File("./war/img");

    uploadedFile.mkdir();


  String kk=uploadedFile.getAbsolutePath();
 

  String pathname_dir=kk+"/"+saveFile;  
   //String pathname_dir="C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\jk\\"+saveFile;  
    File filepath=new File(pathname_dir);  
     out.println("filepath_  "+filepath);  
    fileOut = new FileOutputStream(filepath);  
    fileOut.write(dataBytes, startPos, (endPos - startPos));  
    fileOut.flush();  
    out.println("<h1> your files are saved</h1></body></html>");  
     out.close();  
 
         File database_filename=new File(pathname_dir);  
             fis=new FileInputStream(database_filename);  

int len=(int)database_filename.length();
             PreparedStatement ps = conn.prepareStatement("insert into new (image) values (?)");  
             ps.setBinaryStream(1,fis,len);  
             ps.executeUpdate();  
             ps.close();  
             flag=1;  
 
}  
 
if(flag==1)  
{  
fileOut.close();  
fis.close();  
}  
}catch(Exception e)  
{  
System.out.println("Exception Due to"+e);  
e.printStackTrace();  
}  
}  
}  


Required Four extra Jar File 
1) commons-fileupload-1.1.1
2)commons-io-1.4
3)mysql-connector-java-5.1.7-bin
4)gwtext


 

File Upload using smart gwt

 FileUploadsmart.java
package com.client;

import com.shared.FieldVerifier;
import com.smartgwt.client.types.Encoding;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.HiddenItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.UploadItem;
import com.smartgwt.client.widgets.layout.VLayout;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.LinkItem;


public class FileUploadsmart implements EntryPoint {

  private static final String SERVER_ERROR = "An error occurred while "
      + "attempting to contact the server. Please check your network "
      + "connection and try again.";

 
  private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);

 
  public void onModuleLoad() {
     
     // String url =GWT.getModuleBaseURL()+"upload";
 
 

        VLayout layout = new VLayout();
        layout.setSize("100px", "44px");
       
        final DynamicForm uploadForm = new DynamicForm();       
        uploadForm.setSize("54px", "147px");
        uploadForm.setEncoding(Encoding.MULTIPART);
       
       
          UploadItem fileItem = new UploadItem("image");
       
         // fileItem.setShouldSaveValue(true);
        //  fileItem.setShowDisabled(false);
        //  fileItem.setShowHint(false);
        //  fileItem.setShowTitle(false);
         
          
        uploadForm.setAction(GWT.getModuleBaseURL()+"upload");
        IButton uploadButton = new IButton("Attachment");
        uploadButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler()
        {
            @Override
            public void onClick(
                    com.smartgwt.client.widgets.events.ClickEvent event) {
                // TODO Auto-generated method stub
                uploadForm.submitForm();
            }
        });
           
    uploadForm.setItems(fileItem);
       
        layout.setMembers(uploadForm, uploadButton);

       
       
       
        RootPanel.get().add(layout, 2, 2);
    }
}




Servlet Mapping in web.xml


 <servlet>
   <servlet-name>upload</servlet-name>
   <servlet-class>com.server.FileUploadServlet</servlet-class>
 </servlet>


 <servlet-mapping>
   <servlet-name>upload</servlet-name>
   <url-pattern>/ FileUploadsmart/upload</url-pattern>
 </servlet-mapping>
 








Server
  FileUploadServlet.java

package com.server;


import java.io.*;

import java.sql.*;
import java.util.*;
import java.text.*;
import java.util.regex.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import org.mortbay.jetty.Response;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;  
import java.sql.*;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.ServletInputStream.*;  
import java.io.PrintWriter;  
 
public class FileUploadServlet extends HttpServlet {  
 
public void doPost(HttpServletRequest req,HttpServletResponse res)  
{
    File uploadedFile;
 
   
    System.out.print("on server");
try{  
 
Class.forName("com.mysql.jdbc.Driver");  
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/image","root","enggheads"); 

PrintWriter out=res.getWriter();  
 
//out.println("<br>Content type is :: " +contentType);  
//to get the content type information from JSP Request Header  
String contentType = req.getContentType();  
int flag=0;  
FileInputStream fis=null;  
FileOutputStream fileOut=null;  
//here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0  
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))  
{  
DataInputStream in = new DataInputStream(req.getInputStream());  
//we are taking the length of Content type data  
int formDataLength = req.getContentLength();  
byte dataBytes[] = new byte[formDataLength];  
int byteRead = 0;  
int totalBytesRead = 0;  
 
//this loop converting the uploaded file into byte code  
while (totalBytesRead < formDataLength) {  
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);  
totalBytesRead += byteRead;  
}  
 
res.setContentType("application/octet-stream");
String file = new String(dataBytes);  
//for saving the file name  
String saveFile = file.substring(file.indexOf("filename=\"") + 10);  
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));  
out.println("savefiledddd"+saveFile);  
int extension_save=saveFile.lastIndexOf("\"");  
String extension_saveName=saveFile.substring(extension_save);  
 
//Here we are invoking the absolute path out of the encrypted data  
 
saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));  
int lastIndex = contentType.lastIndexOf("=");  
String boundary = contentType.substring(lastIndex + 1,contentType.length());  
int pos;  
 
//extracting the index of file  
pos = file.indexOf("filename=\"");  
pos = file.indexOf("\n", pos) + 1;  
pos = file.indexOf("\n", pos) + 1;  
pos = file.indexOf("\n", pos) + 1;  
int boundaryLocation = file.indexOf(boundary, pos) - 4;  
int startPos = ((file.substring(0, pos)).getBytes()).length;  
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;  
 
out.println("savefile"+saveFile);  
 
int file_No=22; 

 uploadedFile=new File("./war/img");

    uploadedFile.mkdir();


  String kk=uploadedFile.getAbsolutePath();
 

  String pathname_dir=kk+"/"+saveFile;  
   //String pathname_dir="C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\jk\\"+saveFile;  
    File filepath=new File(pathname_dir);  
     out.println("filepath_  "+filepath);  
    fileOut = new FileOutputStream(filepath);  
    fileOut.write(dataBytes, startPos, (endPos - startPos));  
    fileOut.flush();  
    out.println("<h1> your files are saved</h1></body></html>");  
     out.close();  
 
         File database_filename=new File(pathname_dir);  
             fis=new FileInputStream(database_filename);  

int len=(int)database_filename.length();
             PreparedStatement ps = conn.prepareStatement("insert into new (image) values (?)");  
             ps.setBinaryStream(1,fis,len);  
             ps.executeUpdate();  
             ps.close();  
             flag=1;  
 
}  
 
if(flag==1)  
{  
fileOut.close();  
fis.close();  
}  
}catch(Exception e)  
{  
System.out.println("Exception Due to"+e);  
e.printStackTrace();  
}  
}  
}