Sunday, April 3, 2011

download

import java.io.*;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author saravana
*/
public class download extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String path= request.getParameter("path");
String filename = request.getParameter("file");
//PrintWriter out = response.getWriter();
System.out.println("inside download servlet");
ServletOutputStream myOut= response.getOutputStream();
try {
File f = new File(path+"\\"+filename);


/*if(f.exists())
// System.out.println(f.toString());
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet download</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet download at " + path + "</h1>");
out.println("<h1>Servlet download at " + filename + "</h1>");*/

response.setContentType("application/download");
response.setHeader("Content-Disposition", "attachment; filename= \""+filename+"\"");

FileInputStream fileIn = new FileInputStream(f);

byte[] outputByte = new byte[4096];
while(fileIn.read(outputByte, 0, 4096) != -1){
myOut.write(outputByte, 0, 4096);
}
}catch (IOException ioe){

throw new ServletException(ioe.getMessage( ));

}

finally {
if (myOut != null)
myOut.close( );
if (buf != null)
buf.close( );
}
}
}

resume upload

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException ;

import java.util.List;

import javax.servlet. RequestDispatcher;
import javax.servlet. ServletContext;
import javax.servlet. ServletException ;
import javax.servlet. ServletInputStream;
import javax.servlet. ServletOutputStream;
import javax.servlet. http.HttpServlet ;
import javax.servlet. http.HttpServletRequest;
import javax.servlet. http.HttpServletResponse;

import org.apache.commons. fileupload.FileItem;
import org.apache.commons. fileupload.disk.DiskFileItemFactory;
import org.apache.commons. fileupload.portlet.PortletFileUpload;
import org.apache.commons. fileupload.servlet.ServletFileUpload;
import org.apache.struts. upload.FormFile;

import com.oreilly. servlet.MultipartRequest;
import com.oreilly. servlet.multipart.MultipartParse r;
public class uploadFile extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 6807130476935151822 L;

public void service (HttpServletRequest req, HttpServletResponse res)
throws IOException , ServletException
{

System.out.println( " :in upload File :");


doPost(req,res) ;

}

