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();  
}  
}  
}  
 


Tuesday, 19 July 2011

File download using smart gwt

Smart file upload and download is very easy in comparison of gwt and gwt-ext.

Client side


 Canvas canvas = new Canvas();
            canvas.setSize("355px", "280px");
           
    final DynamicForm uploadForm = new DynamicForm();

    uploadForm.setEncoding(Encoding.MULTIPART);
        UploadItem fileItem = new UploadItem("image");
        TextItem nameItem = new TextItem("imageName");
        TextItem descriptionItem = new TextItem("description");
        HiddenItem spaceImageIdItem = new HiddenItem("spaceImageId");
        HiddenItem propertyIdItem = new HiddenItem("propertyId");
        propertyIdItem.setValue(23);
        spaceImageIdItem.setValue(0);
          
 canvas.addChild(uploadForm);
           uploadForm.moveTo(6, 109);
          
          
           uploadForm.setAction("/XmlServlet1");
           IButton uploadButton = new IButton("Download");
           canvas.addChild(uploadButton);
           uploadButton.moveTo(218, 156);
           uploadButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler(){
              



               @Override
               public void onClick(ClickEvent event) {
                  
                   uploadForm.submitForm();
                  
               }
           });
            layout.addMember(canvas);


Server side code same as gwt ext xml servlet .java file.



xmlServlet1.java
package com.server;



import java.io.*;


import java.sql.*;
import java.util.*;
import java.text.*;
import java.util.regex.*;

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 XmlServlet1 extends HttpServlet {

public void doPost(HttpServletRequest req,HttpServletResponse res)
{
    File uploadedFile;

 
    System.out.print("on server");
try{
  
 // String filename =

    File uploadedFile1=new File("./img/"+"happybir.jpg" );

  


  String kk=uploadedFile1.getAbsolutePath();

  System.out.print(kk);

    File f=new File(kk);

    //System.out.println("foder is " + folder);
    res.setContentType("application/octet-stream");
    res.setHeader("Content-disposition", "attachment;filename=\"" +"happybir.jpg" + "\"");
    //res.setHeader("Content-Disposition","attachment; filename=;");
    ServletOutputStream stream = res.getOutputStream();
    BufferedInputStream fif = new BufferedInputStream(new FileInputStream(f));
    int data;
    while((data = fif.read()) != -1) {
    stream.write(data);
    }
    fif.close();
    stream.close();

}catch(Exception e)
{
System.out.println("Exception Due to"+e);
e.printStackTrace();
}
}
}

Friday, 15 July 2011

Download the image from server side at client side using button in gwt

 


Server Side Code 
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{
   
 // String filename =

    File uploadedFile1=new File("./img/"+"happybir.jpg" );

   


  String kk=uploadedFile1.getAbsolutePath();

  System.out.print(kk);

    File f=new File(kk);
 
    //System.out.println("foder is " + folder);
    res.setContentType("application/octet-stream");
    res.setHeader("Content-disposition", "attachment;filename=\"" +"happybir.jpg" + "\"");
    //res.setHeader("Content-Disposition","attachment; filename=;");
    ServletOutputStream stream = res.getOutputStream();
    BufferedInputStream fif = new BufferedInputStream(new FileInputStream(f));
    int data;
    while((data = fif.read()) != -1) {
    stream.write(data);
    }
    fif.close();
    stream.close();
 
}catch(Exception e) 

System.out.println("Exception Due to"+e); 
e.printStackTrace(); 


}  


Client side


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 FileDownload  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;

public class FileUploadWindow {

    FormPanel formPanel = new FormPanel();





    public FileUploadWindow() {
       
       
    RootPanel r=RootPanel.get();


    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);


