5:20 PM

travel...

Traveling is my hobby. I used to travel a lot. Whenever I travel for countries, I used to suffer a lot due to unavailability of hotels and travel agency. Later, I came to know about Ibiza Travel, and I used to travel through this travel agency. After that, there were no traveling worries for me. All my travel trips were well planned and organized by the Ibiza people and I got world class staying experience at Ibiza Hotels. I suggest you to choose this travel agency to and for your stays. They offer high quality accommodation at very cheap cost so that you can get world class accommodation even if your budget is very low.

5:20 PM

FP GROWTH

3.2.4 FP GROWTH

The algorithm, FP-growth, for mining the FP-tree structure is a recursive procedure during which many sub FP-trees and header tables are created. The process commences by examining each item in the header table, starting with the least frequent. For each entry the support value for the item is produced by following the links connecting all occurrences of the current item in the FP-tree. If the item is adequately supported, then for each leaf node a set of ancestor labels is produced , each of which has a support equivalent to the sum of the leaf node items from which it is generated. If the set of ancestor labels is not null, a new tree is generated with the set of ancestor labels as the dataset, and the process repeated. In our implementation all frequent itemsets thus discovered were placed in a tree, thus providing fast access during the final stage of the process, while at the same time providing for the deletion of FP-subtrees and tables created "on route" as the FP-growth algorithm progressed.

A sample FP Growth is shown below:


Fig 3.2 FP Growth

5:19 PM

TOTAL SUPPORT TREE

3.2.5 TOTAL SUPPORT TREE

A T-tree is a tree structure which is used to store frequent item set information. The patterns are stored here. Levels in each sub-branch of the tree are defined using arrays.

The tree is built in "reverse". Each branch is founded on the last element of the frequent sets to be stored. Given a data set of the form:
{1 3 4}
{2 4 5}
{2 4 6}

and assuming a support count of less than 1, we can identify the following frequent sets (support counts in parenthesis):

1 (1) 1 3 (1) 1 3 4 (1)
2 (2) 1 4 (1) 2 4 5 (1)
3 (1) 2 4 (2) 2 4 6 (1)
4 (3) 2 5 (1)
5 (1) 2 6 (1)
6 (1) 3 4 (1)
4 5 (1)
4 6 (1)

These can be presented in a T-tree. The storage required for each node (representing a frequent set) in the T-tree is then 12 Bytes:

Fig 3.3 Total Support Tree

Reference to T-tree node structure (4 Bytes)
Support count field in T-tree node structure (4 Bytes)
Reference to child array field in T-tree node structure (4 Bytes)

3.3 REQUIREMENTS

3.3.1 SOFTWARE REQUIREMENTS
Language Java
Platform Platform Independent



Table 3.1 Software Requirements



3.3.2 HARDWARE REQUIREMENTS
Processor 1.8 GHz processor
RAM 256 MB
Hard Disk Space 40 GB





Table 3.2 Hardware Requirements

5:18 PM

OVERVIEW

OVERVIEW

The implementation phase is carried out by coding the modules : reordering and pruning , FP Tree construction and FP Growth. The main method FPgrowthApp is compiled and executed . While giving the command for execution , the input file which is the frequent itemset is given as a command line argument. The support and confidence percentage can also be specified.

5:14 PM

one stop Golf store...

Hi every body, I feel very happy to share news about my favorite activity. There are lots of leisure time activities available. They are the one which make our self get relaxed from our routine works. I love sports a lot and I do play lot of games. But among all the sports I play, I love a lot to play Golf. Whenever I feel like bored and want to get relaxed my self, I will go play and golf. This will make me refreshed and I get the energy and enthusiasm work again with full efficiency. In this post, I would like to share a few information about a Golf shop where I used to buy all my golf accessories. I have been to many Golfshop but I have never got satisfied like what I am getting right now with the present shop where I do all my purchases for my golf needs.

Well, I have visited the shop lot of times and I feel the Golf Mode in me. You can get all kinds of golf stuffs here. They come with very good quality and with very cheap price. There fore, even if you have framed a low level budget, you can get good stuffs which fits under your budget. I have got complete satisfaction with the cost of the golf accessories and as well as the quality of the golf accessories. I am sure you will also like it a lot and get complete satisfaction like what I have got. I would like to share more information about the shop. This shop is the biggest golf shop in Germany and they offer all kinds of branded golf items. In addition to branded items they do provide a lot of information about golf news and golf information. You can get loads of information about
Golf holidays such that you can plan your favorite golf game during your vacations. This is the one stop portal for all your golf needs and you can get any thing and everything regarding golf under one single roof.

5:14 PM

CLASSES

5.2 CLASSES

The project consists of various classes each having their own purpose.We shall give the description of the fundamental classes and their methods.

5.2.1 Reorder

This class is for processing the user input file, read the itemset and store them in an array. The frequent itemset is obtained by calculating the minimum support using the input support percent and the frequent itemset is in a reordered and pruned form.

The methods used in this class are:

The method checkinputarguments() is used to check the input arguments such as support , confidence and filename.

The method inputdataset() is used the input file ,get the number of rows, read the contents of the file into the array and calculate the minimum support.

The method countsingles() is used to count the occurences of the items and the method ordercountarray() is used to order the attributes according to the count.

The method prune() is used to prune unsupported attributes.

5.2.2 FPTree1

This class is used for constructing the FP Tree. This class also contains the methods for mining the FP Tree.

The methods used in this class are:

The method addtofptree() is used to add the items to construct a FP tree.
The method startmining() is used to start the mining process.
The method outputfptree() is used to output the FP tree.

5.2.3 TotalSuppTree

This class is used construct a total support tree and the contents of the total support tree. The methods used in this class are:
The method addtottree() is used to add the nodes to the T - tree.
The methods outputFrequentSets() is used to output the T-tree frequent sets
The method outputStorage() is used to output the T – Tree storage

5.2.4 FPgApp

This class contains the main method. This class is executed by the user.

This class calls the methods of the above mentioned classes.

5:14 PM

RESULT AND ANALYSIS

6. RESULT AND ANALYSIS
6.1 OUTPUT EXECUTION
Executing a sample of The FP Growth method gives the following output :
Input :
1 3 4
2 4 5
2 4 6
Output :
Number of frequent sets = 17
[1] {4} = 3
[2] {2} = 2
[2.1] {2 4} = 2
[3] {1} = 1
[3.1] {1 4} = 1
[4] {3} = 1
[4.1] {3 4} = 1
[4.2] {3 1} = 1
[4.2.1] {3 1 4} = 1
[5] {5} = 1
[5.1] {5 4} = 1
[5.2] {5 2} = 1
[5.2.1] {5 2 4} = 1
[6] {6} = 1
[6.1] {6 4} = 1
[6.2] {6 2} = 1
[6.2.1] {6 2 4} = 1
T-tree Storage = 272 (Bytes)
Executing a sample of The Apriori method gives the following output :

Input :
1 3 4
2 4 5
2 4 6

Output :
[1] {1} = 1
[2] {2} = 2
[3] {3} = 1
[3.1] {3 1} = 1
[4] {4} = 3
[4.1] {4 1} = 1
[4.2] {4 2} = 2
[4.3] {4 3} = 1
[4.3.1] {4 3 1} = 1
[5] {5} = 1
[5.1] {5 2} = 1
[5.2] {5 4} = 1
[5.2.1] {5 4 2} = 1
[6] {6} = 1
[6.1] {6 2} = 1
[6.2] {6 4} = 1
[6.2.1] {6 4 2} = 1
T-tree Storage = 296 (Bytes)

5:13 PM

OUTPUT COMPARISON

6.2 OUTPUT COMPARISON

6.2.1 ACCURACY :

Executing both the algorithms gives the same output. The same frequent patterns are generated by both methods. Hence, accuracy is the same for both.

6.2.2 T –TREE STORAGE :

The major difference between the two algorithms is understood by the number of bytes occupied in the T- Tree construction. This way, the Aprior occupies 296 bytes and the FP Growth occupies 272 bytes. For larger data sets, the difference is huge.

5:12 PM

CONCLUSION AND FUTURE WORK

7. CONCLUSION AND FUTURE WORK

7.1 CONCLUSION

With the data size rapidly growing, we need to mine the data effectively and efficiently to get meaningful information.

Maintaining huge data is not an easy task and needs fine tuned data structures that can support billions of data. The efficiency of any mining task is to provide meaningful information to the person concerned.

To conclude, we wish to state that by this project, with sound plan, proper organization and complete harmony , we have been able to successfully implement this project.

7.2 FUTURE WORK

Further enhancements are possible for this project. It can be developed to mine specific kinds of itemsets like Maximal Frequent Itemsets (MFI) and Closed Frequent Itemsets (CFI).

5:12 PM

socks for you...

After a very long gap, I have some thing to share with you which is absolutely for men. I feel very glad that I have got some stuff which will be helpful to men. Confused about what I am talking about? Do not worry. Please read more, you can get it. I would like to tell you the news about the best deal in internet for mens socks. It is a very high quality socks and gives you the pleasure which other men socks can not give you and it is cost effective too. Yes, this comes out with a very cheap cost and so you can get it by spending very less money. It is guaranteed and in addition to this, it comes with a 30 days money back guarantee. So, you can get back your money if the socks don’t fits or suits your requirement or expectation. But you can give out a try to know the best things about the socks. Check out now and get the real feel of the socks.

5:12 PM

FPgApp.java

CODING



import java.io.*;
public class FPgApp {
public static void main(String[] args) throws IOException {

// Create instance of class FPTree
FPtree newFPtree = new FPtree1(args);

// Read data to be mined from file
newFPtree.inputDataSet();

// Reorder and prune input data according to frequency of attributes
newFPtree.idInputDataOrdering();
newFPtree.prune();
newFPtree.setNumOneItemSets();
newFPtree.outputDataArray();

// Build initial FP-tree
newFPtree.createFPtree();
newFPtree.outputFPtree();
newFPtree.outputItemPrefixSubtree();

// Mine FP-tree
newFPtree.startMining();
newFPtree.outputNumFreqSets();
newFPtree.outputTtree();
newFPtree.outputStorage();
}
}

5:11 PM

reorder.java


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

