Monday, March 28, 2011

Select text file data based on length

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, " ");
            //First value
            int max1=a[0];
            for(int l=col-3;l<=a.length-1;l=l+3){
            int sp1=loc/col;
            FileReader fr1 = new FileReader("D:\\abc.txt");
            BufferedReader br1 = new BufferedReader(fr1);

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

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

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



Wednesday, March 16, 2011

sorting in javascript

    function countInputs() {
        var arr=new Array();

<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()"/>
<p id="m1"></p>
<p id="m2"></p>
<p id="m3"></p>
<p id="m4"></p>

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.
Ø 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.
Ø 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.
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.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);
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)
                if(i == 0)
                        }catch(Exception e){}
                }   else if(i==1)
                        }catch(Exception e){}
                }   else if(i==2)
                        }catch(Exception e){}

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