Thursday, August 13, 2015

webserver program using sockets

http://www.cs.uic.edu/~troy/spring05/cs450/sockets/socket.html

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

class WebServer
{
 public static void main (String args[]) throws Exception
  {
   String requestMessageLine;
   String fileName;

   // check if a port number is given as the first command line argument
   // if not argument is given, use port number 6789
   int myPort = 6789;
   if (args.length > 0)
     {
      try {
    myPort = Integer.parseInt(args[0]);
   } 
      catch (ArrayIndexOutOfBoundsException e) 
          {
    System.out.println("Need port number as argument");
    System.exit(-1);
   } 
      catch (NumberFormatException e) 
          {
    System.out.println("Please give port number as integer.");
    System.exit(-1);
   }
     }

   // set up connection socket
   ServerSocket listenSocket = new ServerSocket (myPort);

   // listen (i.e. wait) for connection request
   System.out.println ("Web server waiting for request on port " + myPort);
   Socket connectionSocket = listenSocket.accept();

   // set up the read and write end of the communication socket
   BufferedReader inFromClient = new BufferedReader (
                 new InputStreamReader(connectionSocket.getInputStream()));
   DataOutputStream outToClient = new DataOutputStream (
                 connectionSocket.getOutputStream());

   // retrieve first line of request and set up for parsing
   requestMessageLine = inFromClient.readLine();
   System.out.println ("Request: " + requestMessageLine);
   StringTokenizer tokenizedLine = new StringTokenizer(requestMessageLine);

   // check for GET request
   if (tokenizedLine.nextToken().equals("GET"))
     {
      fileName = tokenizedLine.nextToken();

      // remove leading slash from line if exists
      if (fileName.startsWith("/") == true)
          fileName = fileName.substring(1);

      // access the requested file
      File file = new File(fileName);

      // convert file to a byte array
      int numOfBytes = (int) file.length();
      FileInputStream inFile = new FileInputStream (fileName);
      byte[] fileInBytes = new byte[numOfBytes];
      inFile.read(fileInBytes);

      // Send reply 
      outToClient.writeBytes ("HTTP/1.0 200 Document Follows\r\n");
      if (fileName.endsWith(".jpg"))
          outToClient.writeBytes ("Content-Type: image/jpeg\r\n");
      if (fileName.endsWith(".gif"))
          outToClient.writeBytes ("Content-Type: image/gif\r\n");
      outToClient.writeBytes ("Content-Length: " + numOfBytes + "\r\n");
      outToClient.writeBytes ("\r\n");
      outToClient.write(fileInBytes, 0, numOfBytes);

      // read and print out the rest of the request
      requestMessageLine = inFromClient.readLine();
      while (requestMessageLine.length() >= 5)
         {
          System.out.println ("Request: " + requestMessageLine);
          requestMessageLine = inFromClient.readLine();
         }
      System.out.println ("Request: " + requestMessageLine);

      connectionSocket.close();
     }
   else
     {
      System.out.println ("Bad Request Message");
     }
  }
}

      
          

Saturday, August 8, 2015

tcp ip

Distributed Program Construction

Fall 2002

Lecture 3:  Network Programming: TCP/IP, Streams and SocketsPeter Druschel


COMP 413

    Layered Protocols

  • Lack of shared memory requires message-based IPC.
  • Protocols: standard rules that govern format, order, meaning, content of messages (e.g., retransmit message)
  • The OSI Model:  Layers of (independent) protocols
    • Encapsulation on send - Each layer adds a header (sometimes trailer), and passes the results to level below
    • Decapsulation on receive - strip layer's packet and pass to layer above
    • Each layer is oblivious to packets in lower levels