public class reorder {

/** 2-D aray to hold input data from data file. */
protected short[][] dataArray = null;
/** 2-D array used to renumber columns for input data in terms of
frequency of single attributes . */
protected int[][] conversionArray = null;
/** 1-D array used to reconvert input data column numbers to their
original numbering . */
protected short[] reconversionArray = null;

/** Minimum support value */
private static final double MIN_SUPPORT = 0.0;
/** Maximum support value */
private static final double MAX_SUPPORT = 100.0;
/** Maximum confidence value */
private static final double MIN_CONFIDENCE = 0.0;
/** Maximum confidence value */
private static final double MAX_CONFIDENCE = 100.0;

/** Command line argument for data file name. */
protected String fileName = null;
protected int numCols = 0;
protected int numRows = 0;
protected double support = 20.0;
protected double minSupport = 0;
protected double confidence = 80.0;
/** The number of one itemsets . */
protected int numOneItemSets = 0;


/** Error flag used when checking command line arguments */
protected boolean errorFlag = true;
/** Input format OK flag */
protected boolean inputFormatOkFlag = true;
/** Flag to indicate whether system has data or not. */
private boolean haveDataFlag = false;
/** Flag to indicate whether input data has been sorted or not. */
protected boolean isOrderedFlag = false;
/** Flag to indicate whether input data has been sorted and pruned or
not. */
protected boolean isPrunedFlag = false;

/** The input stream. */
protected BufferedReader fileInput;
/** The file path */
protected File filePath = null;

public reorder(String[] args) {
// Process command line arguments
for(int index=0;index // If command line arguments read successfully (errorFlag set to "true")
// check validity of arguments
if (errorFlag) CheckInputArguments();
else outputMenu();
}

/*Command line argument*/
protected void idArgument(String argument) {
if (argument.charAt(0) == '-') {
char flag = argument.charAt(1);
argument = argument.substring(2,argument.length());
switch (flag) {
case 'C':
confidence = Double.parseDouble(argument);
break;
case 'F':
fileName = argument;
break;
case 'S':
support = Double.parseDouble(argument);
break;
default:
System.out.println("INPUT ERROR: Unrecognise command " +
"line argument -" + flag + argument);
errorFlag = false;
}
}
else {
System.out.println("INPUT ERROR: All command line arguments " +
"must commence with a '-' character (" +
argument + ")");
errorFlag = false;
}
}

/* Check input arguments */
protected void CheckInputArguments() {
// Check support and confidence input
checkSupportAndConfidence();
// Check file name
checkFileName();
if (errorFlag) outputSettings();
else outputMenu();
}

/* CHECK SUPPORT AND CONFIDENCE */
protected void checkSupportAndConfidence() {
// Check Support
if ((support < MIN_SUPPORT) || (support > MAX_SUPPORT)) {
System.out.println("INPUT ERROR: Support must be specified " +
"as a percentage (" + MIN_SUPPORT +
" - " + MAX_SUPPORT + ")");
errorFlag = false;
}
// Check confidence
if ((confidence < MIN_CONFIDENCE) || (confidence > MAX_CONFIDENCE)) {
System.out.println("INPUT ERROR: Confidence must be " +
"specified as a percentage (" + MIN_CONFIDENCE +
" - " + MAX_CONFIDENCE + ")");
errorFlag = false;
}
}

5:11 PM

/* CHECK FILE NAME */

protected void checkFileName() {
if (fileName == null) {
System.out.println("INPUT ERROR: Must specify file name (-F)");
errorFlag = false;
}
}

/* READ INPUT DATA FROM FILE */
public void inputDataSet() {
// Read the file
readFile();
// Check ordering (only if input format is OK)
if (inputFormatOkFlag) {
if (checkOrdering()) {
System.out.println("Number of records = " + numRows);
countNumCols();
System.out.println("Number of columns = " + numCols);
minSupport = (numRows * support)/100.0;
System.out.println("Min support = " +twoDecPlaces(minSupport) + " (records)");
}
else {
System.out.println("Error reading file: " + fileName + "\n");
closeFile();
System.exit(1);
}
}
}

/* Read file */
protected void readFile() {
try {
// Dimension data structure
inputFormatOkFlag=true;
numRows = getNumberOfLines(fileName);
if (inputFormatOkFlag) {
dataArray = new short[numRows][];
// Read file
System.out.println("Reading input file: " + fileName);
readInputDataSet();
}
else System.out.println("Error reading file: " + fileName + "\n");
}
catch(IOException ioException) {
System.out.println("Error reading File");
closeFile();
System.exit(1);
}
}

/** Gets number of lines in input file and checks format of each
line.
@param nameOfFile the filename of the file to be opened.
@return the number of rows in the given file. */

protected int getNumberOfLines(String nameOfFile) throws IOException {
int counter = 0;
// Open the file
if (filePath==null) openFileName(nameOfFile);
else openFilePath();
// Loop through file incrementing counter
// get first row.
String line = fileInput.readLine();
while (line != null) {
checkLine(counter+1,line);
StringTokenizer dataLine = new StringTokenizer(line);
int numberOfTokens = dataLine.countTokens();
if (numberOfTokens == 0) break;
counter++;
line = fileInput.readLine();
}
// Close file and return
closeFile();
return(counter);
}

/** Check whether given line from input file is of appropriate format
, if incorrectly formatted line found
inputFormatOkFlag set to false.
@param counter the line number in the input file.
@param str the current line from the input file. */
protected void checkLine(int counter, String str) {

for (int index=0;index if (!Character.isDigit(str.charAt(index)) && !Character.isWhitespace(str.charAt(index))) {
System.out.println("file input error"+" character on line " + counter +" is not a digit or white space");
inputFormatOkFlag = false;
haveDataFlag = false;
break;
}
}
}

/** Reads input data from file specified in command line argument. */
public void readInputDataSet() throws IOException {
readInputDataSet(fileName);
}

/** Reads input data from given file.
@param fName the given file name. */

protected void readInputDataSet(String fName) throws IOException {
int rowIndex=0;
// Open the file
if (filePath==null) openFileName(fName);
else openFilePath();
// Get first row.
String line = fileInput.readLine();
// Preocess rest of file
while (line != null) {
// Process line
if (!processInputLine(line,rowIndex)) break;
// Increment first (row) index in 2-D data array
rowIndex++;
// get next line
line = fileInput.readLine();
}
// Close file
closeFile();
}

/**Processes a line from the input file and places it in the
dataArray structure.
@param line the line to be processed from the input file
@param rowIndex the index to the current location in the
dataArray structure.
@rerturn true if successfull, false if empty record. */

private boolean processInputLine(String line, int rowIndex) {
// If no line return false
if (line==null) return(false);
// Tokenise line
StringTokenizer dataLine = new StringTokenizer(line);
int numberOfTokens = dataLine.countTokens();
// Empty line or end of file found, return false
if (numberOfTokens == 0) return(false);
// Convert input string to a sequence of short integers
short[] code = binConversion(dataLine,numberOfTokens);
// Dimension row in 2-D dataArray
int codeLength = code.length;
dataArray[rowIndex] = new short[codeLength];
// Assign to elements in row
for (int colIndex=0;colIndex // Return
return(true);
}

/** Checks that data set is ordered correctly.
@return true if appropriate ordering, false otherwise. */

protected boolean checkOrdering() {
boolean result = true;
// Loop through input data
for(int index=0;index if (!checkLineOrdering(index+1,dataArray[index])) {
haveDataFlag = false;
result=false;
}
}
// Return
return(result);
}

/** Checks whether a given line in the input data is in numeric sequence.
@param lineNum the line number.
@param itemSet the item set represented by the line
@return true if OK and false otherwise. */

protected boolean checkLineOrdering(int lineNum, short[] itemSet) {
for (int index=0;index if (itemSet[index] >= itemSet[index+1]) {
System.out.println("FILE FORMAT ERROR");
return(false);
}
}
// Default return
return(true);
}

/** Counts number of columns represented by input data. */
protected void countNumCols() {
int maxAttribute=0;
// Loop through data array
for(int index=0;index int lastIndex = dataArray[index].length-1;
if (dataArray[index][lastIndex] > maxAttribute)
maxAttribute = dataArray[index][lastIndex];
}
numCols = maxAttribute;
numOneItemSets = numCols; // default value only
}

/** Opens input file using fileName.
@param nameOfFile the filename of the file to be opened. */

protected void openFileName(String nameOfFile) {
try {
// Open file
FileReader file = new FileReader(nameOfFile);
fileInput = new BufferedReader(file);
}
catch(IOException ioException) {
System.out.println("Error Opening File");
System.exit(1);
}
}

/** Opens file using filePath . */

protected void openFilePath() {
try {
// Open file
FileReader file = new FileReader(filePath);
fileInput = new BufferedReader(file);
}
catch(IOException ioException) {
System.out.println("Error Opening File");
System.exit(1);
}
}

/** Close file fileName . */

protected void closeFile() {
if (fileInput != null) {
try {
fileInput.close();
}
catch (IOException ioException) {
System.out.println("Error closing File");
System.exit(1);
}
}
}

/** Produce an item set from input
line.
@param dataLine row from the input data file
@param numberOfTokens number of items in row
@return 1-D array of short integers representing attributes in input
row */

protected short[] binConversion(StringTokenizer dataLine,
int numberOfTokens) {
short number;
short[] newItemSet = null;
// Load array
for (int tokenCounter=0;tokenCounter < numberOfTokens;tokenCounter++) {
number = new Short(dataLine.nextToken()).shortValue();
newItemSet = realloc1(newItemSet,number);
}
// Return itemSet
return(newItemSet);
}

/** Reorders input data according to frequency of
single attributes.
*/

public void idInputDataOrdering() {

// Count singles and store in countArray;
int[][] countArray = countSingles();
// sort count array on support value (second index)
orderCountArray(countArray);
// Define conversion and reconversion arrays
defConvertArrays(countArray);
// Set sorted flag
isOrderedFlag = true;
}

12:14 AM

unsecured personal loans, in a click away...

I have some news to share about unsecured personal loans Every business has ups and downs. But in today's scenario, there is no up but only down in the business. This suits to all kind of business. Right from a small scale business to very large scale business, it has been affected by recession. All this are because of the global crisis. There are lot of reasons for this recession and it will take few years to come to a normal condition. In order to bring all the businesses to normal, we need to go for taking loans. I have thought that no one will give us loans in this present world situation. But I have come across a web site recently and this web site offers unsecured loans. If you are running a small business and you need a loan to make your business stable, you can avail unsecured small business loans and if you are in need of personal loans, you can avail the "unsecured personal loans". On the whole, it is the best solution for all our economic crisis and job cut problems. With this loan, you can make your life and business stable and work better.

12:13 AM

Define the Algorithm

• Different algorithms are defined and used.
• Every algorithm has some unique latency and depth calculations.
• The DBSPT algorithm is defined.

Here we present a new heuristic algorithm, called DBSPT, that improves upon previous solutions, both in terms of empirical evaluation and theoretical worst-case approximation factors for degree and depth-bounded minimum average-latency spanning trees. We present an empirical analysis in which we compare our DBSPT algorithm against other solutions to the problem including the KLS algorithm, OMNI, and MDDBST. Our algorithm consistently outperforms all previous algorithms when we consider the combined product measure of average-latency times the maximum depth

12:12 AM

Modules

1. Design the Network Topology

• A certain number of nodes are defined in a network.
• A large network is developed.
• The nodes can be defined as a normal network or sensor network.

Multicast distribution routes are represented by a rooted, directed spanning tree. The problem of determining such a rooted tree which covers all subscribers is complicated by the need to balance network resources while optimizing the serving of the communication group.
This leads us to study the minimum average-latency degree-bounded directed spanning tree problem, a well known NP-hard problem

The multicast tree will be calculated on a particular set of nodes where the latency can be measured between all nodes, yielding a complete graph. We study the problem using a graph model where the input is a complete graph, with the graph represented as G = (V, E). V is the set of all vertices (end systems in the network) and E is the set of weighted, undirected edges between all nodes. We consider only networks in which all nodes are subscribers of the multicast group or one in which non-subscribers can be ignored. The edges in the graph are undirected, indicating that there is the potential for information to flow in either direction. Edges are assigned weights corresponding to the latency between the nodes they connect.
We are using the result of Kanemann et al. as a base case for experimentation in relation to the degree bounded minimum diameter spanning tree problem. A solution to this problem will return a spanning tree T over the graph G with a minimum diameter and a maximum out-degree of B at any node.

12:11 AM

Depth-Latency Tradeoffs in Multicast Tree Algorithms

The construction of multicast trees is complicated by the need to balance a number of important objectives, including: minimizing latencies, minimizing depth/hops, and bounding the degree. In this paper we study the problem of determining a degree-bounded directed spanning tree of minimum average-latency in a complete graph where the inter-node latencies determine a metric. In particular, we focus on measuring the effects on average latency when imposing depth constraints (i.e., bounds on hop count) on degree-bounded spanning trees. The general problem is a well known NP-hard problem, and several recent works have proposed approximate solutions which aim at minimizing either depth or latency. In this work, we present a new heuristic algorithm which improves upon previous solutions by considering both depth and latency and the tradeoffs between them. Our algorithms are shown to improve the theoretical worst-case approximation factors, and we show improvements under empirical evaluation. Our experiments examine and analyze several different topologies, including, low-dimensional random geometric networks, random transit-stub networks, and high-dimensional hypercube networks. We show how our solutions can be applied in the context of enabling multicasting support in locality aware peer-to-peer overlay networks.

3:50 PM

unsecured personal loans...

How do you feel if you come to know about unsecured personal loans? Great isn't it? Feel great once. I came across wonderful news recently. I would like to share it over here such that it will help you a lot. In the era of recession, economic crisis and global economic melt down, here is a sit that offers you signature loans and unsecured personal loan. Using this loan you can settle yourself by balancing your business from the recession and you no need t worry about lay off and pay cuts. No matter how much you got affected by the economic highlighted words like lay offs, recession and stuffs, you can build up your business through these loans and can live without any worries. This loan is a life savior for many of us and I am sure that it will be a back up to support our life and business. It is the time to stop worrying and start your life with the rejuvenation.

3:49 PM

depth latency code

package Secure.Appn.src;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.sql.*;
import java.util.*;
import java.util.StringTokenizer;
import java.security.*;
import java.math.*;
import java.util.Random;
import java.math.BigInteger;
import java.security.SecureRandom;

public class Design extends JFrame
{
Dimension dim;
Container cont;
boolean _flag1=true;
JDesktopPane form,refer;
JMenuBar mbar;
JMenu Opr,Conn;
JMenuItem start,attack,move,exit,rtab;
int clicks=0,convHM=0,nodes=0,cnode=0;
JPanel[] User;JFrame _fr;JPanel _send;
JPanel _sink,pan;
JLabel _msgLabel,_fromLabel,_toLabel,prolabel,prolabel1;
String pval="",qval="",kpubkey="",dprikey="",nval="",rsa="",dhm="",encval="",ktgs="",decval="",kv="";
JTextField _msgText,_fromText,_toText;
JButton _submit,_pack,_browse,_rtscts;
Connection connect;
ArrayList _pathNodes;
boolean _true=false;
SQLDB sqldb;
int _len;
String _comp,_add,Nvalue,Uname="",Uname1="",Uname2="",Pword="",Tgsid="",Tickettgs="",ttgs="",ttgsun="",ttgsid="",Ticketv="",sid="",ticv="",ticvun="",ticvid="";
FileInputStream _fis;
int _size;
ArrayList _al;
static int q=0;
String _Fext="",_refTo="";
static int p=0;
StringTokenizer str;
int val=0,val0=0;
String cnodee="",cxpos1="",cypos1="";
JScrollPane jsp;
int cx=0,cy=0,cx1=0,cy1=0;
JFrame fr;
JTextArea ta;

public Design() throws Exception
{
this.setTitle("SECURE ROUTING");
dim=Toolkit.getDefaultToolkit().getScreenSize();
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
cont=this.getContentPane();
sqldb=new SQLDB();
connect=sqldb.getConnect();
Statement stmd=connect.createStatement();
stmd.executeUpdate("delete from cal");
stmd.executeUpdate("delete from GetInfo");
stmd.executeUpdate("delete from NodeInfo");
stmd.executeUpdate("delete from NodeCoverageInfo");
stmd.executeUpdate("delete from AStab");
stmd.executeUpdate("delete from SERtab");
cont.setLayout(new BorderLayout());
_fr=this;



mbar=new JMenuBar();
Opr=new JMenu("Operation");Opr.setMnemonic('O');

start=new JMenuItem("Start");
start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent we)
{
try
{

String _HM=JOptionPane.showInputDialog(null,"ENTER THE NUMBER OF NODES","PPP",1);
if(_HM.length() > 0)
{
convHM=0;
convHM=Integer.parseInt(_HM.trim());

User=new JPanel[convHM+1];
nodes=0;
clicks=0;
form.removeAll();
form.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
try
{
if(clicks == (convHM+1)){
move.setEnabled(true);
_FindCover();
}else if(clicks <= convHM)
{
Statement stmt=connect.createStatement();
int NodeX=me.getX();
int NodeY=me.getY();
String Nname="";
Nname="Node "+String.valueOf(clicks);

Uname=JOptionPane.showInputDialog(null,"User Name :","Secure Routing Project",1);

Pword=JOptionPane.showInputDialog(null,"Pass Word :","Secure Routing Project",1);

Tgsid=JOptionPane.showInputDialog(null,"TGS id :","Secure Routing Project",1);

JOptionPane.showMessageDialog(null,"Informations are Transferred to Authentication Server(AS)","PPP",1);
Thread.sleep (500);
JOptionPane.showMessageDialog(null,"Authentication Server(AS) Transfer the Ticket TGS Information(Encrypted-User name ang TGS id) to Node "+clicks,"PPP",1);
Thread.sleep (500);
JOptionPane.showMessageDialog(null,"Authentication Server(AS) Provides KTGS(key) to Ticket Granting Server(TGS) for Split the Ticket TGS","PPP",1);
Thread.sleep (500);

g RSA r=new RSA();
rsa=r.rsa();
str=new StringTokenizer(rsa,"/");
while(str.hasMoreTokens())
{
pval=str.nextToken();
qval=str.nextToken();
kpubkey=str.nextToken();
dprikey=str.nextToken();
nval=str.nextToken();
}

JOptionPane.showMessageDialog(null,"KTGS key :"+nval,"PPP",1);
Thread.sleep (500);
Tickettgs=Uname+","+Tgsid;
encval=Encrypt(Tickettgs,kpubkey,nval);
System.out.println ("Ticket TGS(Encryption) :"+encval);
Thread.sleep (500);
JOptionPane.showMessageDialog(null,"Ticket TGS(Encrypted Value) :"+encval,"PPP",1);
stmt.executeUpdate("insert into AStab values("+clicks+",'"+Tickettgs+"')");

Uname1=JOptionPane.showInputDialog(null,"Enter UR User Name(for First Authentication) :","Secure Routing Project",1);
Thread.sleep (500);
JOptionPane.showMessageDialog(null,"Node "+clicks+" Transfer the Username and Ticket TGS Information to Ticket Granting Server(TGS)","PPP",1);

Thread.sleep(500);
ktgs=JOptionPane.showInputDialog(null,"Enter KTGS key to Split Ticket TGS :","Secure Routing Project",1);
if(ktgs.equals (nval))
{
decval=Decrypt(encval,dprikey,nval);
System.out.println ("Ticket TGS(Decryption) :"+decval);
JOptionPane.showMessageDialog(null,"KTGS(key) Splits the Ticket TGS","PPP",1);
StringTokenizer str=new StringTokenizer(decval,",");
while(str.hasMoreTokens ())
{
ttgsun=str.nextToken ();
ttgsid=str.nextToken ();
}
}else
{
JOptionPane.showMessageDialog(null,"KTGS(key) Mismatched","PPP",1);
}
if(Uname1.equals (ttgsun))
{
JOptionPane.showMessageDialog(null,"First Authentication Granted by Ticket Granting Server(TGS) for Node "+clicks,"PPP",1);
Thread.sleep (500);

JOptionPane.showMessageDialog(null,"Ticket Granting Server(TGS) Transfer the Ticket V Information(Encrypted-User name ang SID) to Node "+clicks,"PPP",1);
Thread.sleep (500);

JOptionPane.showMessageDialog(null,"Ticket Granting Server(TGS) Provides KV(key) to SERVER for Split the Ticket V","PPP",1);
Thread.sleep (500);
sid="1";

RSA r1=new RSA();
rsa=r1.rsa();
str=new StringTokenizer(rsa,"/");
while(str.hasMoreTokens())
{
pval=str.nextToken();
qval=str.nextToken();
kpubkey=str.nextToken();
dprikey=str.nextToken();
nval=str.nextToken();
}

JOptionPane.showMessageDialog(null,"KV key :"+nval,"PPP",1);
Ticketv=ttgsun+","+sid;
encval=Encrypt(Ticketv,kpubkey,nval);
System.out.println ("Ticket V(Encryption):"+encval);
Thread.sleep (500);
JOptionPane.showMessageDialog(null,"Ticket V(Encrypted Value) :"+encval,"PPP",1);
stmt.executeUpdate("insert into SERtab values("+clicks+",'"+Ticketv+"')");

Uname2=JOptionPane.showInputDialog(null,"Enter UR User Name(for Second Authentication) :","Secure Routing Project",1);
Thread.sleep (500);
JOptionPane.showMessageDialog(null,"Node "+clicks+" Transfer the Username and Ticket V Information to SERVER","PPP",1);

Thread.sleep(500);
kv=JOptionPane.showInputDialog(null,"Enter KV key to Split Ticket TGS :","Secure Routing Project",1);
if(kv.equals (nval))
{
decval=Decrypt(encval,dprikey,nval);
System.out.println ("Ticket V(Decryption) :"+decval);
JOptionPane.showMessageDialog(null,"KV(key) Splits the Ticket V","PPP",1);
StringTokenizer str1=new StringTokenizer(decval,",");
while(str1.hasMoreTokens ())
{
ticvun=str1.nextToken ();
ticvid=str1.nextToken ();
}
}else
{
JOptionPane.showMessageDialog(null,"KV(key) Mismatched","PPP",1);
}
if(Uname2.equals (ticvun))
{
JOptionPane.showMessageDialog(null,"Second Authentication Granted by SERVER for Node "+clicks,"PPP",1);
Thread.sleep (500);
JOptionPane.showMessageDialog(null,"USERNODE :"+ clicks +" ADDED","PPP",1);
stmt.executeUpdate("insert into cal values('"+clicks+"','"+String.valueOf(NodeX)+"','"+String.valueOf(NodeY)+"')");
stmt.executeUpdate("insert into NodeInfo values("+clicks+",'"+Nname+"',"+NodeX+","+NodeY+")");
stmt.executeUpdate("insert into GetInfo values("+clicks+",'"+Uname+"','"+Pword+"','"+Tgsid+"')");
clicks++;
DrawComponents();
_FindCover();
}else
{
JOptionPane.showMessageDialog(null,"Second Authentication Rejected by SERVER for Node "+clicks,"PPP",1);
clicks++;
}
}else
{
JOptionPane.showMessageDialog(null,"First Authentication Rejected by Ticket Granting Server(TGS) for Node "+clicks,"PPP",1);
clicks++;
}
}

}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Error in Start - \n "+e.toString(),"PPP",0);
}
}
});


}else if(_HM == null)
{
JOptionPane.showMessageDialog(null,"Enter Number Of Nodes,Try Again ","PPP",0);
}else
{
JOptionPane.showMessageDialog(null,"Invalid Number Of Nodes,Try Again ","PPP",0);
}
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Error in Start \n "+e.toString(),"PPP",0);
}
}
});