public void doPost(HttpServletRequest req, HttpServletResponse res)
{
System.out.println( " :in do post upload File :");
String message="";
try{
MultipartRequest mr=new MultipartRequest( req,"c:\\ testUpload" );
// MultipartParser mp=new MultipartParser( );

if (ServletFileUpload. isMultipartConte nt(req)){

ServletFileUpload servletFileUpload = new ServletFileUpload( new
DiskFileItemFactory ());
List fileItemsList = servletFileUpload.parseRequest( req);
for(FileItem fi : fileItemsList)
{ System.out.println( "uploaded file name " + fi.getName() );
byte fileByteData []=fi.get();
ByteArrayOutputStre am baos = new ByteArrayOutputStre am();
System.out.println( "File Name : " +
fi.getName() .substring( fi.getName( ).lastIndexOf( "\\")+1)) ;
FileOutputStream fileOut=new FileOutputStream( "c:\\"+
fi.getName() .substring( fi.getName( ).lastIndexOf( "\\")+1)) ;
byte[] array = fi.get();
for (int cnt = 0; cnt e= req.getParameterNam es();
System.out.println( "Request Parameters : " );
try{

ServletInputStream is= req.getInputStream( );

Object o=req.getParameter( "file");

System.out.println( o.getClass( ).toString( ));



}catch(Exception ex)
{
System.out.println( "EX : " + ex.getMessage( ));


}
while(e.hasMoreElem ents())
{
System.out.println( e.nextElement( ));
}*/

}

}

Friday, April 1, 2011

upload Image in java

image.java
------------
import java.io.*;
import java.util.*;

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

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;

public class image extends HttpServlet {

private static final long serialVersionUID = 1L;

public void destroy() {
super.destroy(); // Just puts "destroy" string in log

}

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
String ename ="";
String empcnumber = "";
String empemailid = "";
String address1 = "";
String address2 = "";
int count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0;
if (!isMultipart) {
System.out.println("File Not Uploaded");
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
FileItem fileItem = null;
String filePath = "D:\\Tomcat 6.0\\webapps\\Upload\\images";
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
fileItem = (FileItem) itr.next();
if (fileItem.isFormField()) {
String name = fileItem.getFieldName();
String value = fileItem.getString();
if (name.equals("empname")) {
ename = value;
count1 = 1;
}
if (name.equals("address1")) {
address1 = value;
count2 = 2;
}
if (name.equals("address2")) {
address2 = value;
count5 = 5;
}
if (name.equals("contactnumber")) {
empcnumber = value;
count3 = 3;
}

if (name.equals("emailid")) {
count4 = 4;
empemailid = value;
}

} else {
try {

File uploadedFile = null;
String myFullFileName = fileItem.getName(), myFileName = "", slashType = (myFullFileName.lastIndexOf("\\") > 0) ? "\\" : "/";
int startIndex = myFullFileName.lastIndexOf(slashType);
myFileName = myFullFileName.substring(startIndex + 1,myFullFileName.length());
uploadedFile = new File(filePath, myFileName);
fileItem.write(uploadedFile);
out.println("");
out.println("");
out.println("
");
out.println("");
out.println("
");
if(count1==1)
out.println("
"); if(count2==2) out.println(" "); if(count5==5) out.println(" "); if(count3==3) out.println(" "); if(count4==4) out.println("
Name:"+ename+"
Addresss:"+address1+"
"+address2+"
Contact No"+empcnumber+"
Email ID"+empemailid+"
");

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

}
}
}
}

public void init() throws ServletException {
// Put your code here
}

}

index.jsp
---------
<html>
 <head><title>Upload page</title></head>
 <body>
 <form action="image" method="post" enctype="multipart/form-data">
   <center>
   <table border="2">
       <tr>
           <td align="right">Employee Name:</td>
           <td ><input type="text" name="empname"></td>
       </tr>
       <tr>
           <td align="right">Employee Address:</td>
           <td ><input type="text" name="address1"></td>
       </tr>
       <tr>
           <td>
           </td>
           <td>
              <input type="text" name="address2">
           </td>
       </tr>
       <tr>
           <td align="right">Contact Number:</td>
           <td ><input type="text" name="contactnumber"></td>
       </tr>
       <tr>
           <td align="right">Employee Email ID:</td>
           <td ><input type="text" name="emailid"></td>
       </tr>
      

       <tr>
           <td align="right">Employee Image </td>
           <td>
               <input name="file" type="file" id="file">
           </td>
       </tr>
      

         <tr>
            <td align="center">
               <input type="submit" name="Submit" value="Submit"/>
               <input type="reset" name="Reset" value="Reset"/>

            </td>
         </tr>
    </table>
    </center>
 </form>
 </body>
 </html>

 download these jar files
------------------------
commons-fileupload-1.2
commons-io-1.3.1
commons-lang-2.1











Monday, March 28, 2011

Select text file data based on length

import java.io.*;
import java.util.*;

public class select {
    public static void main(String[] args) {
        int j=0,i=0,loc=0,col=0;
        String line;int []a=new int[15];
        try {
            FileReader fr = new FileReader("D:\\abc.txt");
            BufferedReader br = new BufferedReader(fr);
            while ((line = br.readLine()) != null) {
                StringTokenizer st2 = new StringTokenizer(line, " ");
                col=0;
                while(st2.hasMoreTokens()){
                    a[j]=st2.nextToken().length();
                    j++;
                    col++;
                }
                i++;
            }
            br.close();
            //First value
            int max1=a[0];
            for(int l=col-3;l<=a.length-1;l=l+3){
                if(max1<a[l]){
                    max1=a[l];
                    loc=l;
                }
            }
            int sp1=loc/col;
            FileReader fr1 = new FileReader("D:\\abc.txt");
            BufferedReader br1 = new BufferedReader(fr1);

            for(int k=0;k<sp1;k++){
                br1.readLine();
            }
            if((line = br1.readLine()) != null) {
                System.out.println(line);
            }
            br1.close();
            //Second value
            int max2=a[1];
            for(int l=col-2;l<=a.length-1;l=l+3){
                if(max2<a[l]){
                    max2=a[l];
                    loc=l;
                }
            }
            int sp2=loc/col;
            FileReader fr2 = new FileReader("D:\\abc.txt");
            BufferedReader br2 = new BufferedReader(fr2);

            for(int k=0;k<sp2;k++){
                br2.readLine();
            }
            if((line = br2.readLine()) != null) {
                System.out.println(line);
            }
            br2.close();
            //Third value
            int max3=a[1];
            for(int l=col-1;l<=a.length-1;l=l+3){
                if(max3<a[l]){
                    max3=a[l];
                    loc=l;
                }
            }
            int sp3=loc/col;
            FileReader fr3 = new FileReader("D:\\abc.txt");
            BufferedReader br3 = new BufferedReader(fr3);

            for(int k=0;k<sp3;k++){
                br3.readLine();
            }
            if((line = br3.readLine()) != null) {
                System.out.println(line);
            }
            br3.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Wednesday, March 16, 2011

sorting in javascript

<html>
<head>
<script>
    function countInputs() {
        var arr=new Array();
        arr[0]=document.frm.data1.value;
        arr[1]=document.frm.data2.value;
        arr[2]=document.frm.data3.value;
        arr[3]=document.frm.data4.value;
        arr.sort();
        document.getElementById('m1').innerHTML=arr[0];
        document.getElementById('m2').innerHTML=arr[1];
        document.getElementById('m3').innerHTML=arr[2];
        document.getElementById('m4').innerHTML=arr[3];


           
    }
</script>
</head>
<body><center>
    <br><br><br><br><br><br>
<form name="frm">
    <input type="text" name="data1"/><br><br>
    <input type="text" name="data2"/><br><br>
    <input type="text" name="data3"/><br><br>
    <input type="text" name="data4"/><br><br>
    <input type="button" value="send"  onclick="countInputs()"/>
</form>
<p id="m1"></p>
<p id="m2"></p>
<p id="m3"></p>
<p id="m4"></p>
</center>
</body>
</html>

Monday, March 7, 2011

Major Differences


Feature Struts 1 Vs Struts 2
Action classes
Ø Struts 1 require Action classes to extend an abstract base class. A common problem in Struts 1 is programming to abstract classes instead of interfaces.
Ø A Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom services. Struts 2 provide a base Action Support class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with a execute signature can be used as an Struts 2 Action object.
Threading Model
Ø Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1 Actions and requires extra care to develop. Action resources must be thread-safe or synchronized.
Ø Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, Servlets containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)
Servlet Dependency
Ø Struts1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked.
Ø Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.
Testability
Ø A major hurdle to testing Struts 1 Actions is that the execute method exposes the Servlet API. A third-party extension, Struts Test Case, offers a set of mock object for Struts 1.
Ø Struts 2 Actions can be tested by instantiating the Action, setting properties, and invoking methods. Dependency Injection support also makes testing simpler.
Harvesting Input
Ø Struts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. DynaBeans can used as an alternative to creating conventional ActionForm classes, but, here too, developers may be red scribing existing JavaBeans.
Ø Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties. The Action properties can be accessed from the web page via the taglibs. Struts 2 also support the ActionForm pattern, as well as POJO form objects and POJO Actions. Rich object types, including business or domain objects, can be used as input/output objects. The ModelDriven feature simplifies taglib references to POJO input objects.
Expression Language
Ø Struts 1 integrate with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support.
Ø Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
Binding values into views
Ø Struts 1 uses the standard JSP mechanism for binding objects into the page context for access.
Ø Struts 2 use a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows reuse of views across a range of types which may have the same property name but different property types.
Type Conversion
Ø Struts 1 ActionForm properties are usually all Strings. Struts 1 uses Commons-Beanutils for type conversion. Converters are per-class, and not configurable per instance.
Ø Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.
Validation
Ø Struts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator. Classes can have different validation contexts for the same class, but cannot chain to validations on sub-objects.
Ø Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.
 Control of Action Execution
Ø Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle.
Ø Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.
Hibernate Vs JDBC
Ø With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema.
Ø Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this. 
Ø With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.  
Ø Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.  
Ø JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task.  
Ø Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.
Ø Application using JDBC to handle persistent data (database tables) having database   specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. 
Ø Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.  
Ø With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.  
Ø Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.
Ø With JDBC, caching is maintained by hand-coding.  
Ø Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.  
Ø In JDBC there is no check that always every user has updated data. This check has to be added by the developer.  
Ø Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.  
Application Server vs Web Server
Ø Application servers and web servers are common terminologies when discussing the World Wide Web. Many of us have already encountered a web server, even though most people do not know it. A web server refers to the software or hardware that is used to serve content, like HTML pages and other media, to end users. This is what your web browser communicates with and gets information from. On the other hand, an application server refers the software or hardware that runs specific applications. These applications do not have a GUI and only supplies data to clients.
Ø Application servers and web servers have many uses and it is not uncommon for a site to have both of these servers. The web server delivers the primary content while the application server runs the applications that provide additional content. Both can exist without the other though. Web servers for simple content do not need application servers. Applications servers that target non web-based networks do not need to have web servers.
Ø Application servers are a lot more flexible than web servers because of the way they are set-up; applications have a lot more resources and freedom in execution. This may open-up the server to certain vulnerabilities that attackers can exploit. The limited things that can be done on a web server make it easier to secure.
Summary:
1. An application server is a platform for running specific applications while a                web server is a platform for delivering content over the internet
2. Application servers are often deployed in support of a web server
3. Application servers are more flexible than web servers
4. Application servers are less secure than web servers
5. An application server and web server can reside in the same machine

What the difference between hibernate and spring

Spring provides hibernate template and it has many advantages like
1) It removes boiler plate code like getting connection from data source try/catch block for closing connection. So that developer can focus on writing business logic rather than writing boiler plate code everywhere.

2) Spring hibernate Template also throws Runtime exception compared to checked exception which allows to remove writing try/catch block in each DAO.

3) It also gives richer template class using which developer can write query code easily. This template class also allows getting session explicitly so if developer wants to get session object and work on it then it's possible.
4) Spring provides support for both hibernate and JDBC. It provides template classes which contains all common code. But JDBC as we all know is not an ORM tool it does not represent rows as objects whereas Hibernate does that

What is the difference between Hibernate and EJB
Ø hibernate is a ORM(object relation mapping ) tool which can be used for creating a mapping between plain java bean objects (POJO) and a persistent storage (rdbms).The EJB 3.0 specification is divided into two parts the first which deals with session and MDBs and the second which deals with persistence and entity beans. The latter part is called JPA(java persistence API ). Hibernate 3.0 implements the JPA specification.EJB 2.1 is a specification for defining loosely coupled reusable business components.
Ø EJB 2.1 and hibernate serve two different purposes. Hibernate can be co related with the entity beans in EJB 2.1.HIbernate offers far more extensive features then plain entity beans. Still there are no containers (application servers) available which fully implement the EJB 3.0 specification. Depending upon the business needs hibernate framework can be used in conjunction with EJB2.1 to achieve the JPA abstraction.

Swing table

import javax.swing.*;
import javax.swing.table.*;
import java.io.File;
import java.util.Date;

public class FileTableDemo {
  public static void main(String[] args) {
    // Figure out what directory to display
    File dir;
    if (args.length > 0) dir = new File(args[0]);
    else dir = new File(System.getProperty("user.home"));

    // Create a TableModel object to represent the contents of the directory
    FileTableModel model = new FileTableModel(dir);

    // Create a JTable and tell it to display our model
    JTable table = new JTable(model);

    // Display it all in a scrolling window and make the window appear
    JFrame frame = new JFrame("FileTableDemo");
    frame.getContentPane().add(new JScrollPane(table), "Center");
    frame.setSize(600, 400);
    frame.setVisible(true);
  }
}
class FileTableModel extends AbstractTableModel {
      protected File dir;
      protected String[] filenames;

      protected String[] columnNames = new String[] {
        "name", "size", "last modified", "directory?", "readable?", "writable?"
      };

      protected Class[] columnClasses = new Class[] {
        String.class, Long.class, Date.class,
          Boolean.class, Boolean.class, Boolean.class
      };

      // This table model works for any one given directory
      public FileTableModel(File dir) {
        this.dir = dir;
        this.filenames = dir.list();  // Store a list of files in the directory
      }

      // These are easy methods
      public int getColumnCount() { return 6; }  // A constant for this model
      public int getRowCount() { return filenames.length; }  // # of files in dir

      // Information about each column
      public String getColumnName(int col) { return columnNames[col]; }
      public Class getColumnClass(int col) { return columnClasses[col]; }

      // The method that must actually return the value of each cell
      public Object getValueAt(int row, int col) {
        File f = new File(dir, filenames[row]);
        switch(col) {
        case 0: return filenames[row];
        case 1: return new Long(f.length());
        case 2: return new Date(f.lastModified());
        case 3: return f.isDirectory() ? Boolean.TRUE : Boolean.FALSE;
        case 4: return f.canRead() ? Boolean.TRUE : Boolean.FALSE;
        case 5: return f.canWrite() ? Boolean.TRUE : Boolean.FALSE;
        default: return null;
        }
      }
    }

Traffic Example in swing

import java.applet.*;
import java.awt.*;

public class Traffic extends Applet implements Runnable {

  
    static int i = 0;
    Thread t1, t2, t3;

    public void paint(Graphics g)
         {
        g.drawOval(50,350,30,30);
        g.drawOval(50,300,30,30);
        g.drawOval(50,250,30,30);
        
                if(i == 0)
        {
                        g.setColor(Color.RED);
                        g.fillOval(50,250,30,30);
                        try{
                        t1.sleep(5000);
                        }catch(Exception e){}
            repaint();
            i=1;
                }   else if(i==1)
        {
                        g.setColor(Color.YELLOW);
            g.fillOval(50,300,30,30);
                        try{
                        t2.sleep(1000);
                        }catch(Exception e){}
            repaint();
            i=2;
                }   else if(i==2)
        {
                        g.setColor(Color.GREEN);
                        g.fillOval(50,350,30,30);
                        try{
                        t3.sleep(4000);
                        }catch(Exception e){}
            repaint();
            i=0;
               }
       
         }

    @Override
    public void run() {
        // TODO Auto-generated method stub
       
    }
}
/*
 * <APPLET CODE="Traffic" height=700 width=500> </APPLET>
 */

Wednesday, February 23, 2011

Generate PDF

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
public class PDFServlet extends HttpServlet {
 public void init(ServletConfig config) throws ServletException {
  super.init(config);
 }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request, response);
 }
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String query = null;
  response.setContentType("application/pdf"); // Code 1
   //PrintWriter pw=response.getWriter();
  Document document = new Document();
  try {
   PdfWriter.getInstance(document, response.getOutputStream()); // Code
                   // 2
   document.open();
   try {
    int rcount = 0;
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection(
      "jdbc:oracle:thin:@localhost:1521", "hr", "tiger");
    query = "SELECT * FROM REGIONS";
    Statement state = conn.createStatement(
      ResultSet.CONCUR_UPDATABLE,
      ResultSet.TYPE_SCROLL_SENSITIVE);
    ResultSet rs = state.executeQuery(query);
    ResultSetMetaData mdata = rs.getMetaData();
    int colcount = mdata.getColumnCount();
    PdfPTable table = new PdfPTable(1);
    while (rs.next()) {
     rcount++;
    }
    rs.beforeFirst();
    rs.next();
    table.addCell(mdata.getColumnName(colcount));
    rs.beforeFirst();
    for (int i = 1; i <= rcount; i++) {
     for (int j = 1; j <= colcount-1; j++) {
    
      table.addCell(rs.getString("region_name"));
     }
    }
    document.add(table);
    document.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  } catch (DocumentException e) {
   e.printStackTrace();
  }
 }
}

Saturday, February 19, 2011

when click a radio button display related text boxes

<html>
<head>
<script language='javascript'>
function display(){   
     if(document.frmRadio.selType[0].checked){
       document.getElementById('div1').style.display = 'block';
       document.getElementById('div2').style.display = 'block' ;
     }
     else{
       document.getElementById('div2').style.display =  'none';
       document.getElementById('div1').style.display = 'block';
     }       
}
</script>
</head>
<body>
<form name='frmRadio'>
<tr><td><input type=radio name='selType' onclick='display()'> Display dropdown & textbox</td></tr>
<tr><td><input type=radio name='selType' onclick='display()'> Display Textbox Only</td></tr>
<tr height='30'><td>&nbsp;</td></tr>
<div id='div1' style=display:none>
<tr>
  <td><input type='text' name='txtName'></td>
</tr>
</div>
<div id='div2' style=display:none>
<tr>
  <td>
      <select name='selOption'>
         <option value='A'>A</option>
         <option value='B'>B</option>
      </select>
  </td>
</tr>
</div>
</form>
</body>
</html>

Wednesday, February 16, 2011

bat file of project

start firefox "http://localhost:9090/nani/query.html"

Tuesday, February 15, 2011

Swing table with file data

import java.awt.Color;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class InsertFileDataToJTable extends AbstractTableModel {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    Vector<String> data;
    Vector<String> columns;
    int i = 1;

    public InsertFileDataToJTable() {
        String line;
        data = new Vector<String>();
        columns = new Vector<String>();
        try {
            FileReader fr1 = new FileReader("D:\\abc.txt");
            BufferedReader br = new BufferedReader(fr1);
            StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
            /*while (st1.hasMoreTokens())
                columns.addElement(st1.nextToken());*/
            int f = 4,l=f+4;
            while (i < f) {
                br.readLine();
                i++;
            }
            while (f <= l) {
                if ((line = br.readLine()) != null) {
                    StringTokenizer st2 = new StringTokenizer(line, " ");
                    while (st2.hasMoreTokens())
                        data.addElement(st2.nextToken());
                    f++;
                }
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    protected String[] columnNames = new String[] {"ID", "NAME", "ADD"};
    public int getRowCount() {
        return data.size() / getColumnCount();
    }
    public String getColumnName(int col) { return columnNames[col]; }
    public int getColumnCount() {
        return columns.size();
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        String name=(String) data.elementAt((rowIndex * getColumnCount())
                + columnIndex);
        return name;
    }

    public static void main(String s[]) {
        InsertFileDataToJTable model = new InsertFileDataToJTable();
        JTable table = new JTable();
        table.setModel(model);
        table.setBackground(Color.orange);
        JScrollPane scrollpane = new JScrollPane(table);
        JPanel panel = new JPanel();
        panel.add(scrollpane);
        JFrame frame = new JFrame();
        frame.add(panel, "Center");
        frame.pack();
        frame.setVisible(true);
      
    }
}

Saturday, December 25, 2010

Mahesh Babu Photos



















Friday, December 24, 2010

how to retrive table data in struts

Action class:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class tableAction extends Action {
   
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        try{
            tableForm data = (tableForm) form;
            String s[]=null;
            String uname=data.getUsername();
            String pas=data.getPassword();
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","tiger");
            PreparedStatement ps1=con.prepareStatement("insert into stdval values(?,?)");
            ps1.setString(1,uname);
            ps1.setString(2,pas);
            int i=ps1.executeUpdate();
            if(i==1){
                System.out.println("insert");
            }else{
                System.out.println("fail");
            }
            PreparedStatement ps=con.prepareStatement("select * from stdval");
            ResultSet rs=ps.executeQuery();
            /*ResultSetMetaData rsmd=rs.getMetaData();
            int no=rsmd.getColumnCount();
            for(int count=1;count<=no;count++){
                s[count]=rsmd.getColumnName(count);
            }
            request.setAttribute("count",no);
            request.setAttribute("header",s);*/
            int c=0;
            ArrayList al=new ArrayList();
            while(rs.next()){
                c=1;
                tableForm data1=new tableForm();
                data1.setUsername(rs.getString("use"));
                data1.setPassword(rs.getString("pass"));
                al.add(data1);
            }
            if(c==0){
                return mapping.findForward("fail");
            }else{
                request.setAttribute("res",al);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return mapping.findForward("success");
    }
}
FormBean:
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
import org.apache.struts.action.ActionForm;

/**
 * MyEclipse Struts
 * Creation date: 10-24-2010
 *
 * XDoclet definition:
 * @struts.form name="data"
 */
public class tableForm extends ActionForm {
    /*
     * Generated fields
     */

    /** password property */
    private String password;

    /** username property */
    private String username;

    /*
     * Generated Methods
     */

    /**
     * Returns the password.
     * @return String
     */
    public String getPassword() {
        return password;
    }

    /**
     * Set the password.
     * @param password The password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * Returns the username.
     * @return String
     */
    public String getUsername() {
        return username;
    }

    /**
     * Set the username.
     * @param username The username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }
}
index.jsp:
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@page import="java.util.*"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>

    <head>
       
    </head>
    <body><center>
        <html:form action="/data">
            UserName : <html:text property="username" /><br />
            Password : <html:text property="password" /><br />
            <html:submit />
        </html:form></center>
    </body>

<table border="1" align="center">
    <%
        ArrayList as = (ArrayList) request.getAttribute("res");
       
    %>
    <logic:notEmpty name="res" scope="request">
        <tr bgcolor="red">
            <th>UserName</th>
            <th>Password</th>
        </tr>
        <logic:iterate id="id1" collection="<%=as%>">
            <tr>
                <td><center><bean:write name="id1" property="username"/></center></td>
                <td><center><bean:write name="id1" property="password"/></center></td>
            </tr>
        </logic:iterate>
    </logic:notEmpty>

</table>
failure.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'fail.jsp' starting page</title>
   
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
 
  <body>
    This is my JSP page. <br>
  </body>
</html>