Sunday, June 19, 2016

JavaProgram Collection2


  public void setK(int k) {
    this.k = k;
  }


  // To cluster the whole data

  public void clustering() {
try
{
        System.out.println("Clustering .............."+this.k);
     // initialize the clusters in the cluster list
int q;
int r;
double minDistance=0.0;
       this.clusterlist.clear();
//this.scluster.clear();
for(int l=0;l { ArrayList t = new ArrayList();
          t.add(new Integer(l));
this.clusterlist.add(t);
//this.scluster.add(t);
  }
//System.out.println("initial clusterlist " + this.clusterlist);
//System.in.read();
    int tk1=0;
    int tk2=0;
    double tvalue1,tvalue2;

l1:  while(true)
{
      // h++;
   int h=-1;
 loop:     for (int i = 0; i < this.valuelist.size(); i++)
{
ArrayList temp1 = new ArrayList();
    temp1 = (ArrayList)this.valuelist.get(i);
//System.out.println( "i is "+i+ "   "+temp1);
//System.in.read();
tvalue1 = ((Double) temp1.get(0)).doubleValue();
if (tvalue1 == 99.0 )
continue loop;
       for (int j = 0; j < this.valuelist.size(); j++)
          // computer the Euclidean distance between the tuple and the centroid.
{
  ArrayList temp2 = new ArrayList();
        temp2 = (ArrayList)this.valuelist.get(j);
//System.out.println("j is "+j+ "    "+temp2 );
//System.in.read();
tvalue2 = ((Double)temp2.get(0)).doubleValue();
if ((i!=j) && (tvalue2!=99.0))
{
         //System.out.println("inside j" );
 
          double distance = euDistance(temp1,temp2);
 h++;
// if((i==0) &&(j==0))
if(h ==0)
minDistance = distance;
else
          if (distance >= minDistance)
{
           minDistance = distance;
   tk1 = i;
   tk2 = j;
            //System.out.println("mindist  "+minDistance+" "+tk1+"   "+tk2);
           }
}

 } // for j

      } // for i

//System.out.println("inside do "+tk1+"   "+tk2);

ArrayList temp3 = new ArrayList();
ArrayList temp4 = new ArrayList();
         temp3 = (ArrayList)this.valuelist.get(tk1);
temp4 = (ArrayList)this.valuelist.get(tk2);
//System.out.println(temp3);
//System.out.println(temp4);
ArrayList temp5 = new ArrayList();
for(int p=0;p {
double value1 = ( (Double) temp3.get(p)).doubleValue();
double value2 = ( (Double) temp4.get(p)).doubleValue();
if ( value1 < value2 )
temp5.add(new Double(value1));
else
temp5.add(new Double(value2));
        }
//System.out.println(temp5);
this.valuelist.set(tk1,temp5);
      //System.out.println(this.valuelist.get(tk1));
//this.valuelist.remove(tk2);
ArrayList temp6 = new ArrayList();
        temp6.add(new Double(99.0));
this.valuelist.set(tk2,temp6);
//System.out.println(this.valuelist.size());

//System.out.println(this.clusterlist.size());
//System.out.println("h is " + h);

// To merge clusters

int y1=0;
int y2=0;
int f1=0;
int f2= 0;

 for (int x=0;x   {
   ArrayList cluster = (ArrayList)this.clusterlist.get(x);  
   for(int z= 0; z {
int s = ((Integer)cluster.get(z)).intValue();
if ( s==tk1)
          y1 = x;
         if(s==tk2)
  y2 =x;
 }
    } //for x
//System.out.println("y1 "+y1+ "y2 " + y2);
    ArrayList cluster1 = new ArrayList();
    ArrayList temp7 = (ArrayList)this.clusterlist.get(y1);
//System.out.println("get y1 " +temp7);
int size = temp7.size();
//System.out.println("size is " + size);
   for(int s=0;s     {
        int v1 = ((Integer)temp7.get(s)).intValue();
        //System.out.println(" v1 is " + v1);
        cluster1.add(new Integer(v1));
}
//System.out.println("cluster is  "+cluster1);
     
 temp7 = (ArrayList)this.clusterlist.get(y2);
   for(int y=0;y     {
int v2= ((Integer)temp7.get(y)).intValue();
cluster1.add(new Integer(v2));
}

//System.out.println(cluster1);
        this.clusterlist.set(y1, cluster1);
this.clusterlist.remove(y2);
 q = this.clusterlist.size();
 r = this.k;

//System.out.println("q is  "+q + "  "+r);
if( q == r)
break l1;
}
//System.out.println("cluster nos "+ this.clusterlist.size());
/*ArrayList t1= new ArrayList();
t1= (ArrayList)this.clusterlist.get(0);
System.out.println(t1.size());
ArrayList t2= new ArrayList();
t2= (ArrayList)this.clusterlist.get(1);
System.out.println(t2.size());
ArrayList t3= new ArrayList();
t3= (ArrayList)this.clusterlist.get(2);
System.out.println(t3.size());*/


}
catch(Exception e)
{ }
     
  }


   // Compute the Euclidean Distance between two tuples.
 
  protected double euDistance(ArrayList tuple1, ArrayList tuple2) {
    double sum = 0;
    for (int i = 0; i < tuple1.size(); i++) {
      double value1 = ( (Double) tuple1.get(i)).doubleValue();
      double value2 = ( (Double) tuple2.get(i)).doubleValue();
      sum += Math.pow( (value1 - value2), 2);
    }
    return Math.sqrt(sum);
  }


 
   /**
   * Output the clustering results.
   */
  public boolean output(String filename) {
    try {
      // check if any of the possible output files exists.
      boolean fileExist = false;
System.out.println("clusterlist size " + this.clusterlist.size());
      for (int i = 0; i < this.clusterlist.size(); i++) {
        File outputFile = new File("./" + filename + "_" + (i + 1) + ".rsl");
        if (outputFile.exists()) {
          fileExist = true;
          break;
        }
      }

      if (fileExist) {
        BufferedReader lineReader = new BufferedReader(new InputStreamReader(
            System.in));
        while (true) {
          System.out.print("The filename has existed. Overwrite? (Y/N)");
          String st = lineReader.readLine();
          if (st.equals("Y")) {
            break;
          }
          else if (st.equals("N")) {
            return false;
          }
        }
      } // if

      // Output: 1. Print the centriod and the number of data points in each cluster.
      // 2. Store the actual data points of each cluster in a separate file.
      for (int i = 0; i < this.clusterlist.size(); i++) {
       // ArrayList centroid = (ArrayList)this.centroidlist.get(i);
        ArrayList cluster = (ArrayList)this.clusterlist.get(i);

        // 1. Print the centriod and the number of data points in each cluster.
        int size = cluster.size();
        System.out.println("--------  Cluster " + (i + 1) + " (" + size +
                           " data)  --------");
       // System.out.print("    Centroid: (");
        //for (int j = 0; j < this.attrlist.size(); j++) {
        //  double value = ( (Double) centroid.get(j)).doubleValue();
         // if (j == this.attrlist.size() - 1) {
         //   System.out.println(this.double2string(value, 2) + ")\n"); // last attribute.
         // }
         // else {
         //   System.out.print(this.double2string(value, 2) + ", ");
         // }
       // }

        // 2. Store the actual data points of each cluster in a separate file.
        File outputFile = new File("./" + filename + "_" + (i + 1) + ".rsl");
        BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile, false));
        StringBuffer buf = new StringBuffer();
        for (int m = 0; m < cluster.size(); m++) {
          ArrayList tuple = (ArrayList)this.origvalues.get( ( (Integer) cluster.
              get(m)).intValue());
         System.out.println(tuple);
         
          for (int j = 0; j < this.attrlist.size(); j++) {
            double value = ( (Double) tuple.get(j)).doubleValue();
            if (j == this.attrlist.size()-1 ) {
            buf.append(this.double2string(value, 2) +"\n"); // last attribute.
                   
            }
            else {
              buf.append(this.double2string(value, 2) + ", "); // last attribute.
            }
          }
         
         
         
        }
        writer.write(buf.toString());
        writer.close();
      } // for
    }
    catch (IOException e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }









































  private String double2string(double d, int decimal) {
    String str = Double.toString(d);
    int length = str.indexOf('.') + decimal + 1;
    if (str.length() < length) {
      length = str.length();
    }
    return str.substring(0, length);
  }
}
// Program for complete Clustering

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

public class clinks {
  private File namefile = null;
  private File datafile = null;
  private int k=-1;
  private ArrayList clusterlist = new ArrayList(); // to store the clusters. Each cluster is a list of IDs of the tuples
  private ArrayList attrlist = new ArrayList(); // to store the attributes
  private ArrayList valuelist = new ArrayList(); // to store all the tuples (cases). Each tuple is a list of attrvalues.
  private ArrayList origvalues=new ArrayList();

  public clinks() {
  }

public static void main(String[] args)throws Exception {
    try {
      // load the file specified by filename.
      System.out.print("Enter the input file name: ");
      BufferedReader lineReader = new BufferedReader(new InputStreamReader(
          System.in));
      String fileitemname = lineReader.readLine();
      clinks sl = new clinks();
      if (sl.loadFiles(fileitemname) == false) {
        return;
      }

      // handle the inputted 'K'.
      while (true) {
        System.out.print("Input 'K' (int): ");
        try {
          int k = Integer.parseInt(lineReader.readLine());
sl.setK(k);
         break;
        }
        catch (NumberFormatException ee) {
          System.out.println("Format error! Please input an integer!!!");
        }
      }

      // handle the method of choosing seeds.
 
      sl.clustering();
      String outputFilename = "";
     do {
        System.out.print("Please specify the output filename: ");
        outputFilename = lineReader.readLine();
      }
      while (!sl.output(outputFilename));

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

  //To check filename and load data from file

  public boolean loadFiles(String fileitemname) {
    // validate if the files exist.
    this.namefile = new File("./" + fileitemname + ".names");
    if (!this.namefile.exists()) {
      System.out.println("The file .names doesn't exist!");
      return false;
    }
    this.datafile = new File("./" + fileitemname + ".data");
    if (!this.datafile.exists()) {
      System.out.println("The file .data doesn't exist!");
      return false;
    }

    this.loadName();
    this.loadData();
    return true;
  }

 // Load attr from the '.names' file.
 
 
protected boolean loadName() {
    try {
      BufferedReader reader = new BufferedReader(new FileReader(this.namefile));
      String line = "";
      int ind = 0;
      while ( (line = reader.readLine()) != null) {
        ind = line.indexOf('|');
        if (ind >= 0) {
          line = line.trim().substring(0, ind).trim();
        }
        if (line.equals("")) {
          continue;
        }

        ind = line.indexOf(':');

        if (ind >= 0) {
          // read attribute names into the "attrlist".
          String name = line.substring(0, ind);
          this.attrlist.add(name);
        }
      } // while readLine()

      return true;

    }
    catch (IOException ex) {
      System.out.println("File I/O error. Please verify the .names file");
      return false;
    }
  }

    // Load data from the '.data' file.
 
  protected void loadData() {
    try {
      BufferedReader reader = new BufferedReader(new FileReader(this.datafile));
      String line = "";
      int ind = 0;
      while ( (line = reader.readLine()) != null) {
        // remove the annotation
       // ind = line.indexOf('|');
       // if (ind >= 0) {
         // line = line.trim().substring(0, ind).trim();
       // }
        if (line.equals("")) {
          continue;
        }

        ArrayList tuple = new ArrayList();
        ind = line.indexOf(',');
        while (ind > 0) {
          String attrvalue = line.substring(0, ind);
          tuple.add(new Double(attrvalue));

          line = line.substring(ind + 1).trim();
         
          ind = line.indexOf(',');
        } // while
this.valuelist.add(tuple);
        this.origvalues.add(tuple);

      } // while readLine()
    }
    catch (Exception ex) {
      System.out.println("File I/O error. Please verify the .data file");
      }
  }

  public void setK(int k) {
    this.k = k;
  }


  // To cluster the whole data

  public void clustering() {
try
{
        System.out.println("Clustering .............."+this.k);
     // initialize the clusters in the cluster list
int q;
int r;
double minDistance=0.0;
       this.clusterlist.clear();
//this.scluster.clear();
for(int l=0;l { ArrayList t = new ArrayList();
          t.add(new Integer(l));
this.clusterlist.add(t);
//this.scluster.add(t);
  }
//System.out.println("initial clusterlist " + this.clusterlist);
//System.in.read();
    int tk1=0;
    int tk2=0;
    double tvalue1,tvalue2;

l1:  while(true)
{
      // h++;
   int h=-1;
 loop:     for (int i = 0; i < this.valuelist.size(); i++)
{
ArrayList temp1 = new ArrayList();
    temp1 = (ArrayList)this.valuelist.get(i);
//System.out.println( "i is "+i+ "   "+temp1);
//System.in.read();
tvalue1 = ((Double) temp1.get(0)).doubleValue();
if (tvalue1 == 99.0 )
continue loop;
       for (int j = 0; j < this.valuelist.size(); j++)
          // computer the Euclidean distance between the tuple and the centroid.
{
  ArrayList temp2 = new ArrayList();
        temp2 = (ArrayList)this.valuelist.get(j);
//System.out.println("j is "+j+ "    "+temp2 );
//System.in.read();
tvalue2 = ((Double)temp2.get(0)).doubleValue();
if ((i!=j) && (tvalue2!=99.0))
{
         //System.out.println("inside j" );
 
          double distance = euDistance(temp1,temp2);
 h++;
// if((i==0) &&(j==0))
if(h ==0)
minDistance = distance;
else
          if (distance <= minDistance)
{
           minDistance = distance;
   tk1 = i;
   tk2 = j;
            //System.out.println("mindist  "+minDistance+" "+tk1+"   "+tk2);
           }
}

 } // for j

      } // for i

//System.out.println("inside do "+tk1+"   "+tk2);

ArrayList temp3 = new ArrayList();
ArrayList temp4 = new ArrayList();
         temp3 = (ArrayList)this.valuelist.get(tk1);
temp4 = (ArrayList)this.valuelist.get(tk2);
//System.out.println(temp3);
//System.out.println(temp4);
ArrayList temp5 = new ArrayList();
for(int p=0;p {
double value1 = ( (Double) temp3.get(p)).doubleValue();
double value2 = ( (Double) temp4.get(p)).doubleValue();
if ( value1 < value2 )
temp5.add(new Double(value1));
else
temp5.add(new Double(value2));
        }
//System.out.println(temp5);
this.valuelist.set(tk1,temp5);
      //System.out.println(this.valuelist.get(tk1));
//this.valuelist.remove(tk2);
ArrayList temp6 = new ArrayList();
        temp6.add(new Double(99.0));
this.valuelist.set(tk2,temp6);
//System.out.println(this.valuelist.size());

//System.out.println(this.clusterlist.size());
//System.out.println("h is " + h);

// To merge clusters

int y1=0;
int y2=0;
int f1=0;
int f2= 0;

 for (int x=0;x   {
   ArrayList cluster = (ArrayList)this.clusterlist.get(x);  
   for(int z= 0; z {
int s = ((Integer)cluster.get(z)).intValue();
if ( s==tk1)
          y1 = x;
         if(s==tk2)
  y2 =x;
 }
    } //for x
//System.out.println("y1 "+y1+ "y2 " + y2);
    ArrayList cluster1 = new ArrayList();
    ArrayList temp7 = (ArrayList)this.clusterlist.get(y1);
//System.out.println("get y1 " +temp7);
int size = temp7.size();
//System.out.println("size is " + size);
   for(int s=0;s     {
        int v1 = ((Integer)temp7.get(s)).intValue();
        //System.out.println(" v1 is " + v1);
        cluster1.add(new Integer(v1));
}
//System.out.println("cluster is  "+cluster1);
     
 temp7 = (ArrayList)this.clusterlist.get(y2);
   for(int y=0;y     {
int v2= ((Integer)temp7.get(y)).intValue();
cluster1.add(new Integer(v2));
}

//System.out.println(cluster1);
        this.clusterlist.set(y1, cluster1);
this.clusterlist.remove(y2);
 q = this.clusterlist.size();
 r = this.k;

//System.out.println("q is  "+q + "  "+r);
if( q == r)
break l1;
}
//System.out.println("cluster nos "+ this.clusterlist.size());
/*ArrayList t1= new ArrayList();
t1= (ArrayList)this.clusterlist.get(0);
System.out.println(t1.size());
ArrayList t2= new ArrayList();
t2= (ArrayList)this.clusterlist.get(1);
System.out.println(t2.size());
ArrayList t3= new ArrayList();
t3= (ArrayList)this.clusterlist.get(2);
System.out.println(t3.size());*/


}
catch(Exception e)
{ }
     
  }


   // Compute the Euclidean Distance between two tuples.
 
  protected double euDistance(ArrayList tuple1, ArrayList tuple2) {
    double sum = 0;
    for (int i = 0; i < tuple1.size(); i++) {
      double value1 = ( (Double) tuple1.get(i)).doubleValue();
      double value2 = ( (Double) tuple2.get(i)).doubleValue();
      sum += Math.pow( (value1 - value2), 2);
    }
    return Math.sqrt(sum);
  }














 
   /**
   * Output the clustering results.
   */
  public boolean output(String filename) {
    try {
      // check if any of the possible output files exists.
      boolean fileExist = false;


for (int i=0;i {
 ArrayList temp = (ArrayList)this.clusterlist.get(i);
 for(int j=0;j {
for (int l=0; l {
int v1 = ((Integer)temp.get(j)).intValue();
int v2 = ((Integer)temp.get(l)).intValue();
if ( v1 < v2 )
{
 temp.set(j,new Integer(v2));
 temp.set(l,new Integer(v1));
}
}
}
this.clusterlist.set(i,temp);
         }


     //System.out.println("clusterlist size " + this.clusterlist.size());
      for (int i = 0; i < this.clusterlist.size(); i++) {
        File outputFile = new File("./" + filename + "_" + (i + 1) + ".rsl");
        if (outputFile.exists()) {
          fileExist = true;
          break;
        }
      }

      if (fileExist) {
        BufferedReader lineReader = new BufferedReader(new InputStreamReader(
            System.in));
        while (true) {
          System.out.print("The filename has existed. Overwrite? (Y/N)");
          String st = lineReader.readLine();
          if (st.equals("Y")) {
            break;
          }
          else if (st.equals("N")) {
            return false;
          }
        }
      } // if

      // Output: 1. Print the centriod and the number of data points in each cluster.
      // 2. Store the actual data points of each cluster in a separate file.
      for (int i = 0; i < this.clusterlist.size(); i++) {
       // ArrayList centroid = (ArrayList)this.centroidlist.get(i);
        ArrayList cluster = (ArrayList)this.clusterlist.get(i);

        // 1. Print the centriod and the number of data points in each cluster.
        int size = cluster.size();
        //System.out.println("--------  Cluster " + (i + 1) + " (" + size +
                           //" data)  --------");
       // System.out.print("    Centroid: (");
        //for (int j = 0; j < this.attrlist.size(); j++) {
        //  double value = ( (Double) centroid.get(j)).doubleValue();
         // if (j == this.attrlist.size() - 1) {
         //   System.out.println(this.double2string(value, 2) + ")\n"); // last attribute.
         // }
         // else {
         //   System.out.print(this.double2string(value, 2) + ", ");
         // }
       // }

        // 2. Store the actual data points of each cluster in a separate file.
        File outputFile = new File("./" + filename + "_" + (i + 1) + ".rsl");
        BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile, false));
        StringBuffer buf = new StringBuffer();
        for (int m = 0; m < cluster.size(); m++) {
int tupleIndex=((Integer)cluster.get(m)).intValue();
        /*add [index, data1,data2,.....data-n]******/
      buf.append(tupleIndex+", ");

          ArrayList tuple = (ArrayList)this.origvalues.get( ( (Integer) cluster.
              get(m)).intValue());
         System.out.println(tuple);
         
          for (int j = 0; j < this.attrlist.size(); j++) {
            double value = ( (Double) tuple.get(j)).doubleValue();
            if (j == this.attrlist.size()-1 ) {
            buf.append(this.double2string(value, 2) +"\n"); // last attribute.
                   
            }
            else {
              buf.append(this.double2string(value, 2) + ", "); // last attribute.
            }
          }
         
         
         
        }
        writer.write(buf.toString());
        writer.close();
      } // for
    }
    catch (IOException e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }









































  private String double2string(double d, int decimal) {
    String str = Double.toString(d);
    int length = str.indexOf('.') + decimal + 1;
    if (str.length() < length) {
      length = str.length();
    }
    return str.substring(0, length);
  }
} import java.net.Socket;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;

public class clnt
{
public static void main(String args[])
{

Socket sock;                  //  Declare the socket

//  Instantiate the socket using  host name  and port number
try
{
     sock = new Socket("localhost",1024);
}

catch(IOException ioe)
  {
     System.out.println("Error opening socket: " + ioe.getMessage());
     return;
  }

try
 {
     //  Instantiate an output stream tied directly to the socket

     DataOutputStream oStream = new DataOutputStream(sock.getOutputStream());
   
     //  write a string and an int to the output stream, i.e. transmit them to the server

     oStream.writeUTF("Hello!");
     oStream.writeInt(3);
}

catch(IOException ioe)
{
    System.out.println("Write error: " + ioe.getMessage());
}

try
{
     sock.close();
}
catch(IOException ioe)
{
     System.out.println("Close error: " + ioe.getMessage());
}
}
}
/*

- Clock. The name says it all

*/

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

class clock
{
public static void main(String[] args)
{
Date d = new Date();
System.out.println("Date is " + d);


}
}import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ColorDemo extends JFrame implements ActionListener
{
Color c1;
JButton b,b1;
JColorChooser c;
JPanel p1;
ColorDemo()
  {
  b=new JButton("Apply");
  b.addActionListener(this);
  b1=new JButton("ColorChooser");
  b1.addActionListener(this);
  c=new JColorChooser();
  p1=new JPanel();
  Container ct=getContentPane();

  ct.add(b1,BorderLayout.NORTH);
  ct.add(p1,BorderLayout.CENTER);
  ct.add(b,BorderLayout.SOUTH);
  setTitle("Demo");
  setSize(400,400);
  setVisible(true);

  }
  public void actionPerformed(ActionEvent ae)
  {
  if(ae.getSource()==b1)
        {
c1= c.showDialog(this,"ColorDialog",Color.RED);
}
  if(ae.getSource()==b)
  {
  p1.setBackground(c1);
  }

  }
  public static void main(String arg[])
  {
  new ColorDemo();
  }
  }
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* */
public class ColorForm extends Applet implements AdjustmentListener,ActionListener
{
Label l1,l2,l3,l4,l5;
TextField t1,t2,t3;
Button b1;
Scrollbar r,g,b;
int r1,g1,b2;
Panel p1,p2,p3,p4,p5,p6,mp;
Color c;
public void init()
{
l1=new Label("Red");
l2=new Label("Green");
l3=new Label("Blue");
l4=new Label("Preview");
l5=new Label("");
t1=new TextField(5);
t2=new TextField(5);
t3=new TextField(5);
b1=new Button("Apply");
b1.addActionListener(this);
r=new Scrollbar(Scrollbar.HORIZONTAL,0,25,0,275);
r.addAdjustmentListener(this);
g=new Scrollbar(Scrollbar.HORIZONTAL,0,20,0,275);
g.addAdjustmentListener(this);
b=new Scrollbar(Scrollbar.HORIZONTAL,0,20,0,275);
b.addAdjustmentListener(this);
setLayout(null);

l1.setBounds(30,30,40,30);  add(l1);
r.setBounds(140,30,100,30);  add(r);
t1.setBounds(250,30,100,30);  add(t1);


/*p1=new Panel();
p1.add(l1); p1.add(r); p1.add(t1);
p2=new Panel();
p2.add(l2); p2.add(g); p2.add(t2);
p3=new Panel();
p3.add(l3); p3.add(b); p3.add(t3);
p4=new Panel();
p4.add(l4);
p5=new Panel();
p5.add(l5);
p6=new Panel();
p6.add(b1);
mp=new Panel(new GridLayout(6,1));
mp.add(p1);mp.add(p2);mp.add(p3);mp.add(p4);mp.add(p5);mp.add(p6);
add(mp);*/
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
if(ae.getSource()==r)
{
r1=r.getValue();
t1.setText(""+r.getValue());
}
if(ae.getSource()==g)
{
g1=g.getValue();
t2.setText(""+g.getValue());
}
if(ae.getSource()==b)
{
b2=b.getValue();
t3.setText(""+b2);
}
c=new Color(r1,g1,b2);
l5.setBackground(c);
}
public void actionPerformed(ActionEvent ae)
{
setBackground(c);
}
}import java.awt.*;
import java.applet.*;
/* */
public class ColorThread extends Applet implements Runnable
{
Thread th;
Color c;
public void start()
{
th=new Thread(this,"ColorThread");
th.start();
}
public void stop()
{
th=null;
}
public void run()
{
while(true)
{
c=new Color((float)Math.random(),(float)Math.random(),(float)Math.random());
repaint();
try
{
th.sleep(1000);
}
catch(Exception e)
{
System.out.println("Error is"+e);
}
}
}
public void paint(Graphics g)
{
setBackground(c);
try
{
th.sleep(1000);
}
catch(Exception e)
{
System.out.println("Error is"+e);
}
}
}


import java.awt.*;
import java.applet.*;
/* */
public class ColorThread1 extends Applet implements Runnable
{
Thread th;
Color c;
Label l1;
int x,y;
public void init()
{
l1=new Label("Hello Froiends..");
add(l1);
    }
public void start()
{
th=new Thread(this,"ColorThread1");
th.start();
}
public void stop()
{
th=null;
}
public void run()
{
while(true)
{
l1.setLocation(x,y);
if(x>=600)
{
x=50;
}
else
{
 x=x+50;
 }
c=new Color((float)Math.random(),(float)Math.random(),(float)Math.random());
repaint();
try
{
th.sleep(500);
}
catch(Exception e)
{
System.out.println("Error is"+e);
}
}
}
public void paint(Graphics g)
{
setBackground(c);
try
{
th.sleep(1000);
}
catch(Exception e)
{
System.out.println("Error is"+e);
}
}
}


/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package compressionFilters;

import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Implementation of javax.servlet.Filter used to compress
 * the ServletResponse if it is bigger than a threshold.
 *
 * @author Amy Roh
 * @author Dmitri Valdin
 * @version $Revision$, $Date$
 */

public class CompressionFilter implements Filter{

    /**
     * The filter configuration object we are associated with.  If this value
     * is null, this filter instance is not currently configured.
     */
    private FilterConfig config = null;

    /**
     * Minimal reasonable threshold
     */
    private int minThreshold = 128;


    /**
     * The threshold number to compress
     */
    protected int compressionThreshold;

    /**
     * Debug level for this filter
     */
    private int debug = 0;

    /**
     * Place this filter into service.
     *
     * @param filterConfig The filter configuration object
     */

    public void init(FilterConfig filterConfig) {

        config = filterConfig;
        if (filterConfig != null) {
            String value = filterConfig.getInitParameter("debug");
            if (value!=null) {
                debug = Integer.parseInt(value);
            } else {
                debug = 0;
            }
            String str = filterConfig.getInitParameter("compressionThreshold");
            if (str!=null) {
                compressionThreshold = Integer.parseInt(str);
                if (compressionThreshold != 0 && compressionThreshold < minThreshold) {
                    if (debug > 0) {
                        System.out.println("compressionThreshold should be either 0 - no compression or >= " + minThreshold);
                        System.out.println("compressionThreshold set to " + minThreshold);
                    }
                    compressionThreshold = minThreshold;
                }
            } else {
                compressionThreshold = 0;
            }

        } else {
            compressionThreshold = 0;
        }

    }

    /**
    * Take this filter out of service.
    */
    public void destroy() {

        this.config = null;

    }

    /**
     * The doFilter method of the Filter is called by the container
     * each time a request/response pair is passed through the chain due
     * to a client request for a resource at the end of the chain.
     * The FilterChain passed into this method allows the Filter to pass on the
     * request and response to the next entity in the chain.
     * This method first examines the request to check whether the client support
     * compression.
     * It simply just pass the request and response if there is no support for
     * compression.
     * If the compression support is available, it creates a
     * CompressionServletResponseWrapper object which compresses the content and
     * modifies the header if the content length is big enough.
     * It then invokes the next entity in the chain using the FilterChain object
     * (chain.doFilter()),
     **/

    public void doFilter ( ServletRequest request, ServletResponse response,
                        FilterChain chain ) throws IOException, ServletException {

        if (debug > 0) {
            System.out.println("@doFilter");
        }

        if (compressionThreshold == 0) {
            if (debug > 0) {
                System.out.println("doFilter gets called, but compressionTreshold is set to 0 - no compression");
            }
            chain.doFilter(request, response);
            return;
        }

        boolean supportCompression = false;
        if (request instanceof HttpServletRequest) {
            if (debug > 1) {
                System.out.println("requestURI = " + ((HttpServletRequest)request).getRequestURI());
            }

            // Are we allowed to compress ?
            String s = (String) ((HttpServletRequest)request).getParameter("gzip");
            if ("false".equals(s)) {
                if (debug > 0) {
                    System.out.println("got parameter gzip=false --> don't compress, just chain filter");
                }
                chain.doFilter(request, response);
                return;
            }

            Enumeration e =
                ((HttpServletRequest)request).getHeaders("Accept-Encoding");
            while (e.hasMoreElements()) {
                String name = (String)e.nextElement();
                if (name.indexOf("gzip") != -1) {
                    if (debug > 0) {
                        System.out.println("supports compression");
                    }
                    supportCompression = true;
                } else {
                    if (debug > 0) {
                        System.out.println("no support for compresion");
                    }
                }
            }
        }

        if (!supportCompression) {
            if (debug > 0) {
                System.out.println("doFilter gets called wo compression");
            }
            chain.doFilter(request, response);
            return;
        } else {
            if (response instanceof HttpServletResponse) {
                CompressionServletResponseWrapper wrappedResponse =
                    new CompressionServletResponseWrapper((HttpServletResponse)response);
                wrappedResponse.setDebugLevel(debug);
                wrappedResponse.setCompressionThreshold(compressionThreshold);
                if (debug > 0) {
                    System.out.println("doFilter gets called with compression");
                }
                try {
                    chain.doFilter(request, wrappedResponse);
                } finally {
                    wrappedResponse.finishResponse();
                }
                return;
            }
        }
    }

    /**
     * Set filter config
     * This function is equivalent to init. Required by Weblogic 6.1
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
        init(filterConfig);
    }

    /**
     * Return filter config
     * Required by Weblogic 6.1
     */
    public FilterConfig getFilterConfig() {
        return config;
    }

}

/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package compressionFilters;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * Very Simple test servlet to test compression filter
 * @author Amy Roh
 * @version $Revision$, $Date$
 */

public class CompressionFilterTestServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        ServletOutputStream out = response.getOutputStream();
        response.setContentType("text/plain");

        Enumeration e = ((HttpServletRequest)request).getHeaders("Accept-Encoding");
        while (e.hasMoreElements()) {
            String name = (String)e.nextElement();
            out.println(name);
            if (name.indexOf("gzip") != -1) {
                out.println("gzip supported -- able to compress");
            }
            else {
                out.println("gzip not supported");
            }
        }


        out.println("Compression Filter Test Servlet");
        out.close();
    }

}

/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package compressionFilters;

import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;


/**
 * Implementation of ServletOutputStream that works with
 * the CompressionServletResponseWrapper implementation.
 *
 * @author Amy Roh
 * @author Dmitri Valdin
 * @version $Revision$, $Date$
 */

public class CompressionResponseStream
    extends ServletOutputStream {


    // ----------------------------------------------------------- Constructors


    /**
     * Construct a servlet output stream associated with the specified Response.
     *
     * @param response The associated response
     */
    public CompressionResponseStream(HttpServletResponse response) throws IOException{

        super();
        closed = false;
        this.response = response;
        this.output = response.getOutputStream();

    }


    // ----------------------------------------------------- Instance Variables


    /**
     * The threshold number which decides to compress or not.
     * Users can configure in web.xml to set it to fit their needs.
     */
    protected int compressionThreshold = 0;

    /**
     * Debug level
     */
    private int debug = 0;

    /**
     * The buffer through which all of our output bytes are passed.
     */
    protected byte[] buffer = null;

    /**
     * The number of data bytes currently in the buffer.
     */
    protected int bufferCount = 0;

    /**
     * The underlying gzip output stream to which we should write data.
     */
    protected GZIPOutputStream gzipstream = null;

    /**
     * Has this stream been closed?
     */
    protected boolean closed = false;

    /**
     * The content length past which we will not write, or -1 if there is
     * no defined content length.
     */
    protected int length = -1;

    /**
     * The response with which this servlet output stream is associated.
     */
    protected HttpServletResponse response = null;

    /**
     * The underlying servket output stream to which we should write data.
     */
    protected ServletOutputStream output = null;


    // --------------------------------------------------------- Public Methods

    /**
     * Set debug level
     */
    public void setDebugLevel(int debug) {
        this.debug = debug;
    }


    /**
     * Set the compressionThreshold number and create buffer for this size
     */
    protected void setBuffer(int threshold) {
        compressionThreshold = threshold;
        buffer = new byte[compressionThreshold];
        if (debug > 1) {
            System.out.println("buffer is set to "+compressionThreshold);
        }
    }

    /**
     * Close this output stream, causing any buffered data to be flushed and
     * any further output data to throw an IOException.
     */
    public void close() throws IOException {

        if (debug > 1) {
            System.out.println("close() @ CompressionResponseStream");
        }
        if (closed)
            throw new IOException("This output stream has already been closed");

        if (gzipstream != null) {
            flushToGZip();
            gzipstream.close();
            gzipstream = null;
        } else {
            if (bufferCount > 0) {
                if (debug > 2) {
                    System.out.print("output.write(");
                    System.out.write(buffer, 0, bufferCount);
                    System.out.println(")");
                }
                output.write(buffer, 0, bufferCount);
                bufferCount = 0;
            }
        }

        output.close();
        closed = true;

    }


    /**
     * Flush any buffered data for this output stream, which also causes the
     * response to be committed.
     */
    public void flush() throws IOException {

        if (debug > 1) {
            System.out.println("flush() @ CompressionResponseStream");
        }
        if (closed) {
            throw new IOException("Cannot flush a closed output stream");
        }

        if (gzipstream != null) {
            gzipstream.flush();
        }

    }

    public void flushToGZip() throws IOException {

        if (debug > 1) {
            System.out.println("flushToGZip() @ CompressionResponseStream");
        }
        if (bufferCount > 0) {
            if (debug > 1) {
                System.out.println("flushing out to GZipStream, bufferCount = " + bufferCount);
            }
            writeToGZip(buffer, 0, bufferCount);
            bufferCount = 0;
        }

    }

    /**
     * Write the specified byte to our output stream.
     *
     * @param b The byte to be written
     *
     * @exception IOException if an input/output error occurs
     */
    public void write(int b) throws IOException {

        if (debug > 1) {
            System.out.println("write "+b+" in CompressionResponseStream ");
        }
        if (closed)
            throw new IOException("Cannot write to a closed output stream");

        if (bufferCount >= buffer.length) {
            flushToGZip();
        }

        buffer[bufferCount++] = (byte) b;

    }


    /**
     * Write b.length bytes from the specified byte array
     * to our output stream.
     *
     * @param b The byte array to be written
     *
     * @exception IOException if an input/output error occurs
     */
    public void write(byte b[]) throws IOException {

        write(b, 0, b.length);

    }


    /**
     * Write len bytes from the specified byte array, starting
     * at the specified offset, to our output stream.
     *
     * @param b The byte array containing the bytes to be written
     * @param off Zero-relative starting offset of the bytes to be written
     * @param len The number of bytes to be written
     *
     * @exception IOException if an input/output error occurs
     */
    public void write(byte b[], int off, int len) throws IOException {

        if (debug > 1) {
            System.out.println("write, bufferCount = " + bufferCount + " len = " + len + " off = " + off);
        }
        if (debug > 2) {
            System.out.print("write(");
            System.out.write(b, off, len);
            System.out.println(")");
        }

        if (closed)
            throw new IOException("Cannot write to a closed output stream");

        if (len == 0)
            return;

        // Can we write into buffer ?
        if (len <= (buffer.length - bufferCount)) {
            System.arraycopy(b, off, buffer, bufferCount, len);
            bufferCount += len;
            return;
        }

        // There is not enough space in buffer. Flush it ...
        flushToGZip();

        // ... and try again. Note, that bufferCount = 0 here !
        if (len <= (buffer.length - bufferCount)) {
            System.arraycopy(b, off, buffer, bufferCount, len);
            bufferCount += len;
            return;
        }

        // write direct to gzip
        writeToGZip(b, off, len);
    }

    public void writeToGZip(byte b[], int off, int len) throws IOException {

        if (debug > 1) {
            System.out.println("writeToGZip, len = " + len);
        }
        if (debug > 2) {
            System.out.print("writeToGZip(");
            System.out.write(b, off, len);
            System.out.println(")");
        }
        if (gzipstream == null) {
            if (debug > 1) {
                System.out.println("new GZIPOutputStream");
            }
            response.addHeader("Content-Encoding", "gzip");
            gzipstream = new GZIPOutputStream(output);
        }
        gzipstream.write(b, off, len);

    }


    // -------------------------------------------------------- Package Methods


    /**
     * Has this response stream been closed?
     */
    public boolean closed() {

        return (this.closed);

    }

}
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package compressionFilters;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.ServletResponseWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * Implementation of HttpServletResponseWrapper that works with
 * the CompressionServletResponseStream implementation..
 *
 * @author Amy Roh
 * @author Dmitri Valdin
 * @version $Revision$, $Date$
 */

public class CompressionServletResponseWrapper extends HttpServletResponseWrapper {

    // ----------------------------------------------------- Constructor

    /**
     * Calls the parent constructor which creates a ServletResponse adaptor
     * wrapping the given response object.
     */

    public CompressionServletResponseWrapper(HttpServletResponse response) {
        super(response);
        origResponse = response;
        if (debug > 1) {
            System.out.println("CompressionServletResponseWrapper constructor gets called");
        }
    }


    // ----------------------------------------------------- Instance Variables

    /**
     * Original response
     */

    protected HttpServletResponse origResponse = null;

    /**
     * Descriptive information about this Response implementation.
     */

    protected static final String info = "CompressionServletResponseWrapper";

    /**
     * The ServletOutputStream that has been returned by
     * getOutputStream(), if any.
     */

    protected ServletOutputStream stream = null;


    /**
     * The PrintWriter that has been returned by
     * getWriter(), if any.
     */

    protected PrintWriter writer = null;

    /**
     * The threshold number to compress
     */
    protected int threshold = 0;

    /**
     * Debug level
     */
    private int debug = 0;

    /**
     * Content type
     */
    protected String contentType = null;

    // --------------------------------------------------------- Public Methods


    /**
     * Set content type
     */
    public void setContentType(String contentType) {
        if (debug > 1) {
            System.out.println("setContentType to "+contentType);
        }
        this.contentType = contentType;
        origResponse.setContentType(contentType);
    }


    /**
     * Set threshold number
     */
    public void setCompressionThreshold(int threshold) {
        if (debug > 1) {
            System.out.println("setCompressionThreshold to " + threshold);
        }
        this.threshold = threshold;
    }


    /**
     * Set debug level
     */
    public void setDebugLevel(int debug) {
        this.debug = debug;
    }


    /**
     * Create and return a ServletOutputStream to write the content
     * associated with this Response.
     *
     * @exception IOException if an input/output error occurs
     */
    public ServletOutputStream createOutputStream() throws IOException {
        if (debug > 1) {
            System.out.println("createOutputStream gets called");
        }

        CompressionResponseStream stream = new CompressionResponseStream(origResponse);
        stream.setDebugLevel(debug);
        stream.setBuffer(threshold);

        return stream;

    }


    /**
     * Finish a response.
     */
    public void finishResponse() {
        try {
            if (writer != null) {
                writer.close();
            } else {
                if (stream != null)
                    stream.close();
            }
        } catch (IOException e) {
        }
    }


    // ------------------------------------------------ ServletResponse Methods


    /**
     * Flush the buffer and commit this response.
     *
     * @exception IOException if an input/output error occurs
     */
    public void flushBuffer() throws IOException {
        if (debug > 1) {
            System.out.println("flush buffer @ CompressionServletResponseWrapper");
        }
        ((CompressionResponseStream)stream).flush();

    }

    /**
     * Return the servlet output stream associated with this Response.
     *
     * @exception IllegalStateException if getWriter has
     *  already been called for this response
     * @exception IOException if an input/output error occurs
     */
    public ServletOutputStream getOutputStream() throws IOException {

        if (writer != null)
            throw new IllegalStateException("getWriter() has already been called for this response");

        if (stream == null)
            stream = createOutputStream();
        if (debug > 1) {
            System.out.println("stream is set to "+stream+" in getOutputStream");
        }

        return (stream);

    }

    /**
     * Return the writer associated with this Response.
     *
     * @exception IllegalStateException if getOutputStream has
     *  already been called for this response
     * @exception IOException if an input/output error occurs
     */
    public PrintWriter getWriter() throws IOException {

        if (writer != null)
            return (writer);

        if (stream != null)
            throw new IllegalStateException("getOutputStream() has already been called for this response");

        stream = createOutputStream();
        if (debug > 1) {
            System.out.println("stream is set to "+stream+" in getWriter");
        }
        //String charset = getCharsetFromContentType(contentType);
        String charEnc = origResponse.getCharacterEncoding();
        if (debug > 1) {
            System.out.println("character encoding is " + charEnc);
        }
        // HttpServletResponse.getCharacterEncoding() shouldn't return null
        // according the spec, so feel free to remove that "if"
        if (charEnc != null) {
            writer = new PrintWriter(new OutputStreamWriter(stream, charEnc));
        } else {
            writer = new PrintWriter(stream);
        }
       
        return (writer);

    }


    public void setContentLength(int length) {
    }


    /**
     * Returns character from content type. This method was taken from tomcat.
     * @author rajo
     */
    private static String getCharsetFromContentType(String type) {

        if (type == null) {
            return null;
        }
        int semi = type.indexOf(";");
        if (semi == -1) {
            return null;
        }
        String afterSemi = type.substring(semi + 1);
        int charsetLocation = afterSemi.indexOf("charset=");
        if(charsetLocation == -1) {
            return null;
        } else {
            String afterCharset = afterSemi.substring(charsetLocation + 8);
            String encoding = afterCharset.trim();
            return encoding;
        }
    }

}
class ConstructTest
{
int x=2;
ConstructTest()
{
System.out.println("This is Default constructor");
}
ConstructTest(int x1)
{
x=x1;
System.out.println("This is Paraterized consturctor x="+x);
}
void  Square()
{
int s=x*x;
System.out.println("Sqaure of "+x+"is:"+s);
}
public static void main(String arg[])
{
ConstructTest t1=new ConstructTest();
ConstructTest t2=new ConstructTest(10);
t1.Square();
t2.Square();
}
}
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package listeners;


import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;


/**
 * Example listener for context-related application events, which were
 * introduced in the 2.3 version of the Servlet API.  This listener
 * merely documents the occurrence of such events in the application log
 * associated with our servlet context.
 *
 * @author Craig R. McClanahan
 * @version $Revision$ $Date$
 */

public final class ContextListener
    implements ServletContextAttributeListener, ServletContextListener {


    // ----------------------------------------------------- Instance Variables


    /**
     * The servlet context with which we are associated.
     */
    private ServletContext context = null;


    // --------------------------------------------------------- Public Methods


    /**
     * Record the fact that a servlet context attribute was added.
     *
     * @param event The servlet context attribute event
     */
    public void attributeAdded(ServletContextAttributeEvent event) {

log("attributeAdded('" + event.getName() + "', '" +
   event.getValue() + "')");

    }


    /**
     * Record the fact that a servlet context attribute was removed.
     *
     * @param event The servlet context attribute event
     */
    public void attributeRemoved(ServletContextAttributeEvent event) {

log("attributeRemoved('" + event.getName() + "', '" +
   event.getValue() + "')");

    }


    /**
     * Record the fact that a servlet context attribute was replaced.
     *
     * @param event The servlet context attribute event
     */
    public void attributeReplaced(ServletContextAttributeEvent event) {

log("attributeReplaced('" + event.getName() + "', '" +
   event.getValue() + "')");

    }


    /**
     * Record the fact that this web application has been destroyed.
     *
     * @param event The servlet context event
     */
    public void contextDestroyed(ServletContextEvent event) {

log("contextDestroyed()");
this.context = null;

    }


    /**
     * Record the fact that this web application has been initialized.
     *
     * @param event The servlet context event
     */
    public void contextInitialized(ServletContextEvent event) {

this.context = event.getServletContext();
log("contextInitialized()");

    }


    // -------------------------------------------------------- Private Methods


    /**
     * Log a message to the servlet context application log.
     *
     * @param message Message to be logged
     */
    private void log(String message) {

if (context != null)
   context.log("ContextListener: " + message);
else
   System.out.println("ContextListener: " + message);

    }


    /**
     * Log a message and associated exception to the servlet context
     * application log.
     *
     * @param message Message to be logged
     * @param throwable Exception to be logged
     */
    private void log(String message, Throwable throwable) {

if (context != null)
   context.log("ContextListener: " + message, throwable);
else {
   System.out.println("ContextListener: " + message);
   throwable.printStackTrace(System.out);
}

    }


}
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id$
 *
 */

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import util.HTMLFilter;

/**
 * Example servlet showing request headers
 *
 * @author James Duncan Davidson
 */

public class CookieExample extends HttpServlet {

    ResourceBundle rb = ResourceBundle.getBundle("LocalStrings");
   
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        out.println("");
        out.println("");
        out.println("");

        String title = rb.getString("cookies.title");
        out.println("" + title + "");
        out.println("

");        out.println("");

// relative links

        // XXX
        // making these absolute till we work out the
        // addition of a PathInfo issue

        out.println("");
        out.println("                    "width=24 align=right border=0 alt=\"view code\">
");        out.println("");
        out.println("                    "width=24 align=right border=0 alt=\"return\">
");
        out.println("

" + title + "

");

        Cookie[] cookies = request.getCookies();
        if ((cookies != null) && (cookies.length > 0)) {
            out.println(rb.getString("cookies.cookies") + "
");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                out.print("Cookie Name: " + HTMLFilter.filter(cookie.getName())
                          + "
");
                out.println("  Cookie Value: "
                            + HTMLFilter.filter(cookie.getValue())
                            + "

");
            }
        } else {
            out.println(rb.getString("cookies.no-cookies"));
        }

        String cookieName = request.getParameter("cookiename");
        String cookieValue = request.getParameter("cookievalue");
        if (cookieName != null && cookieValue != null) {
            Cookie cookie = new Cookie(cookieName, cookieValue);
            response.addCookie(cookie);
            out.println("");
            out.println(rb.getString("cookies.set") + "
");
            out.print(rb.getString("cookies.name") + "  "
                      + HTMLFilter.filter(cookieName) + "
");
            out.print(rb.getString("cookies.value") + "  "
                      + HTMLFilter.filter(cookieValue));
        }
       
        out.println("");
        out.println(rb.getString("cookies.make-cookie") + "
");
        out.print("
        out.println("CookieExample\" method=POST>");
        out.print(rb.getString("cookies.name") + "  ");
        out.println("
");
        out.print(rb.getString("cookies.value") + "  ");
        out.println("
");
        out.println("
");
           
           
        out.println("
");        out.println("
");    }

    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        doGet(request, response);
    }

}


// Fig. 14.27: WriteRandomFileTest.java
// This program tests class WriteRandomFile.
import java.io.*;
import java.awt.*;
import java.awt.event.*;


public class WriteRandomFileTest
{
   public static void main( String args[] )
   {
      WriteRandomFile application = new WriteRandomFile();
      application.openFile();
      application.addRecords();
      application.closeFile();
   } // end main
} // end class WriteRandomFileTest
class MyException extends Exception
{
   int num=0;
     MyException()
      {
       System.out.println("Default of myexception"+num);
      }
      MyException(int n)
      {
        num=n;
        System.out.println("Parametrized constructor of myexception"+num);
       }
      public String toString()
      {
       return"Sqr is not allowed for -ve no."+num;
      }
 }
     class CustomException
      {
       void Sqr(int num)throws MyException
       {
        if(num<0 p="">         {
          throw new MyException(num);
         }
        else
         {
          int s=num*num;
          System.out.println("Sqr of "+num+" is "+s);
         }
        }
      public static void main(String arg[])
       {
        CustomException ce=new CustomException();
         try{
           ce.Sqr(10);
           ce.Sqr(-9);
           }catch(MyException me)
            {
             System.out.println("Caught inside main"+me);
             me.printStackTrace();
            }
           }
  }
 class DataDemo
{
 public void demo(String msg)
  {
   System.out.println("["+msg);
   try{
   Thread.sleep(2000);
   }catch(Exception e)
     {
      System.out.println("Error is "+e);
      }
   System.out.println("]");
   }
  }

class DataImpl implements Runnable
{
 Thread t;
 DataDemo d;
 String msg;
  DataImpl(DataDemo d,String msg)
  {
   t=new Thread(this);
   t.start();
    this.d=d;
    this.msg=msg;
    }
    public void run()
    {
     d.demo(msg);
     }
   }
   public class WithoutSynch
   {
    public static void main(String arg[])
    {
     DataDemo d=new DataDemo();
     DataImpl obj1=new DataImpl(d,"Hello");
     DataImpl obj2=new DataImpl(d,"Friends");
     DataImpl obj3=new DataImpl(d,"GOODLUCK");
     }
     }class DefaultHandling
{
public static void main(String s[])
{
int a=10;
int b=0;
System.out.println("a="+a+"\n b="+b);
int c=a/b;
System.out.println("result is "+c);
System.out.println("hello ");
}
}class DefaultHandling1
{
public static void main(String s[])
{
try
{
int a=10;
int b=0;
System.out.println("a="+a+"\n b="+b);
int c=a/b;
System.out.println("result is "+c);

}
catch(Exception e)
{
System.out.println("Error is "+e);
e.printStackTrace();
}
System.out.println("hello ");
}
} class DefHand
 {
    public static void main(String arg[])
     {
       try{
        int a=10,b=20;
        System.out.println("Value of a="+a+"and b="+b);
        int c=a/b;
        System.out.println("Result ="+c);
       }catch(Exception ae)
       {
         System.out.println("Error is"+ae);
        }finally
        {
         System.out.println("Hello");
      }
      }
     }
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
import java.awt.*;
public class DisplayAllRecords extends JFrame implements ActionListener
{
JLabel lb1,lb2;
JTextField jtf;
JTextArea jta;
JTable jtab;
JScrollPane jsp;
Vector head,row,data;
JButton b1;
JPanel p1,p2, p3,mp;
Connection con;
Statement st;
ResultSet rs;
ResultSetMetaData rsmd;

public DisplayAllRecords()
{
lb1=new JLabel("Sql Query");
lb2=new JLabel("All Records are");
jtf=new JTextField(80);
jtab=new JTable();
jsp=new JScrollPane(jtab,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
b1=new JButton("Execute");
b1.addActionListener(this);
p1=new JPanel(); p1.add(lb1); p1.add(jtf); p1.add(b1);
p2=new JPanel(); p2.add(lb2);
p3=new JPanel(); p3.add(jsp);
mp=new JPanel(); mp.add(p1);mp.add(p2);mp.add(p3);
getContentPane().add(mp);

setTitle("Display");
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:stud_ash");
       JOptionPane.showMessageDialog(this,"Data Base Connected");
}catch(Exception e)
  {
  System.out.println("Error is"+e);
         }
public Vector getData(String query)
{
try
{
st=con.createStatement();
rs=st.executeQuery();
}catch(Exception e)
  {
  System.out.println("Error is"+e);
         }

}

}
public static void main(String arg[])
{
  new DisplayAllRecords();
}
}
// Demonstrate InetAddress.
import java.net.*;
import java.io.*;

class DNS
{
  public static void main(String args[]) throws IOException
   {
     try
      {
       InetAddress[] SW = InetAddress;
       getAllByName("java.sun.com");
       for(int i=0;i       System.out.println(SW[i]);
      }
     catch(Exception e)
      {
        System.out.println("Error in catch" +e);
      }
  }
}





class DoWhile {
   public static void main(String[] args) {
       
   int b = 9 ;
   System.out.println("Sebelum do");
   do {
    System.out.println("Nilai b : "+b);
    b--;
       } while (b>=10);
    System.out.println("Setelah do");  
  }
}
import java.awt.*;
import java.applet.*;
public class draw extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.green);
g.drawLine(0,20,170,20);
g.setColor(Color.blue);    
g.drawLine(20,0,20,170);
g.setColor(Color.red);    
 
g.fillRect(30,60,60,60);
g.setColor(Color.gray);    
g.drawRoundRect(100,40,60,50,15,15);
g.setColor(Color.orange);    
g.fillRoundRect(30,140,60,40,15,15);
}
}
/*


*/

import java.net.*;
import java.io.*;
public class echo
{
     public static void main(String argv[])
     {
          Socket es=null;
          PrintStream os=null;
          DataInputStream is=null;
          DataInputStream stdin=new DataInputStream(System.in);

          try
          {
               es=new Socket("127.0.0.1",17);
               is=new DataInputStream(es.getInputStream());
               os=new PrintStream(es.getOutputStream());
             
          }
          catch (Exception e)
          {
               System.err.println(e);
           }

           if(es!=null && os!=null && is!=null)
           {
               try
               {
                    String userip;
                    while((userip=stdin.readLine())!=null)
                    {
                         os.println(userip);
                         String serverip =is.readLine();
                         System.out.println("echo: " + serverip);
                    }
                    os.close();
                    is.close();
                    es.close();
              }
              catch(Exception e)
              {
               System.err.println(e);
              }
         }
      }
 }

import java.net.*;
import java.io.*;
public class echoclnt
{
     public static void main(String argv[])
     {
          Socket es=null;
          PrintStream os=null;
          DataInputStream is=null;
          DataInputStream stdin=new DataInputStream(System.in);

          try
          {
               es=new Socket("127.0.0.1",17);
               is=new DataInputStream(es.getInputStream());
               os=new PrintStream(es.getOutputStream());

          }
         catch (Exception e)
          {
               System.err.println(e);
           }
           if(es!=null && os!=null && is!=null)
           {
               try
               {
                    String userip;
                    while((userip=stdin.readLine())!=null)
                    {
                         os.print(userip);
                         String serverip =is.readLine();
                        System.out.println("echo: " + serverip);
                   }
                    os.close();
                    is.close();
                    es.close();
              }
              catch(Exception e)
              {
               System.err.println(e);
              }

             }
   }
 }

import java.io.*;
import java.net.*;
public class echoser
{
     public static void main(String args[])
     {
          ServerSocket ss=null;
          try
          {
               System.out.println("Creating server socket");
               ss=new ServerSocket(17);
               System.out.println("Done");
          }
          catch(Exception e)
          {
               System.out.println(e);
          }
          while(true)
          {
               try
               {
                    System.out.println("Waiting for a connection");
                    Socket s=ss.accept();
                    PrintStream ps=new PrintStream(s.getOutputStream());
                    System.out.println("Passing the quote..");
                    InputStream is=s.getInputStream();
                    int ch;
                    while((ch=is.read())!=-1)
                    {
                         ps.print((char)ch);
                         System.out.print((char)ch);
                    }
                    ps.close();
                    is.close();
                }
                catch(Exception e)
                {
                    System.out.println(e);
                    System.exit(0);
                }
           }
        }
   }

/*

- Explains the use of Enumerators or 'enum'

*/

import java.io.*;

class enumerators
{
public static void main(String[] args)
{
enum size {Small, Medium, Large, XLarge};

size s1 = size.Small;
}
}
//to create a panel

import java.awt.*;
//
public class epanel   extends Frame
 {
 epanel()
 {
  Panel p1=new Panel();
 // Panel p2=new Panel();

  setBackground(new Color(5,5,5));
  p1.setBounds(12,81,50,50);
 // p2.setBounds(162,81,50,50);
  p1.setBackground(new Color(255,255,255));
//  p2.setBackground(new Color(180,0,0));

  add(p1);
 // add(p2);
  setVisible(true);

 }
 public static void main(String [] s)
 {
 epanel e=new epanel();
 }
}
import java.awt.*;
import java.applet.*;

//

public class event extends Applet
 {
  static final int n =4;
  Label lab;
  public void init()
   {
    setLayout(new GridLayout(n,n));
    setFont(new Font("Verdana",Font.BOLD,24));

    for(int i=0;i     {
      for(int j=0;j       {
       int k=i*n+j;
        if(k>0)
         add(new Button("  "+k));
      }
    }

    lab = new Label(" * ", Label.CENTER);
    setFont(new Font("TimesRoman",Font.ITALIC,24));
    add(lab);
  }
 public boolean action(Event e, Object obj)
  {
    if(e.target instanceof Button)
      {
       lab.setText((String) obj);
      }
      return false;
    }
  }
 
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.applet.Applet;
 /*
   

*/ public class event2 extends Applet implements ActionListener
{       String msg =" "; Button b1,b2,b3;
        public void init()
        {
                b1=new Button("ONE");
                b2=new Button("TWO");
                b3=new Button("THREE");
                b1.addActionListener(this);
                b2.addActionListener(this);
                b3.addActionListener(this);
                add(b1); add(b2); add(b3);
        }
        public void actionPerformed(ActionEvent ae)
        {
          String str = ae.getActionCommand();
          if(str.equals("ONE"))
           {
            msg = "You Pressed ONE";
           }
          if(str.equals("TWO"))
           {
            msg = "You Pressed TWO";
           }
          if(str.equals("THREE"))
           {
            msg = "You Pressed THREE";
           }
            repaint();
        }
        public void paint(Graphics g)
        {
                g.setColor(new Color(50,100,200));
                g.drawString(msg,100,100);
        }
}

import java.io.*;
class ex{
public static void main(String args[]) throws IOException
{
int i,j,k;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter two numbers");
i=Integer.parseInt(br.readLine());
j=Integer.parseInt(br.readLine());
k=i+j;
System.out.println ("k" + k);}
}
 
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.applet.Applet;
 /*
 
*/ public class ex9a extends Applet implements Runnable,ActionListener
{       Thread t1; String msg; Button b1,b2,b3,b4; int x=10,y=10;
        public void init()
        {       msg="Hai! Welcome to Applet";
                t1=new Thread(this,"one");
                b1=new Button("Start");
                b2=new Button("Suspend");
                b3=new Button("Resume");
                b4=new Button("Stop");
                b1.addActionListener(this);
                b2.addActionListener(this);
                b3.addActionListener(this);
                b4.addActionListener(this);
                add(b1); add(b2); add(b3); add(b4);
        }
        public void actionPerformed(ActionEvent ae)
        {
          if(ae.getSource()==b1) {  t1.start(); }
          else if(ae.getSource()==b2) { t1.suspend();}
          else if(ae.getSource()==b3){ t1.resume(); }
          else if(ae.getSource()==b4){ t1.stop(); }
        }
        public void run()
        {
         try { while(true) {
                if(x>700) {  x=10; }
                repaint();
                Thread.sleep(1000);                          
              } }
              catch(Exception e) { e.printStackTrace(); }
        }
        public void paint(Graphics g)
        {
                g.setColor(new Color(128,218,97));
                y=250;
                g.drawString(msg,x+=10,y);
        }
}
import java.io.*;

class exam{

public static void main (String args[]) throws IOException
{

BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
String str;
System.out.println ("enter lines of text");
System.out.println ("enter stop to quit");


do{
str=br.readLine();
System.out.println ("u entered" +str);
}while (!str.equals("stop"));
}
}import java.io.*;
import java.util.Scanner;


class examp{

public static void main (String args[]) throws IOException
{

Scanner br = new Scanner (System.in);
String str;
System.out.println ("enter lines of text");
System.out.println ("enter stop to quit");


do{
str=br.next();
System.out.println ("u entered" +str);
}while (!str.equals("stop"));
}
}/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package filters;


import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


/**
 * Example filter that can be attached to either an individual servlet
 * or to a URL pattern.  This filter performs the following functions:
 *

     *
  • Attaches itself as a request attribute, under the attribute name

  •  *     defined by the value of the attribute initialization
     *     parameter.
     *
  • Calculates the number of milliseconds required to perform the

  •  *     servlet processing required by this request, including any
     *     subsequently defined filters, and logs the result to the servlet
     *     context log for this application.
     *
     *
     * @author Craig McClanahan
     * @version $Revision$ $Date$
     */

    public final class ExampleFilter implements Filter {


        // ----------------------------------------------------- Instance Variables


        /**
         * The request attribute name under which we store a reference to ourself.
         */
        private String attribute = null;


        /**
         * The filter configuration object we are associated with.  If this value
         * is null, this filter instance is not currently configured.
         */
        private FilterConfig filterConfig = null;


        // --------------------------------------------------------- Public Methods


        /**
         * Take this filter out of service.
         */
        public void destroy() {

            this.attribute = null;
            this.filterConfig = null;

        }


        /**
         * Time the processing that is performed by all subsequent filters in the
         * current filter stack, including the ultimately invoked servlet.
         *
         * @param request The servlet request we are processing
         * @param result The servlet response we are creating
         * @param chain The filter chain we are processing
         *
         * @exception IOException if an input/output error occurs
         * @exception ServletException if a servlet error occurs
         */
        public void doFilter(ServletRequest request, ServletResponse response,
                             FilterChain chain)
    throws IOException, ServletException {

    // Store ourselves as a request attribute (if requested)
    if (attribute != null)
       request.setAttribute(attribute, this);

    // Time and log the subsequent processing
    long startTime = System.currentTimeMillis();
            chain.doFilter(request, response);
    long stopTime = System.currentTimeMillis();
    filterConfig.getServletContext().log
       (this.toString() + ": " + (stopTime - startTime) +
        " milliseconds");

        }


        /**
         * Place this filter into service.
         *
         * @param filterConfig The filter configuration object
         */
        public void init(FilterConfig filterConfig) throws ServletException {

    this.filterConfig = filterConfig;
            this.attribute = filterConfig.getInitParameter("attribute");

        }


        /**
         * Return a String representation of this object.
         */
        public String toString() {

    if (filterConfig == null)
       return ("InvokerFilter()");
    StringBuffer sb = new StringBuffer("InvokerFilter(");
    sb.append(filterConfig);
    sb.append(")");
    return (sb.toString());

        }


    }

    import javax.swing.JOptionPane;
    import java.lang.*;

    class Excercise2
    {
    public static void main(String s[])
    {

    String sr=JOptionPane.showInputDialog("enter name");
    JOptionPane.showMessageDialog(null,sr);


    }

    }import javax.swing.JOptionPane;

    public class Exercise1
    {
       
        public static void main(String[] args)
        {
        String name="";
        name=JOptionPane.showInputDialog("Please enter your name ");
        String msg="Hello "+name+" !";
        JOptionPane.showMessageDialog(null,msg);
        }
    }
    import java.io.*;

    public class Exercise10
    {
       
        public static void main(String[] args) throws IOException
        {
        int a,b,c,d,x,y;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter First Number: ");
        a=Integer.parseInt(br.readLine());
        System.out.println("Enter Second Number: ");
        b=Integer.parseInt(br.readLine());
        System.out.println("Enter Number of Sequence: ");
        y=Integer.parseInt(br.readLine());
        System.out.print("The Numbers are: "+a+" "+b);
        x=1;
        while (x<=y)
        {
        c=a+b;
        System.out.print(" "+c);
        a=b;
        b=c;
        x++;
        }
       
        }
    }
    import javax.swing.JOptionPane;
    public class Exercise12
    {
       
        public static void main(String[] args)
        {
        String word;
        word=JOptionPane.showInputDialog("Enter a Word: ");
        StringBuffer Name=new StringBuffer (word);
           System.out.print(Name);
    System.out.print(Name.reverse());
        }
    }
    import javax.swing.JOptionPane;

    public class Exercise2
    {
       
        public static void main(String[] args)
        {
        String word,word1,word2;
        word= JOptionPane.showInputDialog("Input First Word: ");
        word1= JOptionPane.showInputDialog("Input Second Word: ");
        word2= JOptionPane.showInputDialog("Input Third Word: ");
        //JOptionPane.showMessageDialog(null,"Input words are: "+" "+word+" "+word1+" "+word2);
    JOptionPane.showMessageDialog(null,"Input words are: "+word+word1+word2);    
    }
    }
    import javax.swing.JOptionPane;

    public class Exercise6
    {
            public static void main(String[] args)
            {
        double Average;
        double sMath,sJava,sSociology,sHumanities,sPhysics;
        sMath=Double.parseDouble(JOptionPane.showInputDialog("Input Grade for Math "));
        sJava=Double.parseDouble(JOptionPane.showInputDialog("Input Grade for Java "));
        sSociology=Double.parseDouble(JOptionPane.showInputDialog("Input Grade for Sociology "));
        sHumanities=Double.parseDouble(JOptionPane.showInputDialog("Input Grade for Humanities "));
        sPhysics=Double.parseDouble(JOptionPane.showInputDialog("Input Grade for Physics "));
        Average=((sMath+sJava+sSociology+sHumanities+sPhysics)/5);
        JOptionPane.showMessageDialog(null,"The Average is "+Average);
       
        if (Average >= 75.0)
       
        {
        JOptionPane.showMessageDialog(null,"Passed");
        }
        else
        {
        JOptionPane.showMessageDialog(null,"Failed");
        }
            }
    }
    import javax.swing.JOptionPane;

    public class Exercise7
    {
       
        public static void main(String[] args)
        {
        Double Activity,Quiz,Attendance,Assignment,Exam,Grade;
        Activity=Double.parseDouble(JOptionPane.showInputDialog("Enter partial Grade for Activity "));
        Quiz=Double.parseDouble(JOptionPane.showInputDialog("Enter partial Grade for Quiz "));
        Attendance=Double.parseDouble(JOptionPane.showInputDialog("Enter partial Grade for Attendance "));
        Assignment=Double.parseDouble(JOptionPane.showInputDialog("Enter partial Grade for Assignment "));
        Exam=Double.parseDouble(JOptionPane.showInputDialog("Enter partial Grade for Exam "));
        Grade=((Activity*0.15)+(Quiz*0.15)+(Attendance*0.10)+(Assignment*0.10)+(Exam*0.5));
        JOptionPane.showMessageDialog(null,"Your grade for this subject is "+Grade);
        if(Grade >= 75.0)
        {
        JOptionPane.showMessageDialog(null,"Passed");
        }
        else
        {
        JOptionPane.showMessageDialog(null,"Failed");
        }
        }
    }
    import javax.swing.JOptionPane;

    public class Exercise8 {
       
        public static void main(String[] args)
        {
        int num1,num2,choice,result;
        num1=Integer.parseInt(JOptionPane.showInputDialog("Enter First Number"));
        num2=Integer.parseInt(JOptionPane.showInputDialog("Enter Second Number"));
        choice=Integer.parseInt(JOptionPane.showInputDialog("Select Operation:\n1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division"));
       
        if(choice==1)
        {
        result=num1+num2;
        JOptionPane.showMessageDialog(null,"The result is: "+result);
        }
    else if(choice==2)
    {
    result=num1-num2;
    JOptionPane.showMessageDialog(null,"The result is: "+result);
    }  
    else if(choice==3)
    {
    result=num1*num2;
    JOptionPane.showMessageDialog(null,"The result is: "+result);
    }
    else if(choice==4)
    {
    result=num1/num2;
    JOptionPane.showMessageDialog(null,"The result is: "+result);
    }
    else
    {
    JOptionPane.showMessageDialog(null,"Illegal Operation");
    }
        }
    }
    import javax.swing.JOptionPane;

    public class Exercise9
    {
       
        public static void main(String[] args)
        {
        int num1;
        num1=Integer.parseInt(JOptionPane.showInputDialog("Enter number:"));
       
        if(num1==1)
        {
        JOptionPane.showMessageDialog(null,"Red");
        }
        else if(num1==2)
        {
        JOptionPane.showMessageDialog(null,"White");
        }
        else if(num1==3)
        {
        JOptionPane.showMessageDialog(null,"Blue");
        }
        else if(num1==4)
        {
        JOptionPane.showMessageDialog(null,"Orange");
        }
        else if(num1==5)
        {
        JOptionPane.showMessageDialog(null,"Yellow");
        }
        else if(num1==6)
        {
        JOptionPane.showMessageDialog(null,"Green");
        }
        else if(num1==7)
        {
        JOptionPane.showMessageDialog(null,"Brown");
        }
        else if(num1==8)
        {
        JOptionPane.showMessageDialog(null,"Black");
        }
        else if(num1==9)
        {
        JOptionPane.showMessageDialog(null,"Gold");
        }
        else
        {
        JOptionPane.showMessageDialog(null,"Gray");
        }
        }
    }
    import java.util.Scanner;
    import javax.swing.JOptionPane;

    public class ExperimentOne
    {
    public static void main ( String [] x)
    {
    double max = 0;
    Scanner sc= new Scanner (System.in);
    //Scanner num2= new Scanner (System.in);
    //Scanner num3= new Scanner (System.in);
    // Method 1

    int num1= Integer.parseInt (JOptionPane.showInputDialog("Enter num1: "));
    int num2= Integer.parseInt (JOptionPane.showInputDialog("Enter num2: "));
    int num3= Integer.parseInt (JOptionPane.showInputDialog("Enter num3: "));



    //Method 2
    /*
    int num1 = sc.nextInt();
    int num2 = sc.nextInt();
    int num3 = sc.nextInt();
    */
    if (num1 > num2 && num1>num3) max=num1;
    if (num2 > num1 && num2>num3) max=num2;
    if (num3 > num2 && num3>num1) max=num3;

    System.out.println ("The Max. Number is: "+ max);

    }
    }/*

    - This program would calculate the no.s exponent value
    - Eg: 2 cube = 8

    */

    import java.io.*;

    class exponent
    {
    int performExponent(int b, int e)
    {
    int ans = 0;
    int temp = b;

    for(int i=1; i {
    temp = temp*b;
    ans = temp;
    }
    return ans;
    }

    public static void main(String[] args)
    {
    String sbase;
    String sexp;
    int base = 0;
    int exp = 0;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    try
    {
    System.out.print("Enter the base value: ");
    sbase = br.readLine();
    base = Integer.parseInt(sbase);

    System.out.print("Enter the base value: ");
    sexp = br.readLine();
    exp = Integer.parseInt(sexp);
    }
    catch(IOException ioe)
    {
    System.out.println("Error!!!");
    System.exit(1);
    }

    exponent e1 = new exponent();
    int answer = e1.performExponent(base, exp);

    System.out.println(base + "^" + exp + " = " + answer);
    }
    }import java.io.*;
    import java.lang.reflect.*;
    public class exsam
    {
    public static void main(String arg[])
    {
    try
    {
    System.out.println("try");
    Class c=Class.forName("sam");
    Object o=c.newInstance();
    Object obar[]={new String[]{}};
    Class clob[]={obar[0].getClass()};
    Method m=c.getDeclaredMethod("main",clob);
    m.invoke(null,obar);
    }
    catch(Exception e){
    System.out.println(e);
    }
    }
    }/*

    - This program calculates the factorial for a given number.

    */

    import java.io.*;

    class factorial
    {
    int calculateFactorial(int n)
    {
    int ans = 1;

    for(int i=1; i<=n; i++)
    {
    ans = ans*i;
    }
    return ans;
    }

    public static void main(String[] args)
    {
    String number;
    int num = 0;
    int answer = 0;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    System.out.print("Enter the Number: ");

    try
    {
    number = br.readLine();
    num = Integer.parseInt(number);
    }
    catch(IOException ioe)
    {
    System.out.println("Error!!!");
    System.exit(1);
    }

    factorial f = new factorial();
    answer = f.calculateFactorial(num);
    System.out.println(num + "! = " + answer);
    }
    }
    //importing io classes
    import java.io.*;



    class  Fibonacci
    {
    public static void main(String[] args) throws IOException
    {
    DataInputStream in=new DataInputStream(System.in);
    String s;
    int a=1,b=1,c=a+b;
    int n;

    System.out.print("Enter nth value?");
    s=in.readLine();
    n=Integer.parseInt(s);
                    System.out.print(a+","+b);
    while(c<=n)
    {
                            System.out.print(c+",");
    a=b;
    b=c;
    c=a+b;
    }
    }
    }

    //importing io classes
    import java.io.*;


    class  Fibonacci_rec
    {
    public int fibo(int n)
    {
    if (n == 1)
    return 1;
    else if (n == 2)
    return 1;
    else
    return fibo(n-1) + fibo(n-2);
    }
    /*
    This method will do exactly that, it will invoke the two previous versions of itself, and those invoked will invoke their previous selves and so on until one of them reaches f(2) or f(1).
    It's easy to use this method in a loop to print out many Fibonacci numbers:
    */


    public static void main(String[] args)
    {

    Fibonacci_rec f=new Fibonacci_rec();
    for (int i=1; i<10 i="" nbsp="" p=""> System.out.println(f.fibo(i));


    }
    }
    import java.io.*;
    import java.util.*;
    class FileDemo
    {
       public static void main(String arg[])
        {
         File f=new File("xyz.txt");
         System.out.println("File object= "+f);
         System.out.println("File path= "+f.getPath());
         System.out.println("File Absolute path= "+f.getAbsolutePath());
         System.out.println("Contents= "+f.length());
         System.out.println(f.exists() ? "File is in existence": "File not in existence");
         System.out.println(f.canRead() ? "File is readable": "File not readable");
         System.out.println(f.canWrite() ? "File is in writable": "File not writable");
         System.out.println("Parent= "+f.getParent());
         System.out.println("Name= "+f.getName());
         System.out.println("Flie Modi at="+ new Date(f.lastModified()));
        }
       }import java.io.*;
    import java.util.*;
    class FileDemo1
    {
       public static void main(String arg[])
        {
         File f1=new File("c:/ashish/xxx");
         File f2=new File("c:/ram/siva/jj");
         if(f1.mkdirs())
          {
      System.out.println("Path found and Dir Created");
     }
     else
      {
         System.out.println("Dir Exist");
    }
     if(f2.mkdirs())
      {
         System.out.println("Nested Dir are Created");
    }
    else
    {
      System.out.println("Nested Dir Exists");
     }

    }
    }import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    /*
    program compiled by RVS@CSE to open a file dialog box using menu item clicks
    */

    class filedialog extends WindowAdapter implements ActionListener
    {
    Frame f;
         
    public void actionPerformed(ActionEvent e)
    {
    FileDialog fd;
    String s=e.getActionCommand();
    //opening dialog box
    if (s.equals("OPEN"))
    {
           fd=new FileDialog(f,"RVS@Open Dialog",FileDialog.LOAD);
    fd.show();
    }
    else
    if (s.equals("SAVE"))
    {
           fd=new FileDialog(f,"RVS@Save Dialog",FileDialog.SAVE);
    fd.show();
    }

    }

            public void windowClosing(WindowEvent e)
            {
                    Frame f;
                    f=(Frame)e.getSource();
                    f.dispose();
            }
            public filedialog()
            {
                    f=new Frame("Naveen....");
                    Panel p=new Panel();
                    MenuBar m=new MenuBar();
                    Menu file=new Menu("FILE");
                    Menu edit=new Menu("EDIT");
                    Menu view=new Menu("VIEW");
                    Menu tool=new Menu("TOOL");
                    MenuItem New=new MenuItem("NEW");
                    MenuItem open=new MenuItem("OPEN");
    //adding action listener
    open.addActionListener(this);
                    MenuItem save=new MenuItem("SAVE");
    //adding action listener
    save.addActionListener(this);
                    MenuItem advanceopt=new MenuItem("ADVANCEOPT");
                    MenuItem copy=new MenuItem("COPY");
                    MenuItem paste=new MenuItem("PASTE");
                    MenuItem toolbars=new MenuItem("TOOLBARS");
                    file.add(New);
                    file.add(open);
                    file.add(save);
                    tool.add(advanceopt);
                    edit.add(copy);
                    edit.add(paste);
                    view.add(toolbars);
                    m.add(file);
                    m.add(edit);
                    m.add(view);
                    m.add(tool);
                   
                    f.setMenuBar(m);
    f.addWindowListener(this);
                    f.setSize(300,400);
                    f.setVisible(true);
             }
           public static void main(String args[])
           {
                  new filedialog();
           }
    }

    /*
    class Filedialog
    {
            Frame f=new Frame();
    }
    *///fd.LOAD;
    import java.io.*;
    class FileInStream {
        public static void main(String[] args){
            if(args.length==0) {
                System.out.println("Anda harus memasukkan nama file sebagai parameternya.");
                return;
            }
            byte data;
            FileInputStream fin=null;
            try{
                fin = new FileInputStream(args[0]);
                do{
                    data = (byte)fin.read();
                    System.out.print((char)data);
                }while(data!=-1);
    }catch(FileNotFoundException e) {
                System.out.println("File : " + args[0] + " tidak ditemukan.");
            }catch(IOException e) {
                System.out.println("Eksepsi tidak diketahui : " + e);
            }finally {
                //tutup file
                if(fin!=null) {
                    try{
                        fin.close();
                    }catch(IOException err) {
                        System.out.println("Eksepsi tidak diketahui : " + err);
                    }
                }
            }
        }
    }import java.io.*;
    import java.util.*;
    class FileListDemo
    {
    public static void main(String s[])
    {
    //File f1=new File("d:/Rahul");
    File f1=new File("F:/studies");
    String str[]=f1.list();
    for(int i=0;i {
    File f2=new File(f1,str[i]);
    if(f2.isFile())
    {
    System.out.println(f2+" is file");
    }
    else if(f2.isDirectory())
    {
    System.out.println(f2+" is Directory");
    }
    }
    }
    }

    ashish is a good boy.I just told a big joke.
    This is a demo.
    I like java.
    This is an example.
    Bas itna hi.
    import java.io.*;
    class FileOutStream {
        public static void main(String[] args){
            if(args.length==0) {
                System.out.println("Anda harus memasukkan nama file sebagai parameternya.");
                return;
            }
            byte data;
            FileOutputStream fout=null;
            try{
                fout = new FileOutputStream(args[0]);
                System.out.println("Ketik data yang ingin Anda tulis ke file.");
                System.out.println("Ketik Q jika Anda ingin berhenti.");
                data = (byte)System.in.read();
                while(data!=(byte)'Q'){
                    fout.write(data);
                    data = (byte)System.in.read();
                }
            }catch(FileNotFoundException e) {
                System.out.println("File : " + args[0] + " tidak dapat dibuka atau dibuat.");
            }catch(IOException e) {
                System.out.println("Eksepsi tidak diketahui : " + e);
            }finally {
                //tutup file
                if(fout!=null) {
                    try{
                        fout.close();
                    }catch(IOException err) {
                        System.out.println("Eksepsi tidak diketahui : " + err);
                    }
                }
            }
        }
    }import java.io.*;
    class fileread
    {
            public static void main(String args[]) throws IOException
            {
                    int ch,ctr=1;
                    String fname;
                    DataInputStream in=new DataInputStream(System.in);

                    System.out.print("Enter a file name?");
                    fname=in.readLine();
                    //opening file
                    FileInputStream f=new FileInputStream(fname);

                    System.out.print(ctr+" ");

                    while((ch=f.read())!=-1)
                    {
                            System.out.print((char)ch);
           
                            if(ch=='\n')
                            {
                            ctr++;
                            System.out.print(ctr+" ");
                            }
                    }
            }
    }




    import java.io.*;
    class filestat
    {
            public static void main(String args[]) throws IOException
            {
                    int pre=' ' , ch , ctr=0 , L=0 , w=1;
                    String fname;
                    DataInputStream in=new DataInputStream(System.in);
                    System.out.print("Enter a file name?");
                    fname=in.readLine();
                    //opening file
                    FileInputStream f=new FileInputStream(fname);
                    while((ch=f.read())!=-1)
                    {
                            //char count
                            if(ch!=' ' && ch!='\n')
                            ctr++;
                            //line count
                            if(ch=='\n')
                            L++;
                            //word count
                            if(ch==' ' && pre!=' ')
                            w++;
                            pre=ch;
                    }
                    System.out.println("Char count="+ctr);
                    System.out.println("Word count="+(w+(L-1)));
                    System.out.println("Line count="+L);
            }
    }




    import java.io.*;
    class filetest
    {
            public static void main(String args[]) throws IOException
            {
                    String fname;
                    DataInputStream in=new DataInputStream(System.in);

                    System.out.print("Enter a file name?");
                    fname=in.readLine();
                    //opening file
                    File f=new File(fname);

    if(f.exists())
                    System.out.println("File exists..");
                    else
                    System.out.println("File not exists..");

                    if(f.canRead())
                    System.out.println("File is readable..");
                    else
                    System.out.println("File is not readable..");

                    if(f.canWrite())
                    System.out.println("File is writable..");
                    else
                    System.out.println("File is not Writable..");

                    System.out.println("File length :"+f.length());
            }
    }




    //PROG 1:
    //ON PRESSING RED BUTTON ,THE FIRST RECTANGLE SHOULD START FILLING WID RED COLOR,GREEN WITH GREEN COLOR AND BLUE WITH BLUE COLOR
    //submitted by:Tarveen Kaur Bhatia(RICA)


    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class FillRect extends JFrame implements ActionListener,Runnable{
    JButton red,green,blue;
    Graphics g;
    Thread t1,t2,t3;
    int x1,y1,x2,y2;
    JPanel p1;
    public FillRect()
    {
        p1=new JPanel();
        red=new JButton("RED");
    blue=new JButton("BLUE");
    green=new JButton("GREEN");
    p1.add(red);
          p1.add(blue);
    p1.add(green);
        getContentPane().add(p1,BorderLayout.NORTH);
    red.addActionListener(this);
    blue.addActionListener(this);
    green.addActionListener(this);
    setSize(300,300);
    setVisible(true);
    }


    public void draw()
    {
    Graphics g=getGraphics();
    g.drawRect(40,100,60,50);
    g.drawRect(120,100,60,50);
    g.drawRect(200,100,60,50);
    }
    public void actionPerformed(ActionEvent ae)
    {


    g=getGraphics();

      if(ae.getSource()==red)
    {

    x1=40;x2=100;
    g.setColor(Color.red);
    t1=new Thread(this);
    t1.start();

       }
    else if(ae.getSource()==blue)
    {

    g.setColor(Color.blue);
    x1=120;x2=180;
    t2=new Thread(this);
    t2.start();

        }

    else  if(ae.getSource()==green)
    {
    g.setColor(Color.green);
                         x1=200;x2=260;
    t3=new Thread(this);
    t3.start();

        }


          }
    public void run()
    {
    y1=100;y2=100;
    for(int i=0;i<=50;i++)
    {
                  try
      {

     Thread.sleep(50);
     g.drawLine(x1,y1+i,x2,y2+i);

    }
            catch(Exception e)
            {
    System.out.println("Inside Catch : " + e);
            }
           }

    }



    public static void main(String args[])
    {
    FillRect r=new FillRect();
      r.draw();

    }
    }

    public class first
    {

    public static void main(String args[])
    {

    second s= new second() ;



    s.sec();

    System.out.println("/n/nretur to main!!!");



    }

    }


    import java.io.*;
    class Fisdemo
    {
     public static void main(String args[])
     {
       try
       {
       FileInputStream fis= new FileInputStream("Fisdemo.java ");
       int d=0;
       while((d=fis.read())!=-1)
       {
         System.out.print((char)d);
       }
       fis.close();
       System.out.println("Reading is over");
     }
     catch(IOException ie)
     {
       System.out.println("Error is" +ie);
      }
     }
     }  import java.io.*;
      class FISDemo
      {
      public static void main(String s[])
      {
      try
      {
    BufferedReader br=neew BufferedReader(new InputStreamReader(S
      FileInputStream fis=new FileInputStream("FISDemo.java");
      int i=0;
      while((i=fis.read())!=-1)
      {
      System.out.print((char)i);
      }
      fis.close();
      System.out.println("\nReading is over");
      }

    No comments:

    Post a Comment

    உப்பு மாங்காய்

    சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...