COMP 413

    OSI Layers

  • Physical - Transmit 0s and 1s.  Signaling interface
    • voltage, data transfer-rate, network connector
  • Data Link - Error-free transmission (detection and correction)
    • group bits into frames (leading and trailing separators), use checksum to detect errors (example: Ethernet)
  • Network - purpose: route packets in a WAN. 2 types:
    • Connection-oriented (ATM) - setup a route first, use for all subsequent traffic
    • Connectionless (IP) - no setup, data divided into packets, each packet routed independent of all other ones.
  • Transport - Reliable transmission of messages (e.g., TCP)
    • Break messages into packets, assign sequence number
    • Control over packets sent, recieved, capacity
    • Over connectionless layers, messages may arrive in different order
  • Session - dialog control, synchronization facilities (for checkpointing)
  • Presentation - structuring of the data sent (e.g., employee record), independent of application. (e.g., XDR, encryption)
  • Application - collection of protocols for common activities (e.g., telnet, ftp)



COMP 413

    IP - Network layer protocol (addressing)

Connectionless, packet delivery protocol, over virtual (software) network. Best-effort, but unreliable: packets may be lost, duplicated, delayed, out-of-order, with no indication to service user
Roles: 1. defines packet format and processing; 2. addressing hosts; 3. routing packets
IP global addressing scheme:
  • IP address is a pair (netid, hostid) - network address assigned centrally, hostid assigned locally.
  • Each IP address indicates a connection to a network (a host can have multiple IP addresses).
  • 4 bytes: w.x.y.z  w - determines the number of hosts in the network
    • class A: 1-126 (up to 16M hosts)
    • class B: 128-191 (up to 65536 hosts)
    • class C: 192-223 (up to 256 hosts)
    • class D: multicast networks
    • all 1s in hostid - broadcast address
  • 127 netid - loopback
  • 0 netid - this network; all 0s, this host
  • subnetting - allow multiple physical local networks with same netid
    • IP consists of Internet portion (site) and local portion (physical local network+hostid)
     


COMP 413

    UDP

  • Minimal transport protocol
    • differentiate among multiple sources via ports
    • provides checksum to validate packets
    • UDP message is encapsulated in an IP datagram
  • No state management, control flow, data integrity
    • no delivery guarantees. packets may be lost
    • if receiver gets a corrupted packet, it is simply discarded
    • any desired QoS should be programmed
  • should be used when:
    • transport overhead must be minimized (e.g., Video-on-demand)
    • reliability is not crucial
    • small, independent packets are sent (reduce overhead)
    • examples: NFS, DNS, NTP, SNMP



COMP 413


    TCP - Reliable Stream Transport

Properties: Stream-oriented (ordered); Virtual circuit connection (reliable); buffered transfer (efficient); full-duplex
positive acknowledgement with retransmission:
  • segments are ack. by receiver, If unack. after timeout, sender retransmits.
  • problem - waste of bandwidth
  • sliding window - window allows transmission of n octets before ack.
    • when first octet gets ack., window slides by one
    • if all octets in window sent, sender waits
  • Variable window size - for end-to-end flow-control
    • receiver sends with ack. a window advertisement
    • sender varies window size accordingly
  • Adaptive Timeout
    • problem: impossible to know a priori how quickly ack. should return
      • different networks, varying traffic
    • solution: estimate timeout based on history
      • RTT = (alpha * old_RTT) + ((1-alpha) * new_RTT_sample)
      • timeout = beta * RTT  (beta > 1)
    • problem: what is a good value for beta ?
      • when close to RTT - improves throughput (early detection), but wastes bandwidth (false detection)
      • in early implementations beta = 2 (constant), recent methods are adaptive


COMP 413


    TCP - Cont.

Congestion control: severe delays due to overload at routers (packet loss)
problem: endpoints see delay - might retransmit
solution: window = min(advertisement, congestion)
  • segment loss -> reduce congestion win. by half
  • remaining segments in window -> double timeout
  • slow-start: increment size by 1 for each ack.
Connection Establishment
Connection identified by a pair of endpoints (host,port)
  • an endpoint can be shared by multiple connections
Three-way handshake:
  • site 1 (active) sends SYN(x) (active open)
  • site 2 (passive) replies with SYN(y) + ACK(x+1)
  • site1  sends ACK(y+1)

  •  
After connection, bi-directional stream, e.g.:
  • site 1 sends segments data (may be along ACK(y+1))
  • site 2 ACKs, processes data, and replies
Closing connection (3-way)
  • site 1 closes (half) connection and sends FIN(x)
  • site 2 sends ACK(x+1), closes connection, sends FIN(y) (avoids retransmission of Fin(x))
  • site 1 sends ACK(y+1)
     