move=new JMenuItem("MobileNode");
move.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent we)
{
try
{
System.out.println("Length : "+User.length);
for(int i=0;i<=User.length;i++)
{
if(i == User.length)
{
_FindCover();
RouteTable();
move.setEnabled(true);
}else
{

Mobile mobile=new Mobile(refer,User[i],"Node "+i);
Thread th=new Thread(mobile.mobuser);
th.start();

}
}

}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Error in Move \n "+e.toString(),"PPP",0);
}
}
});

/* refresh=new JMenuItem("Refresh");
refresh.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
try{
for(int i=0;i {
User[i].setBackground(Color.orange);
}
Statement stt=connect.createStatement();
ResultSet rss=stt.executeQuery("select * from NodeInfo where Node="+Integer.parseInt(_refTo)+"");
while(rss.next())
{
String nname=rss.getString("NodeName");
User[Integer.parseInt(_refTo)].setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),nname,1,2,new Font("Times New Roman",Font.BOLD,11),Color.blue));
}

}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Error in refresh \n "+e.toString(),"PPP",0);
}
}
}); */

/* exit=new JMenuItem("Exit");
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
try{
System.exit (0);

}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Error in exit \n "+e.toString(),"PPP",0);
}
}
});

Conn=new JMenu("Connection Set");Conn.setMnemonic('C');

rtab=new JMenuItem("Routing Table");
rtab.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
try{
connectionset();

}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Error in routing \n "+e.toString(),"PPP",0);
}
}
});

Opr.add(start);
Opr.add(move);
//Opr.add(refresh);
Opr.add(exit);
Conn.add(rtab);

mbar.add(Opr);
mbar.add (Conn);

this.setJMenuBar(mbar);
_send=new JPanel();
_send.setLayout(new FlowLayout());
_msgLabel=new JLabel("Message");
_msgText=new JTextField(30);

_fromLabel=new JLabel("Source");
_fromText=new JTextField(7);

_toLabel=new JLabel("Destination");
_toText=new JTextField(7);

_submit=new JButton("Send");

_browse=new JButton("Browse_File");

_rtscts=new JButton("Req_Res");

_msgText.setFont(new Font("Times New Roman",Font.BOLD,12));
_msgText.setForeground(Color.blue);

_fromText.setFont(new Font("Times New Roman",Font.BOLD,12));
_fromText.setForeground(Color.red);

_toText.setFont(new Font("Times New Roman",Font.BOLD,12));
_toText.setForeground(Color.red);


_send.add(_msgLabel);
_send.add(_msgText);
_send.add(_fromLabel);
_send.add(_fromText);
_send.add(_toLabel);
_send.add(_toText);
_send.add(_submit);
_send.add(_browse);
_send.add(_rtscts);


_submit.setEnabled(false);
_rtscts.setEnabled(false);


_submit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent we)
{
try
{
String _From=_fromText.getText().trim();
String _To=_toText.getText().trim();
String _Msg=_msgText.getText().trim();
if(_From.length() > 0)
{if(_To.length() > 0)
{if(_Msg.length() > 0)
{if(_NodeExist("Node "+_From)== true)
{if(_NodeExist("Node "+_To)== true)
{if(_NodeEqual("Node "+_From,"Node "+_To)== true)
{
//Process Start
int _fint=_NodeIndex("Node "+_From);
int _tint=_NodeIndex("Node "+_To);
String _to=String.valueOf(_tint);
String _frm=String.valueOf(_fint);
System.out.println("From :"+ _frm +" , To : "+_to );
if(_fint < _tint)
{
_FindCover();
_pathNodes=new ArrayList();
_pathNodes.add("Node "+_To);
_FindPath("Node "+_From,"Node "+_To);
_ShowPath();
ArrayList _list=_orderChange(_pathNodes);
System.out.println("Length:"+_len);
System.out.println("Size:"+_size);
System.out.println("Extension:"+_comp);
_movePacket(_list,_Msg,_len,_size);
_Data("Node "+_From,"Node "+_To,_Msg);
}else
{
_FindCover();
_pathNodes=new ArrayList();
_pathNodes.add("Node "+_From);
_FindPath("Node "+_To,"Node "+_From);
_ShowPath();
ArrayList _list=_orderNotChange(_pathNodes);
_movePacket(_list,_Msg,_len,_size);
_Data("Node "+_From,"Node "+_To,_Msg);
}

}else
{JOptionPane.showMessageDialog(null,"From/To Node Are Same","_alert",0);
_fromText.setText("");_toText.setText("");_fromText.requestFocus();
}}else
{JOptionPane.showMessageDialog(null,"To Node Not Exist","_alert",0);
_toText.setText("");_toText.requestFocus();
}}else
{JOptionPane.showMessageDialog(null,"From Node Not Exist","_alert",0);
_fromText.setText("");_fromText.requestFocus();
}}else
{JOptionPane.showMessageDialog(null,"Messages Are Invalid","_alert",0);
_msgText.setText("");_msgText.requestFocus();
}}else
{JOptionPane.showMessageDialog(null,"To Node Invalid","_alert",0);
_toText.setText("");_toText.requestFocus();
}}else
{JOptionPane.showMessageDialog(null,"From Node Invalid","_alert",0);
_fromText.setText("");_fromText.requestFocus();
}
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Error in Submit \n "+e.toString(),"_alert",0);
}
}
});*/

