Peer2Peer File Sharing System With Chat Using Java.
Peer2Peer File Sharing System With Chat Using Java.
By Nitika Sharma
CHAPTER NO.
TITLE
PAGE NO.
1.
INTRODUCTION
1.1 Types of Peer to Peer.............2 1.1.1 Unstructured P2P2 1.1.2 Centralized P2P.3 1.2 Applications.......3 1.3 Advantages.................................3 1.4 Objective ......4 1.5 Scope...4
5.
TECHNOLOGY TO BE USED
5.1 Introduction to Java....13 5.1.1 Java Virtual Machine...13 5.1.2 Principles..13 5.1.3 Versions....14 5.1.4 Features of Java Language..14 5.2 Multi Threading.........16 5.2.1 Benefits of using threads..17 5.2.2 Life Cycle of a Thread17 5.2.3 Thread Priority in Java.18 5.3 Socket Programming in Java...19 5.3.1 Ports and Sockets.20 5.4 Networking In Java.22
7. PROJECT PLANNING
7.1 7.2 7.3 Project Planning & Scheduling .26 Sotware Configuration Management.28 Problem Analysis.29
8. REQUIREMENT ANALYSIS
8.1 8.2 Requirement Analysis.30 Types of Requirements.32
10. MODULES
10.1 10.2 10.3 10.4 10.5 10.6 Create Main P2P Server ..38 Create Main P2P Client ...39 Create Miniserver & Miniclient 40 Manage Online or Offline User List...41 Sharing Files On P2P Network42 Receive Search Request On Server Side .43
5
Sharing Files On Peers & Sending Results Back ..44 Downloading File From Other Peer ...45 Peers Can Chat & Ask Other Peers To Share Files ..46
11. DESIGN
11.1 Design Phase..48
15.6.2 Shared Folder....68 15.6.3 To Download existing file..68 15.6.4 To Rename the file...69 Changing the Shared Path.....71 15.7 15.8 To Test the Speed...74 15.9 To View Attached Peers......77 15.10 To view Download History......79 15.11 To cancel Download80 15.12 Message Sending..83 15.13 Changing Themes86 15.14 Coding of client & inner classes.......88
12. FUTURE & FURTHER ENHANCEMENT OF PROJECT...........144 13. APPENDIX..145 14. BIBLIOGRAPHY147
Page No.
Thread Priority .............18
Figures
5.1 5.3 Life Cycle Of Thread...17 Socket Programming.....19
5.3.1 Connection request from Client....20 5.3.2 Connection Build From Server.......21 5.4 6.1 9.1 Ports help Computer to Identify service......22 SDLC Waterfall Model.....24 Client Server Interaction34
9.2.1 P2P Architecture.....36 11.1 Design Phase....48 12.1 Data Flow Diagrams Notations.50
CHAPTER 1
Page | 1
Peer-to-peer computing is the sharing of computer resources and services by direct exchange between systems. In a peer-to-peer architecture, computers that have traditionally been used solely as clients communicate directly among themselves and can act as both clients and a server, assuming whatever role is most efficient for the network. Another big attraction of file-sharing is cost : Users can download as many songs as they like from each other, for free. With the price of CDs often well over $20, many music-lovers have engaged in file-sharing despite the legal risks involved. Moreover, many consumers are loath to spend $20 for a compilation of songs when they are really only interested in one of the tracks on the CD. They may turn to file-sharing in order to download the one song that they want, without having to purchase the full CD.
1.1.2 Centralized peer-to-peer network: In this, central server is used for indexing
functions and to bootstrap the entire system. Although this has similarities with a structured architecture, the connections between peers are not determined by any algorithm.
1.2 Applications
Many file sharing networks, such as gnutella, G2 and the eDonkey network popularized peer to peer technologies. From 2004 on, such networks form the largest contributor of network traffic on the Internet. Peer-to-peer content delivery networks (P2P-CDN). Peer-to-peer content services, e.g. caches for improved performance such as Correli Caches. Software publication and distribution (Linux, several games) via file sharing networks.
1.3 Advantages
In P2P networks clients provide resources, which may include bandwidth, storage space and computing power. This property is one of the major advantages of using P2P networks because it makes the setup and running costs very small for the original content distributor. As nodes arrive and demand on the system increases, the total capacity of the system also increases, and the likelihood of failure decreases. If one peer on the network fails to function properly, the whole network is not compromised or damaged. In contrast, in a typical client server architecture, clients share only their demands with the system, but not their resources. In this case, as more clients join the system, fewer resources are available to serve each client, and if the central server fails, the entire network is taken down. The decentralized nature of P2P networks increases robustness because it removes the single point of failure that can be inherent in a client-server based system. Another important property of peer-to-peer systems is the lack of a system administrator. This leads to a network that is easier and faster to setup and keep running because a full staff is not required to ensure efficiency and stability. Decentralized networks introduce new security issues because they are designed so that each user is responsible for controlling their data and resources.A user may encounter harmful data by downloading a file that was originally uploaded as a virus disguised in an .exe, .mp3, .avi, or any other filetype.
Page | 3
1.4 Objective
The objective of the Project is to allow users to download media files such as music, movies, and games using a P2P software client that searches for other connected computers. The "peers" are computer systems connected to each other through the Internet. Thus, the only requirements for a computer to join peer-to-peer networks are an Internet connection and P2P software. The first generation of P2P software is Napster, a central server-based model that was eventually shut down. The second generation of P2P software is Gnutella and Kazaa ,which are user-based models. BitTorrent became the third generation of P2P networks. File transfers involve two computers, often designated as a client and a server and most operations are for the copying files from one machine to another.Most WEB and FTP servers are punished for being popular. Since all uploading is done from one central place, a popular site needs more resources (CPU and bandwidth) to be able to cope. With the use of P2P, the clients automatically mirror the files they download, easing the publisher's burden. Peer to Peer File Sharing System allows peers to search , download and upload files to other peers by just having the list of online clients from server. Peers manage on their own for downloading files.A chat feature is also added so that they can chat with their friends.
1.5 Scope
You can configure computers in peer to peer workgroups to allow sharing of files, printers and other resources across all of the devices. Peer networks allow data to be shared easily in both directions, whether for downloads to your computer or uploads from your computer. On the Internet, peer to peer networks handle a very high volume of file sharing traffic by distributing the load across many computers. Because they do not rely exclusively on central servers, P2P networks both scale better and are more resilient than client-server networks in case of failures or traffic bottlenecks. Peer to peer networking is common on small local area networks (LANs), particularly home networks. Both wired and wireless home networks can be configured as peer to peer environments. Computers in a peer to peer network run the same networking protocols and software. Peer networks are also often situated physically near to each other, typically in homes, small businesses or schools. Some peer networks, however, utilize the Internet and are geographically dispersed worldwide.
Page | 4
CHAPTER 2
FEATURES OF PROJECT
Page | 5
FEATURES OF PROJECT
There are several features of P2P file sharing system: 1. Creating Main P2P Server. 2. Creating Main P2P Client. 3. Creating Miniserver on P2P Client. 4. Creating Miniclient on P2P Client. 5. Manage online or offline user Lists in real time. 6. Sharing files on P2P Network. 7. Receive search request. 8. Search file on peers and sending results to other peer, who made search request. 9. Downloading File from other peer. 10. Uploading file to other. 11.Peers can change their Shared Path 12. Peers can chat and ask other peer to share files. 13. View Attached Peers. 14. To View the download history. 15. To check the link speed of uploading clients. 16.Peer can cancel downloading of the file. Last but not the least feature is : Peers can change the themes of client GUI according to their choice.
Page | 6
CHAPTER 3
Page | 7
CHAPTER 4
Page | 9
4.1 NETBEANS
NetBeans is an IDE (Interactive Development Environment) Software which has been used in this project to make the software. The NetBeans IDE is an open-source integrated development environment written entirely in Java using the NetBeans Platform. NetBeans IDE supports development of all Java application types out of the box. NetBeans is a user-friendly interactive software for Java based applications. This can be downloaded from the companys website for free. The advantage of using NetBeans is that we can build and run the project in same interface window. The NetBeans Platform allows applications to be developed from a set of modular software components called modules. A module is a Java archive file that contains Java classes written to interact with the NetBeans Open APIs and a manifest file that identifies it as a module. Applications built on modules can be extended by adding new modules. Since modules can be developed independently, applications based on the NetBeans platform can be extended by third party developers.. Using an Integrated Development Environment (IDE) for developing applications saves you time by managing windows, settings, and data. In addition, an IDE can store repetitive tasks through macros and abbreviations. Drag-and-drop features make creating graphical user interface (GUI) components or accessing databases easy, and highlighted code and debugging features alert you to errors in code. NetBeans provides the services common to creating desktop applications -- such as window and menu management, settings storage -- and is also the first IDE to fully support JDK 6.0 features. The NetBeans platform and IDE are free for commercial and noncommercial use, and they are supported by Sun Microsystems.
Automatic indentation, which is customizable Word matching with the same initial prefixes Navigation of current class and commonly used features Macros and abbreviations Goto declaration and Goto class Matching brace highlighting JumpList allows you to return the cursor to previous modification
Page | 11
CHAPTER 5
TECHNOLOGY TO BE USED
Page | 12
5.1.2 Principles
There were five primary goals in the creation of the Java language : It should be "simple, object-oriented and familiar" It should be "robust and secure" It should be "architecture-neutral and portable" It should execute with "high performance" It should be "interpreted, threaded, and dynamic"
Page | 13
5.1.3 Versions
Major release versions of Java, along with their release dates : JDK 1.0 (January 23, 1996) JDK 1.1 (February 19, 1997) J2SE 1.2 (December 8, 1998) J2SE 1.3 (May 8, 2000) J2SE 1.4 (February 6, 2002) J2SE 5.0 (September 30, 2004) Java SE 6 (December 11, 2006) Java SE 7 (July 28, 2011)
Good Performance : Interpretation of byte codes slowed performance in early versions, but advanced virtual machines with adaptive and just-in-time compilation and other techniques now typically provide performance up to 50% to 100% the speed of C++ programs. Threading : Lightweight processes, called threads, can easily be spun off to perform multiprocessing.Can take advantage of multiprocessors where available.Great for multimedia displays. Built-in Networking : Java was designed with networking in mind and comes with many classes to develop sophisticated Internet communications. Several features of C & C++ eliminated: No memory pointers No preprocessor Array index limit checking Features such as eliminating memory pointers and by checking array limits greatly help to remove program bugs. The garbage collector relieves programmers of the big job of memory management. These and the other features can lead to a big speedup in program development compared to C/C++ programming. Java I/O Routines : Java provides several tools for the input and output of data, ranging from the Abstract Window Toolkit (AWT) or the Swing Components to the core System functions of Java classes. The AWT is exactly what it says it is: a set of components for designing windows and graphical user interfaces that uses the peer components of the underlying operating system for their implementation. Streams : Java provides several different kinds of streams, each designed to handle a different kind of data. The standard input and output streams form the basis for all the others.InputStream and OutputStream are both available for you to use as is, or you can derive more complicated stream schemes from them. In order to create the other kinds of Java streams, first you must create and define the basic streams. Perhaps the most-used stream formats are the DataInputStream and the DataOutputStream. Both of these streams enable you to read or write primitive data types, giving you the flexibility within your application to control the results of your application's execution. Without this kind of functionality, you would have to write specific bytes rather than reading specific data. Input and Output Using System Class: One of the classes Java includes in every applet or application, whether you specify that it do so or not, is the System class. The System class
Page | 15
provides support for input/output (I/O) using the Java console; you are to provide the ability to write to the console, read from the console, and write errors to the user. The Java console is provided in two ways, one for browsers and one for applications. In the browser environment the console is a separate browser window that has controls for scrolling and clearing. For applications run from the operating system (OS) command line, the console is the text interface you see and suffers the same problems as the text base OS environment (lack of scrolling backwards Input Using the System Class Input in the System class is actually handled by the InputStream class contained in the Java I/O routines. System.in is an object of type InputStream that is created, maintained, and initialized by the System class. In other words, it's yours for the taking; you don't have to do a thing to use it. Output Using the System Class As with input, output is handled through streams. How can output be a stream if a stream is a sequence of characters from a source? Well, the source is your application, and the stream is routed to a device known as the standard output. The standard output is usually your monitor, but it could be other things as well. Most notably, the standard output is set to be the Java console when an applet runs within Netscape Navigator.
you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.
5.2.1 Benefits of using threads: The Java language includes a powerful threading facility
built into the language. The threading facility can be used to: Increase the responsiveness of GUI applications Take advantage of multiprocessor systems Simplify program logic when there are multiple independent entities Perform blocking I/O without blocking the entire program When multiple threads execute byte-code instruction sequences in the same program, that action is known as multithreading.
5.2.2 Life Cycle of a Thread : A thread goes through various stages in its life cycle. For
example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.
Page | 21
Figure 5.4: Ports help computers to identify which service data is for Advantages of Networking
Networking has a lot of advantages over traditional advertising and marketing. These are the most important advantages: More business : As you develop networking skills and contacts, youll find that the amount of work you get from referrals accounts for the largest part of your new business. And the most profitable. Better business : The business you get from referrals will usually be from happy customers. This will mean that your best customers, those who pay on time and without headaches, will be the ones who send you the additional business. Cost savings : As you get more business through referrals, youll find less and less need to advertise and market your business. This means less of the associated costs. And since youll be getting better quality business, it means less bad debts.
Page | 22
CHAPTER 6
Page | 23
The relationship of each stage to the others can be roughly described as a waterfall, where the outputs from a specific stage serve as the initial inputs for the following stage. During each stage, additional information is gathered or developed, combined with the inputs, and used to produce the stage deliverables.
Page | 24
Maintenance
Inevitably the system will need maintenance. Software will definitely undergo change once it is delivered to the customer. Change could happen because of some unexpected input values into the system. In addition, the changes in the system could directly affect the software operations. The software should be developed to accommodate changes that could happen during the post implementation period.
Page | 25
CHAPTER 7
Page | 26
Page | 27
Goals
The goals of SCM are generally: Configuration identification Identifying configurations, configuration items and baselines. Configuration control Implementing a controlled change process. This is usually achieved by setting up a change control board whose primary function is to approve or reject all change requests that are sent against any baseline. Configuration status accounting Recording and reporting all the necessary information on the status of the development process. Process management Ensuring adherence to the organizations development process.
Page | 28
Page | 29
CHAPTER 8
REQUIREMENT ANALYSIS
Page | 30
Eliciting requirements: the task of communicating with customers and users to determine what their requirements are. This is sometimes also called requirements gathering. Analyzing requirements: determining whether the stated requirements are unclear, incomplete, ambiguous, or contradictory, and then resolving these issues. Recording requirements: Requirements might be documented in various forms, such as natural-language documents, use cases, user stories, or process specifications
Architectural Requirements
Architectural requirements explain what has to be done by identifying the necessary system architecture of a system.
Structural Requirements
Structural requirements explain what has to be done by identifying the necessary structure of a system.
Behavioral Requirements
Behavioral requirements explain what has to be done by identifying the necessary behavior of a system.
Functional Requirements
Functional requirements explain what has to be done by identifying the necessary task, action or activity that must be accomplished. Functional requirements analysis will be used as the toplevel functions for functional analysis.
Non-functional Requirements
Non-functional requirements are requirements that specify criteria that can be used to judge the operation of a system, rather than specific behaviors.
Page | 32
CHAPTER 9
Page | 33
web servers, ftp servers, application servers, database servers, name servers, mail servers, file servers, print servers, and terminal servers. Most web services are also types of servers. In a traditional client/server setup, your home PC acts as a client and sends requests to machines- servers-- somewhere inside the cloud of the Internet to get things done: browsing the web or getting email. In a P2P paradigm, on the other hand, your home PC (for example) may connect, through the Internet, directly to tens or hundreds of other home PCs (or other machines at the 'edge') in order to share information and data. Some of the issues that need to be handled in such a situation include: Connectivity: how to find and connect other P2P nodes that are running in the network (unlike traditional servers, they don't have a fixed, known IP address) Instability: nodes may always be joining and leaving the network (unlike servers-- web, email, etc., which we usually depend on to "be there") Message routing: how messages should be routed to get from one node to another (where the two nodes may not directly know about each other) Searching (somewhat related to routing): how to find desired information from the nodes connected to the network
Page | 35
CHAPTER 10
MODULES
Page | 37
MODULES
.1
CLIENT 1
CLIENT 2
P2P SERVER WILL CONTAIN ALL THE INFORMATION ABOUT THE PEER
CLIENT 4
CLIENT 3
In this module, numbers of clients are connected to the main peer to peer server. In this, P2P server will contain all the information about the connected peer. In this module we have created a one main class P2PServerGUI in which we have two inner classes : p2pserver & client handler.
Page | 38
.2
Main Client
Main Client
Main Client
Main Client
In this, Main Clients are created and then connected to the P2P server. P2P server will contains the IP addresses of connected main clients. If the client will get offline then its IP address wil be remove from P2P sever GUI.
Page | 39
.3
Connection with Mini Client Main Server P2P SERVER (MAIN) Mini Server Channel for getting
MINI CLIENT - Basically for Connecting Two Another Peers. MINI SERVER - Service for other Peers to Connect.
In this module, we have P2P Main Client and P2P Main Server. Every client is itself a mini client and mini server. In mini server there is one miniserver request handler which will use the DataOutput Stream & DataInput Stream.It will help us in searching and downloading the file from other peer.
Page | 40
.4
Connected
192.168.137.21
192.168.137.21
Connected
192.168.137.78
192.168.137.78 -------------------------------------
Not Connected
192.168.137.99
In this module, P2P Main Server contains the list of IP addresses of connected users.P2P server will show the names of the user which are online and connected to the main server & does not contain the names of those user which are offline.
Page | 41
.5
P2P or Peer-to-peer file sharing allows users to download media files such as music, movies, and games using a P2P software client that searches for other connected computers. The only requirements for a computer to join peer-to-peer networks are an Internet connection and P2P software.
Page | 42
.6
192.168.137.21
192.168.137.78 -------------------------------------
(like 2.jpg)
Page | 43
.7
1)
192.168.137.21
1.) Search 1.mp3 4.) Send list of clients having the file Online Systems 2.) Do You have 1.mp3
192.168.137.78 192.168.137.21 192.168.137.78
Yes ------>
-------------------------------------
No ------->
In this, Client 1 searches for the file like one.mp3 from P2P main server and in response P2P main server sends list of clients having the file. If the other client will not have the file then message File not found will be shown on the side of requesting peer. If the peer have that specified copy or other related file ,then the files will be displayed on the Jtable.
Page | 44
.8
MAIN CLIENT
MINI CLIENT
Now Client 1 has the list of peers having searched file. Then Client 1 will get connected to mini server. Client can download file from other peer through mini server. Mini Server will upload file to other peer. The peer will select the file he/she need and start downloading it.If that file is already existing in their shared folder , miniserver will ask them file already exist do you want to download it and rename it
Page | 45
.9
Send text ( ask for file ) Main Client 1 Connected Send text ( chat text ) Main Client 2
To chat we have two clients Client 1 and Client 2 and they are connected to each other. Client 1 send text(ask for file), in response Client 2 send text(chat text file).Client1& Client 2 are connected to P2P server. In this module we will create a TextArea in our mainclient form .The text of textfield will be move to the selected IP and it will be displayed on other IP textfield.
Page | 46
CHAPTER 11
DESIGN
Page | 47
Requirements Document
DESIGN STAGE
Design Document
CHAPTER 12
Page | 49
12.1 INTRODUCTION
A data-flow diagram (DFD) is a graphical representation of the "flow" of data through an information system. DFDs can also be used for the visualization of data processing. On a DFD, data items flow from an external data source or an internal data store to an internal data store or an external data sink, via an internal process.A DFD provides no information about the timing or ordering of processes, or about whether processes will operate in sequence or in parallel. It is common practice to draw a context-level data flow diagram first, which shows the interaction between the system and external agents which act as data sources and data sinks. On the context diagram (also known as the Level 0 DFD) the system's interactions with the outside world are modeled purely in terms of data flows across the system boundary. The context diagram shows the entire system as a single process, and gives no clues as to its internal organization. This context-level DFD is next "exploded", to produce a Level 1 DFD that shows some of the detail of the system being modeled. The Level 1 DFD shows how the system is divided into subsystems, each of which deals with one or more of the data flows to or from an external agent, and which together provide all of the functionality of the system as a whole. It also identifies internal data stores that must be present in order for the system to do its job, and shows the flow of data between the various parts of the system.
Page | 50
CLIENT 2
CLIENT n
System requirement of our software is pretty low. Shared System performance of our software will be pretty high then other exiting systemsDownloading due to Files Files multithreading feature of java. P2P MAIN Our system is platform independent.
SERVER
Page | 51
CONNECTION TO
CLIENT
IP of Online Clients
MAIN SERVER
GET IP
CLIENT 1
CONNECT TO MINISERVE
SELECT FILES
SHARE FILES
Page | 52
Broadcast Search
CLIENT 2
CLIENT 1
MINI SERVER
Search Results
CLIENT n
DOWNLOAD
Page | 53
CHAPTER 13
P2P SERVER
CLIENT HANDLER
Page | 54
CLIENT
MINI SERVER
MINI CLIENT
SHARED PATH
CLIENT GUI
PEER INFO
HISTORY1
TEST SPEED
TESTING
Page | 55
CHAPTER 14
GANTT CHART
TIME TASK
Analysis System Design Coding Unit Testing Integration Testing System Testing Implementation
Page | 56
CHAPTER 15
Page | 57
Page | 58
On the Click of Start Button List of Online Peers will be display on server.
Page | 59
Page | 60
Page | 61
Page | 62
On Click of Getlist Button One Peer will get the list of other Online Peers
Page | 63
Page | 64
Page | 65
Page | 66
Page | 67
Page | 68
Page | 69
Downloading Complete
Page | 70
Page | 71
Page | 72
Page | 73
15.8 Testing the Speed of other peers so that one can decide from which peer he can download the file in less time and faster.
Page | 74
Page | 75
One can view others peers who are downloading files from his/her computer
Page | 76
Page | 77
Page | 78
Download History
Page | 79
Page | 80
Page | 81
Downloading Cancelled
Page | 82
Page | 83
Page | 84
Page | 85
Page | 86
Peacock Theme
Page | 87
import com.sun.org.apache.bcel.internal.generic.BREAKPOINT; import java.awt.Button; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import javax.swing.table.AbstractTableModel; import java.util.*; import java.net.*; import java.io.*; import java.text.DecimalFormat; import javax.swing.JOptionPane; import java.util.Date; import java.util.Calendar; import java.text.SimpleDateFormat; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; public class clientGUI extends javax.swing.JFrame {
Page | 88
ServerSocket sersock; ArrayList<String> al = new ArrayList<String>(); tablemodel tm; JLabel lb ; String speed3; ArrayList<SearchFiles> files = new ArrayList<SearchFiles>(); tablemodel1 tm1; String msg = ""; ArrayList<speed> sp1 = new ArrayList<speed>(); ArrayList<SearchFiles> upc = new ArrayList<SearchFiles>(); ArrayList<history> his=new ArrayList<history>(); tablemodel3 tm3 = new tablemodel3(); boolean searchRequest = false; boolean downloadRequest = false; boolean canceldownload=false; boolean test=false; boolean testDownloadingSpeed=false; boolean progressbar=false; client cl; miniclient mc; miniserver ms = new miniserver(); FileReader fr1; BufferedReader br1; String sharedpath;
Page | 89
searchpath sp; Socket sc4; String ip; String fileToDownload = ""; Long per; testspeed ts; tablemodel4 tm4 ; tablemodel5 tm5=new tablemodel5(); boolean view=false; boolean getlist=false; boolean MessageRequest=false; String text="c:\\shared"; public clientGUI( ) { Try { ip= JOptionPane.showInputDialog("enter the ip address of server"); if(ip!=null) { File f = new File("c:\\shared"); File f3=new File("e:\\download_history.txt"); File f4=new File("e:\\sharedpath.txt"); File test = new File("c:\\shared\\test1.exe"); int count3=0;
Page | 90
if (!(f.exists())) { JOptionPane.showMessageDialog(null, "folder shared doesnot not exist...so create it first"); f.mkdir(); } if(!(f3.exists())) { JOptionPane.showMessageDialog(null, "text document download history doesnot not exist...so create it first"); f3.createNewFile(); } if(!(f4.exists())) { JOptionPane.showMessageDialog(null, "sharedpath document doesnot not exist...so create it first"); f4.createNewFile(); BufferedWriter output = new BufferedWriter(new FileWriter(f4)); output.write(text); output.close(); } fr1 = new FileReader("e:\\sharedpath.txt"); br1 = new BufferedReader(fr1); sharedpath = br1.readLine(); fr1.close(); FileOutputStream test1= new FileOutputStream(test);
Page | 91
byte b[]=new byte[50*1024*1024]; test1.write(b); System.out.println("MY SHARED FOLDER IS : " + sharedpath); tm = new tablemodel(); tm1 = new tablemodel1(); initComponents(); jTable2.getColumnModel().getColumn(0).setCellRenderer(new CellModel()); setSize(1000, 800); setVisible(true); jpbar.setVisible(false); jLabeldw.setVisible(false); jLabel5.setVisible(false); jEditorPane1.setContentType("text/html"); FileReader fd=new FileReader("e:\\download_history.txt"); BufferedReader br3=new BufferedReader(fd); String filed; String sized; String ip2; String date2; while(true) { String fs=br3.readLine(); if(fs==null || fs.equals("")) {
Page | 92
break; } StringTokenizer sfs= new StringTokenizer(fs,";"); filed=sfs.nextToken(); ip2=sfs.nextToken(); sized=sfs.nextToken(); date2=sfs.nextToken(); his.add(new history(filed,ip2,sized,date2)); } tm5.fireTableDataChanged(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Cannot connect to server"); } } bt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btActionPerformed(evt); } }); getContentPane().add(bt); bt.setBounds(20, 60, 160, 40); jButton1.setFont(new java.awt.Font("Tahoma", 1, 12));
Page | 93
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/5617537541701984404.png"))); // NOI18N jButton1.setText("Get List"); jButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton1MouseClicked(evt); } }); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1); jButton1.setBounds(190, 60, 160, 40); getContentPane().add(j); j.setBounds(280, 280, 120, 0); jButton2.setFont(new java.awt.Font("Tahoma", 1, 12)); jButton2.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/images/check.gif"))); // NOI18N jButton2.setText("Check Mini Server"); jButton2.addActionListener(new java.awt.event.ActionListener() {
Page | 94
public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2); jButton2.setBounds(20, 310, 180, 40); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); jLabel1.setText("MINI SERVER STATUS : "); getContentPane().add(jLabel1); jLabel1.setBounds(210, 320, 190, 30); getContentPane().add(tfsearch); tfsearch.setBounds(390, 60, 240, 40); btsearch.setFont(new java.awt.Font("Tahoma", 1, 12)); btsearch.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/images/search.png"))); // NOI18N btsearch.setText("Search"); btsearch.setMaximumSize(new java.awt.Dimension(131, 41)); btsearch.setMinimumSize(new java.awt.Dimension(131, 41)); btsearch.setPreferredSize(new java.awt.Dimension(131, 41)); btsearch.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btsearchMouseClicked(evt);
Page | 95
} }); btsearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btsearchActionPerformed(evt); } }); getContentPane().add(btsearch); btsearch.setBounds(640, 60, 150, 40); jTable2.setModel(tm1); jTable2.setRowHeight(35); jScrollPane2.setViewportView(jTable2); getContentPane().add(jScrollPane2); jScrollPane2.setBounds(390, 110, 580, 190); btpath.setFont(new java.awt.Font("Tahoma", 1, 12)); btpath.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/images/1907449.png"))); // NOI18N btpath.setText("My shared path"); btpath.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btpathActionPerformed(evt);
Page | 96
}); getContentPane().add(jButton3); jButton3.setBounds(580, 310, 180, 40); btdh.setFont(new java.awt.Font("Tahoma", 1, 12)); btdh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/h5.jpg"))); // NOI18N btdh.setText("Download History"); btdh.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btdhActionPerformed(evt); } }); getContentPane().add(btdh); btdh.setBounds(770, 360, 200, 40); themes.setFont(new java.awt.Font("Tahoma", 1, 12)); themes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select Theme", "Baby Blue", "Aqua Green", "Plain Brown", "Pink Passion", "Abstract Blue ", "Peacock", "Stunningl Blue", "Amazing Cyan ", "Crazy Flowers" })); themes.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { themesActionPerformed(evt); }
Page | 97
}); getContentPane().add(themes); themes.setBounds(800, 20, 170, 30); jButton4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton4.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/images/delete_over.png") )); // NOI18N jButton4.setText("Cancel Download"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); getContentPane().add(jButton4); jButton4.setBounds(770, 410, 200, 40); jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/abcd.jpg"))); getContentPane().add(jLabel6); jLabel6.setBounds(0, 0, 990, 720); pack(); }// </editor-fold>//GEN-END:initComponents private void btActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_btActionPerformed cl = new client(ip); jLabel5.setVisible(true);
Page | 98
cl.pw.println("getlist"); cl.pw.flush(); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_jButton2ActionPerformed int n = jTable1.getSelectedRow(); if (n != -1) { miniclient mc = new miniclient(ip); } else { JOptionPane.showMessageDialog(null, "Select IP first !!!"); } }//GEN-LAST:event_jButton2ActionPerformed private void btsearchActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_btsearchActionPerformed if(getlist==false) { JOptionPane.showMessageDialog(null,"first click the start & getlist button"); } searchRequest = true;
Page | 99
for (int i = 0; i < al.size(); i++) { clientGUI.miniclient obj = new clientGUI.miniclient(al.get(i)); } }//GEN-LAST:event_btsearchActionPerformed private void btpathActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_btpathActionPerformed sp = new searchpath(this, sharedpath); }//GEN-LAST:event_btpathActionPerformed private void btdownloadActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_btdownloadActionPerformed try { int p; p = jTable2.getSelectedRow(); progressbar=true; canceldownload=false; if (p == -1) { JOptionPane.showMessageDialog(this, "Please select an item from list before sending download request"); } else { jpbar.setString("0 %"); downloadRequest = true;
Page | 100
fileToDownload = files.get(p).filename; miniclient mc = new miniclient(files.get(p).ipAddress); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Client is offline !!!"); } }//GEN-LAST:event_btdownloadActionPerformed private void btdownloadItemStateChanged(java.awt.event.ItemEvent evt) {//GENFIRST:event_btdownloadItemStateChanged // TODO add your handling code here: }//GEN-LAST:event_btdownloadItemStateChanged private void viewButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_viewButton3ActionPerformed peerinfo pinfo = new peerinfo(); }//GEN-LAST:event_viewButton3ActionPerformed private void btchatActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_btchatActionPerformed try { MessageRequest = true; int m; m = jTable1.getSelectedRow(); if (m != -1) {
Page | 101
String ip = al.get(m); clientGUI.miniclient obj = new clientGUI.miniclient(ip); } else { JOptionPane.showMessageDialog(null, "Please select an IP Address before sending message"); MessageRequest = true; } } catch (Exception ex) { ex.printStackTrace(); } }//GEN-LAST:event_btchatActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_jButton3ActionPerformed sp1.clear(); System.out.println("link speed object to be created"); testspeed ts=new testspeed(); }//GEN-LAST:event_jButton3ActionPerformed private void btdhActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_btdhActionPerformed history1 h1=new history1(); }//GEN-LAST:event_btdhActionPerformed private void themesActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_themesActionPerformed
Page | 102
int m; m=jTable2.getSelectedRow(); if (m == -1) { JOptionPane.showMessageDialog(this, " Start download first"); } else { int p=JOptionPane.showConfirmDialog(this, "Are you sure to cancel download", "cancel download",JOptionPane.OK_CANCEL_OPTION); if(p==JOptionPane.YES_OPTION) { progressbar=false; jpbar.setValue(0); jpbar.setVisible(false); jLabeldw.setVisible(false); canceldownload=true; JOptionPane.showMessageDialog(null, "Downloading is cancelled"); } if(p==JOptionPane.NO_OPTION) { canceldownload=false; } } } catch(Exception ex)
Page | 103
{ ex.printStackTrace(); } }//GEN-LAST:event_jButton4ActionPerformed public class client implements Runnable { Socket sock; Thread t1; BufferedReader brn, brk; PrintWriter pw; Thread t; String s; client(String ip) { Try { sock = new Socket(ip, 9000); brn = new BufferedReader(new InputStreamReader(sock.getInputStream())); pw = new PrintWriter(sock.getOutputStream()); brk = new BufferedReader(new InputStreamReader(System.in)); t = new Thread(this); t.start(); } catch (Exception e)
Page | 104
{ JOptionPane.showMessageDialog(null,"Cannot connected to server"); } } public void run() { try { while (true) { s = brn.readLine(); if (s.startsWith("SIZE")) { al.clear(); StringTokenizer st = new StringTokenizer(s); st.nextToken(); int size = Integer.parseInt(st.nextToken()); for (int i = 0; i < size; i++) { al.add(brn.readLine()); tm.fireTableDataChanged(); } } }
Page | 105
catch (Exception ex) { JOptionPane.showMessageDialog(null,"Main Server Is Not Running"); ex.printStackTrace(); } } } class tablemodel extends AbstractTableModel { String columns[] = {"IP Address"}; public String getColumnName(int c) { return (columns[c]); } Class columnstype[] = {String.class}; public Class getColumnClass(int i) { return columnstype[i]; } public int getColumnCount() { return 1; } public int getRowCount()
Page | 106
{ }
return al.size();
public Object getValueAt(int rowIndex, int columnIndex) { return al.get(rowIndex); } } class tablemodel1 extends AbstractTableModel { String title[] = {"FILE NAME", "IP ADDRESS", "FILE SIZE"}; @Override public String getColumnName(int m) { return title[m]; } public int getRowCount() { return files.size(); } public int getColumnCount() { return title.length; } public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { return files.get(rowIndex).filename; } else if (columnIndex == 1) { return files.get(rowIndex).ipAddress; } else {
Page | 107
return files.get(rowIndex).filesizekb; } } } class CellModel extends DefaultTableCellRenderer { JLabel lb = new JLabel(); ImageIcon icon; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (column == 0) { if (files.get(row).filename.endsWith(".jpg")) { icon = new ImageIcon(getClass().getResource("/images/jpg.png")); } else if (files.get(row).filename.endsWith(".exe")) { icon = new ImageIcon(getClass().getResource("/images/j.jpeg")); } else if (files.get(row).filename.endsWith(".pdf")) { icon = new ImageIcon(getClass().getResource("/images/pdf_icon.png")); } else if (files.get(row).filename.endsWith(".mp3")) { icon = new ImageIcon(getClass().getResource("/images/mp3.gif")); } else if (files.get(row).filename.endsWith(".doc")) { icon = new ImageIcon(getClass().getResource("/images/doc.png")); } else if (files.get(row).filename.endsWith(".mp4")) { icon = new ImageIcon(getClass().getResource("/images/mp4.gif")); } else if (files.get(row).filename.endsWith(".txt")) {
Page | 108
icon = new ImageIcon(getClass().getResource("/images/download.jpg")); } lb.setIcon(icon); lb.setText(files.get(row).filename); //lb.setOpaque(true); } else if (column == 1) { lb.setText(files.get(row).ipAddress); lb.setOpaque(true); } else { lb.setText(files.get(row).filesizekb); lb.setOpaque(true); } return lb; } } public class miniserver implements Runnable { Thread t1; Socket sc; miniserver() { t1 = new Thread(this); t1.start(); }
Page | 109
public void run() { try { sersock = new ServerSocket(9600); System.out.println("MiniServer started"); while (true) { sc = sersock.accept(); miniserver_requesthandler msrh = new miniserver_requesthandler(sc); System.out.println("Object of miniserver build"); } } catch (Exception ex) { ex.printStackTrace(); } } public class miniserver_requesthandler implements Runnable { Thread t2; Socket sc1; DataOutputStream dos; DataInputStream dis; String s;
Page | 110
miniserver_requesthandler(Socket sc1) { try { System.out.println("mini_server request handler constructor"); this.sc1 = sc1; dos = new DataOutputStream(this.sc1.getOutputStream()); dis = new DataInputStream(this.sc1.getInputStream()); t2 = new Thread(this); t2.start(); } catch (Exception ex) { ex.printStackTrace(); } } public void run() { try { String s3; System.out.println("In miniserver run mehtod"); s = dis.readLine(); System.out.println("Read first line in miniserver : " + s);
Page | 111
if (s.equals("check miniserver")) { dos.writeBytes("mini server is running\r\n"); dos.flush(); } String s1 = ""; while (true) { s1 = dis.readLine(); if(s1==null) break; System.out.println("Read second line : " + s1); if (s1.startsWith("search")) { StringTokenizer st = new StringTokenizer(s1, ","); st.nextToken(); String strToSearch = st.nextToken(); System.out.println("File to search is : " + strToSearch); File f = new File(sharedpath); String files[] = f.list(); System.out.println("Total files searched : " + files.length); int count = 0; for (int i = 0; i < files.length; i++) {
Page | 112
if (files[i].indexOf(strToSearch) != -1) { count++; } } dos.writeBytes("SIZE " + count + "\r\n"); dos.flush(); int i; if (count > 0) { for (i = 0; i < files.length; i++) { if (files[i].indexOf(strToSearch) != -1) { dos.writeBytes(files[i] + "\r\n"); dos.flush(); File file2 = new File(sharedpath + "\\" + files[i]); long fileSize = file2.length(); dos.writeLong(fileSize); dos.flush(); } } } break;
Page | 113
} else if (s1.startsWith("download")) { FileInputStream fis; System.out.println("In download block"); Try { int r; StringTokenizer str2 = new StringTokenizer(s1, ","); str2.nextToken(); String strdw = str2.nextToken(); long size1; String read; long size; System.out.println("Request at miniserver : " + strdw); if(strdw.equals("test1.exe")) { File test=new File("c:\\shared\\test1.exe"); fis = new FileInputStream(test); size=test.length(); dos.writeLong(size); } else {
Page | 114
File f = new File(sharedpath + "\\" + strdw); size = f.length(); fis = new FileInputStream(f); dos.writeLong(size); dos.flush(); } if(size<1024) { read=size+"bytes"; } else if(size<1048576) { read =(float) (size / 1024)+ "kb"; } else if(size<1024*1024*1024) { read = (int) (size / 1024*1024)+"mb"; } else { read = (float) (size / 1024*1024*1024)+"gb"; } upc.add(new SearchFiles(strdw, sc.getInetAddress().getHostAddress(), read )); tm3.fireTableDataChanged();
Page | 115
byte b[] = new byte[1024 * 1024]; long count = 0; while (true) { r = fis.read(b, 0, 1024 * 1024); dos.write(b, 0, r); dos.flush(); count = count + r; if (count == size) { break; } } fis.close(); System.out.println("File send "); for (int i = 0; i < upc.size(); i++) { if ((upc.get(i).filename).equals(strdw)) { upc.remove(i); tm3.fireTableDataChanged(); break; } }
Page | 116
} catch (Exception ex) { ex.printStackTrace(); } break; } else if (s1.startsWith("sending message from,")) { StringTokenizer mp = new StringTokenizer(s1, ","); mp.nextToken(); msg = msg + "<h3 color=\"blue\">Message from</h3>" + sc1.getInetAddress().getHostAddress() + "\n" + mp.nextToken() + "\n\n"; jEditorPane1.setText(msg); } } } catch (Exception ex) { ex.printStackTrace(); } } } } public class miniclient implements Runnable
Page | 117
{ Socket sc3; Socket sc4; PrintWriter pw1; DataInputStream dis; DataOutputStream dos; Thread t; String ip; int index; long flength; double speed1; FileWriter fw; String history; miniclient(String ip) { try { this.ip = ip; sc3 = new Socket(this.ip, 9600); System.out.println("Connection build with miniserver..."); dis = new DataInputStream(sc3.getInputStream()); dos = new DataOutputStream(sc3.getOutputStream()); dos.writeBytes("check miniserver\r\n"); dos.flush(); t = new Thread(this); t.start();
Page | 118
} catch (Exception ex) { ex.printStackTrace(); } } public void run() { if(progressbar==true) { jpbar.setBackground(Color.WHITE); jpbar.setForeground(Color.BLUE); jpbar.setStringPainted(true); } boolean b1 = true; try { long start = System.currentTimeMillis(); System.out.println(start); String s = dis.readLine(); if (s.equals("mini server is running")) { jLabel1.setText("MINI SERVER IS RUNNING"); } if (searchRequest == true) { files.clear();
Page | 119
String str = tfsearch.getText().trim(); if (str.equals("") || str == null) { JOptionPane.showMessageDialog(null, "Write proper string first"); } else { dos.writeBytes("search," + str + "\r\n"); dos.flush(); String res = dis.readLine(); { StringTokenizer st = new StringTokenizer(res); st.nextToken(); int size = Integer.parseInt(st.nextToken()); if (size == 0) { System.out.println("not found"); JOptionPane.showMessageDialog(null, "File not found!!"); } else { for (int i = 0; i < size; i++) { String filename = dis.readLine();
Page | 120
flength = (dis.readLong()); if (flength >= 1024 && flength < 1024 * 1024) { flength = (long) (flength / 1024); files.add(new SearchFiles(filename, ip, flength + " KB") } else if (flength >= 1024 * 1024 && flength < 1024 * 1024 * 1024) { flength = (long) (flength / (1024 * 1024)); files.add(new SearchFiles(filename, ip, flength + " MB")); } else if (flength >= 1024 * 1024 * 1024 && flength < 1024 * 1024 * 1024 * 1024) { flength = (long) (flength / (1024 * 1024 * 1024)); files.add(new SearchFiles(filename, ip, flength + " GB")); } else { files.add(new SearchFiles(filename, ip, flength + " bytes")); } tm1.fireTableDataChanged(); } } }
Page | 121
} searchRequest = false; } if (downloadRequest == true) { jpbar.setVisible(true); jpbar.setValue(0); dos.writeBytes("download," + fileToDownload + "\r\n"); dos.flush(); long start1 = System.currentTimeMillis(); long size = dis.readLong(); byte b[] = new byte[1024 * 1024]; long count = 0; int r; int p; String m; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:MM:SS"); Date date = new Date(); String d= dateFormat.format(date); p = jTable2.getSelectedRow(); FileOutputStream fos; fileToDownload = files.get(p).filename; String ipadd=files.get(p).ipAddress; int u = fileToDownload.lastIndexOf(".");
Page | 122
String ext = fileToDownload.substring(u); boolean flag1 = false; File f1 = new File(sharedpath +"\\"+fileToDownload); long dwnld; if (f1.exists()) //logic if same file already exists { int n; n = JOptionPane.showConfirmDialog(null, "do you want to download existing file", null, JOptionPane.YES_NO_OPTION); if (JOptionPane.NO_OPTION == n) { JOptionPane.showMessageDialog(null, "no we don't want to download"); } else if (JOptionPane.YES_OPTION == n) //downloading Logic to replace file { int p1 = JOptionPane.showConfirmDialog(null, "do you want to rename the existing file", null, JOptionPane.YES_NO_OPTION); if (JOptionPane.YES_OPTION == p1) { String name = JOptionPane.showInputDialog("Rename", fileToDownload.substring(0, u)); if (name == null) { flag1 = true; } else { f1 = new File(sharedpath + "\\" + name + ext); } fos = new FileOutputStream(sharedpath + "\\" + name + ext);
Page | 123
while (true) { if(canceldownload==true) { break; } r = dis.read(b, 0, 1024 * 1024); count = count + r; fos.write(b, 0, r); dwnld = System.currentTimeMillis(); double diff = (dwnld - start) / 1000.0; double speed = count / diff; if(progressbar==true) {jpbar.setValue(0); per = (count * 100 / size); jpbar.setEnabled(downloadRequest); jpbar.setValue((int) (count * 100 / size)); jpbar.setString(per + "% complete"); jLabeldw.setVisible(true); if (speed <= 1024) { jLabeldw.setText("Speed is " + speed + "bps"); } if (speed > 1024 && speed <= 1024 * 1024) { jLabeldw.setText("Speed is " + (int) (speed / (1024)) + " kbps");
Page | 124
} if (speed > 1024 * 1024 && speed <= 1024 * 1024 * 1024) { jLabeldw.setText("Speed is " + (int) (speed / (1024 * 1024)) + " mbps"); } if (speed > 1024 * 1024 * 1024 && speed <= 1024 * 1024 * 1024 * 1024) { jLabeldw.setText("Speed is " + (int) (speed / (1024 * 1024 * 1024)) + " gbps"); } } if (count == size) { break; } } fos.close(); if(!canceldownload) { int a = JOptionPane.showConfirmDialog(null,"Open downloaded file ???"); if(a==JOptionPane.YES_OPTION) { System.out.println("explorer.exe "+sharedpath + "\\" + fileToDownload); Process p2 = Runtime.getRuntime().exec("explorer.exe "+sharedpath +"\\"+ fileToDownload); } jTable2.clearSelection(); FileWriter fw=new FileWriter("e:\\download_history.txt",true);
Page | 125
if (JOptionPane.NO_OPTION == p1) { JOptionPane.showMessageDialog(null, "no we don't want to rename"); } } } } else //downloading logic for new file { fos = new FileOutputStream(sharedpath + "\\" + fileToDownload); while (true) { if (canceldownload==true) { break; } r = dis.read(b, 0, 1024 * 1024); count = count + r;
Page | 126
fos.write(b, 0, r); dwnld = System.currentTimeMillis(); double diff = (dwnld - start) / 1000; double speed = count / diff; if(progressbar==true) { per = (count * 100 / size); jpbar.setEnabled(downloadRequest); jpbar.setValue((int) (count * 100 / size)); jpbar.setString(per + "% complete"); jLabeldw.setVisible(true); double sp; String speed2; if (speed <1024) { sp=speed; DecimalFormat df=new DecimalFormat("0.00"); speed2=df.format(sp); speed3=speed2; jLabeldw.setText("Speed is " + speed3 + "bps"); } if (speed > 1024 && speed <= 1024 * 1024) { sp=(float)speed/1024; DecimalFormat df=new DecimalFormat("0.00"); speed2=df.format(sp);
Page | 127
speed3=speed2; jLabeldw.setText("Speed is " + speed3 + " kbps"); } if (speed > 1024 * 1024 && speed <= 1024 * 1024 * 1024) { sp=(float)speed/1024*1024; DecimalFormat df=new DecimalFormat("0.00"); speed2=df.format(sp); speed3=speed2; jLabeldw.setText("Speed is " + speed3 + " mbps"); } if (speed > 1024 * 1024 * 1024 && speed <= 1024 * 1024 * 1024 * 1024) { sp=(float)speed/1024*1024*1024; DecimalFormat df=new DecimalFormat("0.00"); speed2=df.format(sp); speed3=speed2; jLabeldw.setText("Speed is " + speed3 + " gbps"); } } if (count == size) { break; } } fos.close(); if(!canceldownload)
Page | 128
{ int a = JOptionPane.showConfirmDialog(null,"Open downloaded file ???"); if(a==JOptionPane.YES_OPTION) { System.out.println("explorer.exe "+sharedpath + "\\" + fileToDownload); Process p1 = Runtime.getRuntime().exec("explorer.exe "+sharedpath +"\\"+ fileToDownload); } } jTable2.clearSelection(); FileWriter fw=new FileWriter("e:\\download_history.txt",true); PrintWriter pw1 = new PrintWriter(fw); pw1.println(fileToDownload+";"+ipadd+";"+size+";"+date); pw1.flush(); his.add(newhistory(fileToDownload,ipadd,Long.toString(size),date.toString())); tm5.fireTableDataChanged(); } } downloadRequest = false; if (MessageRequest == true) { dos.writeBytes("sending message from," + textboxchat.getText() + "\r\n"); dos.flush(); msg = msg + "\nMessage"+ "<h3 color=\"black\">" + textboxchat.getText() + "\n" + "</h3 ><h3 color=\"red\">sent to:</h3>" + ip + "\n";
Page | 129
jEditorPane1.setText(msg); textboxchat.setText(""); } MessageRequest = false; if(testDownloadingSpeed==true) { System.out.println("In test downloadspeed==true"); dos.writeBytes("download,test1.exe\r\n"); dos.flush(); File f= new File("e:\\test2.exe"); FileOutputStream fos= new FileOutputStream(f); byte b[] = new byte[1024*1024]; int r; long count=0; long size1 = dis.readLong(); long start1=new Date().getTime(); System.out.println(start1); while(true) { r=dis.read(b,0,1024*1024); System.out.println("Bytes received >>>>"); fos.write(b,0,r); count+=r; System.out.println(count+" "+size1);
Page | 130
if(count==size1) break; } fos.close(); long current1=new Date().getTime(); long sec=(current1-start1)/1000; long speed1=(50*1024*1024)/sec; Float sp; String speed2; String speed4; if(speed1>1024*1024&&speed1<1024*1024*1024) { sp=(float)speed1/1024*1024; jLabeldw.setText("Speed is " + sp + " mbps"); sp1.add(new speed(ip,(sp+"mbps"))); } tm4.fireTableDataChanged(); testDownloadingSpeed=false; } if(view==true) { int u1 = fileToDownload.lastIndexOf("."); String name1=fileToDownload.substring(0,u1); String ext1 = fileToDownload.substring(u1);
Page | 131
if(ext1.equals("jpg")) { Process process = Runtime.getRuntime().exec("explorer.exe"+sharedpath+"\\"+fileToDownload); view=false; } } } catch (Exception ex) { ex.printStackTrace(); } } } public class peerinfo extends JFrame { JTable jtable3; JPanel jp; JScrollPane jsp; JLabel j2; JLabel jl; peerinfo() { jp = new JPanel(); jp.setSize(1000, 800); j2 = new JLabel(); jp.add(j2); j3 = new JLabel();
Page | 132
j4 = new JLabel(); j2.setFont(new java.awt.Font("Serif", 3, 48)); j2.setText("Connected Peers"); jp.add(j3); j3.setFont(new java.awt.Font("Tahoma", 1, 18)); j3.setText("Downloading Clients :"); j3.setBounds(120, 50, 400, 150); jl = new JLabel(); jl.setSize(1000, 700); jp.add(j4); j4.setBounds(600, 150, 300, 300); j4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/peers.png"))); j2.setBounds(350, 2, 440, 100); tm3 = new tablemodel3(); jtable3 = new JTable(tm3); jp.setLayout(null); jsp = new JScrollPane(jtable3); jsp.setBounds(100, 150, 400, 370); jp.add(jsp); add(jp); jp.add(jl); jl.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/solid-babyblue.jpg"))); setVisible(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Page | 133
setSize(1000, 800); tm3.fireTableDataChanged(); } } public class testspeed extends JFrame implements ActionListener { JTable jtable4; JPanel jp1; JButton bt; JLabel tl; JScrollPane jsp1; ArrayList<speed> sp1 = new ArrayList<speed>(); JLabel pic; JLabel lb; JLabel back; JLabel head; testspeed() { back=new JLabel(); back.setSize(1000, 700); jp1 = new JPanel(); jp1.setSize(1000, 800); head=new JLabel(); head.setFont(new java.awt.Font("Serif", 3, 48));
Page | 134
head.setText("Speed Testing"); jp1.add(head); head.setBounds(300, 2, 440, 100); jp1.setLayout(null); bt=new JButton(); jp1.add(bt); bt.setSize(150, 30); bt.setBounds(220, 560, 160, 40); bt.setText("Check Link Speed"); pic=new JLabel(); pic.setBounds(530, 160, 430, 350); pic.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Animated_Aston_Martin_Speedometer _1.gif"))); jp1.add(pic); bt.addActionListener( this); tl=new JLabel(); lb=new JLabel(); jp1.add(tl); jp1.add(lb); tl.setBounds(220,600,250,40); tl.setVisible(false); lb.setVisible(false); tm4 = new tablemodel4(); jtable4 = new JTable(tm4);
Page | 135
lb.setFont(new java.awt.Font("Serif", 3, 18)); lb.setText("Checking link speed...please wait !!!!!!"); lb.setBounds(100,550,400,90); lb.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/3d.gif"))); jsp1 = new JScrollPane(jtable4); jsp1.setBounds(100, 150, 400, 370); jp1.add(jsp1); add(jp1); jp1.add(back); back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/solid-babyblue.jpg"))); setVisible(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setSize(1000, 800); }
class testing implements Runnable { Thread y; testing() { y=new Thread(this); y.start(); } public void run()
Page | 136
{ int countn=0; try { InetAddress addr=InetAddress.getLocalHost(); String b=addr.getHostAddress(); System.out.println("my address"+b); for(int u=0;u<al.size();u++) { if(al.get(u).equals(b)) { continue; } else { testDownloadingSpeed=true; miniclient on=new miniclient(al.get(u)); System.out.println("object created"+ ++countn); on.t.join(); } } } catch(Exception r) {
Page | 137
r.printStackTrace(); } } } public class history1 extends JFrame { JTable jt5; JPanel jp2; JScrollPane jsp1; JLabel j1; JLabel back; JLabel pic; history1() { jp2 = new JPanel(); back=new JLabel(); back.setSize(1000, 700); jp2.setSize(1000, 800); jp2.setLayout(null); jt5=new JTable(); tm5=new tablemodel5(); jt5 = new JTable(tm5); j1=new JLabel(); j1.setFont(new java.awt.Font("Serif", 3, 48));
Page | 138
j1.setText("Download History"); j1.setBounds(350, 2, 440, 100); pic=new JLabel(); pic.setBounds(550, 180, 400, 350); pic.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/hist.png"))); jp2.add(pic); jsp1 = new JScrollPane(jt5); jsp1.setBounds(100, 150, 400, 370); jp2.add(jsp1); add(jp2); jp2.add(j1); jp2.add(back); back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/solid-babyblue.jpg"))); setVisible(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setSize(1000, 800); tm5.fireTableDataChanged(); } } class tablemodel3 extends AbstractTableModel { String title[] = {"File Name", "IP Address", "File Size"}; public int getRowCount() {
Page | 139
return upc.size(); } public int getColumnCount() { return 3; } @Override public String getColumnName(int m) { return title[m]; } public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { return upc.get(rowIndex).filename; } else if (columnIndex == 1) { return upc.get(rowIndex).ipAddress; } else { return upc.get(rowIndex).filesizekb;
Page | 140
} } } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new clientGUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bt; private javax.swing.JButton btchat; private javax.swing.JButton btdh; private javax.swing.JButton btdownload; private javax.swing.JTable jTable1; private javax.swing.JTable jTable2; private javax.swing.JProgressBar jpbar; private javax.swing.JTextField textboxchat; private javax.swing.JTextField tfsearch; private javax.swing.JComboBox t
Page | 141
Page | 142
FUTURE OF PROJECT
Resuming Broken Downloads
When downloading large files, the download can break or be Interrupted. This means that you need to start all over to download it, which can be a real hassle for large files, or slow connections. When we will download the files in parts, it will reduce traffic congestion on network.
E-commerce
Consumer to Consumer e-commerce is one of the most popular services on the Internet. A centralized trading platform (such as eBay) enables consumers to trade, buy or sell their goods. However in a centralized system, there is always a possibility of a failure - such as the server goes down or is busy. P2P enabled e-commerce can remove the centralized system and so lessen the possibility of failures. However there are many things that have to be implemented for a P2P system for e-commerce to work - it has to be secure, transactional and workflow-based to track different stages of the sales process
Page | 143
CHAPTER 12
Appendix
Abstraction: Abstraction allows us to layer semantics of complex system, breaking them into more manageable pieces. API Package: Application Programming Interface: API contains a large number of packages which offers a different way to look at and handles certain I/O operation. AWT: Abstract Window Toolkit: It examines the standard controls and layout managers defined by JAVA. Bytecode: Bytecode is a highly optimized set of instructions designed to be executed by the java run time system. CSS: Cascading Style Sheets is a style sheet language used to describe the presentation semantics (that is, the look and formatting) of a document written in a markup language. Its most common application is to style web pages written in HTML and XHTML, but the language can be applied to any kind of XMLdocument, including SVG and XUL. Constraints : Any condition that limits the solutions to a problem. Console: It refers to that portion of a computer which is used for communication between operation or maintenance engineers and the computer mostly with the help of displays and manual controls. Encapsulation: Encapsulation is the mechanism that binds together code and data it manipulates, and keeps both safe from outside interference and misuse. Errors: An error is abnormal condition that arises in a code sequence at execution time. Exception: An exception is abnormal condition that arises in a code sequence at error time. Frontend: The part of project which is responsible for collecting input in various forms from the user and to processing it to conform to a specification the backend can use. Javax.swing : A java toolkit for developing graphical user interfaces (GUI) it includes elements such as menus, toolbar, and dialogue boxes. Java.io: It contains classes that are stream oriented and support input and output.
Page | 144
Java.awt.event : Provides interfaces and classes for dealing with different types events fired by awt components. Java.sql : provides the API for accessing and processing data stored in a data source using the java programming language. Java.util : It contains the collection framework, legacy collection classes, event model, date and time facilities, and internationalization utility classes. JDK : Java Development Kit: It is a basically a software development kit which is use to write and run java programs. JDBC : Java Data Base Compiler: It provides a standard interface for accessing a relational. It contains a set of classes and methods for issuing SQL statements, table updates, and calls to stored procedures. JRE : Java Runtime Environment: Is software which is required to run java applications interpretively on a target hardware and operating system platform. JVM : Java Virtual Machine: JVM is an interpreter for Bytecode. It provides the hardware platform specifications to which you compile all java technology code. URL : Uniform Resource locator: It is a unique address given to a particular web page. J2SE : Java 2 Standard Edition (Core Java). J2EE : Java 2 Enterprise Edition (Advanced Java).
Page | 145
CHAPTER 13 BIBLIOGRAPHY
Books
J2SE Notes -- VMM J2EE Notes VMM Sun Microsystems: Java Programming Language Student Guide
Websites
www.wikipedia.org www.ebooks.com www.google.com
Page | 146
(O-0)Abee(0-O)