COMP 413
DNS
  •  Distributed mapping between hostnames and IP numbers
  • the same host may have multiple names (aliases)
  • the same name may refer to different hosts (RR  DNS)
  • Provides:
  • lookup services (name resolver)
  • maintains the database of hostnames
  • arranged in a hierarchy of nameservers
  • each host is configured to know about its local nameserver
  • nameservers typically keep cache of hostnames to speedup lookup



COMP 413

Introduction to Streams
The model:
  • Stream: An abstraction of a connection to a communication channel (TCP/IP network, the memory, file, a terminal, etc.).
  • Endpoint (port). Used to denote a communicating entity during network channel creation. I.e., in place of a file pathname, the combination of hostname, port is used to create a channel.
  • In Java, data is written to the channel with an OutputStream and read

  • from the channel with an InputStream.
     
Properties of streams:
  • FIFO: The first thing written to the OutputStream will be the first thing read from the corresponding InputStream.
  • Sequential access: Allows to read/write bytes only one after the other. (There are several exceptions.)
  • Read-only or write-only: A stream supports only writing to a channel or only reading from the channel.
  • Blocking: A thread that reads/writes data blocks while no data is yet

  • available to read, or when the write operation is in progress. Very little
    support for non-blocking I/O in Java.


COMP 413
Client-Side Networking with TCP










The model:

  • Class java.net.InetAddress represents a host address - its IP address (e.g., 128.42.1.197) and also, if available, its DNS name (e.g., vaud.cs.rice.edu).
  • Class java.net.Socket represents a TCP connection for establishing a stream-based communication channel with a remote host.
    • The remote address is designated by a host name (InetAddress) and a port number.
    • The socket occupies a local port for communication.
    • The getOutputStream and getInputStream methods return streams for access to the channel (to write to it and to read from it).



COMP 413



A TCP Client Example







import java.io.*;
import java.net.*;
// Get an html page and print it on the console.
public class GetPage {
  public static void main(String[] args) throws IOException {
    // Get the URL.
    URL url = new URL(args[0]);
    String host = url.getHost();
    int port = url.getPort();
    String file = url.getFile();
    if (port == -1) port = 80;
    // Open a TCP socket.
    Socket socket = new Socket(host, port);
    // Prepare to read/write data.
    OutputStream rawOut = socket.getOutputStream();
    InputStream rawIn = socket.getInputStream();
    BufferedOutputStream bufOut = new BufferedOutputStream(rawOut);
    DataOutputStream out = new DataOutputStream(bufOut);
    DataInputStream in = new DataInputStream(rawIn);
    // Send the http request.
    out.writeBytes("GET "+file+" HTTP/1.0\r\n\r\n");
    out.flush();
    // Receive the page and echo to the console.
    String input;
    while((input = in.readLine()) != null)
      System.out.println(input);
  }
}




COMP 413
Server-Side Networking with TCP
The model:
  • Class java.net.ServerSocket is the mechanism by which a server can accept connections from clients across a network.
  • The procedure is this:
    • A ServerSocket is opened on a particular local port, on the server host.
    • Clients will connect to this port.
    • For each connection ServerSocket creates a fresh Socket through which the server can communicate with the client.
  • Notice:
    • Available port numbers: 1 - 65535.
    • Ports 1 - 1023 are reserved for system services and should not be used by applications.
    • If port 0 is specified, then the operating system will select an arbitrary valid and free port.
    • The operating system maintains a queue of client connections that were not yet accepted by the server. They are removed from the queue one-by-one as the server explicitly accepts connections.


COMP 413
A TCP Server Example






import java.io.*;
import java.net.*;

// An echo server.
public class EchoServer {
  public static void main(String[] args) throws IOException {
    int port = Integer.parseInt(args[0]);
    // Wait for client?s connection
    ServerSocket server = new ServerSocket(port);
    Socket client = server.accept();
    server.close();
    // Handle a connection and exit.
    try {
      InputStream in = client.getInputStream();
      OutputStream out = client.getOutputStream();
      new PrintStream(out).println("Welcome!");
      int x;
      while((x = in.read()) > -1)
        out.write(x);
    } finally {
      client.close();
    }
  }
}