    formPanel.add(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()+"XmlServlet", null, Connection.GET, "Saving Data...", false);
    }
    }
    });
    }
    }));
    formPanel.addFormListener(new FormListenerAdapter(){
    public boolean doBeforeAction(Form form) {return true;}
    public void onActionComplete(Form form, int httpStatus, java.lang.String responseText){
       
        System.out.println(responseText);
    Image image = new Image("./img/"+"monica.txt");
    image.setSize("300px", "300px");




    }
    public void onActionFailed(Form form, int httpStatus, java.lang.String responseText){
    com.google.gwt.user.client.Window.alert("File upload is failed.");
    }
    });
    r.add(formPanel);
    formPanel.setSize("100px","100px");

    }

    }


 

Monday, 11 July 2011

Getting Started with SmartGWT

Introduction to SmartGWT

I recently started working with SmartGWT, a framework based on GWT that provides a comprehensive widget library for your application UI as well as assistance for server-side for data management. You can take look at its pretty functionality at the SmartGWT showcase.

 Creating the GWT project

First step is to download the library from the downloads section. The version I will be using for this tutorial is 2.1 (download directly from here). Extract the ZIP file and in the new directory you will find the framework's documentation, some samples, “Hello World” examples and of course the necessary JAR files. Open the JavaDocs in a new browser tab.