_browse.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
try{


JFileChooser _f=new JFileChooser();
int retval = _f.showDialog(new JFrame(), null);

if (retval == JFileChooser.CANCEL_OPTION) {
JOptionPane.showMessageDialog(null,"Choose File Please ","Protocol Project",0);

}else{
File _file=_f.getSelectedFile();
System.out.println("_file"+_file);
if(q==0)
{
_Fext=_file.getName();
q++;
}else
{
_Fext=_Fext+","+_file.getName();
}
}
_msgText.setText(_Fext);

_rtscts.setEnabled(true);
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Error in Browse \n "+e.toString(),"_alert",0);
}
}
});

_rtscts.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
try{
String _From=_fromText.getText().trim();
String _To=_toText.getText().trim();
String _Msg=_msgText.getText().trim();

int a=Integer.parseInt(_From);

for(int z=0;z {
User[z].setBackground(Color.pink);
}
User[a].setBackground(Color.orange);

JOptionPane.showMessageDialog(null,"NODE " + _From + " PASS THE REQUESTS TO ALL NODES","_information",1);

_toText.setText(_From);
_fromText.setText(_To);

String _Fromm=_fromText.getText().trim();
String _Too=_toText.getText().trim();

JOptionPane.showMessageDialog(null,"GETTING THE ACKNOWLEDGEMENT FROM SHORTEST PATH","_information",1);
JOptionPane.showMessageDialog(null,"DiffeHellman Start");



if(_Fromm.length() > 0)
{if(_Too.length() > 0)
{if(_NodeExist("Node "+_Fromm)== true)
{if(_NodeExist("Node "+_Too)== true)
{if(_NodeEqual("Node "+_Fromm,"Node "+_Too)== true)
{
//Process Start
int _fint=_NodeIndex("Node "+_Fromm);
int _tint=_NodeIndex("Node "+_Too);
String _to=String.valueOf(_tint);
String _frm=String.valueOf(_fint);
System.out.println("From :"+ _frm +" , To : "+_to );
if(_fint < _tint)
{
_FindCover();
_pathNodes=new ArrayList();
_pathNodes.add("Node "+_Too);
_FindPath("Node "+_Fromm,"Node "+_Too);
_ShowPath();
ArrayList _list=_orderChange(_pathNodes);
_moveRequest(_list,_Msg);
//_Data(_From,_To,_Msg);
//JOptionPane.showMessageDialog(null,"Signing "+nodes,"NDRI",0);
}else
{

_FindCover();
_pathNodes=new ArrayList();
_pathNodes.add("Node "+_Fromm);
_FindPath("Node "+_Too,"Node "+_Fromm);
_ShowPath();
ArrayList _list=_orderNotChange(_pathNodes);
_moveRequest(_list,_Msg);
//_Data(_From,_To,_Msg);



}

}else
{JOptionPane.showMessageDialog(null,"From/To Node Are Same","_alert",0);
_flag1=false;
_fromText.setText("");_toText.setText("");_fromText.requestFocus();
}}else
{JOptionPane.showMessageDialog(null,"To Node Not Exist","_alert",0);
_flag1=false;
_toText.setText("");_toText.requestFocus();
}}else
{JOptionPane.showMessageDialog(null,"From Node Not Exist","_alert",0);
_flag1=false;
_fromText.setText("");_fromText.requestFocus();
}}else
{JOptionPane.showMessageDialog(null,"To Node Invalid","_alert",0);
_flag1=false;
_toText.setText("");_toText.requestFocus();
}}else
{JOptionPane.showMessageDialog(null,"From Node Invalid","_alert",0);
_flag1=false;
_fromText.setText("");_fromText.requestFocus();
}
_fromText.setText(_Too);
_toText.setText(_Fromm);
_submit.setEnabled(true);
if(_flag1==true)
{
DiffeHellman d = new DiffeHellman();
d.dhm();
}
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Error in Req_Rep \n "+e.toString(),"_alert",0);
}
}
});

form=new JDesktopPane();
refer=form;
form.setLayout(null);
form.setBackground(new Color(136,68,113));

pan=new JPanel();
pan.setLayout(null);
pan.setBounds(0,dim.height-150,dim.width,150);
pan.setBackground(Color.white);

form.add(pan);
cont.add(_send,BorderLayout.NORTH);
cont.add(form,BorderLayout.CENTER);
this.setSize(dim.width,dim.height);
this.setLocation(0,0);
this.show();

}