COMP 413



Final Notes on TCP Servers
Non-blocking servers:
  • There's no real support for non-blocking I/O in Java. The available() method of InputStream provides a workaround.
// Handle two connections simultaneously.
while(true) {
  if (in1.available()) {
    read from InputStream 1
    process the data
  }
  if (in2.available()) {
    read from InputStream 2
    process the data
  }
}
Multithreaded servers:
  • Provides a better solution for dealing with multiple connections concurrently.
  • A new thread is started per new connection.
// The ?main? thread.
ServerSocket server = new ServerSocket(port);
while(true) {
  Socket client = server.accept();
  // Creating and starting a separate new thread
  // to handle the connection.
  Thread thread = new ConnectionThread(client);
  thread.start();
}



COMP 413
Datagram Networking
The model:
  • Class java.net.DatagramPacket represents a single packet. It is used both for sending and receiving UDP packets.
  • Sending a packet involves:
    • Instantiating a DatagramPacket, while providing a message body, target address and port.
  • Receiving a packet involves:
    • Instantiating a DatagramPacket, while providing a buffer to which the accepted packet will be deposited.
  • Class java.net.DatagramSocket represents a UDP socket. Used both for sending and receiving UDP packets.
    • Sending and receiving packets is done with the send and receive methods respectively.
Notice:
  • UDP and TCP ports are different. Thus, a TCP socket can occupy (UDP) port n while a UDP socket occupies a (TCP) port n.


COMP 413
Datagram Networking Example
import java.io.*;
import java.net.*;
// An echo server, this time with UDP.
public class EchoServer {
  public static void main(String[] args) throws IOException {
    // Listen for incoming messages.
    int port = Integer.parseInt(args[0]);
    DatagramSocket socket = new DatagramSocket(port);
    Byte[] buffer = new byte[65535];
    DatagramPacket packet =
      new DatagramPacket(buffer, buffer.length);
    socket.receive(packet);
    // Handle a message.
    InetAddress addr = packet.getAddress();
    port = packet.getPort();
    byte[] data = packet.getData();
    int len = packet.getLength();
    packet = new DatagramPacket(data,len,addr,port);
    socket.send(packet);
  }
}