Next we create a new “Web Application Project” in Eclipse. Choose the profound name “SmartGWTIntroProject” for the project and the appropriate packaging. Make sure that the “Use Google Web Toolkt” checkbox is checked (Google's App Engine is not needed, so do not select that). The wizard will look something like this:



Adding the SmartGWT library

After the project skeleton is created, browse through your filesystem to the project's location and create a new folder named “lib”. Copy the “smartgwt.jar” file from the extracted ZIP to the newly created folder and refresh the project in Eclipse, so that the new file appears there. Then configure your project's classpath to include the JAR file (Project → Properties → Java Build Path → Add JARs...). Standard stuff so far. The expanded project in Eclipse should look like this:



Then edit the module xml file (named “SmartGWTIntroProject.gwt.xml”) and add the following line after the standard “inherits” declarations:

1<inherits name="com.smartgwt.SmartGwt"/>

The module xml file will be:


01<?xml version="1.0" encoding="UTF-8"?>
02<module rename-to='smartgwtintroproject'>
03<!-- Inherit the core Web Toolkit stuff.                        -->
04<inherits name='com.google.gwt.user.User'/>
05 
06<!-- Inherit the default GWT style sheet.  You can change       -->
07<!-- the theme of your GWT application by uncommenting          -->
08<!-- any one of the following lines.                            -->
09<!-- <inherits name='com.google.gwt.user.theme.standard.Standard'/> -->
10<!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
11<!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/>     -->
12 
13<!-- Other module inherits                                      -->
14 
15<inherits name="com.smartgwt.SmartGwt"/>
16 
17<!-- Specify the app entry point class.                         -->
18<entry-point class='com.javacodegeeks.smartgwt.client.client.SmartGWTIntroProject'/>
19 
20<!-- Specify the paths for translatable code                    -->
21<source path='client'/>
22<source path='shared'/>
23 
24</module>

This allows GWT to know that your application will be using the SmartGWT library.

UPDATE: The 'com.google.gwt.user.theme.standard.Standard' declaration should be removed or commented out like above, since it conflicts with certain SmartGWT styles.

After this, locate the main HTML inside the “war” folder. Edit that and add the following line before the compiled module declaration :

1<script>var isomorphicDir="smartgwtintroproject/sc/";</script>

UPDATE: From version 2.2, there is no longer need to define the isomorpihcDir value. Check the Release Notes for Smart GWT 2.2. However, for this tutorial (version 2.1 used) the declaration is needed.

In the same file, scroll down and find the following lines:

1<td id="nameFieldContainer"></td>
2<td id="sendButtonContainer"></td>

Replace those with the following:

1<td id="formContainer"></td>
2<td id="buttonContainer"></td>

Those are the HTML elements that will hold the text item and the button that we will add later.

The full HTML file follows:

01<!doctype html>
02<!-- The DOCTYPE declaration above will set the    -->
03<!-- browser's rendering engine into               -->
04<!-- "Standards Mode". Replacing this declaration  -->
05<!-- with a "Quirks Mode" doctype may lead to some -->
06<!-- differences in layout.                        -->
07 
08<html>
09<head>
10<meta http-equiv="content-type" content="text/html; charset=UTF-8">
11 
12<!--                                                               -->
13<!-- Consider inlining CSS to reduce the number of requested files -->
14<!--                                                               -->
15<link type="text/css" rel="stylesheet" href="SmartGWTIntroProject.css">
16 
17<!--                                           -->
18<!-- Any title is fine                         -->
19<!--                                           -->
20<title>Web Application Starter Project</title>
21 
22<!--                                           -->
23<!-- This script loads your compiled module.   -->
24<!-- If you add any GWT meta tags, they must   -->
25<!-- be added before this line.                -->
26<!--                                           -->
27<script>var isomorphicDir="smartgwtintroproject/sc/";</script> //add this line in own project
28<script type="text/javascript" language="javascript" src="smartgwtintroproject/smartgwtintroproject.nocache.js"></script>
29</head>
30 
31<!--                                           -->
32<!-- The body can have arbitrary html, or      -->
33<!-- you can leave the body empty if you want  -->
34<!-- to create a completely dynamic UI.        -->
35<!--                                           -->
36<body>
37 
38<!-- OPTIONAL: include this if you want history support -->
39<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
40 
41<!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
42<noscript>
43<div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
44 
45Your web browser must have JavaScript enabled
46in order for this application to display correctly.
47</div>
48 
49</noscript>
50 
51<h1>
52Web Application Starter Project</h1>
53 
54<table align="center">
55<tr>
56<td colspan="2" style="font-weight:bold;">Please enter your name:</td>       
57</tr>
58 
59<tr>
60<td id="formContainer"></td>
61<td id="buttonContainer"></td>
62</tr>
63 
64<tr>
65<td colspan="2" style="color:red;" id="errorLabelContainer"></td>
66</tr>
67 
68</table>
69 
70</body>
71</html> Creating the application entrypoint

When a GWT is created via Eclipse, a lot of auto-generated files are created. One of those is the main Java file in the “client” package, which works as the application's entrypoint. So, remove the generated code and add the following:

01package com.javacodegeeks.smartgwt.client.client;
02 
03import com.google.gwt.core.client.EntryPoint;
04import com.google.gwt.user.client.ui.RootPanel;
05import com.smartgwt.client.util.SC;
06import com.smartgwt.client.widgets.IButton;
07import com.smartgwt.client.widgets.events.ClickEvent;
08import com.smartgwt.client.widgets.events.ClickHandler;
09import com.smartgwt.client.widgets.form.DynamicForm;
10import com.smartgwt.client.widgets.form.fields.TextItem;
11 
12public class SmartGWTIntroProject implements EntryPoint {
13     
14    public void onModuleLoad() {
15         
16        final DynamicForm form = new DynamicForm();
17        final TextItem textItem = new TextItem();
18        textItem.setTitle("Name");
19        form.setFields(textItem);
20        final IButton button = new IButton("Hello");
21         
22        button.addClickHandler(new ClickHandler() {
23            public void onClick(ClickEvent event) {
24                String name = textItem.getValue().toString();
25                SC.say("Hello " + name);
26            }
27        });
28         
29        RootPanel.get("formContainer").add(form);
30        RootPanel.get("buttonContainer").add(button);
31         
32    }
33 
34}

Make sure that the imported packages are as shown above, because SmartGWT uses classes with names same with those of the core GWT framework.

Launching the application
Next, we are ready to launch our application. Choose Run → Run As → Web Application and use your favourite browser to access the provided URL:

http://127.0.0.1:8888/SmartGWTIntroProject.html?gwt.codesvr=127.0.0.1:9997

You should be able to see the following:



That's it. Now you are ready to create some cool applications, powered by SmartGWT.