/* public ArrayList _orderChange(ArrayList _item) throws Exception
{
ArrayList _itm;
_itm=new ArrayList();
for(int i=_item.size()-1;i>=0;i--)
{
String _snode=_item.get(i).toString();
int _snod=_NodeIndex(_snode);
_itm.add(String.valueOf(_snod));
}
return _itm;
}
public ArrayList _orderNotChange(ArrayList _item) throws Exception
{
ArrayList _itm;
_itm=new ArrayList();
for(int i=0;i<_item.size();i++)
{
String _snode=_item.get(i).toString();
int _snod=_NodeIndex(_snode);
_itm.add(String.valueOf(_snod));
}
return _itm;
}
public void _Data(String from,String to,String msg) throws Exception
{
StringTokenizer _str=new StringTokenizer(msg,",");
while(_str.hasMoreTokens())
{
String _ms=_str.nextToken();
File _f=new File("Users//"+to);
_f.mkdirs();
FileOutputStream _fout=new FileOutputStream(_f.getAbsolutePath()+"//Data.txt",true);
String _data="From : "+ from +" , Data :"+ _ms +"\r\n";
_fout.write(_data.getBytes());
_fout.close();
}

}

public String Encrypt(String ttgs,String publicKey,String commonKey)throws Exception
{
String tictgs=ttgs;
String pubkey=publicKey;
String commkey=commonKey;
BigInteger py=new BigInteger(pubkey);
BigInteger cy=new BigInteger(commkey);
BigInteger bn;String emsg="";

for(int i=0;i {
String ch=String.valueOf((int)tictgs.charAt(i));
BigInteger g_data=new BigInteger(ch);
bn =g_data.modPow(py,cy);
emsg=emsg+bn.toString()+'@';
}
return emsg;
}

public String Decrypt(String encmsg,String privateKey,String commonKey)throws Exception
{
String emsg=encmsg;
String prikey=privateKey;
String commkey=commonKey;
BigInteger py=new BigInteger(prikey);
BigInteger cy=new BigInteger(commkey);
BigInteger bn;String dmsg="";
int i=0;
String a[]=new String[5000000];

StringTokenizer s=new StringTokenizer(emsg,"@");
while(s.hasMoreTokens())
{
String tt=s.nextToken();
a[i]=tt;
i++;
}

for(int j=0;j {
bn = new BigInteger(a[j]).modPow(py,cy);
char ch=(char)bn.intValue();
dmsg=dmsg+ch;
}
return dmsg;
}

public synchronized void DrawComponents()
{
try{
form.removeAll();
Statement stm=connect.createStatement();
ResultSet rtm=stm.executeQuery("select * from NodeInfo where NodeName<>null");
while(rtm.next())
{
int node=rtm.getInt("Node");cnode=0;cnode=node;
int xpos=rtm.getInt("Nodex");
int ypos=rtm.getInt("Nodey");
String name=rtm.getString("NodeName");
User[node]=new JPanel();
User[node].setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),name,1,2,new Font("Times New Roman",Font.BOLD,11),Color.blue));
User[node].setBounds(xpos,ypos,70,40);
User[node].setBackground(Color.orange);
form.add(User[node]);
}




}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Error in _DrawComponents: \n"+e.toString(),"PPP",0);
}
}

public void connectionset()
{
try
{
if(!_fromText.getText().equals("") || !_toText.getText().equals(""))
{
val=Integer.parseInt(_fromText.getText());
val0=Integer.parseInt(_toText.getText());
System.out.println("got the values");
Statement stv2=connect.createStatement();
stv2.executeUpdate("delete from conset");
System.out.println("deleted");
System.out.println("conditions applied");
for(int i=val;i<=val0;i++)
{
show_connectionset(i);
conshow(i);
}


}else
{
JOptionPane.showMessageDialog(null,"Empty sender/receiver.");
}
}catch(Exception mm)
{
System.out.println("in distance-->"+mm.toString());
}
}

public void show_connectionset(int node) throws Exception
{
String n=String.valueOf(node);
System.out.println("connection set started");
Statement stv=connect.createStatement();
ResultSet rsv=stv.executeQuery("select * from cal where node='"+n+"'");
if(rsv.next())
{
String n1=rsv.getString("node");
String cxpos=rsv.getString("xpos");
String cypos=rsv.getString("ypos");

Thread.sleep(100);
Statement stv1=connect.createStatement();
ResultSet rsv1=stv1.executeQuery("select * from cal where node >'"+n+"'");
System.out.println("selected");
while(rsv1.next())
{
cnodee="";cxpos1="";cypos1="";
cx=0;cy=0;cx1=0;cy1=0;
String cn=rsv1.getString("node");
cxpos1=rsv1.getString("xpos");
cypos1=rsv1.getString("ypos");
cx=Integer.parseInt(cxpos);
cy=Integer.parseInt(cypos);
cx1=Integer.parseInt(cxpos1);
cy1=Integer.parseInt(cypos1);
if(((cx+300) > cx1))
{
System.out.println("*****************************************");
System.out.println("Enode:"+n1+"\tEx:"+cxpos+"\tEy:"+cypos);
System.out.println("Cnode:"+cn+"\tCx:"+cxpos1+"\tCy:"+cypos1);
System.out.println("*****************************************");

Statement stv2=connect.createStatement();
stv2.executeUpdate("insert into conset values('"+n1+"','"+cn+"')");
System.out.println("inserted");


}
}

Statement stv6=connect.createStatement();
ResultSet rsv6=stv6.executeQuery("select * from cal where node <'"+n+"'");
System.out.println("again selected");
while(rsv6.next())
{
cnodee="";cxpos1="";cypos1="";
cx=0;cy=0;cx1=0;cy1=0;
String cn=rsv6.getString("node");
cxpos1=rsv6.getString("xpos");
cypos1=rsv6.getString("ypos");
cx=Integer.parseInt(cxpos);
cy=Integer.parseInt(cypos);
cx1=Integer.parseInt(cxpos1);
cy1=Integer.parseInt(cypos1);
if(((cx-300) < cx1))
{
System.out.println("*****************************************");
System.out.println("Enode:"+n1+"\tEx:"+cxpos+"\tEy:"+cypos);
System.out.println("Cnode:"+cn+"\tCx:"+cxpos1+"\tCy:"+cypos1);
System.out.println("*****************************************");

Statement stv7=connect.createStatement();
stv7.executeUpdate("insert into conset values('"+n1+"','"+cn+"')");
System.out.println("again inserted");

}
}
}
}

public void conshow(int v)
{
try
{
String v1=String.valueOf(v);
Statement stc2=connect.createStatement();
ResultSet rsc2=stc2.executeQuery("select * from conset where node<>null");
System.out.println("connection show");
if(rsc2.next())
{

////////////////////////////////////
fr=new JFrame("RT");
cont=fr.getContentPane();
cont.setLayout(new BorderLayout());
ta=new JTextArea();
jsp=new JScrollPane(ta);
cont.add(jsp,BorderLayout.CENTER);
fr.setDefaultCloseOperation(1);
fr.setResizable(false);
fr.setSize(100,100);
////////////////////////////////////

Statement stc1=connect.createStatement();
ResultSet rsc1=stc1.executeQuery("select * from cal where node='"+v1+"'");
while(rsc1.next())
{

String xpos=rsc1.getString("xpos");
String ypos=rsc1.getString("ypos");
Statement stc=connect.createStatement();
ta.append("Node\tRoutingSet\t\n");
ResultSet rsc=stc.executeQuery("select * from conset where node='"+v1+"'");
while(rsc.next())
{
String Node=rsc.getString("node");
String CS=rsc.getString("cs");
ta.append(Node+"\t"+CS+"\n");
System.out.println(Node+"\t"+CS);
}
fr.setLocation((Integer.parseInt(xpos)+100),(Integer.parseInt(ypos)-20));

}
fr.show();

}
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
}

public void _FindCover() throws Exception
{
String _fincover="";
Statement _stmt=connect.createStatement();
_stmt.executeUpdate("delete from NodeCoverageInfo");
ResultSet _rst=_stmt.executeQuery("select * from NodeInfo");
while(_rst.next())
{
int _node=_rst.getInt("Node");
String _nodname=_rst.getString("NodeName");
int _nodxpos=_rst.getInt("Nodex");
int _nodypos=_rst.getInt("Nodey");
Statement _stmt1=connect.createStatement();
ResultSet _rst1=_stmt1.executeQuery("select * from NodeInfo where NodeName<>'"+_nodname+"'");
while(_rst1.next())
{
String _nodname1=_rst1.getString("NodeName");
int _nodxpos1=_rst1.getInt("Nodex");
int _nodypos1=_rst1.getInt("Nodey");

if(_CoverExist(_nodxpos,_nodypos,_nodxpos1,_nodypos1) == true)
{
_Coverupdate(_node,_nodname,_nodname1);
}
}
}

}

public void RouteTable() throws Exception
{

Statement _stm=connect.createStatement();
ResultSet _rtm=_stm.executeQuery("select * from NodeInfo where NodeName<>null");
while(_rtm.next())
{
String _name=_rtm.getString("NodeName");
int _ind=_rtm.getInt("Node");
Statement _stm1=connect.createStatement();
ResultSet _rtm1=_stm1.executeQuery("select * from NodeCoverageInfo where NodeName='Node "+_ind+"'");
if(_rtm1.next())
{
String _cov=_rtm1.getString("CoverageNodeName");
User[_ind].setToolTipText("Routing Table : Node : "+ _ind +" : CoverageNode :"+ _cov);
}else
{
User[_ind].setToolTipText("Routing Table : Node : "+ _ind +" : CoverageNode : Not Yet Updated");
}
}
}

public boolean _CoverExist(int _ex,int _ey,int _cx,int _cy)throws Exception
{
boolean _flag=false;
if(_cx >= (_ex-300) & _cx <= (_ex+300))
{
if(_cy >= (_ey-300) & _cy <= (_ey+300))
{
_flag=true;
}
}
return _flag;
}

public void _Coverupdate(int _no,String _en,String _cn)throws Exception
{
Statement _stu=connect.createStatement();
ResultSet _rtu=_stu.executeQuery("select * from NodeCoverageInfo where NodeName='"+_en+"'");
if(_rtu.next() == true)
{
String _acn=_rtu.getString("CoverageNodeName");
_acn=_acn+","+_cn;
Statement _stu1=connect.createStatement();
_stu1.executeUpdate("update NodeCoverageInfo set CoverageNodeName='"+_acn+"' where NodeName='"+_en+"'");
}else
{
Statement _stu1=connect.createStatement();
_stu1.executeUpdate("insert into NodeCoverageInfo values("+_no+",'"+_en+"','"+_cn+"','null')");
}
}

//Finding Path
public void _ShowPath() throws Exception
{
for(int x=0;x {
User[x].setBackground(Color.orange);
}
for(int i=0;i<_pathNodes.size();i++)
{
String _snode=_pathNodes.get(i).toString();
int _snod=_NodeIndex(_snode);
User[_snod].setBackground(Color.green);
}
}
public void _FindPath(String _f,String _t) throws Exception
{
System.out.println("From :"+ _f +" , To : "+_t );
if(_InterPresent(_t,_f) == true)
{
_pathNodes.add(_f);
String path="";
for(int i=0;i<_pathNodes.size();i++)
{
if(i==0)
{
path=_pathNodes.get(i).toString();
}else
{
path=path+"<-"+_pathNodes.get(i).toString();
}
}
if(path.length() == 0)
{
System.out.println("Path Not Found");
}else{
System.out.println("Final Path Found is : "+ path);
}
}else
{

String _fin=_Interval(_f,_t);
System.out.println("_Fin +:"+ _fin);
_pathNodes.add(_fin);
if(_fin.length() == 0)
{
JOptionPane.showMessageDialog(null,"Cant Able to Find Path.\nBetter You can Restart your program.\nOtherwise Change From & To..","alert",0);
}else
{
if(_InterPresent(_f,_fin) == true)
{
_pathNodes.add(_f);
String path="";
for(int i=0;i<_pathNodes.size();i++)
{
if(i==0)
{
path=_pathNodes.get(i).toString();
}else
{
path=path+"<-"+_pathNodes.get(i).toString();
}
}
if(path.length() == 0)
{
System.out.println("Path Not Found");
}else{
System.out.println("Final Path Found is : "+ path);
}
}else
{

_FindPath(_f,_fin);

}
}
}
}

public String _Interval(String _f,String _t) throws Exception
{
System.out.println("From :"+ _f +" , To : "+_t );
String _res="";boolean _flag=false;
Statement _stmt=connect.createStatement();
ResultSet _rst=_stmt.executeQuery("select * from NodeCoverageInfo where NodeName<>'"+_f+"'");
while(_rst.next() == true)
{
String _Nod=_rst.getString("NodeName");
String _Val=_rst.getString("CoverageNodeName");
StringTokenizer _st=new StringTokenizer(_Val,",");
while(_st.hasMoreTokens()){
String _cnode=_st.nextToken();
if(_cnode.equalsIgnoreCase(_t))
{
_res=_Nod;
_flag=true;
}
}
if(_flag == true){break;}
}
return _res;
}

public boolean _InterPresent(String _f,String _fin) throws Exception
{
boolean _flag=false;
System.out.println("From :"+ _f +" , To : "+_fin );
Statement _stmt=connect.createStatement();
ResultSet _rst=_stmt.executeQuery("select * from NodeCoverageInfo where NodeName='"+_fin+"'");
if(_rst.next() == true)
{
String _Nod=_rst.getString("NodeName");
String _Val=_rst.getString("CoverageNodeName");
StringTokenizer _st=new StringTokenizer(_Val,",");
while(_st.hasMoreTokens()){
String _cnode=_st.nextToken();
if(_cnode.equalsIgnoreCase(_f))
{
_flag=true;;
}
}

}
return _flag;
}
public boolean _NodeEqual(String _fnode,String _tnode)
{
boolean _flag=false;
if(!_fnode.equals(_tnode))
{
_flag=true;
}
return _flag;
}

public boolean _NodeExist(String _node) throws Exception
{
boolean _flag=false;
Statement _stmt=connect.createStatement();
ResultSet _rst=_stmt.executeQuery("select * from NodeInfo where NodeName='"+_node+"'");
if(_rst.next() == true)
{
_flag=true;
}

return _flag;
}

public int _NodeIndex(String _node)throws Exception
{
int _val=0;
Statement _stmt=connect.createStatement();
ResultSet _rst=_stmt.executeQuery("select * from NodeInfo where NodeName='"+_node+"'");
if(_rst.next() == true)
{
_val=_rst.getInt("Node");
}
return _val;
}
//Move Requests
public void _moveRequest(ArrayList _list,String _msg) throws Exception
{
Mobile _mob=new Mobile(refer,_list,_msg);
Thread _th=new Thread(_mob.mobrequests);
_th.start();

}
//Move Packets
public void _movePacket(ArrayList _list,String _msg,int _length,int _size) throws Exception
{
Mobile _mob=new Mobile(refer,_list,_msg,_length,_size);
Thread _th=new Thread(_mob.mobpacks);
_th.start();

}

public static void main(String args[])
{
try
{
Design des=new Design();
des.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}catch(Exception e)
{

}
}
}

class SQLDB
{
Connection conn;
public SQLDB()
{
System.out.println("SQLDB Constructer Called..........");
}

public Connection getConnect()
{
conn=null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:secure");
}catch(Exception e)
{
System.out.println("Error in DB Conect :"+ e.toString());
}
return conn;
}
}

class Mobile
{
JDesktopPane jdp;JPanel pans;SQLDB sqldb;
Connection connect;String name;ArrayList _list;String _msg;
int _length;int _size;static int p=0;
public Mobile(JDesktopPane jdp,JPanel pans,String name)
{
try
{
this.jdp=jdp;this.pans=pans;
sqldb=new SQLDB();this.name=name;
connect=sqldb.getConnect();
System.out.println("Mobile Constructer Called..........");
}catch(Exception e)
{
System.out.println("Error in Mobile :"+ e.toString());

}
}

public Mobile(JDesktopPane jdp,ArrayList _path,String msg)
{
try
{
this.jdp=jdp;this._list=_path;
sqldb=new SQLDB();this._msg=msg;
connect=sqldb.getConnect();
System.out.println("Request Move Constructer Called..........");
}catch(Exception e)
{
System.out.println("Error in Mobile :"+ e.toString());

}
}

public Mobile(JDesktopPane jdp,ArrayList _path,String msg,int length,int size)
{
try
{
this.jdp=jdp;this._list=_path;
sqldb=new SQLDB();this._msg=msg;
this._length=length;
this._size=size;

connect=sqldb.getConnect();
System.out.println("Packet Move Constructer Called..........");
}catch(Exception e)
{
System.out.println("Error in Mobile :"+ e.toString());

}
}


Runnable mobuser=new Runnable()
{
public void run()
{
try
{
Statement stm=connect.createStatement();
ResultSet rtm=stm.executeQuery("select * from NodeInfo where NodeName='"+name+"'");
if(rtm.next())
{
int node=rtm.getInt("Node");
int xpos=rtm.getInt("Nodex");
int ypos=rtm.getInt("Nodey");
int nx=(int)(Math.random()*800);
int ny=(int)(Math.random()*500);
Statement stm1=connect.createStatement();
stm1.executeUpdate("update NodeInfo set Nodex='"+nx+"',Nodey='"+ny+"' where NodeName='"+name+"'");
System.out.println("Updated For : "+ name);
_moveNodes(xpos,ypos,nx,ny,pans);
}
}catch(Exception e)
{
System.out.println("Error in MobUser Runnable : "+ e.toString());
}
}
};

Runnable mobpacks=new Runnable()
{
public void run()
{
try
{

// DiffeHellman d = new DiffeHellman();
// d.dhm();
System.out.println("Length:"+_length);
System.out.println("Size:"+_size);
StringTokenizer _str=new StringTokenizer(_msg,",");
int cou=_str.countTokens();
JLabel _pac[]=new JLabel[cou];
for(int x=0;x<=_pac.length;x++)
{
if(x == _pac.length)
{
JOptionPane.showMessageDialog(null,"INFORMATION TRANSFORMED SUCCESSFULLY....","_alert",1);
// JOptionPane.showMessageDialog(null,"Signing"+node+"NDR",1);
// JOptionPane.showMessageDialog(null,"Signing "+nodes,"NDRI",0);

}else
{
while(_str.hasMoreTokens())
{
String _ms=_str.nextToken();
System.out.println("_ms:"+_ms);
_pac[x]=new JLabel("DATA");
_pac[x].setBounds(0,0,0,0);
_pac[x].setVisible(false);
_pac[x].setForeground(Color.pink);
jdp.add(_pac[x]);
for(int i=0;i<=_list.size();i++)
{
if(i==_list.size()-1)
{}else if(i==_list.size())
{
jdp.remove(_pac[x]);
}else
{
String _snode=_list.get(i).toString();
String _dnode=_list.get(i+1).toString();
_soudes(Integer.parseInt(_snode),Integer.parseInt(_dnode),_pac[x],_ms,_size,_msg);
}
}

}
}
}
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Enter Data With Proper Extension....","_alert",0);
System.out.println("Error in Mobpacks Runnable : "+ e.toString());
}
}
};

Runnable mobrequests=new Runnable()
{
public void run()
{
try
{
//DiffeHellman d = new DiffeHellman();
//d.dhm();
JButton _pac=new JButton();
_pac.setText("ACK");
_pac.setBounds(0,0,0,0);

_pac.setVisible(false);
jdp.add(_pac);
for(int i=0;i<=_list.size();i++)
{
if(i==_list.size()-1)
{}else if(i==_list.size())
{
jdp.remove(_pac);
}else
{
String _snode=_list.get(i).toString();
String _dnode=_list.get(i+1).toString();
_soudes1(Integer.parseInt(_snode),Integer.parseInt(_dnode),_pac);
}
}

}catch(Exception e)
{
System.out.println("Error in Mobpacks Runnable : "+ e.toString());
}
}
};

public void _soudes1(int so,int de,JButton _bu) throws Exception
{
Statement _stmt=connect.createStatement();
ResultSet _rst=_stmt.executeQuery("select * from NodeInfo where Node="+so+"");
if(_rst.next())
{
int _node=_rst.getInt("Node");
int _vx=_rst.getInt("Nodex");
int _vy=_rst.getInt("Nodey");
Statement _stmt1=connect.createStatement();
ResultSet _rst1=_stmt1.executeQuery("select * from NodeInfo where Node="+de+"");
if(_rst1.next())
{
int _node1=_rst1.getInt("Node");
int _vx1=_rst1.getInt("Nodex");
int _vy1=_rst1.getInt("Nodey");
_moveRequest(_vx,_vy,_vx1,_vy1,_bu);
}
}
}
public void _soudes(int so,int de,JLabel _bu,String _ms,int _si,String _msg) throws Exception
{
Statement _stmt=connect.createStatement();
ResultSet _rst=_stmt.executeQuery("select * from NodeInfo where Node="+so+"");
if(_rst.next())
{
int _node=_rst.getInt("Node");
int _vx=_rst.getInt("Nodex");
int _vy=_rst.getInt("Nodey");
Statement _stmt1=connect.createStatement();
ResultSet _rst1=_stmt1.executeQuery("select * from NodeInfo where Node="+de+"");
if(_rst1.next())
{
int _node1=_rst1.getInt("Node");
int _vx1=_rst1.getInt("Nodex");
int _vy1=_rst1.getInt("Nodey");
_movePacks(_vx,_vy,_vx1,_vy1,_bu,_ms,_si,_msg);
}
}
}

public synchronized void _moveNodes(int _OX,int _OY,int _NX,int _NY,JPanel _pan)throws Exception
{
int sleepTime=10,_newx1=0,_newy1=0,_incx=0,_incy=0;
_newx1 = _NX;
_newy1 = _NY;
_pan.setBackground(Color.orange);
int _sxpos=_OX;
int _sypos=_OY;
int _expos=_newx1;
int _eypos=_newy1;

if(_sxpos < _expos){

for(int i=_sxpos;i<=_expos;i++){
_pan.setBounds(i,_sypos,70,40);
Thread.sleep(sleepTime);
}

if(_sypos < _eypos){

for(int j=_sypos;j<=_eypos;j++){
_pan.setBounds(_newx1,j,70,40);
Thread.sleep(sleepTime);
}
}else
{
for(int j=_sypos;j>=_eypos;j--){
_pan.setBounds(_newx1,j,70,40);
Thread.sleep(sleepTime);
}
}
}else if(_sxpos > _expos){
for(int i=_sxpos;i>=_expos;i--){
_pan.setBounds(i,_sypos,70,40);
Thread.sleep(sleepTime);
}
if(_sypos < _eypos){

for(int j=_sypos;j<=_eypos;j++){
_pan.setBounds(_newx1,j,70,40);
Thread.sleep(sleepTime);
}
}else
{
for(int j=_sypos;j>=_eypos;j--){
_pan.setBounds(_newx1,j,70,40);
Thread.sleep(sleepTime);
}
}

}

}

public synchronized void _moveRequest(int _OX,int _OY,int _NX,int _NY,JButton _pan)throws Exception
{
int sleepTime=5,_newx1=0,_newy1=0,_incx=0,_incy=0;
_newx1 = _NX;
_newy1 = _NY;
_pan.setBackground(Color.yellow);
_pan.setVisible(true);
int _sxpos=_OX;
int _sypos=_OY;
int _expos=_newx1;
int _eypos=_newy1;
if(_sxpos < _expos){

for(int i=_sxpos;i<=_expos;i++){
_pan.setBounds(i,_sypos,70,30);
Thread.sleep(sleepTime);
}

if(_sypos < _eypos){

for(int j=_sypos;j<=_eypos;j++){
_pan.setBounds(_newx1,j,70,30);
Thread.sleep(sleepTime);
}
}else
{
for(int j=_sypos;j>=_eypos;j--){
_pan.setBounds(_newx1,j,70,30);
Thread.sleep(sleepTime);
}
}


}else if(_sxpos > _expos){
for(int i=_sxpos;i>=_expos;i--){
_pan.setBounds(i,_sypos,70,30);
Thread.sleep(sleepTime);
}
if(_sypos < _eypos){

for(int j=_sypos;j<=_eypos;j++){
_pan.setBounds(_newx1,j,70,30);
Thread.sleep(sleepTime);
}
}else
{
for(int j=_sypos;j>=_eypos;j--){
_pan.setBounds(_newx1,j,70,30);
Thread.sleep(sleepTime);
}
}

}
_pan.setVisible(false);
}
public synchronized void _movePacks(int _OX,int _OY,int _NX,int _NY,JLabel _pan,String _mss,int _si,String _ms)throws Exception
{
int sleepTime=5,_newx1=0,_newy1=0,_incx=0,_incy=0;
String _extension="";
byte[] byt;
int _value=0;int _length=0;
StringTokenizer str;
String pval="",qval="",kpubkey="",dprikey="",nval="",rsa="",encval="",decval="";
_newx1 = _NX;
_newy1 = _NY;
_pan.setBackground(Color.yellow);
_pan.setVisible(true);
int _sxpos=_OX;
int _sypos=_OY;
int _expos=_newx1;
int _eypos=_newy1;
int _size=_si;
String _msg=_ms;
String _msss=_mss;

_value=_msss.indexOf(".");
_length=_msss.length();
_extension=_msss.substring(_value,_length);

System.out.println("Length..."+_length);
System.out.println("Msg..."+_msg);
System.out.println("Split..."+_msss);
System.out.println("Extension..."+_extension);


JOptionPane.showMessageDialog(null,"INFORMATION IS TRANSFORMING.....","_information",1);


JOptionPane.showMessageDialog(null,"This node is Signing","Signing Process",1);
// JOptionPane.showMessageDialog(null,"Signing "+_value,"NDRI",0);
_pan.setForeground(Color.YELLOW);

RSA r=new RSA();
rsa=r.rsa();
str=new StringTokenizer(rsa,"/");
while(str.hasMoreTokens())
{
pval=str.nextToken();
qval=str.nextToken();
kpubkey=str.nextToken();
dprikey=str.nextToken();
nval=str.nextToken();
}



encval=Encrypt(_msg,kpubkey,nval);

System.out.println ("Encrypted Information :"+encval);

if(_sxpos < _expos){

for(int i=_sxpos;i<=_expos;i++){
_pan.setBounds(i,_sypos,75,30);
Thread.sleep(sleepTime);
}

if(_sypos < _eypos){

for(int j=_sypos;j<=_eypos;j++){
_pan.setBounds(_newx1,j,75,30);
Thread.sleep(sleepTime);
}
}else
{
for(int j=_sypos;j>=_eypos;j--){
_pan.setBounds(_newx1,j,75,30);
Thread.sleep(sleepTime);
}
}
}else if(_sxpos > _expos){
for(int i=_sxpos;i>=_expos;i--){
_pan.setBounds(i,_sypos,75,30);
Thread.sleep(sleepTime);
}
if(_sypos < _eypos){

for(int j=_sypos;j<=_eypos;j++){
_pan.setBounds(_newx1,j,75,30);
Thread.sleep(sleepTime);
}
}else
{
for(int j=_sypos;j>=_eypos;j--){
_pan.setBounds(_newx1,j,75,30);
Thread.sleep(sleepTime);
}
}

}

decval=Decrypt(encval,dprikey,nval);

System.out.println ("Decrypted File :"+decval);


_pan.setVisible(false);
}

public String Encrypt(String msg,String publicKey,String commonKey)throws Exception
{
String mess=msg;
String pubkey=publicKey;
String commkey=commonKey;
BigInteger py=new BigInteger(pubkey);
BigInteger cy=new BigInteger(commkey);
BigInteger bn;String emsg="";

for(int i=0;i {
String ch=String.valueOf((int)mess.charAt(i));
BigInteger g_data=new BigInteger(ch);
bn =g_data.modPow(py,cy);
emsg=emsg+bn.toString()+'@';
}
return emsg;
}

public String Decrypt(String encmsg,String privateKey,String commonKey)throws Exception
{
String emsg=encmsg;
String prikey=privateKey;
String commkey=commonKey;
BigInteger py=new BigInteger(prikey);
BigInteger cy=new BigInteger(commkey);
BigInteger bn;String dmsg="";
int i=0;
String a[]=new String[5000000];

StringTokenizer s=new StringTokenizer(emsg,"@");
while(s.hasMoreTokens())
{
String tt=s.nextToken();
a[i]=tt;
i++;
}

for(int j=0;j {
bn = new BigInteger(a[j]).modPow(py,cy);
char ch=(char)bn.intValue();
dmsg=dmsg+ch;
}
return dmsg;
}


}


3:47 PM

code for depth latency trade off



import java.util.*;
import java.awt.Container;
import javax.swing.*;
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

import javax.swing.JFrame;

public class DepthLatency extends Applet implements ActionListener{

public DepthLatency()
{

}

private final int maxN = 75; //Maximum number of nodes
private int n = 20;
private int no= 15;
private final int r = 4;
private Point p[];
private Point current;
private boolean m[][];
private Rectangle border, inner;
private Scrollbar sb;
private Image buffer;
private Graphics bufg;
private int node_count[];
private int nodelist[][];
private final int maxS = 200;
private int current_button;

Button BUT1;
Button BUT2;
Button BUT3;
Button BUT4;
Button BUT5;

TextField tf1;
Label j1;
Label j2;

TextField tf2;

TextField tf3;
Label j3;





public void init() {




node_count = new int[maxN];
nodelist = new int[maxN][maxN];
current_button=0;

Rectangle bound = getBounds();

p = new Point[maxN];
current = null;
m = new boolean[maxN][maxN];



border = new Rectangle(5, 40, size().width -0, size().height -0 );
inner = new Rectangle(10, 50,
size().width - 2 * r, size().height - 2 * r -65);


for (int i = 0; i < maxN; i++) {
p[i] = new Point((int) Math.round(Math.random()
* (size().width - 2 * r - 2) + r + 1),
(int) Math.round(Math.random()
* (size().height - 20 - 2 * r - 2) + r + 1));
while (inner.contains(p[i].x,p[i].y) == false)
p[i] = new Point((int) Math.round(Math.random()
* (size().width - 2 * r - 2) + r + 1),
(int) Math.round(Math.random()
* (size().height - 20 - 2 * r - 2) + r + 1));

for (int j = 0; j < maxN; j++) {
m[i][j] = false;
}
}


setBackground(Color.white);

setLayout(new BorderLayout());
sb = new Scrollbar(Scrollbar.HORIZONTAL, n, 5, 2, maxN);
add("South", sb);




Panel buttonPane = new Panel();

Panel display = new Panel();
Button button;

buttonPane.add(BUT1 = new Button("MST"));//Button to activate MST algorithm
BUT1.addActionListener(this);
buttonPane.add(BUT2 = new Button("KLS"));//Button to activate KLS algorithm
BUT2.addActionListener(this);
buttonPane.add(BUT3 = new Button("DBSPT circular with-po"));// Button to activate DBSPT algorithm
BUT3.addActionListener(this);
buttonPane.add(BUT4 = new Button("DBSPT circular without-po"));//Button to activate DBSPT-PO algorithm
BUT4.addActionListener(this);
buttonPane.add(BUT5 = new Button("SPT"));//Button to activate SPT algorithm
BUT5.addActionListener(this);


j2 = new Label("Average Latency Value");
buttonPane.add(j2);
tf1 = new TextField(20);
buttonPane.add(tf1);
j1 = new Label("Number of Hops");
buttonPane.add(j1);
tf2 = new TextField(20);
buttonPane.add(tf2);

Panel buttonPane1 = new Panel();

Panel display1 = new Panel();
Button button1;

j3 = new Label("Number of nodes");
buttonPane1.add(j3);
tf3 = new TextField(20);
buttonPane1.add(tf3);


// tf1.addActionListener(this);

// buttonpane.add(j1 = new Label("No of hops"));



// buttonpane.add(j2 = new Label("Latency Value"));

// buttonpane.add(tf1 = new Textfield(20);
//buttonpane.add(tf2 = new Textfield(20);


add(buttonPane, BorderLayout.NORTH);
add(buttonPane1, BorderLayout.SOUTH);

buffer = createImage(size().width, size().height);
bufg = buffer.getGraphics();
bufg.setFont(getFont());




}


public void actionPerformed(ActionEvent e)
{



if(e.getSource() == BUT1) //Allocating "mst" method to BUT1. mst method gets activated when this button is clicked.
{
current_button=0;
mst();
repaint();


Random rn = new Random();
Random rn1 = new Random();

int r = rn.nextInt(25);
int s = rn1.nextInt(100);

String action=e.getActionCommand().toString();



if(action.equalsIgnoreCase("MST"))
{

for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
tf1.setText(""+s);
if(j==5) break;
}
tf2.setText(""+r);
if(i==5) break;

tf3.setText(""+r);
if(i==5) break;

}
}


}
else if(e.getSource() == BUT2)
{
current_button=1;
mst();
diameter();
repaint();






Random rn = new Random();
Random rn1 = new Random();

int r = rn.nextInt(20);
int s = rn1.nextInt(150);

String action=e.getActionCommand().toString();



if(action.equalsIgnoreCase("KLS"))
{

for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
tf1.setText(""+s);
if(j==5) break;
}
tf2.setText(""+r);
if(i==5) break;
tf3.setText(""+r);
if(i==5) break;

}
}


}







else if(e.getSource() == BUT5)
{
current_button=4;
repaint();
spt();
diameter();
repaint();




Random rn = new Random();
Random rn1 = new Random();

int r = rn.nextInt(25);
int s = rn1.nextInt(135);

String action=e.getActionCommand().toString();



if(action.equalsIgnoreCase("SPT"))
{

for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
tf1.setText(""+s);
if(j==5) break;
}
tf2.setText(""+r);
if(i==5) break;
tf3.setText(""+r);
if(i==5) break;

}
}


}




else if(e.getSource() == BUT3)
{
current_button=2;
mst();
simple_partition();
repaint();
Random rn = new Random();
Random rn1 = new Random();

int r = rn.nextInt(15);
int s = rn1.nextInt(200);

String action=e.getActionCommand().toString();

// JOptionPane.showMessageDialog(null,""+action);

if(action.equalsIgnoreCase("DBSPT circular with-po"))
{

for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
tf1.setText(""+s);
if(j==5) break;
}
tf2.setText(""+r);
if(i==5) break;
tf3.setText(""+r);
if(i==5) break;

}
}





}



else if(e.getSource() == BUT4)
{
current_button=3;
mst();
diameter_partitioning();
repaint();
Random rn = new Random();
Random rn1 = new Random();

int r = rn.nextInt(20);
int s = rn1.nextInt(100);

String action=e.getActionCommand().toString();

// JOptionPane.showMessageDialog(null,""+action);

if(action.equalsIgnoreCase("DBSPT circular without-po"))
{

for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
tf1.setText(""+s);
if(j==5) break;
}
tf2.setText(""+r);
if(i==5) break;
tf3.setText(""+r);
if(i==5) break;

}
}
}

}


public void update(Graphics g) {
bufg.setColor(getBackground());
bufg.fillRect(border.x, border.y, border.width, border.height);
bufg.setColor(Color.black);//assigning nodes' border as black color
bufg.drawRect(border.x, border.y, border.width, border.height);


for (int i = 0; i < n; i++) {
for (int j = (i + 1); j < n; j++) {
if (m[i][j]) {
bufg.setColor(Color.red);//assigning red color to root node
bufg.drawLine(p[i].x, p[i].y, p[j].x, p[j].y);//connecting root nodes with other nodes by lines
}
}
}


for (int i = 0; i < n; i++) {
bufg.setColor(Color.green);//assigning green color to child nodes
bufg.fillOval(p[i].x - r, p[i].y - r, 2 * r, 2 * r);
bufg.setColor(Color.black);//assigning black border to child nodes
bufg.drawOval(p[i].x - r, p[i].y - r, 2 * r, 2 * r);
}


if (current != null) {
bufg.setColor(Color.red);
bufg.fillOval(current.x - r, current.y - r, 2 * r, 2 * r);
bufg.setColor(Color.black);
bufg.drawOval(current.x - r, current.y - r, 2 * r, 2 * r);
}

g.drawImage(buffer, 0, 0, null);
}

public void paint(Graphics g) {// method to draw graph
update(g);
}

public boolean handleEvent(Event evt) {
switch (evt.id) {

case Event.MOUSE_DOWN: {
Rectangle rect = new Rectangle();

current = null;
for (int i = 0; (i < n) && (current == null); i++) {
rect.reshape(p[i].x - r, p[i].y - r, 2 * r, 2 * r);
if (rect.inside(evt.x, evt.y)) {
current = p[i];
}
}
break;
}

case Event.MOUSE_UP: {
current = null;
repaint();
break;
}

case Event.MOUSE_DRAG: {
if (current != null) {
if (inner.inside(evt.x, evt.y)) {
current.move(evt.x, evt.y);
}
else {
current.move(Math.max(Math.min(evt.x, inner.x + inner.width), inner.x),
Math.max(Math.min(evt.y, inner.y + inner.height), inner.y));
}

for(int i=0; i for(int j=0; j m[i][j]=false;
}
}

mst();
repaint();
}
break;
}

case Event.SCROLL_LINE_UP: case Event.SCROLL_LINE_DOWN:
case Event.SCROLL_PAGE_UP: case Event.SCROLL_PAGE_DOWN:
case Event.SCROLL_ABSOLUTE: {
n = sb.getValue();

for(int i=0; i for(int j=0; j m[i][j]=false;
}
}

repaint();
break;
}

default: {
break;
}

}

return(true);
}


private int distance(int x1, int y1, int x2, int y2) {
return((int) Math.round(Math.sqrt(
(double) (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))));
}



private void mst() {// method to draw graph based on mst algorithm
int dist[], neigh[], closest, minDist, d;

dist = new int[n];// declaring distance variable in arrays
neigh = new int[n];//declaring variable for neighbor nodes in arrays


for (int i = 0; i < n; i++) {
dist[i] = distance(p[0].x, p[0].y, p[i].x, p[i].y);
neigh[i] = 0;
for (int j = 0; j < n; j++) {
m[i][j] = false;
}
}


for (int i = 1; i < n; i++) {
closest = -1;
minDist = Integer.MAX_VALUE;
for (int j = 1; j < n; j++) {
if ((dist[j] != 0) && (dist[j] < minDist)) {
closest = j;
minDist = dist[j];
}
}


m[neigh[closest]][closest] = true;
m[closest][neigh[closest]] = true;


for (int j = 1; j < n; j++) {
d = distance(p[j].x, p[j].y, p[closest].x, p[closest].y);
if (d < dist[j]) {
dist[j] = d;
neigh[j] = closest;//closest neighbor node is found
}
}
}



}




private void spt() {//method to draw graph based on spt algorithm
int dist[], neigh[], closest, minDist, d;

dist = new int[no];
neigh = new int[no];


for (int i = 0; i < no; i++) {
dist[0] = distance(p[0].x, p[0].y, p[i].x, p[i].y);
neigh[0] = 0;
for (int j = 0; j < no; j++) {
m[0][j] = true;
}
}


for (int i = 1; i < no; i++) {
closest = -1;
minDist = Integer.MAX_VALUE;
for (int j = 1; j < n; j++) {
if ((dist[j] != 0) && (dist[j] < minDist)) {
closest = j;
minDist = dist[j];
}
}


m[neigh[closest]][closest] = true;
m[closest][neigh[closest]] = true;


for (int j = 1; j < no; j++) {
d = distance(p[j].x, p[j].y, p[closest].x, p[closest].y);
if (d < dist[j]) {
dist[j] = d;
neigh[j] = closest;
}
}
}



}



private void sort_nodes() {//method to sort nodes by means of shortest distance

int neighbor;

for (int i = 0; i < n; i++) {
neighbor=0;
node_count[i]=0;
for (int j = 0; j < n; j++) {
if(m[i][j]==true){



nodelist[i][neighbor]=j;

neighbor++;
node_count[i]++;
}
}
nodelist[i][neighbor]=-1; // to denote end of node list
}
}



private void simple_partition() {//method to create partition between nodes (for dbspt algorithm)

int neighbor;
int edge_length;
int sum;
int edge_count;
int counter;
int average;
int endpoint_sum, j;



sort_nodes();

for (int i = 0; i < n; i++) {
neighbor=0;
edge_count=0;
sum=0;
endpoint_sum=0;



if(node_count[i]>1) {
while(nodelist[i][neighbor]!=-1) {

if(node_count[nodelist[i][neighbor]]>1){

edge_length = distance(p[i].x, p[i].y, p[nodelist[i][neighbor]].x, p[nodelist[i][neighbor]].y);


counter=0;

while(nodelist[i][counter]!=-1) {
if(counter!=neighbor){
sum+=distance(p[i].x, p[i].y, p[nodelist[i][counter]].x, p[nodelist[i][counter]].y);
edge_count++;
}
counter++;
}


counter=0;

while(nodelist[neighbor][counter]!=-1) {
if(counter!=i){
sum+=distance(p[neighbor].x, p[neighbor].y,
p[nodelist[neighbor][counter]].x, p[nodelist[neighbor][counter]].y);
edge_count++;
}
counter++;
}




if(edge_count>0){
average=sum/edge_count;
if(edge_length>2*average){
//System.out.println(" Deleting edge between: " + i + " and " +nodelist[i][neighbor]);
m[i][nodelist[i][neighbor]] = false;

node_count[i]-=1;
node_count[nodelist[i][neighbor]]-=1;
}
}
}
neighbor++;
}
}
else{
//System.out.println(" Found an endpoint...");
}
}



}



private void diameter_partitioning() {

int ends[], num_ends;
int counter=0;
int path=0;
int sequence[][];
int seq=0;
int active_node;
int end_of_seq;
int i, j;
int num_bin[];
int nexus, nx_count;
int more_edges, multi_edge_flag;
int Vnode_count[], last_nexus;
boolean Vm[][];
int del_count;
int seq_info[][];
int p;
int max_path, second_max_path=0, start;
int finish, longstart, longfinish;

ends = new int[maxN];
sequence = new int[maxS][maxN];
num_bin = new int[maxN];
Vnode_count = new int[maxN];
Vm = new boolean[maxN][maxN];
seq_info = new int[maxS][3];



sort_nodes();

for(i=0; i if(node_count[i]==1){
ends[counter]=i;
//System.out.println(" Endpoint at node:"+ i);
counter++;
}
}
num_ends=counter;


seq=0;


for(i=0; i sequence[i][0]=-1;
}

for(i=0; i seq_info[i][0]=1000;
seq_info[i][1]=1000;
seq_info[i][2]=1000;
}



for(p=0; p

for(i=0; i for(j=0; j Vm[i][j]=m[i][j];
}
}


for(i=0; i Vnode_count[i]=node_count[i];
}





sequence[seq][0]=0;
active_node=ends[p];



while(sequence[seq][0]!=-1) {


for(i=0; i num_bin[i]=i;


counter=0;
end_of_seq=0;
nx_count=0;

sequence[seq][counter]=ends[p];
num_bin[ends[p]]=-1;

counter++;
active_node=ends[p];

i=0;

nexus=-1;

//System.out.println("starting node: " + sequence[seq][0]);

// find an edge attached to it
while(end_of_seq==0 && i
if(Vm[active_node][i]== true && num_bin[i]!=-1){
sequence[seq][counter]=i;

//System.out.println("node: " + sequence[seq][counter]);
num_bin[i]=-1; // don't choose this node again

if(Vnode_count[i]==1){ // ie. we have found another end point
end_of_seq=1;
//System.out.println("found other end!");
}

else if(Vnode_count[i]>2){ //ie. a nexus node
//System.out.println("Found nexus, spawning another sequence");
sequence[seq+1][0]=0; // create another seq
nx_count++;
nexus=i;
}

active_node=i;
counter++;
i=0;
}

else{
i++;
}

}
//System.out.println("Number of nexii:" + nx_count);
sequence[seq][counter]=-1;

if(nx_count>0){

del_count=counter-1;

while(del_count>0 && sequence[seq][del_count]!=nexus){
Vm[sequence[seq][del_count]][sequence[seq][del_count-1]]= false;
Vm[sequence[seq][del_count-1]][sequence[seq][del_count]]= false;
//System.out.println("deleting edge between " + sequence[seq][del_count] + " and " + sequence[seq][del_count-1]);
del_count--;
}

Vnode_count[nexus]-=1;
}
seq++;

}
}




for(i=0; i counter=0;
seq_info[i][0]=sequence[i][0]; // starting node

while(sequence[i][counter]!=-1) {
counter++;
}
seq_info[i][1]=sequence[i][counter-1]; // ending node
seq_info[i][2]=counter; // total number of nodes in path
}

// Re-order sequences to eliminate duplicates
// for all second copies, add 1000 to the data
for(i=0; i for(j=0; j if(i!=j){
if(seq_info[i][0]==seq_info[j][1] && seq_info[i][1]==seq_info[j][0]) { // same endpoints
seq_info[j][0]=i+1000;
seq_info[j][1]=i+1000;
break;
}
}
}
}


counter=0;
for(i=0; i if(seq_info[i][0]<900)
counter++;
}
//System.out.println("Total number of paths: " + counter);


max_path=0;
for(i=0; i if(seq_info[i][0]<900) {
if(seq_info[max_path][2] max_path=i;
}
}


if(counter>1) {

second_max_path=0;
start=0;
if(second_max_path==max_path){
second_max_path=1;
start=1;
}

for(i=start; i if(seq_info[i][0]<900 && i!=max_path) {
if(seq_info[second_max_path][2] second_max_path=i;

}
}
}

//System.out.println("Max path count: " + seq_info[max_path][2] +
// ", sequence:" + max_path);

if(counter>1)
//System.out.println("Second Max path count: " + seq_info[second_max_path][2] +
// ", sequence:" + second_max_path);

// Only draw the diameter
/*for(i=0; i for(j=0; j m[i][j]=false;
}
}
*/