Datagram Networking Example (Cont'd.)






import java.io.*;
import java.net.*;
// A client for the echo server.
public class EchoClient {
  public static void main(String[] args) throws IOException {
    InetAddress host = InetAddress.getByName(args[0]);
    int port = Integer.parseInt(args[1]);
    String message = args[2];
    // Send the message.
    ByteArrayOutputStream byteOut =
      new ByteArrayOutputStream();
    DataOutputStream dataOut =
      new DataOutputStream(byteOut);
    dataOut.writeUTF(message);
    byte[] data = byteOut.toByteArray();
    DatagramPacket packet =
      new DatagramPacket(data,data.length,host,port);
    DatagramSocket socket =
      new DatagramSocket();
    socket.send(packet);
    // Receive and print the message.
    byte[] buffer = new byte[65535];
    packet = new DatagramPacket(buffer,buffer.length);
    socket.receive(packet);
    data = packet.getData();
    int length = packet.getLength();
    ByteArrayInputStream byteIn =
      new ByteArrayInputStream(data, 0, length);
    DataInputStream dataIn =
      new DataInputStream(byteIn);
    String result = dataIn.readUTF();
    System.out.println("Received: "+result);
  }
}






Sunday, August 2, 2015

K-means Algorithm

---------------JCA.java-------------

package org.c4s.algorithm.cluster;
import java.util.Vector;

/**

This class is the entry point for constructing Cluster Analysis objects.
Each instance of JCA object is associated with one or more clusters,
and a Vector of DataPoint objects. The JCA and DataPoint classes are
the only classes available from other packages.
@see DataPoint

**/

public class JCA {
    private Cluster[] clusters;
    private int miter;
    private Vector mDataPoints = new Vector();
    private double mSWCSS;

    public JCA(int k, int iter, Vector dataPoints) {
        clusters = new Cluster[k];
        for (int i = 0; i < k; i++) {
            clusters[i] = new Cluster("Cluster" + i);
        }
        this.miter = iter;
        this.mDataPoints = dataPoints;
    }

    private void calcSWCSS() {
        double temp = 0;
        for (int i = 0; i < clusters.length; i++) {
            temp = temp + clusters[i].getSumSqr();
        }
        mSWCSS = temp;
    }

    public void startAnalysis() {
        //set Starting centroid positions - Start of Step 1
        setInitialCentroids();
        int n = 0;
        //assign DataPoint to clusters
        loop1: while (true) {
            for (int l = 0; l < clusters.length; l++)
            {
                clusters[l].addDataPoint((DataPoint)mDataPoints.elementAt(n));
                n++;
                if (n >= mDataPoints.size())
                    break loop1;
            }
        }
       
        //calculate E for all the clusters
        calcSWCSS();
       
        //recalculate Cluster centroids - Start of Step 2
        for (int i = 0; i < clusters.length; i++) {
            clusters[i].getCentroid().calcCentroid();
        }
       
        //recalculate E for all the clusters
        calcSWCSS();

        for (int i = 0; i < miter; i++) {
            //enter the loop for cluster 1
            for (int j = 0; j < clusters.length; j++) {
                for (int k = 0; k < clusters[j].getNumDataPoints(); k++) {
               
                    //pick the first element of the first cluster
                    //get the current Euclidean distance
                    double tempEuDt = clusters[j].getDataPoint(k).getCurrentEuDt();
                    Cluster tempCluster = null;
                    boolean matchFoundFlag = false;
                   
                    //call testEuclidean distance for all clusters
                    for (int l = 0; l < clusters.length; l++) {
                   
                    //if testEuclidean < currentEuclidean then
                        if (tempEuDt > clusters[j].getDataPoint(k).testEuclideanDistance(clusters[l].getCentroid())) {
                            tempEuDt = clusters[j].getDataPoint(k).testEuclideanDistance(clusters[l].getCentroid());
                            tempCluster = clusters[l];
                            matchFoundFlag = true;
                        }
                        //if statement - Check whether the Last EuDt is > Present EuDt
                       
                        }
//for variable 'l' - Looping between different Clusters for matching a Data Point.
//add DataPoint to the cluster and calcSWCSS

       if (matchFoundFlag) {
tempCluster.addDataPoint(clusters[j].getDataPoint(k));
clusters[j].removeDataPoint(clusters[j].getDataPoint(k));
                        for (int m = 0; m < clusters.length; m++) {
                            clusters[m].getCentroid().calcCentroid();
                        }

//for variable 'm' - Recalculating centroids for all Clusters

                        calcSWCSS();
                    }
                   
//if statement - A Data Point is eligible for transfer between Clusters.
                }
                //for variable 'k' - Looping through all Data Points of the current Cluster.
            }//for variable 'j' - Looping through all the Clusters.
        }//for variable 'i' - Number of iterations.
    }

    public Vector[] getClusterOutput() {
        Vector v[] = new Vector[clusters.length];
        for (int i = 0; i < clusters.length; i++) {
            v[i] = clusters[i].getDataPoints();
        }
        return v;
    }


    private void setInitialCentroids() {
        //kn = (round((max-min)/k)*n)+min where n is from 0 to (k-1).
        double cx = 0, cy = 0;
        for (int n = 1; n <= clusters.length; n++) {
            cx = (((getMaxXValue() - getMinXValue()) / (clusters.length + 1)) * n) + getMinXValue();
            cy = (((getMaxYValue() - getMinYValue()) / (clusters.length + 1)) * n) + getMinYValue();
            Centroid c1 = new Centroid(cx, cy);
            clusters[n - 1].setCentroid(c1);
            c1.setCluster(clusters[n - 1]);
        }
    }

    private double getMaxXValue() {
        double temp;
        temp = ((DataPoint) mDataPoints.elementAt(0)).getX();
        for (int i = 0; i < mDataPoints.size(); i++) {
            DataPoint dp = (DataPoint) mDataPoints.elementAt(i);
            temp = (dp.getX() > temp) ? dp.getX() : temp;
        }
        return temp;
    }

    private double getMinXValue() {
        double temp = 0;
        temp = ((DataPoint) mDataPoints.elementAt(0)).getX();
        for (int i = 0; i < mDataPoints.size(); i++) {
            DataPoint dp = (DataPoint) mDataPoints.elementAt(i);
            temp = (dp.getX() < temp) ? dp.getX() : temp;
        }
        return temp;
    }

    private double getMaxYValue() {
        double temp = 0;
        temp = ((DataPoint) mDataPoints.elementAt(0)).getY();
        for (int i = 0; i < mDataPoints.size(); i++) {
            DataPoint dp = (DataPoint) mDataPoints.elementAt(i);
            temp = (dp.getY() > temp) ? dp.getY() : temp;
        }
        return temp;
    }

    private double getMinYValue() {
        double temp = 0;
        temp = ((DataPoint) mDataPoints.elementAt(0)).getY();
        for (int i = 0; i < mDataPoints.size(); i++) {
            DataPoint dp = (DataPoint) mDataPoints.elementAt(i);
            temp = (dp.getY() < temp) ? dp.getY() : temp;
        }
        return temp;
    }

    public int getKValue() {
        return clusters.length;
    }

    public int getIterations() {
        return miter;
    }

    public int getTotalDataPoints() {
        return mDataPoints.size();
    }

    public double getSWCSS() {
        return mSWCSS;
    }

    public Cluster getCluster(int pos) {
        return clusters[pos];
    }
}

/*-----------------Cluster.java----------------*/

package org.c4s.algorithm.cluster;

import java.util.Vector;

/**
 * This class represents a Cluster in a Cluster Analysis Instance. A Cluster is associated
 * with one and only one JCA Instance. A Cluster is related to more than one DataPoints and
 * one centroid.
 * @author Shyam Sivaraman
 * @version 1.1
 * @see DataPoint
 * @see Centroid
 */



class Cluster {
    private String mName;
    private Centroid mCentroid;
    private double mSumSqr;
    private Vector mDataPoints;

    public Cluster(String name) {
        this.mName = name;
        this.mCentroid = null; //will be set by calling setCentroid()
        mDataPoints = new Vector();
    }

    public void setCentroid(Centroid c) {
        mCentroid = c;
    }

    public Centroid getCentroid() {
        return mCentroid;
    }

    public void addDataPoint(DataPoint dp) { //called from CAInstance
        dp.setCluster(this); //initiates a inner call to
calcEuclideanDistance() in DP.
        this.mDataPoints.addElement(dp);
        calcSumOfSquares();
    }

    public void removeDataPoint(DataPoint dp) {
        this.mDataPoints.removeElement(dp);
        calcSumOfSquares();
    }

    public int getNumDataPoints() {
        return this.mDataPoints.size();
    }

    public DataPoint getDataPoint(int pos) {
        return (DataPoint) this.mDataPoints.elementAt(pos);
    }

    public void calcSumOfSquares() { //called from Centroid
        int size = this.mDataPoints.size();
        double temp = 0;
        for (int i = 0; i < size; i++) {
            temp = temp + ((DataPoint)
this.mDataPoints.elementAt(i)).getCurrentEuDt();
        }
        this.mSumSqr = temp;
    }

    public double getSumSqr() {
        return this.mSumSqr;
    }

    public String getName() {
        return this.mName;
    }

    public Vector getDataPoints() {
        return this.mDataPoints;
    }

}

/*---------------Centroid.java-----------------*/

package org.c4s.algorithm.cluster;

/**
 * This class represents the Centroid for a Cluster. The initial centroid is calculated
 * using a equation which divides the sample space for each dimension into equal parts
 * depending upon the value of k.
 * @author Shyam Sivaraman
 * @version 1.0
 * @see Cluster
 */

class Centroid {
    private double mCx, mCy;
    private Cluster mCluster;

    public Centroid(double cx, double cy) {
        this.mCx = cx;
        this.mCy = cy;
    }

    public void calcCentroid() { //only called by CAInstance
        int numDP = mCluster.getNumDataPoints();
        double tempX = 0, tempY = 0;
        int i;
        //caluclating the new Centroid
        for (i = 0; i < numDP; i++) {
            tempX = tempX + mCluster.getDataPoint(i).getX();
            //total for x
            tempY = tempY + mCluster.getDataPoint(i).getY();
            //total for y
        }
        this.mCx = tempX / numDP;
        this.mCy = tempY / numDP;
        //calculating the new Euclidean Distance for each Data Point
        tempX = 0;
        tempY = 0;
        for (i = 0; i < numDP; i++) {
            mCluster.getDataPoint(i).calcEuclideanDistance();
        }
        //calculate the new Sum of Squares for the Cluster
        mCluster.calcSumOfSquares();
    }

    public void setCluster(Cluster c) {
        this.mCluster = c;
    }

    public double getCx() {
        return mCx;
    }

    public double getCy() {
        return mCy;
    }

    public Cluster getCluster() {
        return mCluster;
    }

}

/*----------------DataPoint.java----------------*/

package org.c4s.algorithm.cluster;

/**
    This class represents a candidate for Cluster analysis. A candidate must have
    a name and two independent variables on the basis of which it is to be clustered.
    A Data Point must have two variables and a name. A Vector of  Data Point object
    is fed into the constructor of the JCA class. JCA and DataPoint are the only
    classes which may be available from other packages.
    @author Shyam Sivaraman
    @version 1.0
    @see JCA
    @see Cluster
*/

public class DataPoint {
    private double mX,mY;
    private String mObjName;
    private Cluster mCluster;
    private double mEuDt;

    public DataPoint(double x, double y, String name) {
        this.mX = x;
        this.mY = y;
        this.mObjName = name;
        this.mCluster = null;
    }

    public void setCluster(Cluster cluster) {
        this.mCluster = cluster;
        calcEuclideanDistance();
    }

    public void calcEuclideanDistance() {
   
    //called when DP is added to a cluster or when a Centroid is recalculated.
        mEuDt = Math.sqrt(Math.pow((mX - mCluster.getCentroid().getCx()),
2) + Math.pow((mY - mCluster.getCentroid().getCy()), 2));
    }

    public double testEuclideanDistance(Centroid c) {
        return Math.sqrt(Math.pow((mX - c.getCx()), 2) + Math.pow((mY - c.getCy()), 2));
    }

    public double getX() {
        return mX;
    }

    public double getY() {
        return mY;
    }

    public Cluster getCluster() {
        return mCluster;
    }

    public double getCurrentEuDt() {
        return mEuDt;
    }

    public String getObjName() {
        return mObjName;
    }

}

/*-----------------PrgMain.java---------------*/

import org.c4s.algorithm.cluster.DataPoint;
import org.c4s.algorithm.cluster.JCA;
import java.util.Vector;
import java.util.Iterator;

/**
 * Created by IntelliJ IDEA.
 * User: shyam.s
 * Date: Apr 18, 2004
 * Time: 4:26:06 PM
 */
public class PrgMain {
    public static void main (String args[]){
        Vector dataPoints = new Vector();
        dataPoints.add(new DataPoint(22,21,"p53"));
        dataPoints.add(new DataPoint(19,20,"bcl2"));
        dataPoints.add(new DataPoint(18,22,"fas"));
        dataPoints.add(new DataPoint(1,3,"amylase"));
        dataPoints.add(new DataPoint(3,2,"maltase"));

        JCA jca = new JCA(2,1000,dataPoints);
        jca.startAnalysis();

        Vector[] v = jca.getClusterOutput();
        for (int i=0; i<v.length; i++){
            Vector tempV = v[i];
            System.out.println("-----------Cluster"+i+"---------");
            Iterator iter = tempV.iterator();
            while(iter.hasNext()){
                DataPoint dpTemp = (DataPoint)iter.next();
                System.out.println(dpTemp.getObjName()+"
["+dpTemp.getX()+","+dpTemp.getY()+"]");
            }
        }
    }
}

Source Code for Data Structures and Algorithm Analysis in Java

http://users.cis.fiu.edu/~weiss/dsaajava3/code/