From 599b63599ba0df3a018fab54770721cca32ef15b Mon Sep 17 00:00:00 2001 From: Michael Reber Date: Mon, 18 Nov 2019 13:43:20 +0100 Subject: [PATCH] Adding some more java stuff --- java/CLChat Client.java | 137 +++++++++++++ java/CLChatServer.java | 129 ++++++++++++ java/Client Server Using RMI.java | 59 ++++++ java/Creating a Non-Blocking Socket.java | 36 ++++ java/DateClient.java | 49 +++++ java/DateServer.java | 61 ++++++ java/FTPLogin.java | 66 +++++++ java/IPC Client Server Program.java | 69 +++++++ ...priori algorithm for association rule.java | 92 +++++++++ ...ementation of Agglomerative Algorithm.java | 187 ++++++++++++++++++ ...ation of clustering algorithm K-means.java | 138 +++++++++++++ java/Interprocess communication.java | 81 ++++++++ java/LoadBalancer.java | 54 +++++ java/Multi ClassLoader Demo.java | 83 ++++++++ java/Mutual Exclusion Algorithm.java | 108 ++++++++++ java/MyThread.java | 47 +++++ java/Parallel Algorithms.java | 29 +++ java/Ping a server.java | 23 +++ java/Port Scanner.java | 46 +++++ java/SimpleApacheSoapClient.java | 50 +++++ java/SquareKaro.java | 23 +++ java/SquareResult.java | 17 ++ java/Squarer.java | 44 +++++ ...o implement Na‹ve Bayesian Classifier.java | 154 +++++++++++++++ java/Using Proxy.java | 167 ++++++++++++++++ 25 files changed, 1949 insertions(+) create mode 100644 java/CLChat Client.java create mode 100644 java/CLChatServer.java create mode 100644 java/Client Server Using RMI.java create mode 100644 java/Creating a Non-Blocking Socket.java create mode 100644 java/DateClient.java create mode 100644 java/DateServer.java create mode 100644 java/FTPLogin.java create mode 100644 java/IPC Client Server Program.java create mode 100644 java/Implement Apriori algorithm for association rule.java create mode 100644 java/Implementation of Agglomerative Algorithm.java create mode 100644 java/Implementation of clustering algorithm K-means.java create mode 100644 java/Interprocess communication.java create mode 100644 java/LoadBalancer.java create mode 100644 java/Multi ClassLoader Demo.java create mode 100644 java/Mutual Exclusion Algorithm.java create mode 100644 java/MyThread.java create mode 100644 java/Parallel Algorithms.java create mode 100644 java/Ping a server.java create mode 100644 java/Port Scanner.java create mode 100644 java/SimpleApacheSoapClient.java create mode 100644 java/SquareKaro.java create mode 100644 java/SquareResult.java create mode 100644 java/Squarer.java create mode 100644 java/To implement Na‹ve Bayesian Classifier.java create mode 100644 java/Using Proxy.java diff --git a/java/CLChat Client.java b/java/CLChat Client.java new file mode 100644 index 0000000..ad3be06 --- /dev/null +++ b/java/CLChat Client.java @@ -0,0 +1,137 @@ +CLChat Client + +import java.net.*; +import java.io.*; + +public class CLChatClient { + + static final int DEFAULT_PORT = 1728; // Port where server is + // listening, if no + // port is specified + // on the command line. + + static final String HANDSHAKE = "CLChat"; // Handshake string. + // Each end of the connection sends this string + // to the other just after the connection is + // opened. This is done to confirm that the + // program on the other side of the connection + // is a CLChat program. + + static final char MESSAGE = '0'; // This character is prepended + // to every message that is sent. + + static final char CLOSE = '1'; // This character is sent to + // the connected program when + // the user quits. + + public static void main(String[] args) { + + String computer; // The computer where the server is running, + // as specified on the command line. It can + // be either an IP number or a domain name. + + int port; // The port on which the server listens. + + Socket connection; // For communication with the server. + + TextReader incoming; // Stream for receiving data from server. + PrintWriter outgoing; // Stream for sending data to server. + String messageOut; // A message to be sent to the server. + String messageIn; // A message received from the server. + + /* First, get the computer from the command line. + Get the port from the command line, if one is specified, + or use the default port if none is specified. */ + + if (args.length == 0) { + TextIO.putln("Usage: java SimpleClient []"); + return; + } + + computer = args[0]; + + if (args.length == 1) + port = DEFAULT_PORT; + else { + try { + port= Integer.parseInt(args[1]); + if (port <= 0 || port > 65535) + throw new NumberFormatException(); + } + catch (NumberFormatException e) { + TextIO.putln("Illegal port number, " + args[1]); + return; + } + } + + /* Open a connetion to the server. Create streams for + communication and exchange the handshake. */ + + try { + TextIO.putln("Connecting to " + computer + " on port " + port); + connection = new Socket(computer,port); + incoming = new TextReader(connection.getInputStream()); + outgoing = new PrintWriter(connection.getOutputStream()); + outgoing.println(HANDSHAKE); + outgoing.flush(); + messageIn = incoming.getln(); + if (! messageIn.equals(HANDSHAKE) ) { + throw new IOException("Connected program is not CLChat!"); + } + TextIO.putln("Connected. Enter your first message. +"); + } + catch (Exception e) { + TextIO.putln("An error occurred while opening connection."); + TextIO.putln(e.toString()); + return; + } + + /* Exchange messages with the other end of the connection + until one side or the other closes the connection. + This client program send the first message. After that, + messages alternate strictly back an forth. */ + + try { + while (true) { + TextIO.put("SEND: "); + messageOut = TextIO.getln(); + if (messageOut.equalsIgnoreCase("quit")) { + // User wants to quit. Inform the other side + // of the connection, then close the connection. + outgoing.println(CLOSE); + outgoing.flush(); + connection.close(); + TextIO.putln("Connection closed."); + break; + } + outgoing.println(MESSAGE + messageOut); + outgoing.flush(); + if (outgoing.checkError()) { + throw new IOException("Error ocurred while reading incoming message."); + } + TextIO.putln("WAITING..."); + messageIn = incoming.getln(); + if (messageIn.length() > 0) { + // The first character of the message is a command. + // If the command is CLOSE, then the connection + // is closed. Otherwise, remove the command + // character from the message and procede. + if (messageIn.charAt(0) == CLOSE) { + TextIO.putln("Connection closed at other end."); + connection.close(); + break; + } + messageIn = messageIn.substring(1); + } + TextIO.putln("RECEIVED: " + messageIn); + } + } + catch (Exception e) { + TextIO.putln("Sorry, an error has occurred. Connection lost."); + TextIO.putln(e.toString()); + System.exit(1); + } + + } // end main() +} //end class CLChatClient diff --git a/java/CLChatServer.java b/java/CLChatServer.java new file mode 100644 index 0000000..b75b55b --- /dev/null +++ b/java/CLChatServer.java @@ -0,0 +1,129 @@ +CLChatServer + +import java.net.*; +import java.io.*; + +public class CLChatServer { + + static final int DEFAULT_PORT = 1728; // Port to listen on, + // if none is specified + // on the command line. + + static final String HANDSHAKE = "CLChat"; // Handshake string. + // Each end of the connection sends this string + // to the other just after the connection is + // opened. This is done to confirm that the + // program on the other side of the connection + // is a CLChat program. + + static final char MESSAGE = '0'; // This character is prepended + // to every message that is sent. + + static final char CLOSE = '1'; // This character is sent to + // the connected program when + // the user quits. + + public static void main(String[] args) { + + int port; // The port on which the server listens. + + ServerSocket listener; // Listens for a connection request. + Socket connection; // For communication with the client. + + TextReader incoming; // Stream for receiving data from client. + PrintWriter outgoing; // Stream for sending data to client. + String messageOut; // A message to be sent to the client. + String messageIn; // A message received from the client. + + /* First, get the port number from the command line, + or use the default port if none is specified. */ + + if (args.length == 0) + port = DEFAULT_PORT; + else { + try { + port= Integer.parseInt(args[0]); + if (port < 0 || port > 65535) + throw new NumberFormatException(); + } + catch (NumberFormatException e) { + TextIO.putln("Illegal port number, " + args[0]); + return; + } + } + + /* Wait for a connection request. When it arrives, close + down the listener. Create streams for communication + and exchange the handshake. */ + + try { + listener = new ServerSocket(port); + TextIO.putln("Listening on port " + listener.getLocalPort()); + connection = listener.accept(); + listener.close(); + incoming = new TextReader(connection.getInputStream()); + outgoing = new PrintWriter(connection.getOutputStream()); + outgoing.println(HANDSHAKE); + outgoing.flush(); + messageIn = incoming.getln(); + if (! messageIn.equals(HANDSHAKE) ) { + throw new IOException("Connected program is not CLChat!"); + } + TextIO.putln("Connected. Waiting for the first message. +"); + } + catch (Exception e) { + TextIO.putln("An error occurred while opening connection."); + TextIO.putln(e.toString()); + return; + } + + /* Exchange messages with the other end of the connection + until one side or the other closes the connection. + This server program waits for the first message from + the client. After that, messages alternate strictly + back an forth. */ + + try { + while (true) { + TextIO.putln("WAITING..."); + messageIn = incoming.getln(); + if (messageIn.length() > 0) { + // The first character of the message is a command. + // If the command is CLOSE, then the connection + // is closed. Otherwise, remove the command + // character from the message and procede. + if (messageIn.charAt(0) == CLOSE) { + TextIO.putln("Connection closed at other end."); + connection.close(); + break; + } + messageIn = messageIn.substring(1); + } + TextIO.putln("RECEIVED: " + messageIn); + TextIO.put("SEND: "); + messageOut = TextIO.getln(); + if (messageOut.equalsIgnoreCase("quit")) { + // User wants to quit. Inform the other side + // of the connection, then close the connection. + outgoing.println(CLOSE); + outgoing.flush(); // Make sure the data is sent! + connection.close(); + TextIO.putln("Connection closed."); + break; + } + outgoing.println(MESSAGE + messageOut); + outgoing.flush(); // Make sure the data is sent! + if (outgoing.checkError()) { + throw new IOException("Error ocurred while reading incoming message."); + } + } + } + catch (Exception e) { + TextIO.putln("Sorry, an error has occurred. Connection lost."); + TextIO.putln(e.toString()); + System.exit(1); + } + + } // end main() +} //end class CLChatServer diff --git a/java/Client Server Using RMI.java b/java/Client Server Using RMI.java new file mode 100644 index 0000000..a49512a --- /dev/null +++ b/java/Client Server Using RMI.java @@ -0,0 +1,59 @@ +//AddInterface.java +import java.rmi.*; +public interface AddInterface extends Remote +{ + public int sum(int n1, int n2) throws RemoteException +} + +//Add.java +import java.rmi.*; +import java.rmi.server.*; +public class Add extends UnicastRemoteObject implements AddInterface +{ + int num1, num2 ; + public Add() throws RemoteException + { + } + public int sum(int n1, int n2) throws RemoteException + { + num1=n1; + num2=n2; + return n1+n2; + } +} + +//AddServer.java +import java.rmi.Naming; +public class AddServer +{ + public static void main(String args[]) + { + try + { + Naming.rebind("Add",new Add()); + System.out.println("Server is connected and waiting for client"); + } + catch(Exception e) + { + System.out.println("server could not connect:"+e); + } + } +} + +//AddClient.java +import java.rmi.Naming; +public class AddClient +{ + public static void main(String args[]) + { + try + { + AddInterface ai=(AddInterface)Naming.lookup("//localhost/Add"); + System.out.println("The sum of two nos. is :"+ai.sum(10,2)); + } + catch(Exception e) + { + System.out.println("Client Exception:"+e); + } + } +} diff --git a/java/Creating a Non-Blocking Socket.java b/java/Creating a Non-Blocking Socket.java new file mode 100644 index 0000000..ea836c1 --- /dev/null +++ b/java/Creating a Non-Blocking Socket.java @@ -0,0 +1,36 @@ +Creating a Non-Blocking Socket + +public class test + { + public static void main(String args[]) + { + // Create a non-blocking socket and check for connections + try { + // Create a non-blocking socket channel on port 8080 + SocketChannel sChannel = createSocketChannel("www.xxx", 8080); + + // Before the socket is usable, the connection must be completed + // by calling finishConnect(), which is non-blocking + while (!sChannel.finishConnect()) { + // Do something else + System.out.println("wonderful"); + } + // Socket channel is now ready to use + } + catch (IOException e) { + } + } + + // Creates a non-blocking socket channel for the specified host name and port. + // connect() is called on the new channel before it is returned. + public static SocketChannel createSocketChannel(String hostName, int port) throws IOException + { + // Create a non-blocking socket channel + SocketChannel sChannel = SocketChannel.open(); + sChannel.configureBlocking(false); + + // Send a connection request to the server; this method is non-blocking + sChannel.connect(new InetSocketAddress(hostName, port)); + return sChannel; + } +} diff --git a/java/DateClient.java b/java/DateClient.java new file mode 100644 index 0000000..4683156 --- /dev/null +++ b/java/DateClient.java @@ -0,0 +1,49 @@ +DateClient + +import java.net.*; +import java.io.*; + +public class DateClient { + + static final int LISTENING_PORT = 32007; + + public static void main(String[] args) { + + String computer; // Name of the computer to connect to. + Socket connection; // A socket for communicating with + // that computer. + Reader incoming; // Stream for reading data from + // the connection. + + /* Get computer name from command line. */ + + if (args.length > 0) + computer = args[0]; + else { + // No computer name was given. Print a message and exit. + System.out.println("Usage: java DateClient "); + return; + } + + /* Make the connection, then read and display a line of text. */ + + try { + connection = new Socket( computer, LISTENING_PORT ); + incoming = new InputStreamReader( connection.getInputStream() ); + while (true) { + int ch = incoming.read(); + if (ch == -1 || ch == ' +' || ch == ' +') + break; + System.out.print( (char)ch ); + } + System.out.println(); + incoming.close(); + } + catch (Exception e) { + TextIO.putln("Error: " + e); + } + + } // end main() +} //end class DateClient diff --git a/java/DateServer.java b/java/DateServer.java new file mode 100644 index 0000000..afc51c0 --- /dev/null +++ b/java/DateServer.java @@ -0,0 +1,61 @@ +DateServer + +import java.net.*; +import java.io.*; +import java.util.Date; + +public class DateServe { + + static final int LISTENING_PORT = 32007; + + + public static void main(String[] args) { + + ServerSocket listener; // Listens for incoming connections. + Socket connection; // For communication with the + // connecting program. + + /* Accept and process connections forever, or until + some error occurs. (Note that errors that occur + while communicating with a connected program are + caught and handled in the sendDate() routine, so + they will not crash the server.) + */ + + try { + listener = new ServerSocket(LISTENING_PORT); + TextIO.putln("Listening on port " + LISTENING_PORT); + while (true) { + connection = listener.accept(); + sendDate(connection); + } + } + catch (Exception e) { + TextIO.putln("Sorry, the server has shut down."); + TextIO.putln("Error: " + e); + return; + } + + } // end main() + + + static void sendDate(Socket client) { + // The parameter, client, is a socket that is + // already connected to another program. Get + // an output stream for the connection, send the + // current date, and close the connection. + try { + System.out.println("Connection from " + + client.getInetAddress().toString() ); + Date now = new Date(); // The current data and time. + PrintWriter outgoing; // Stream for sending data. + outgoing = new PrintWriter( client.getOutputStream() ); + outgoing.println( now.toString() ); + outgoing.flush(); // Make sure the data is actually sent! + client.close(); + } + catch (Exception e){ + System.out.println("Error: " + e); + } + } // end sendDate() +} //end class DateServe diff --git a/java/FTPLogin.java b/java/FTPLogin.java new file mode 100644 index 0000000..17bb816 --- /dev/null +++ b/java/FTPLogin.java @@ -0,0 +1,66 @@ +FTPLogin + +import java.io.BufferedReader; +import java.io.PrintWriter; +import java.io.InputStreamReader; +import java.net.Socket; + +public class FTPLogin +{ + public static void main (String args[]) + { + Socket socket = null; + BufferedReader in = null; + PrintWriter out = null; + String line = null; + + if (args.length != 3) + { + System.out.println ("USAGE: IP USER PASS"); + } + + else + { + try + { + socket = new Socket (args[0], 21); + in = new BufferedReader (new InputStreamReader(socket.getInputStream())); + out = new PrintWriter (socket.getOutputStream()); + + out.print("user "+ args[1] + " +"); + out.print("pass "+ args[2] + " +"); + out.print ("pwd +"); + out.print ("quit +"); + out.flush(); + + while ( (line = in.readLine()) != null) + { + System.out.println(line); + } + + + } + catch (Exception e) + { + System.out.println(e.getMessage()); + } + finally + { + try + { + out.close(); + in.close(); + socket.close(); + } + catch (Exception fe) + { + System.out.println ("RESOURCE CLOSE EXCEPTION " +fe.getMessage()); + } + } + } //end else + } //end main +} //end class diff --git a/java/IPC Client Server Program.java b/java/IPC Client Server Program.java new file mode 100644 index 0000000..10adba5 --- /dev/null +++ b/java/IPC Client Server Program.java @@ -0,0 +1,69 @@ +// IPC CLient Program + +import java.net.*; +import java.io.*; +public class IPCClient +{ + public static void main(String args[]) + { + try + { + Socket s=new Socket("localhost",3128); + DataOutputStream dos=new DataOutputStream(s.getOutputStream()); + DataInputStream dis=new DataInputStream(s.getInputStream()); + InputStreamReader isr=new InputStreamReader(System.in); + System.out.println("......Client PROCESS STARTED...."); + System.out.println("Enter the value of 1 and 2 to pass the server process"); + BufferedReader br=new BufferedReader(isr); + int a=Integer.parseInt(br.readLine()); + System.out.println("\Number 1="+a); + dos.writeInt(+a); + int b=Integer.parseInt(br.readLine()); + System.out.println("\Number 2="+b); + dos.writeInt(+b); + int result=dis.readInt(); + System.out.println("Client Process has receieved result from server\n.."); + s.close(); + } + catch(Exception e) + { + System.out.println("Exception "+e); + } + } +} + +//IPC Server + +import java.net.*; +import java.io.*; +public class IPCServer +{ + public static void main(String args[]) + { + System.out.println("......INTERPROCESS COMMUNICATION...."); + System.out.println("......SERVER PROCESS STARTED...."); + System.out.println("......SERVER IS READY AND WAITING TO RECEIVE DATA FROM CLIENT FROM PORT...."+3128); + try + { + ServerSocket ss=new ServerSocket(3128); + Socket clientSocket=ss.accept(); + System.out.println("Client is connected with IP Address"+clientSocket.getInetAddress()+"And Port no"+clientSocket.getPort()); + DataOutputStream dos=new DataOutputStream(clientSocket.getOutputStream()); + DataInputStream dis=new DataInputStream(clientSocket.getInputStream()); + int a=dis.readInt(); + System.out.println("Server recievd"); + System.out.println("\Number 1="+a); + int b=dis.readInt(); + System.out.println("\Number 2="+b); + int c=a+b; + dos.writeInt(c); + System.out.println("Server Process has executed..Requested process and sent result"+c+"To the Client\n"); + clientSocket.close(); + } + catch(Exception e) + { + System.out.println("Exception "+e); + } + } +} + diff --git a/java/Implement Apriori algorithm for association rule.java b/java/Implement Apriori algorithm for association rule.java new file mode 100644 index 0000000..e138485 --- /dev/null +++ b/java/Implement Apriori algorithm for association rule.java @@ -0,0 +1,92 @@ + +import java.io.*; +class apriori +{ + public static void main(String []arg)throws IOException + { + int i,j,m=0; + int t1=0; + BufferedReader b=new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Enter the number of transaction :"); + int n=Integer.parseInt(b.readLine()); + System.out.println("items :1--Milk 2--Bread 3--Coffee 4--Juice 5--Cookies 6--Jam"); + int item[][]=new int[n][6]; + for(i=0; i=50) + q[j]=1; + else + q[j]=0; + if(q[j]==1) + { + t1++; + System.out.println("Item "+itemlist[j]+" is selected "); + } + } + for(j=0; j<6; j++) + { + for(i=0; i=50) + q[j]=1; + else + q[j]=0; + if(q[j]==1) + { + System.out.println("Item "+itemlist[j]+"& "+itemlist[m]+" is selected "); + } + } + } + } +} diff --git a/java/Implementation of Agglomerative Algorithm.java b/java/Implementation of Agglomerative Algorithm.java new file mode 100644 index 0000000..366ac24 --- /dev/null +++ b/java/Implementation of Agglomerative Algorithm.java @@ -0,0 +1,187 @@ + +package tutorial.clustering; +import de.lmu.ifi.dbs.elki.algorithm.AbstractDistanceBasedAlgorithm; +import de.lmu.ifi.dbs.elki.data.type.TypeInformation; +import de.lmu.ifi.dbs.elki.distance.distancefunction.DistanceFunction; +import de.lmu.ifi.dbs.elki.distance.distancevalue.NumberDistance; +import de.lmu.ifi.dbs.elki.logging.Logging; +import de.lmu.ifi.dbs.elki.result.Result; +public class NaiveAgglomerativeHierarchicalClustering> + extends AbstractDistanceBasedAlgorithm +{ + protected NaiveAgglomerativeHierarchicalClustering(DistanceFunction distanceFunction) + { + super(distanceFunction); +// TODO Auto-generated constructor stub + } + public TypeInformation[] getInputTypeRestriction() + { +// TODO Auto-generated method stub + return null; + } + protected Logging getLogger() + { +// TODO Auto-generated method stub + return null; + } +} +/** +* Static class logger. +*/ +private static final Logging LOG = Logging.getLogger(NaiveAgglomerativeHierarchicalClustering.class); +protected Logging getLogger() +{ + return LOG; +} +public TypeInformation[] getInputTypeRestriction() +{ + return TypeUtil.array( + getDistanceFunction().getInputTypeRestriction() + ); +} +// The run method +public Result run(Database db, Relation relation) +{ + return null; +} +DistanceQuery dq = db.getDistanceQuery(relation, getDistanceFunction()); +ArrayDBIDs ids = DBIDUtil.ensureArray(relation.getDBIDs()); +final int size = ids.size(); +LOG.verbose("Notice: SLINK is a much faster algorithm for single-linkage clustering!"); +Computing the distance matrix +double[][] matrix = new double[size][size]; +DBIDArrayIter ix = ids.iter(), iy = ids.iter(); +for (int x = 0; ix.valid(); x++, ix.advance()) + { + iy.seek(0); + for (int y = 0; y < x; y++, iy.advance()) + { + final double dist = dq.distance(ix, iy).doubleValue(); + matrix[x][y] = dist; + matrix[y][x] = dist; + } + } +Algorithm main loop +final int stop = size - numclusters; +FiniteProgress prog = LOG.isVerbose() ? + new FiniteProgress("Agglomerative clustering", stop, LOG) + : null; +for (int i = 0; i < stop; i++) + { +// TODO: find clusters to merge +// TODO: store the merge in auxillary data +// TODO: update distance matrix + if (prog != null) + { + prog.incrementProcessed(LOG); + } + } +if (prog != null) + { + prog.ensureCompleted(LOG); + } +double min = Double.POSITIVE_INFINITY; +int minx = -1, miny = -1; +for (int x = 0; x < size; x++) + { + if (height[x] < Double.POSITIVE_INFINITY) + { + continue; + } + for (int y = 0; y < x; y++) + { + if (height[y] < Double.POSITIVE_INFINITY) + { + continue; + } + if (matrix[x][y] < min) + { + min = matrix[x][y]; + minx = x; + miny = y; + } + } + } +// Avoid allocating memory, by reusing existing iterators: +ix.seek(minx); +iy.seek(miny); +// Perform merge in data structure: x -> y +// Since y < x, prefer keeping y, dropping x. +height[minx] = min; +parent.set(minx, iy); +// Merge into cluster +ModifiableDBIDs cx = clusters.get(minx); +ModifiableDBIDs cy = clusters.get(miny); +if (cy == null) + { + cy = DBIDUtil.newHashSet(); + cy.add(iy); + } +if (cx == null) + { + cy.add(ix); + } +else + { + cy.addDBIDs(cx); + clusters.remove(minx); + } +clusters.put(miny, cy); +// Update distance matrix for y: +for (int j = 0; j < size; j++) + { + matrix[j][miny] = Math.min(matrix[j][minx], matrix[j][miny]); + matrix[miny][j] = Math.min(matrix[minx][j], matrix[miny][j]); + } +Returning a Clustering +final Clustering dendrogram = new Clustering<>( + "Hierarchical-Clustering", "hierarchical-clustering"); +for (int x = 0; x < size; x++) + { + if (height[x] < Double.POSITIVE_INFINITY) + { + continue; + } + DBIDs cids = clusters.get(x); +// For singleton objects, this may be null. + if (cids == null) + { + ix.seek(x); + cids = DBIDUtil.deref(ix); + } + Cluster cluster = new Cluster<>("Cluster", cids); + dendrogram.addToplevelCluster(cluster); + } +return dendrogram; +Updating the constructor +/** +* Threshold, how many clusters to extract. +*/ +int numclusters; +public NaiveAgglomerativeHierarchicalClustering( + DistanceFunction distanceFunction, + int numclusters) +{ + super(distanceFunction); + this.numclusters = numclusters; +} +Adding a Parameterizer +public static class Parameterizer> + extends AbstractDistanceBasedAlgorithm.Parameterizer +{ + int numclusters = 0; + protected void makeOptions(Parameterization config) + { + super.makeOptions(config); + IntParameter numclustersP = new IntParameter(SLINK.Parameterizer.SLINK_MINCLUSTERS_ID); + numclustersP.addConstraint(new GreaterEqualConstraint(1)); + if (config.grab(numclustersP)) + { + numclusters = numclustersP.intValue(); + } + } + protected NaiveAgglomerativeHierarchicalClustering makeInstance() + { + return new NaiveAgglomerativeHierarchicalClustering<>(distanceFunction, numclusters); + } +} diff --git a/java/Implementation of clustering algorithm K-means.java b/java/Implementation of clustering algorithm K-means.java new file mode 100644 index 0000000..50d307f --- /dev/null +++ b/java/Implementation of clustering algorithm K-means.java @@ -0,0 +1,138 @@ + + +import java.util.*; +class k_means +{ + static int count1,count2,count3; + static int d[]; + static int k[][]; + static int tempk[][]; + static double m[]; + static double diff[]; + static int n,p; + static int cal_diff(int a) // This method will determine the cluster in which an element go at a particular step. + { + int temp1=0; + for(int i=0; im[i]) + diff[i]=a-m[i]; + else + diff[i]=m[i]-a; + } + int val=0; + double temp=diff[0]; + for(int i=0; i in; + private BlockingQueue out; + + Squarer(BlockingQueue request, BlockingQueue replies) + { + this.in = request; + this.out = replies; + } + + public void start() + { + new Thread(new Runnable() + { + public void run() + { + while(true) + { + try + { + int x = in.take(); + int y = x*x; + Thread.sleep(2000); + System.out.println("OK, got it. Calculating.."); + Thread.sleep(4000); + out.put(new SquareResult(x,y)); + } + catch(InterruptedException e) + { + System.out.println("interrupted yo"); + } + } + } + }).start(); + } +} + + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +public class SquareKaro +{ + public static void main(String[] args) + { + BlockingQueue number = new LinkedBlockingQueue<>(); + BlockingQueue result = new LinkedBlockingQueue<>(); + Squarer mysquarer = new Squarer(number, result); + mysquarer.start(); + try + { + System.out.println("Hey another process, give me square of => 54"); + number.put(54); + System.out.println(result.take()); + } + catch(Exception e) + { + e.printStackTrace(); + } + } +} + + +public class SquareResult +{ + private int input; + private int output; + public SquareResult(int in, int out) + { + this.input = in; + this.output = out; + } + + @Override public String toString() + { + return input +" ka square hai "+output; + } +} diff --git a/java/LoadBalancer.java b/java/LoadBalancer.java new file mode 100644 index 0000000..d270647 --- /dev/null +++ b/java/LoadBalancer.java @@ -0,0 +1,54 @@ + +import java.util.Scanner; +class LoadBalancer +{ + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + System.out.print("Enter the number of servers:"); + int servers=sc.nextInt(); + System.out.println(); + System.out.print("Enter the number of processes:"); + int Processes=sc.nextInt(); + while(true) + { + printLoad(servers,Processes); + System.out.println("1.Add Servers 2.Remote Servers 3.Add Processes 4.Remove Processes 5.Exit :"); + switch(sc.nextInt()) + { + case 1: + System.out.print("How many more servers?:"); + servers+=sc.nextInt(); + break; + case 2: + System.out.print("How many servers to remove?:"); + servers-=sc.nextInt(); + break; + case 3: + System.out.print("How many more Processes?:"); + Processes+=sc.nextInt(); + break; + case 4: + System.out.print("How many Processes to remove?:"); + Processes-=sc.nextInt(); + break; + case 5: + return; + } + } + } + + static void printLoad(int servers,int Processes) + { + int each=Processes/servers; + int extra=Processes%servers; + int total=0; + for(int i=0; i0)total=each+1; + else total=each; + System.out.println("Server "+(char)('A'+i)+" has "+total+" Processes"); + } + } + +} diff --git a/java/Multi ClassLoader Demo.java b/java/Multi ClassLoader Demo.java new file mode 100644 index 0000000..9bbeea6 --- /dev/null +++ b/java/Multi ClassLoader Demo.java @@ -0,0 +1,83 @@ +Multi ClassLoader Demo + +import java.net.URLClassLoader; +import java.net.URL; +import java.io.File; + +public class MultiCLDemo + { + public static void main(String[] args) + { + if (args.length<3) + { + System.out.println("Usage: java MultiCLDemo "+" ..."); + System.out.println("Loads and runs toString() on class_name "+"found in each subDir."); + System.exit(0); + } + try + { + String className = args[0]; + int count = args.length-1; + URL tmpURL; + Object[] objects = new Object[count]; + URLClassLoader[] loaders = new URLClassLoader[count]; + System.out.println("Loading "+count+" different classes "+"named: "+className); + for (int i=0; i { + tmpURL = new File(args[i+1]).toURL(); + System.out.println("\nLoading from: "+tmpURL); + loaders[i] = new URLClassLoader(new URL[] { tmpURL }); + objects[i] = loaders[i].loadClass(className).newInstance(); + for (int k=0; k<=i; k++) + { + System.out.println("Got object: "+objects[k]); + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } +} + + +/*Some sample classes to load... + +// c:\a/HelloWorld.java +public class HelloWorld + { + public String toString() + { + return "Hello"; + } +} + +// c:\b/HelloWorld.java +public class HelloWorld + { + public String toString() + { + return "World"; + } +} + +// c:\c/HelloWorld.java +public class HelloWorld + { + public String toString() + { + return "Hello World"; + } +} + +The code running... + +java MultiCLDemo HelloWorld a b c + +Loading 3 different classes named: +HelloWorldLoading from: file:/.../class_loader_demo/a/Got object: +HelloLoading from: file:/.../class_loader_demo/b/Got object: +HelloGot object: WorldLoading from: file:/.../class_loader_demo/c/Got object: +HelloGot object: WorldGot object: Hello World + +regards, btcoburn*/ diff --git a/java/Mutual Exclusion Algorithm.java b/java/Mutual Exclusion Algorithm.java new file mode 100644 index 0000000..60e56b6 --- /dev/null +++ b/java/Mutual Exclusion Algorithm.java @@ -0,0 +1,108 @@ +// EchoServer.java +import java.io.*; +import java.net.*; +public class EchoServer implements Runnable +{ + Socket socket=null; + static ServerSocket ss; + EchoServer(Socket newSocket) + { + this.socket=newSocket; + } + public static void main(String args[]) throws IOException + { + ss=new ServerSocket(7000); + System.out.println("Server Started"); + while(true) + { + Socket s = ss.accept(); + EchoServer es = new EchoServer(s); + Thread t = new Thread(es); + t.start(); + } + } + public void run() + { + try + { + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + while(true) + { + System.out.println(in.readLine()); + } + } + catch(Exception e) + {} + } +} + +// EchoClientOne.java +import java.io.*; +import java.net.*; +public class EchoClientOne +{ + public static void main(String args[])throws IOException + { + Socket s=new Socket("localhost",7000); + PrintStream out = new PrintStream(s.getOutputStream()); + ServerSocket ss = new ServerSocket(7001); + Socket s1 = ss.accept(); + BufferedReader in1 = new BufferedReader(new InputStreamReader(s1.getInputStream())); + PrintStream out1 = new PrintStream(s1.getOutputStream()); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String str="Token"; + while(true) + { + if(str.equalsIgnoreCase("Token")) + { + System.out.println("Do you want to send some data"); + System.out.println("Enter Yes or No"); + str=br.readLine(); + if(str.equalsIgnoreCase("Yes")) + { + System.out.println("Enter the data"); + str=br.readLine(); + out.println(str); + } + out1.println("Token"); + } + System.out.println("Waiting for Token"); + str=in1.readLine(); + } + } +} + +// EchoClientTwo.java +import java.io.*; +import java.net.*; +public class EchoClientTwo +{ + public static void main(String args[])throws IOException + { + Socket s=new Socket("localhost",7000); + PrintStream out = new PrintStream(s.getOutputStream()); + Socket s2=new Socket("localhost",7001); + BufferedReader in2 = new BufferedReader(new InputStreamReader(s2.getInputStream())); + PrintStream out2 = new PrintStream(s2.getOutputStream()); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String str; + while(true) + { + System.out.println("Waiting for Token"); + str=in2.readLine(); + if(str.equalsIgnoreCase("Token")) + { + System.out.println("Do you want to send some data"); + System.out.println("Enter Yes or No"); + str=br.readLine(); + if(str.equalsIgnoreCase("Yes")) + { + System.out.println("Enter the data"); + str=br.readLine(); + out.println(str); + } + out2.println("Token"); + } + } + } +} diff --git a/java/MyThread.java b/java/MyThread.java new file mode 100644 index 0000000..2e902a3 --- /dev/null +++ b/java/MyThread.java @@ -0,0 +1,47 @@ +import java.util.*; + +class MyThread implements Runnable +{ + private Thread t; + private String ThreadName; + + MyThread(String name) + { + ThreadName = name; + } + + public void run() + { + System.out.println(ThreadName+" is starting.."); + try + { + Thread.sleep(500); + } + catch (InterruptedException e) + { + System.out.println(ThreadName+"interrupted"); + } + System.out.println(ThreadName+" is stopping.."); + } + + public void start() + { + if(t == null) + { + t = new Thread(this, ThreadName); + t.start(); + } + } +} + +class Test +{ + public static void main(String[] args) + { + MyThread m1 = new MyThread("yo dudes"); + m1.start(); + MyThread m2 = new MyThread("yo buddies again"); + m2.start(); + } +} + diff --git a/java/Parallel Algorithms.java b/java/Parallel Algorithms.java new file mode 100644 index 0000000..f719770 --- /dev/null +++ b/java/Parallel Algorithms.java @@ -0,0 +1,29 @@ + +import java.util.*; +public class ParallelSort +{ + public static void main(String[] args) + { +// Create a list and populate it with random numbers + List list = new ArrayList(); + Random r = new Random(); + for (int x = 0; x < 30000000; x++) + { + list.add(r.nextInt(10000)); + } +// Create two arrays for sorting. + Integer[] array1 = new Integer[list.size()]; + Integer[] array2 = new Integer[list.size()]; + array1 = list.toArray(array1); + array2 = list.toArray(array2); +// sort array + long start = System.currentTimeMillis(); + Arrays.sort(array1); + long end = System.currentTimeMillis(); + System.out.println("Sort Time: " + (end - start)); +// sort array using parallel sort + start = System.currentTimeMillis(); + Arrays.parallelSort(array2); + end = System.currentTimeMillis(); + System.out.println("Parallel Sort Time: " + (end - start)); + } diff --git a/java/Ping a server.java b/java/Ping a server.java new file mode 100644 index 0000000..b473ae9 --- /dev/null +++ b/java/Ping a server.java @@ -0,0 +1,23 @@ +Ping a server + +import java.io.*; +import java.net.*; + + public class PseudoPing { + public static void main(String args[]) { + try { + Socket t = new Socket(args[0], 7); + DataInputStream dis = new DataInputStream(t.getInputStream()); + PrintStream ps = new PrintStream(t.getOutputStream()); + ps.println("Hello"); + String str = is.readLine(); + if (str.equals("Hello")) + System.out.println("Alive!") ; + else + System.out.println("Dead or echo port not responding"); + t.close(); + } + catch (IOException e) { + e.printStackTrace();} + } +} diff --git a/java/Port Scanner.java b/java/Port Scanner.java new file mode 100644 index 0000000..ccab11d --- /dev/null +++ b/java/Port Scanner.java @@ -0,0 +1,46 @@ +Port Scanner + +import java.net.*; +import java.io.IOException; +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; + + public class PScanner { + + public static void main(String[] args) { + InetAddress ia=null; + String host=null; + try { + + host=JOptionPane.showInputDialog("Enter the Host name to scan:\n example: xxx.com"); + if(host!=null){ + ia = InetAddress.getByName(host); + scan(ia); } + } + catch (UnknownHostException e) { + System.err.println(e ); + } + System.out.println("Bye from NFS"); + //System.exit(0); + } + + public static void scan(final InetAddress remote) { + //variables for menu bar + + int port=0; + String hostname = remote.getHostName(); + + for ( port = 0; port < 65536; port++) { + try { + Socket s = new Socket(remote,port); + System.out.println("Server is listening on port " + port+ " of " + hostname); + s.close(); + } + catch (IOException ex) { + // The remote host is not listening on this port + System.out.println("Server is not listening on port " + port+ " of " + hostname); + } + }//for ends + } +} diff --git a/java/SimpleApacheSoapClient.java b/java/SimpleApacheSoapClient.java new file mode 100644 index 0000000..a4b360f --- /dev/null +++ b/java/SimpleApacheSoapClient.java @@ -0,0 +1,50 @@ +SimpleApacheSoapClient + + + +package com.ack.webservices.soap; + +import java.net.URL; +import java.util.Vector; + +import org.apache.soap.Constants; +import org.apache.soap.rpc.Call; +import org.apache.soap.rpc.Parameter; +import org.apache.soap.rpc.Response; + +public class SimpleApacheSoapClient { + public static void main( String[] args ) throws Exception { + // soap service endpoint + //URL url = new URL("http://services.xmethods.com:80/soap/servlet/rpcrouter"); + URL url = new URL( "http://localhost:6666/soap/servlet/rpcrouter" ); + // create a call + Call call = new Call(); + + // Service uses standard SOAP encoding + call.setEncodingStyleURI( Constants.NS_URI_SOAP_ENC ); + + // Set service locator parameters + call.setTargetObjectURI( "urn:xmethods-Temperature" ); + call.setMethodName( "getTemp" ); + + // Create input parameter vector + Vector params = new Vector(); + params.addElement( new Parameter( "zipcode", String.class, "94041", null ) ); + call.setParams( params ); + + // Invoke the service, note that an empty SOAPActionURI of + // "" indicates that intent of the SOAP request is taken to + // be the request URI + Response resp = call.invoke( url, "" ); + + // ... and evaluate the response + if( resp.generatedFault() ) { + throw new Exception(); + } + else { + // Call was successful. Extract response parameter and return result + Parameter result = resp.getReturnValue(); + System.out.println( "temperature is -> " + result.getValue() ); + } + } +} diff --git a/java/SquareKaro.java b/java/SquareKaro.java new file mode 100644 index 0000000..b387425 --- /dev/null +++ b/java/SquareKaro.java @@ -0,0 +1,23 @@ +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +public class SquareKaro +{ + public static void main(String[] args) + { + BlockingQueue number = new LinkedBlockingQueue<>(); + BlockingQueue result = new LinkedBlockingQueue<>(); + Squarer mysquarer = new Squarer(number, result); + mysquarer.start(); + try + { + System.out.println("Hey another process, give me square of => 54"); + number.put(54); + System.out.println(result.take()); + } + catch(Exception e) + { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/java/SquareResult.java b/java/SquareResult.java new file mode 100644 index 0000000..1024ca6 --- /dev/null +++ b/java/SquareResult.java @@ -0,0 +1,17 @@ +public class SquareResult +{ + + private int input; + private int output; + + public SquareResult(int in, int out) + { + this.input = in; + this.output = out; + } + + @Override public String toString() + { + return input +" ka square hai "+output; + } +} \ No newline at end of file diff --git a/java/Squarer.java b/java/Squarer.java new file mode 100644 index 0000000..cc78e84 --- /dev/null +++ b/java/Squarer.java @@ -0,0 +1,44 @@ +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +public class Squarer +{ + private BlockingQueue in; + private BlockingQueue out; + + Squarer(BlockingQueue request, BlockingQueue replies) + { + this.in = request; + this.out = replies; + } + + public void start() + { + new Thread(new Runnable() + { + public void run() + { + while(true) + { + try + { + int x = in.take(); + int y = x*x; + Thread.sleep(2000); + System.out.println("OK, got it. Calculating.."); + Thread.sleep(4000); + out.put(new SquareResult(x,y)); + } + catch(InterruptedException e) + { + System.out.println("interrupted yo"); + } + } + } + }).start(); + } + +} + + + diff --git a/java/To implement Na‹ve Bayesian Classifier.java b/java/To implement Na‹ve Bayesian Classifier.java new file mode 100644 index 0000000..cb7d5b0 --- /dev/null +++ b/java/To implement Na‹ve Bayesian Classifier.java @@ -0,0 +1,154 @@ + +import java.util.*; +class btheo +{ + static char outlook[]= {'S','S','O','R','R','R','O','S','S','R','S','O','O','R'}; + static char temperature[]= {'H','H','H','M','C','C','C','M','C','M','M','M','H','M'}; + static char humidity[]= {'P','P','P','P','N','N','N','P','N','N','N','P','N','P'}; + static char windy[]= {'F','T','F','F','F','T','T','F','F','F','T','T','F','T'}; + static char class1[]= {'N','N','P','P','P','N','P','N','P','P','P','P','P','N'}; + static double prob[][]=new double[4][2]; + static double pp=9.0/14.0; + static double npp=5.0/14.0; + static int flag=0; + static int flag1=0; + static double play_N=1; + static double notplay_N=1; + static void cal_N(int a) + { + if(a==1) + { + for(int i=0; i<4; ++i) + play_N*=prob[i][0]; + play_N*=pp; + //System.out.println("\nValue of N of play \n"+play_N); + } + Else + { + for(int i=0; i<4; ++i) + notplay_N*=prob[i][1 + notplay_N*=npp; + //System.out.println("\nValue of N of No play \n"+notplay_N); + } + } + static double cal_play_prob(char ch) + { + double prob=0; + double count=0; + if(flag==0) + { + for(int i=0; i<14; ++i) + if(outlook[i]==ch && class1[i]=='P') + ++count; + prob=count/9.0; + flag=1; + } + else if + (flag==1) + { + for(int i=0; i<14; ++i) + if(temperature[i]==ch && class1[i]=='P') + ++count; + prob=count/9.0; + flag=2; + } + else if + (flag==2) + { + for(int i=0; i<14; ++i) + if(humidity[i]==ch && class1[i]=='P') + ++count; + prob=count/9.0; + flag=3; + } + else if(flag==3) + { + for(int i=0; i<14; ++i) + if(windy[i]==ch && class1[i]=='P') + ++count; + prob=count/9.0; + } + return prob; + } + static double cal_noplay_prob(char ch) + { + double prob=0; + double count=0; + if(flag1==0) + { + for(int i=0; i<14; ++i) + if(outlook[i]==ch && class1[i]=='N') + ++count; + prob=count/5.0; + flag1=1; + } + else if(flag1==1) + { + for(int i=0; i<14; ++i) + if(temperature[i]==ch && class1[i]=='N') + ++count; + prob=count/5.0; + flag1=2; + } + else if(flag1==2) + { + for(int i=0; i<14; ++i) + if(humidity[i]==ch && class1[i]=='N') + ++count; + prob=count/5.0; + flag1=3; + } + else if(flag1==3) + { + for(int i=0; i<14; ++i) + if(windy[i]==ch && class1[i]=='N') + ++count; + prob=count/5.0; + } + return prob; + } + public static void main(String args[]) + { + Scanner scr=new Scanner(System.in); + System.out.println("Table\n"); + System.out.println("Outlook\t Temperature\t Humidity\t Windy \tClass"); + for(int i=0; i<14; ++i) + { + System.out.print(outlook[i]+"\t\t"+temperature[i]+"\t\t"+humidity[i]+"\t\t"+windy[i]+"\t\t"+class1[i]); + System.out.println(); + } + System.out.println("Menu:\nOutlook: Sunny=S Overcast=O Rain=R\tTemperature: Hot=H Mild=M Cool=C\n"); + System.out.println("Humidity: Peak=P Normal=N\t\tWindy: True=T False=F\n\nYour input should belong to one of these classes.\n"); + System.out.println("class1: Play=P class2:Not Play=NP"); + System.out.println("\nEnter your input: example. t={rain,hot,peak,false} input will be R,H,P,F"); + String s=scr.nextLine(); + char ch; + int count=0; + for(int i=0; i<8; i+=2) + { + ch=s.charAt(i); + prob[count][0]=cal_play_prob(ch); + prob[count][1]=cal_noplay_prob(ch); + ++count; + } + cal_N(1); + cal_N(2); + double pt=play_N+notplay_N; + double prob_of_play=0; + double prob_of_noplay=0; + prob_of_play=play_N/pt; + prob_of_noplay=notplay_N/pt; + System.out.println("\nProbability of play "+prob_of_play); + System.out.println("\nProbability of NO play "+prob_of_noplay ); + if(prob_of_play>prob_of_noplay) + System.out.println("\nThe new tuple classified under \"PLAY\" category.Hence there will be play!!!"); + else + System.out.println("\nThe new tuple classified under \"NO PLAY\" category.Hence there will be NO play."); + } +} +} + + + + + diff --git a/java/Using Proxy.java b/java/Using Proxy.java new file mode 100644 index 0000000..a9fc391 --- /dev/null +++ b/java/Using Proxy.java @@ -0,0 +1,167 @@ +Using Proxy + +import java.net.URL; +import java.net.URLConnection; +import java.net.HttpURLConnection; + +import java.io.InputStream; +import java.io.BufferedReader; +import java.io.InputStreamReader; + +public class ProxyDemo +{ + // Set to true if you want to see verbose output. + private final static boolean bDebug = false; + + /** + * This function makes an HTTP GET request of the specified URL using a proxy if provided. + * If successfully, the HTTP response headers are printed out. + * If the MIME type of the response is text/html, then the number of lines of text + * is printed as well. + * + * @param strURL - A string representing the URL to request, eg, "http://bdn.borland.com/" + * @param strProxy - A string representing either the IP address or host name of the proxy server. + * @param iProxyPort - An integer that indicates the proxy port or -1 to indicate the default port for the protocol. + * @return rc is true if the request succeeded and false otherwise. + */ + static boolean doURLRequest(String strURL, String strProxy, int iProxyPort) + { + boolean rc = false; + + URL url = null; + URLConnection c = null; + + try + { + System.out.println("\nHTTP Request: " + strURL); + + URL urlOriginal = new URL(strURL); + + if ((null != strProxy) && (0 < strProxy.length())) + { + URL urlProxy = new URL(urlOriginal.getProtocol(), + strProxy, + iProxyPort,// A value of -1 means use the default port for the specified protocol. + strURL);// The original URL is passed as "the file on the host". + + System.out.println("Using Proxy: " + strProxy); + if (-1 != iProxyPort) + { + System.out.println("Using Proxy Port: " + iProxyPort); + } + + url = urlProxy; + } + else + { + url = urlOriginal; + } + + c = url.openConnection(); + + // In this example, we only consider HTTP connections. + if (c instanceof HttpURLConnection)// instanceof returns true only if the object is not null. + { + + HttpURLConnection h = (HttpURLConnection) c; + h.connect(); + + String strStatus = h.getResponseMessage() + " (" + h.getResponseCode() + ")"; + System.out.println("HTTP Status: " + strStatus); + + System.out.println("HTTP Response Headers: "); + + // Evidently, index 0 always returns null, so we start with index 1. + for (int i = 1; ; i++) + { + String strKey = h.getHeaderFieldKey(i); + if (null == strKey) + { + break; + } + System.out.println(i + ": " + strKey + ": " + h.getHeaderField(i)); + } + + // Normally at this point, one would download data from the connection. + // For example, if the MIME type is html, then download the string and display it. + String strContentType = h.getContentType(); + if ((null != strContentType) && (0 == strContentType.compareTo("text/html"))) + { + // Set boolean bDebug to true if you want verbose output. + // For simplicity's sake, we just count the number of lines of text. + if (bDebug) System.out.println("Received text/html:["); + + int iNumLines = 0; + + try + { + InputStream in = h.getInputStream(); + BufferedReader data = new BufferedReader(new InputStreamReader(in)); + + String line = null; + while((line = data.readLine()) != null) + { + if (bDebug) System.out.println(line); + + iNumLines++; + } + } + catch(Exception exc2) + { + System.out.println("**** IO failure: " + exc2.toString()); + } + finally + { + if (bDebug) System.out.println("]"); + System.out.println("Received text/html has " + iNumLines + " lines"); + } + } + + h.disconnect(); + } + else + { + System.out.println("**** No download: connection was not HTTP"); + } + + rc = true; + } + // Catch all exceptions. + catch(Exception exc) + { + System.out.println("**** Connection failure: " + exc.toString()); + // System.out.println("**** Connection failure: " + exc.getMessage());// Same as above line but without the exception class name. + } + finally + { + // Do cleanup here. + // For example, the following, in theory, could make garbage collection more efficient. + // This might be the place where you choose to put your method call to your connection's "disconnect()"; + // curiously, while every URLConnection has a connect() method, they don't necessarily have a disconnect() method. + // HttpURLConnection has a disconnect() which is called above. + c = null; + url = null; + + return rc; + } + } + + public static void main(String[] args) + { + // Simple request, not using a proxy server. + ProxyDemo.doURLRequest("http://www.borland.com/", null, -1); + ProxyDemo.doURLRequest("http://www.borland.com", null, -1); + + // Request, using a proxy server. + /** + * @todo: Note that the proxy indicated below will fail. Change to a valid server. + * (If you do not have a proxy server available, then search for a web site that + * lists public HTTP proxy servers. + * I hesitate to list any here as I'm not sure about the "legitimacy" of all these sites.) + */ + // *** If you don't change the proxy setting to something valid in the following, + // then you will get the following error message: + // **** Connection failure: java.net.BindException: Cannot assign requested address: connect + ProxyDemo.doURLRequest("http://www.borland.com/", "0.0.0.0", -1); // **** Change this line to use a valid proxy. + } +}