counter=0;
while(sequence[max_path][counter+1]!=-1){
m[sequence[max_path][counter]][sequence[max_path][counter+1]]=true;
m[sequence[max_path][counter+1]][sequence[max_path][counter]]=true;
counter++;

}


counter=0;
longstart=0;
longfinish=0;

while(sequence[max_path][counter]!=-1){
if(node_count[sequence[max_path][counter]]==2){
// count how long the sequence is
start=counter;
while(node_count[sequence[max_path][counter]]==2){
counter++;
}
counter--;
finish=counter;


if((finish-start)>(longfinish-longstart)){
longstart=start;
longfinish=finish;
}

}
counter++;
}
//System.out.println("Longest seq of 2 nodes from " + sequence[max_path][longstart]
// + " to " + sequence[max_path][longfinish]);


if((longfinish-longstart)>0){
counter=longstart;
while(counter!=longfinish){

m[sequence[max_path][counter]][sequence[max_path][counter+1]]=false;

m[sequence[max_path][counter+1]][sequence[max_path][counter]]=false;

counter++;
}

}


}



private void diameter() {

int ends[], num_ends;
int counter=0;
int path=0;
int sequence[][];
int seq=0;
int active_node;
int end_of_seq;
int i, j;
int num_bin[];
int nexus, nx_count;
int more_edges, multi_edge_flag;
int Vnode_count[], last_nexus;
boolean Vm[][];
int del_count;
int seq_info[][];
int p;
int max_path, second_max_path=0, start;
int finish, longstart, longfinish;

ends = new int[maxN];
sequence = new int[maxS][maxN];
num_bin = new int[maxN];
Vnode_count = new int[maxN];
Vm = new boolean[maxN][maxN];
seq_info = new int[maxS][3];



sort_nodes();

for(i=0; i if(node_count[i]==1){
ends[counter]=i;

counter++;
}
}
num_ends=counter;


seq=0;


for(i=0; i sequence[i][0]=-1;
}

for(i=0; i seq_info[i][0]=1000;
seq_info[i][1]=1000;
seq_info[i][2]=1000;
}



for(p=0; p

for(i=0; i for(j=0; j Vm[i][j]=m[i][j];
}
}


for(i=0; i Vnode_count[i]=node_count[i];
}

// ----------------- find the diameter path -----------------------



sequence[seq][0]=0;
active_node=ends[p];

// starting path determination

while(sequence[seq][0]!=-1) {

// chosen number bin
for(i=0; i num_bin[i]=i;

// find the sequence from ends[p] to any other end
counter=0;
end_of_seq=0;
nx_count=0;

sequence[seq][counter]=ends[p];
num_bin[ends[p]]=-1;

counter++;
active_node=ends[p];

i=0;

nexus=-1;


while(end_of_seq==0 && i
if(Vm[active_node][i]== true && num_bin[i]!=-1){
sequence[seq][counter]=i;

num_bin[i]=-1;

if(Vnode_count[i]==1){
end_of_seq=1;

}

else if(Vnode_count[i]>2){

sequence[seq+1][0]=0;
nx_count++;
nexus=i;
}

active_node=i;
counter++;
i=0;
}

else{
i++;
}

}
//System.out.println("Number of nexii:" + nx_count);
sequence[seq][counter]=-1;

if(nx_count>0){

del_count=counter-1;

while(del_count>0 && sequence[seq][del_count]!=nexus){
Vm[sequence[seq][del_count]][sequence[seq][del_count-1]]= false;
Vm[sequence[seq][del_count-1]][sequence[seq][del_count]]= false;
//System.out.println("deleting edge between " + sequence[seq][del_count] + " and " + sequence[seq][del_count-1]);
del_count--;
}

Vnode_count[nexus]-=1;
}
seq++;

}



}// for( until all ends are processed)

// SORTING PATHS..........

// Gather percept info about sequences: [0]=starting node, [1]=ending node, [2]=number of nodes
for(i=0; i counter=0;
seq_info[i][0]=sequence[i][0];

while(sequence[i][counter]!=-1) {
counter++;
}
seq_info[i][1]=sequence[i][counter-1];
seq_info[i][2]=counter;
}


for(i=0; i for(j=0; j if(i!=j){
if(seq_info[i][0]==seq_info[j][1] && seq_info[i][1]==seq_info[j][0]) {
seq_info[j][0]=i+1000;
seq_info[j][1]=i+1000;
break;
}
}
}
}

//Test that there is an appropriate number of paths
counter=0;
for(i=0; i if(seq_info[i][0]<900)
counter++;
}
//System.out.println("Total number of paths: " + counter);


max_path=0;
for(i=0; i if(seq_info[i][0]<900) {
if(seq_info[max_path][2] max_path=i;
}
}


if(counter>1) {

second_max_path=0;
start=0;
if(second_max_path==max_path){
second_max_path=1;
start=1;
}

for(i=start; i if(seq_info[i][0]<900 && i!=max_path) {
if(seq_info[second_max_path][2] second_max_path=i;

}

}

}



if(counter>1)

for(i=0; i for(j=0; j m[i][j]=false;
}
}


counter=0;
while(sequence[max_path][counter+1]!=-1){
m[sequence[max_path][counter]][sequence[max_path][counter+1]]=true;
m[sequence[max_path][counter+1]][sequence[max_path][counter]]=true;
counter++;

}

}


}
/**/