You are on page 1of 94

Green Data Centers - Cloud-Assisted Mobile Ad Hoc Networks using

network overlay prediction to reduce energy consumption in datacenters


ABSTRACT
Cloud-assisted mobile ad-hoc networks are expected to be so popular in future fifth
generation (5G) mobile network because the significantly faster performance of 5G
communications enables clouds to provide realistic services. On the other hand, the energy
consumption problem will become serious due to the highly increased cloud computing
speed. Mobile communication link loss occurs when a mobile device leaves the network.
Link loss can cause serious energy consumption when the lost link is directly connected to a
cloud data server, which is required to do excessive searching and link routing transactions.
None of the existing normal methods have solved the problem. We show how this problem
can be solved using our proposed mechanism. In the overlay, each peer maintains a tentative
database containing information to be retrieved by routing and searching. Peers communicate
with other peers using messages transmitted over the ad-hoc wireless network. There might
be a direct link or an indirect link between any two peers. If two peers are able to send and
receive messages directly, then there is a direct link between them. Otherwise, intermediary
peers are required to forward transmitted messages, and hence there is an indirect link
between these two peers. In this case the intermediary peers act as routers. For example,
There are only two peers with each having one direct link to a super-peer. All other peers
have indirect links to the super-peer. A peer sends queries for data services and receives the
result from other peers using direct or indirect links. The overlay is self-organizing and
allows peers to join or leave the overlay at any time. The experimental results demonstrate
that our proposed mechanism saves nine times more energy than normal methods.

1. INTRODUCTION
1.1 ABOUT OUR PROJECT
Energy savings are now a mandatory demand of most aspects of information and
communications. Today, scientists are asked to create not only powerful communication
systems but systems that consume less energy. This request has a significant impact on the
design of new wireless communication systems. It also requires improvement in existing
ones. Mobile ad-hoc networks born in the 1970s are a type of wireless network that allows us
to exchange data in a very convenient way. Although limited in power and capability, mobile
ad-hoc networks have proven themselves as convenient infrastructure-free communication
tools. Supporting mobility, allowing better connectivity and performance when moving
between different networks, they promise an important contribution to the future evolution of
the Internet. The combination of cloud computing with mobile ad-hoc networks in 5G
obviously creates new powerful networks by giving additional advantages, significantly
reduced computing, and longer lasting mobility in the network, respectively. These
advantages have facilitated the quick growth of richer applications and services, both of
which require the removal of heavy computing from the mobile device, and so the removal
allows the mobile device to have longer lasting mobility [4]. However, we have faced a heavy
energy consumption problem in cloud computing if a cloud provides data services. In
addition, the extremely higher aggregate data rates and the much lower latencies required by
5G will introduce more energy-consuming technologies (e.g. massive MIMO, native support
for M2M communication) [2]. The rapidly-growing number of richer applications in
cloudassisted mobile ad-hoc networks will make the energy consumption problem worse. It is
an urgent need of both hardware and software solutions to make sure that those networks are
more energy efficient, or greener.In this article we make an issue of excessive energy
consumption in a cloud by the existing normal operational methods when link loss occurs in
cloud data servers. Because a mobile device can often leave a mobile ad-hoc network
connected directly to a cloud, the link between the cloud data server and the mobile device
will often be lost. If a link toward a cloud data server located between the cloud and the
mobile ad-hoc network is lost, another cloud data server connected directly to the mobile adhoc network should run searching and link routing transactions to find the location of the lost

cloud data server. The searching and routing transactions cause excessive energy
consumption. Due to the frequency of link loss in mobile ad-hoc networks, this problem is
critical. Thus, we propose a mechanism to solve excessive energy consumption in cloud data
centers. Our proposed mechanism does not require re-searching and re-link routing for the
lost cloud data server by way of updating link loss information in a content map and sending
the location of queried data kept in the content map. Therefore, additional searching and
routing transactions are not required to find the location of the lost cloud data server. Finally,
we show the results of experimental work to demonstrate significant energy savings by our
proposed mechanism compared to the existing normal method. We also discuss the analysis
of the experimental results and future research topics. The searching and routing transactions
cause excessive energy consumption. Due to the frequency of link loss in mobile ad-hoc
networks this problem is critical. Thus, we propose a mechanism to solve excessive energy
consumption in cloud data centers. Our proposed mechanism does not require re-searching
and re-link routing for the lost cloud data server by way of updating link loss information in a
content map and sending the location of queried data kept in the content map. In the overlay,
each peer maintains a tentative database containing information to be retrieved by routing and
searching. Peers communicate with other peers using messages transmitted over the ad-hoc
wireless network. There might be a direct link or an indirect link between any two peers. If
two peers are able to send and receive messages directly, then there is a direct link between
them. Otherwise, intermediary peers are required to forward transmitted messages, and hence
there is an indirect link between these two peers. In this case the intermediary peers act as
routers.
For example, There are only two peers with each having one direct link to a superpeer. All other peers have indirect links to the super-peer. A peer sends queries for data
services and receives the result from other peers using direct or indirect links. The overlay is
self-organizing and allows peers to join or leave the overlay at any time.

2. SYSTEM SPECIFICATION
2.1 HARDWARE SPECIFICATION

PROCESSOR

Pentium IV

RAM

520 MB(min)

HARD DISK

20 GB

KEY BOARD

Standard Windows Keyboard2

2.2 SOFTWARE SPECIFICATION

OPERATING SYSTEM

- Windows XP/7

PROGRAMMING LANGUAGE

- JAVA/J2EE

JAVA VERSION

- JDK 1.6 & above

SOFTWARE OVERVIEW
ABOUT JAVA
Java is a programming language originally developed by Sun Microsystems and
released in 1995 as a core component of Sun Microsystems' Java platform. The language
derives much of its syntax from C and C++ but has a simpler object model and fewer lowlevel facilities. Java applications are typically compiled to bytecode that can run on any Java
virtual machine (JVM) regardless of computer architecture.
One characteristic of Java is portability, which means that computer programs written
in the Java language must run similarly on any supported hardware/operating-system
platform. One should be able to write a program once, compile it once, and run it anywhere.
This is achieved by compiling the Java language code, not to machine code but to
Java bytecode instructions analogous to machine code but intended to be interpreted by a
virtual machine (VM) written specifically for the host hardware. End-users commonly use a
JRE installed on their own machine, or in a Web browser.
Standardized libraries provide a generic way to access host specific features such as
graphics, threading and networking. In some JVM versions, bytecode can be compiled to
native code, either before or during program execution, resulting in faster execution.
A major benefit of using bytecode is porting. However, the overhead of interpretation
means that interpreted programs almost always run more slowly than programs compiled to
native executables would, and Java suffered a reputation for poor performance. This gap has
been narrowed by a number of optimization techniques introduced in the more recent JVM
implementations.

One such technique, known as (just-in-time compilation) JIT, translates Java bytecode
into native code the first time that code is executed, then caches it. This result in a program
that starts and executes faster than pure interpreted code can, at the cost of introducing
occasional compilation overhead during execution. More sophisticated VMs also use
dynamic recompilation, in which the VM analyzes the behavior of the running program and
selectively recompiles and optimizes parts of the program. Dynamic recompilation can
achieve optimizations superior to static compilation because the dynamic compiler can base
optimizations on knowledge about the runtime environment and the set of loaded classes, and
can identify hot spots - parts of the program, often inner loops, that take up the most
execution time. JIT compilation and dynamic recompilation allow Java programs to approach
the speed of native code without losing portability.
Another technique, commonly known as static compilation, or ahead-of-time (AOT)
compilation, is to compile directly into native code like a more traditional compiler. Static
Java compilers translate the Java source or bytecode to native object code. This achieves
good performance compared to interpretation, at the expense of portability; the output of
these compilers can only be run on a single architecture. AOT could give Java something like
performance, yet it is still not portable since there are no compiler directives, and all the
pointers are indirect with no way to micro manage garbage collection.
Java's performance has improved substantially since the early versions, and
performance of JIT compilers relative to native compilers has in some tests been shown to be
quite similar. The performance of the compilers does not necessarily indicate the performance
of the compiled code; only careful testing can reveal the true performance issues in any
system.
One of the unique advantages of the concept of a runtime engine is that errors
(exceptions) should not 'crash' the system. Moreover, in runtime engine environments such as
Java there exist tools that attach to the runtime engine and every time that an exception of
interest occurs they record debugging information that existed in memory at the time the
exception was thrown (stack and heap values). These Automated Exception Handling tools
provide 'root-cause' information for exceptions in Java programs that run in production,
testing or development environments.

SWINGS:
Swing is a platform-independent, Model-View-Controller GUI framework for Java. It
follows a single-threaded programming model, and possesses the following traits:
PLATFORM INDEPENDENCE:
Swing is platform independent both in terms of its expression (Java) and its
implementation (non-native universal rendering of widgets).
EXTENSIBILITY:
Swing is a highly partitioned architecture, which allows for the "plugging" of various
custom implementations of specified framework interfaces: Users can provide their own
custom implementation(s) of these components to override the default implementations. In
general, Swing users can extend the framework by extending existing (framework) classes
and/or providing alternative implementations of core components.
COMPONENT-ORIENTED :
Swing is a component-based framework. The distinction between objects and
components is a fairly subtle point: concisely, a component is a well-behaved object with a
known/specified characteristic pattern of behaviour. Swing objects asynchronously fire
events, have "bound" properties, and respond to a well-known set of commands (specific to
the component.) Specifically, Swing components are Java Beans components, compliant with
the Java Beans Component Architecture specifications.
CUSTOMIZABLE:
Given the programmatic rendering model of the Swing framework, fine control over
the details of rendering of a component is possible in Swing. As a general pattern, the visual
representation of a Swing component is a composition of a standard set of elements, such as a

"border", "inset", decorations, etc. Typically, users will programmatically customize a


standard Swing component (such as a JTable) by assigning specific Borders, Colors,
Backgrounds, opacities, etc., as the properties of that component. The core component will
then use these property (settings) to determine the appropriate renderers to use in painting its
various aspects. However, it is also completely possible to create unique GUI controls with
highly customized visual representation.
CONFIGURABLE:
Swing's heavy reliance on runtime mechanisms and indirect composition patterns
allows it to respond at runtime to fundamental changes in its settings. For example, a Swingbased application can change its look and feel at runtime. Further, users can provide their
own look and feel implementation, which allows for uniform changes in the look and feel of
existing Swing applications without any programmatic change to the application code.
LIGHTWEIGHT UI :
Swing's configurability is a result of a choice not to use the native host OS's GUI
controls for displaying itself. Swing "paints" its controls programmatically through the use of
Java 2D APIs, rather than calling into a native user interface toolkit. Thus, a Swing
component does not have a corresponding native OS GUI component, and is free to render
itself in any way that is possible with the underlying graphics APIs.
However, at its core every Swing component relies on an AWT container, since
(Swing's) JComponent extends (AWT's) Container. This allows Swing to plug into the host
OS's GUI management framework, including the crucial device/screen mappings and user
interactions, such as key presses or mouse movements. Swing simply "transposes" its own
(OS agnostic) semantics over the underlying (OS specific) components. So, for example,
every Swing component paints its rendition on the graphic device in response to a call to
component.paint(), which is defined in (AWT) Container. But unlike AWT components,
which delegated the painting to their OS-native "heavyweight" widget, Swing components
are responsible for their own rendering.
This transposition and decoupling is not merely visual, and extends to Swing's
management and application of its own OS-independent semantics for events fired within its
component containment hierarchies. Generally speaking, the Swing Architecture delegates

the task of mapping the various flavors of OS GUI semantics onto a simple, but generalized,
pattern to the AWT container. Building on that generalized platform, it establishes its own
rich and complex GUI semantics in the form of the JComponent model. A review of the
source of Container. java and JComponent.java classes is recommended for further insights
into the nature of the interface between Swing's lightweight components and AWT's
heavyweight widgets.
LOOSELY-COUPLED/MVC:
The Swing library makes heavy use of the Model/View/Controller software design
pattern, which conceptually decouples the data being viewed from the user interface controls
through which it is viewed. Because of this, most Swing components have associated models
(which are specified in terms of Java interfaces), and the programmer can use various default
implementations or provide their own. The framework provides default implementations of
model interfaces for all of its concrete components.
Typically, Swing component model objects are responsible for providing a concise
interface defining events fired, and accessible properties for the (conceptual) data model for
use by the associated JComponent. Given that the overall MVC pattern is a loosely-coupled
collaborative object relationship pattern, the model provides the programmatic means for
attaching event listeners to the data model object. Typically, these events are model centric
(ex: a "row inserted" event in a table model) and are mapped by the JComponent
specialization into a meaningful event for the GUI component.
For example, the JTable has a model called TableModel that describes an interface for
how a table would access tabular data. A default implementation of this operates on a twodimensional array.
The view component of a Swing JComponent is the object used to graphically
"represent" the conceptual GUI control. A distinction of Swing, as a GUI framework, is in its
reliance on programmatically-rendered GUI controls (as opposed to the use of the native host
OS's GUI controls). This distinction is a source of complications when mixing AWT controls,
which use native controls, with Swing controls in a GUI.
Finally, in terms of visual composition and management, Swing favors relative
layouts (which specify the positional relationships between components) as opposed to
9

absolute layouts (which specify the exact location and size of components). This bias towards
"fluid"' visual ordering is due to its origins in the applet operating environment that framed
the design and development of the original Java GUI toolkit. (Conceptually, this view of the
layout management is quite similar to that which informs the rendering of HTML content in
browsers, and addresses the same set of concerns that motivated the former.)
LOOK AND FEEL:
Swing allows one to specialize the look and feel of widgets, by modifying the default
(via runtime parameters), deriving from an existing one, by creating one from scratch, or,
beginning with J2SE 5.0, by using the skinnable synth Look and Feel (see Synth Look and
Feel), which is configured with an XML property file. The look and feel can be changed at
runtime, and early demonstrations of Swing frequently provided a way to do this.
RELATIONSHIP TO AWT:
Since early versions of Java, a portion of the Abstract Window Toolkit (AWT) has
provided platform-independent APIs for user interface components. In AWT, each component
is rendered and controlled by a native peer component specific to the underlying windowing
system.
By contrast, Swing components are often described as lightweight because they do not
require allocation of native resources in the operating system's windowing toolkit. The AWT
components are referred to as heavyweight components.
Much of the Swing API is generally a complementary extension of the AWT rather
than a direct replacement. In fact, every Swing lightweight interface ultimately exists within
an AWT heavyweight component because all of the top-level components in Swing (JApplet,
JDialog, JFrame, and JWindow) extend an AWT top-level container. However, the use of
both lightweight and heavyweight components within the same window is generally
discouraged due to Z-order incompatibilities.
The core rendering functionality used by Swing to draw its lightweight components is
provided by Java 2D, another part of JFC.

10

5.2 NETWORKING BASICS:


Ken Thompson and Dennis Ritchie developed UNIX in concert with the C language
at Bell Telephone Laboratories, Murray Hill, New Jersey, in 1969. In 1978, Bill Joy was
leading a project at Cal Berkeley to add many new features to UNIX, such as virtual memory
and full-screen display capabilities. By early 1984, just as Bill was leaving to found Sun
Microsystems, he shipped 4.2BSD, commonly known as Berkeley UNIX.4.2BSD came with
a fast file system, reliable signals, interprocess communication, and, most important,
networking. The networking support first found in 4.2 eventually became the de facto
standard for the Internet. Berkeleys implementation of TCP/IP remains the primary standard
for communications with the Internet. The socket paradigm for inter process and network
communication has also been widely adopted outside of Berkeley.
SOCKET OVERVIEW:
A network socket is a lot like an electrical socket. Various plugs around the network
have a standard way of delivering their payload. Anything that understands the standard
protocol can plug in to the socket and communicate.
Internet protocol (IP) is a low-level routing protocol that breaks data into small
packets and sends them to an address across a network, which does not guarantee to deliver
said packets to the destination.
Transmission Control Protocol (TCP) is a higher-level protocol that manages to
reliably transmit data. A third protocol, User Datagram Protocol (UDP), sits next to TCP and
can be used directly to support fast, connectionless, unreliable transport of packets.
CLIENT/SERVER
A server is anything that has some resource that can be shared. There are compute
servers, which provide computing power; print servers, which manage a collection of
printers; disk servers, which provide networked disk space; and web servers, which store web
pages. A client is simply any other entity that wants to gain access to a particular server.
In Berkeley sockets, the notion of a socket allows as single computer to serve many
different clients at once, as well as serving many different types of information. This feat is
managed by the introduction of a port, which is a numbered socket on a particular machine. A
server process is said to listen to a port until a client connects to it. A server is allowed to
11

accept multiple clients connected to the same port number, although each session is unique.
To mange multiple client connections, a server process must be multithreaded or have some
other means of multiplexing the simultaneous I/O.
RESERVED SOCKETS:
Once connected, a higher-level protocol ensues, which is dependent on which port
you are using. TCP/IP reserves the lower, 1,024 ports for specific protocols. Port number 21
is for FTP, 23 is for Telnet, 25 is for e-mail, 79 is for finger, 80 is for HTTP, 119 is for
Netnews-and the list goes on. It is up to each protocol to determine how a client should
interact with the port.
JAVA AND THE NET:
Java supports TCP/IP both by extending the already established stream I/O interface.
Java supports both the TCP and UDP protocol families. TCP is used for reliable stream-based
I/O across the network. UDP supports a simpler, hence faster, point-to-point datagramoriented model.
INETADDRESS:
The InetAddress class is used to encapsulate both the numerical IP address and the
domain name for that address. We interact with this class by using the name of an IP host,
which is more convenient and understandable than its IP address. The InetAddress class hides
the number inside. As of Java 2, version 1.4, InetAddress can handle both IPv4 and IPv6
addresses.
FACTORY METHODS:
The InetAddress class has no visible constructors. To create an InetAddress object, we use
one of the available factory methods. Factory methods are merely a convention whereby
static methods in a class return an instance of that class. This is done in lieu of overloading a
constructor with various parameter lists when having unique method names makes the results
much clearer.

Three commonly used InetAddress factory methods are shown here.

static InetAddress getLocalHost( ) throws UnknownHostException

12

static InetAddress getByName(String hostName) throws UnknowsHostException

static InetAddress[ ] getAllByName(String hostName)

throws UnknownHostException

The getLocalHost( ) method simply returns the InetAddress object that represents the
local host. The getByName( ) method returns an InetAddress for a host name passed to it. If
these methods are unable to resolve the host name, they throw an UnknownHostException.
On the internet, it is common for a single name to be used to represent several machines.
In the world of web servers, this is one way to provide some degree of scaling. The
getAllByName ( ) factory method returns an array of InetAddresses that represent all of the
addresses that a particular name resolves to. It will also throw an UnknownHostException if
it cant resolve the name to at least one address. Java 2, version 1.4 also includes the factory
method getByAddress( ), which takes an IP address and returns an InetAddress object. Either
an IPv4 or an IPv6 address can be used.
INSTANCE METHODS:
The InetAddress class also has several other methods, which can be used on the
objects returned by the methods just discussed. Here are some of the most commonly used.
Boolean equals (Object other)-

Returns true if this object has the same Internet

address as other.
byte[ ] getAddress( )- Returns a byte array that represents the objects Internet address
in network byte order.
String getHostAddress( )- Returns a string that represents the host address associated
with the InetAddress object.
String getHostName( )- Returns a string that represents the host name associated with
the InetAddress object.
boolean isMulticastAddress( )- Returns true if this Internet address is a multicast
address. Otherwise, it returns false.
String toString( )- Returns a string that lists the host name and the IP address for
conveneince.
13

Internet addresses are looked up in a series of hierarchically cached servers. That


means that your local computer might know a particular name-to-IP-address mapping
autocratically, such as for itself and nearby servers. For other names, it may ask a local DNS
server for IP address information. If that server doesnt have a particular address, it can go to
a remote site and ask for it. This can continue all the way up to the root server, called
InterNIC (internic.net).
TCP/IP CLIENT SOCKETS:
TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-topoint, stream-based connections between hosts on the Internet. A socket can be used to
connect Javas I/O system to other programs that may reside either on the local machine or on
any other machine on the Internet.
There are two kinds of TCP sockets in Java. One is for servers, and the other is for
clients. The ServerSocket class is designed to be a listener, which waits for clients to
connect before doing anything. The Socket class is designed to connect to server sockets and
initiate protocol exchanges.
The creation of a Socket object implicitly establishes a connection between the client
and server. There are no methods or constructors that explicitly expose the details of
establishing that connection. Here are two constructors used to create client sockets:
Socket(String hostName, int port)

Creates a socket connecting the local host to the

named host and port; can throw an UnknownHostException or anIOException.


Socket(InetAddress ipAddress, int port)

Creates a socket using a preexisting

InetAddress object and a port; can throw an IOException.


A socket can be examined at any time for the address and port information associated
with it, by use of the following methods:
InetAddress getInetAddress( )- Returns the InetAddress associated with the Socket
object.
int getPort( ) Returns the remote port to which this Socket object is connected.
int getLocalPort( ) Returns the local port to which this Socket object is connected.

14

Once the Socket object has been created, it can also be examined to gain access to the
input and output streams associated with it. Each of these methods can throw an IOException
if the sockets have been invalidated by a loss of connection on the Net.
InputStream getInputStream( )Returns the InputStream associated with the invoking
socket.
OutputStream getOutputStream( ) Returns the OutputStream associated with the
invoking socket.
TCP/IP SERVER SOCKETS:
Java has a different socket class that must be used for creating server applications.
The ServerSocket class is used to create servers that listen for either local or remote client
programs to connect to them on published ports. ServerSockets are quite different form
normal Sockets.
When we create a ServerSocket, it will register itself with the system as having an
interest in client connections. The constructors for ServerSocket reflect the port number that
we wish to accept connection on and, optionally, how long we want the queue for said port to
be. The queue length tells the system how many client connection it can leave pending before
it should simply refuse connections. The default is 50. The constructors might throw an
IOException under adverse conditions. Here are the constructors:
ServerSocket(int port) Creates server socket on the specified port with a queue length of 50.
Serversocket(int port, int maxQueue)-Creates a server socket on the specified port
with a maximum queue length of maxQueue.
ServerSocket(int port, int maxQueue, InetAddress localAddress)-Creates a server
socket on the specified port with a maximum queue length of maxQueue. On a multihomed
host, localAddress specifies the IP address to which this socket binds.
ServerSocket has a method called accept( ), which is a blocking call that will wait for
a client to initiate communications, and then return with a normal Socket that is then used for
communication with the client

15

3. SYSTEM STUDY &ANALYSIS

3.1. Existing System:


The combination of cloud computing with mobile ad-hoc networks in 5G obviously
creates new powerful networks by giving additional advantages, significantly reduced
computing, and longer lasting mobility in the network, respectively. These advantages have
facilitated the quick growth of richer applications and services, both of which require the
removal of heavy computing from the mobile device, and so the removal allows the mobile
device to have longer lasting mobility [ However, In addition, the extremely higher aggregate
data rates and the much lower latencies required by 5G will introduce more energyconsuming technologies (e.g. massive MIMO, native support for M2M communication) . The
rapidly-growing number of richer applications in cloud assisted mobile ad-hoc networks will
make the energy consumption problem worse. It is an urgent need of both hardware and
software solutions to make sure that those networks are more energy efficient, or greener.
3.1.1.Disadvantages:
We have faced a heavy energy consumption problem in cloud computing if a cloud
provides data services.
The problem of maximizing the energy efficiency in this area and its derivations are
optimization problems.
3.2. Proposed System:
In this article we make an issue of excessive energy consumption in a cloud by the existing
normal operational methods when link loss occurs in cloud data servers. Because a mobile
device can often leave a mobile ad-hoc network connected directly to a cloud, the link
between the cloud data server and the mobile device will often be lost. If a link toward a
cloud data server located between the cloud and the mobile ad-hoc network is lost, another
cloud data server connected directly to the mobile ad-hoc network should run searching and
link routing transactions to find the location of the lost cloud data server. The searching and
routing transactions cause excessive energy consumption. Due to the frequency of link loss in
mobile ad-hoc networks this problem is critical. Thus, we propose a mechanism to solve
excessive energy consumption in cloud data centers. Our proposed mechanism does not

16

require re-searching and re-link routing for the lost cloud data server by way of updating link
loss information in a content map and sending the location of queried data kept in the content
map. In the overlay, each peer maintains a tentative database containing information to be
retrieved by routing and searching. Peers communicate with other peers using messages
transmitted over the ad-hoc wireless network. There might be a direct link or an indirect link
between any two peers. If two peers are able to send and receive messages directly, then there
is a direct link between them. Otherwise, intermediary peers are required to forward
transmitted messages, and hence there is an indirect link between these two peers. In this case
the intermediary peers act as routers. For example, There are only two peers with each having
one direct link to a super-peer. All other peers have indirect links to the super-peer. A peer
sends queries for data services and receives the result from other peers using direct or indirect
links. The overlay is self-organizing and allows peers to join or leave the overlay at any time.
3.2.1. Advantage:
searching and routing transactions are not required to find the location of the lost
cloud data server

17

4. SYSTEM DESIGN AND DEVELOPMENT


4.1. INPUT DESIGN
The input design is the link between the information system and the user. It comprises
the developing specification and procedures for data preparation and those steps are
necessary to put transaction data in to a usable form for processing can be achieved by
inspecting the computer to read data from a written or printed document or it can occur by
having people keying the data directly into the system. The design of input focuses on
controlling the amount of input required, controlling the errors, avoiding delay, avoiding
extra steps and keeping the process simple. The input is designed in such a way so that it
provides security and ease of use with retaining the privacy. Input Design considered the
following things:
What data should be given as input?
How the data should be arranged or coded?
The dialog to guide the operating personnel in providing input.
Methods for preparing input validations and steps to follow when error occur.

The input form of an information system should accomplish one or more of the following
objectives.
1. Input Design is the process of converting a user-oriented description of the input into a
computer-based system. This design is important to avoid errors in the data input process and
show the correct direction to the management for getting correct information from the
computerized system.
2. It is achieved by creating user-friendly screens for the data entry to handle large volume of
data. The goal of designing input is to make data entry easier and to be free from errors. The
data entry screen is designed in such a way that all the data manipulates can be performed. It
also provides record viewing facilities.
3. When the data is entered it will check for its validity. Data can be entered with the help of
screens. Appropriate messages are provided as when needed so that the user will not be in
maize of instant. Thus the objective of input design is to create an input layout that is easy to
follow

18

4.2. OUTPUT DESIGN


A quality output is one, which meets the requirements of the end user and presents the
information clearly. In any system results of processing are communicated to the users and to
other system through outputs. In output design it is determined how the information is to be
displaced for immediate need and also the hard copy output. It is the most important and
direct source information to the user. Efficient and intelligent output design improves the
systems relationship to help user decision-making.
Designing computer output should proceed in an organized, well thought out manner;
the right output must be developed while ensuring that each output element is
designed so that people will find the system can use easily and effectively. When
analysis design computer output, they should Identify the specific output that is
needed to meet the requirements.
Select methods for presenting information.
Create document, report, or other formats that contain information produced by the
system.
The output form of an information system should accomplish one or more of the following
objectives.
1. Convey information about past activities, current status or projections of the
2. Future.
3. Signal important events, opportunities, problems, or warnings.
4. Trigger an action.
5. Confirm an action.

19

4.3. SYSTEM DEVELOPMENT

4.3.1. DESCRIPTION OF MODULES:


System Construction
We consider a cloud-assisted mobile ad-hoc network (MANET) in 5G that is designed
to support multimedia and data services running on mobile devices. The network consists of a
cloud and a mobile ad-hoc network. The cloud is formed by interconnected data servers. The
mobile ad-hoc network is a dynamic set of mobile devices (computers, smartphones, sensors,
etc.) that communicate with each other over wireless links. The advantages of the mobile
cloud network (e.g. support for richer applications, saving on mobile device energy
consumption) for multimedia services have been studied in . In this work, we investigate
aspects of energy efficiency when using cloud-assisted mobile ad-hoc networks for data
services. In reality, data searching (or searching, for short) is most important in cloud-assisted
mobile ad-hoc networks for multimedia and data services. Therefore, we focus on developing
the new mechanisms of two transactions aimed at energy savings.
Peer-to-Peer (P2P) network overlay prediction
In the overlay, each peer maintains a tentative database containing information to be
retrieved by routing and searching. Peers communicate with other peers using messages
transmitted over the ad-hoc wireless network. There might be a direct link or an indirect link
between any two peers. If two peers are able to send and receive messages directly, then there
is a direct link between them. Otherwise, intermediary peers are required to forward
transmitted messages, and hence there is an indirect link between these two peers. In this case
the intermediary peers act as routers. For example, There are only two peers with each having
one direct link to a super-peer. All other peers have indirect links to the super-peer. A peer
sends queries for data services and receives the result from other peers using direct or indirect
links. The overlay is self-organizing and allows peers to join or leave the overlay at any time.
Network Routing Algorithm
We use the Dijkstra algorithm for routing. We consider a network with one super-peer
and two cloud data servers, namely S 1 , S 2 , and S , respectively. The value assigned to a
link between two nodes represents the energy consumed by that link by routing. The value 3

20

assigned to each node represents the energy consumed by searching. We assume that
searching energy consumption is uniquely 1 in all of the nodes. We assume that S is currently
in the overlay, that is, the super-peer and S 3 1 have already left the overlay, that is, now the
cloud data server.
Energy measurement prediction Report
We use integers instead of specific energy measurement units such as header an
prediction because they allow us to better illustrate our idea at an abstract level. We assume
that searching energy consumption is uniquely 1 in all of the cloud data servers. We assume
further that routing energy consumption of a link is an integer between 1 and 5. Then we can
calculate the total energy consumed for routing and searching by a query as demonstrated
above. Figures 5a, 5b, and 5c show the energy consumption comparison of routing
transactions when there are 500 queries in the network with 50, 60, and 100 cloud data
servers, respectively.

21

5. SYSTEM TESTING AND IMPLEMENTATION


5.1. TESTING
The purpose of testing is to discover errors. Testing is the process of trying to discover
every conceivable fault or weakness in a work product. It provides a way to check the
functionality of components, sub assemblies, assemblies and/or a finished product It is the
process of exercising software with the intent of ensuring that the Software system meets its
requirements and user expectations and does not fail in an unacceptable manner. There are
various types of test. Each test type addresses a specific testing requirement.
TYPES OF TESTS
Unit Testing
Unit testing involves the design of test cases that validate that the internal program
logic is functioning properly, and that program inputs produce valid outputs. All decision
branches and internal code flow should be validated. It is the testing of individual software
units of the application .it is done after the completion of an individual unit before
integration. This is a structural testing, that relies on knowledge of its construction and is
invasive. Unit tests perform basic tests at component level and test a specific business
process, application, and/or system configuration. Unit tests ensure that each unique path of a
business process performs accurately to the documented specifications and contains clearly
defined inputs and expected results.
Integration Testing
Integration tests are designed to test integrated software components to determine if
they actually run as one program. Testing is event driven and is more concerned with the
basic outcome of screens or fields. Integration tests demonstrate that although the
components were individually satisfaction, as shown by successfully unit testing, the
combination of components is correct and consistent. Integration testing is specifically aimed
at exposing the problems that arise from the combination of components
Functional Testing
Functional tests provide systematic demonstrations that functions tested are available
as specified by the business and technical requirements, system documentation, and user
22

manuals.
Functional testing is centered on the following items
Valid Input- identified classes of valid input must be accepted
Invalid Input

- identified classes of invalid input must be


rejected

Functions - identified functions must be exercised


Output - identified classes of apps outputs must be
rejected
Organization and preparation of functional tests is focused on requirements, key
functions, or special test cases. In addition, systematic coverage pertaining to identify
Business process flows; data fields, predefined processes, and successive processes must be
considered for testing. Before functional testing is complete, additional tests are identified
and the effective value of current tests is determined.
System Testing
System testing ensures that the entire integrated software system meets requirements.
It tests a configuration to ensure known and predictable results. An example of system testing
is the configuration oriented system integration test. System testing is based on process
descriptions and flows, emphasizing pre-driven process links and integration points.
White Box Testing
White Box Testing is a testing in which in which the software tester has knowledge of
the inner workings, structure and language of the software, or at least its purpose. It is
purpose. It is used to test areas that cannot be reached from a black box level.
Black Box Testing
Black Box Testing is testing the software without any knowledge of the inner
workings, structure or language of the module being tested. Black box tests, as most other
kinds of tests, must be written from a definitive source document, such as specification or

23

requirements document, such as specification or requirements document. It is a testing in


which the software under test is treated, as a black box .you cannot see into it. The test
provides inputs and responds to outputs without considering how the software works.
5.2. IMPLEMENTATION
It making the new system available to a prepared set of users (the deployment), and
positioning on-going support and maintenance of the system within the Performing
Organization (the transition). At a finer level of detail, deploying the system consists of
executing all steps necessary to educate the Consumers on the use of the new system, placing
the newly developed system into production, confirming that all data required at the start of
operations is available and accurate, and validating that business functions that interact with
the system are functioning properly. Transitioning the system support responsibilities
involves changing from a system development to a system support and maintenance mode of
operation, with ownership of the new system moving from the Project Team to the
Performing Organization.
System implementation is the important stage of project when the theoretical design is
tuned into practical system. The main stages in the implementation are as follows
Planning
Training
System testing and
Changeover Planning
Planning is the first task in the system implementation. Planning means deciding on
the method and the time scale to be adopted. At the time of implementation of any system
people from different departments and system analysis involve. They are confirmed to
practical problem of controlling various activities of people outside their own data processing
departments. The line managers controlled through an implementation coordinating
committee. The committee considers ideas, problems and complaints of user department, it
must also consider;
The implication of system environment
Self selection and allocation form implementation tasks
Consultation with unions and resources available
Standby facilities and channels of communication
24

The following roles are involved in carrying out the processes of this phase. Detailed
descriptions of these roles can be found in the Introductions to Sections I and III.
Project Manager
Project Sponsor
Business Analyst
Data/Process Modeler
Technical Lead/Architect
Application Developers
Software Quality Assurance (SQA) Lead
Technical Services (HW/SW, LAN/WAN, TelCom)
Information Security Officer (ISO)
Technical Support (Help Desk, Documentation, Trainers)
Customer Decision-Maker
The purpose of Prepare for System Implementation is to take all possible steps to
ensure that the upcoming system deployment and transition occurs smoothly, efficiently, and
flawlessly. In the implementation of any new system, it is necessary to ensure that the
Consumer community is best positioned to utilize the system once deployment efforts have
been validated. Therefore, all necessary training activities must be scheduled and
coordinated. As this training is often the first exposure to the system for many individuals, it
should be conducted as professionally and competently as possible. A positive training
experience is a great first step towards Customer acceptance of the system.
During System Implementation it is essential that everyone involved be absolutely

25

synchronized with the deployment plan and with each other. Often the performance of
deployment efforts impacts many of the Performing Organizations normal business
operations. Examples of these impacts include:

Consumers may experience a period of time in which the systems that they depend on
to perform their jobs are temporarily unavailable to them. They may be asked to maintain
detailed manual records or logs of business functions that they perform to be entered into the
new system once it is operational.
Technical Services personnel may be required to assume significant implementation
responsibilities while at the same time having to continue current levels of service on other
critical business systems.Technical Support personnel may experience unusually high
volumes of support requests due to the possible disruption of day-to-day processing.
Because of these and other impacts, the communication of planned deployment
activities to all parties involved in the project is critical. A smooth deployment requires strong
leadership, planning, and communications. By this point in the project lifecycle, the team will
have spent countless hours devising and refining the steps to be followed.
During this preparation process the Project Manager must verify that all conditions
that must be met prior to initiating deployment activities have been met, and that the final
green light is on for the team to proceed. The final process within the System Development
Lifecycle is to transition ownership of the system support responsibilities tothe Performing
Organization. In order for there to be an efficient and effective transition, the Project Manager
should make sure that all involved parties are aware of the transition plan, the timing of the
various transition activities, and their role in its execution.
Due to the number of project participants in this phase of the SDLC, many of the
necessary conditions and activities may be beyond the direct control of the Project Manager.
Consequently, all Project Team members with roles in the implementation efforts
must understand the plan, acknowledge their responsibilities, recognize the extent to which
other implementation efforts are dependent upon them, and confirm their commitment.

26

6. CONCLUTION
As a security and energy efficiency issue, cloud servers and super-peers can possibly
be forced to provide a fake content map, which would cause them to consume excessive
energy. A practical and powerful energy saving mechanism to decrease searching and routing
transactions in cloud data servers, because the transactions consume much more energy when
links are lost. The experimental work has proven that our proposed mechanism significantly
reduces energy compared to the normal operational method in data centers. The overlay is
self-organizing and allows peers to join or leave the overlay at any time. Due to its simplicity,
our proposed mechanism is particularly expected to attract many practical uses in data
centers.

27

7. BIBLIOGRAPHY
[1] A. Bianzino, C. Chaudet, D. Rossi, and J. Rougier, A survey of green networking
research, IEEE Communications Surveys and Tutorials, vol. 14, no. 1, pp. 3-20, 2012.
[2] Global e-Sustainability Initiative (GeSI), Smart 2020 report: Global ICT solution case
studies, Technical report, 2008.
[3] A. P. Bianzino, C. Chaudet, D. Rossi et al., The green-game: Striking a balance between
qos and energy saving, in Proc. 23rd International Teletraffic Congress (ITC), pp. 262-269,
September 2011.
[4] N. Niebert, S. Baucke, I. EI-Khayat, M. Johnsson, B. Ohlman, H. Abramowicz, K.
Wuenstel, H. Woesner, J. Quittek, and L.M. Correia, The way 4ward to the creation of a
future internet, in IEEE 19th International Symposium on Personal, Indoor and Mobile Radio
Communications, PIMRC 2008.
[5] G. Tselentis, Towards the future Internet, pp. 91-101. IOS Press, 2009.
[6] M. Siekkinen, V. Goebel, T. Plagemann et al., Beyond the future internet - requirements
of autonomic networking architectures to address long term future networking challenges, in
Proc. the 11th IEEE International Workshop on Future Trends of Distributed Computing
Systems, 2007.
[7] D. Clark, R. Braden A. Falken et al., Fara: Reorganizing the addressing architecture,
presented at ACM Sigcomm Workshops, August, 2003.

28

APPENDIX
A. DATA FLOW DIAGRAM
The DFD is also called as bubble chart. It is a simple graphical formalism that can
be used to represent a system in terms of input data to the system, various
processing carried out on this data, and the output data is generated by this system.
The data flow diagram (DFD) is one of the most important modeling tools. It is
used to model the system components. These components are the system process,
the data used by the process, an external entity that interacts with the system and
the information flows in the system.
DFD shows how the information moves through the system and how it is
modified by a series of transformations. It is a graphical technique that depicts
information flow and the transformations that are applied as data moves from
input to output.
DFD is also known as bubble chart.

Directly connected to MANET

Cloud data server


Source

Find the shortest path

Send the data through peer(Mobile device)

Data send using super-peer connection to the destination

Destination

29

UML Diagram
UML stands for Unified Modeling Language. UML is a standardized general-purpose
modeling language in the field of object-oriented software engineering. The standard is
managed, and was created by, the Object Management Group. The goal is for UML to
become a common language for creating models of object oriented computer software. In its
current form UML is comprised of two major components: a Meta-model and a notation. In
the future, some form of method or process may also be added to; or associated with, UML.
6.3.2 Use Case Diagram
A use case diagram in the Unified Modeling Language (UML) is a type of behavioral
diagram defined by and created from a Use-case analysis. Its purpose is to present a graphical
overview of the functionality provided by a system in terms of actors, their goals (represented
as use cases), and any dependencies between those use cases. The main purpose of a use case
diagram is to show what system functions are performed for which actor. Roles of the actors
in the system can be depicted.

30

Select the file and

calculate the shortest path

Send the data through peer to peer

Check the availability

MANET

Data send with super-peer to peer connections


Sender
(cloud data server)

Receive the data

Mobile User

Class Diagram
In software engineering, a class diagram in the Unified Modeling Language (UML) is a
type of static structure diagram that describes the structure of a system by showing the
system's classes, their attributes, operations (or methods), and the relationships among the

31

classes. It explains which class contains information.

Cloud
Data
server
Cloud
Data
server

Green
data
sender
Green
data
sender

UserName
UserName

NoNo
of of
nodes
nodes

password
password

Sender
data
Sender
data
IP IP
user()
user()
checkAvailable()
checkAvailable()
receiver()
receiver()

UserLogin()
UserLogin()

Shortest path
availability
path

B.

Destination
To peer(mobile device)
Received data

32

receivedata()
dispose()

SAMPLE CODING
Log in.java
package greendata;
import java.io.FileNotFoundException;

receivedata()
dispose()

import java.io.FileOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.*;
/**
*
* @author Admin
*/
public class Login extends javax.swing.JFrame
{
Socket s;
DataInputStream din;
String s1;
/** Creates new form RECEIVER */
public Login()
{
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is


* always regenerated by the Form Editor.
*/

33

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jOptionPane1 = new javax.swing.JOptionPane();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jPasswordField1 = new javax.swing.JPasswordField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(400, 400));
setName("RECEIVER"); // NOI18N
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel2.setFont(new java.awt.Font("Tahoma", 3, 12));
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("ENTER THE NAME :");
getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(120,
110, 120, 30));
getContentPane().add(jTextField1, new
org.netbeans.lib.awtextra.AbsoluteConstraints(300, 110, 160, 30));
jLabel4.setFont(new java.awt.Font("Castellar", 3, 18));
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Optimum relay selection ");
getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(150,
30, 320, 50));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 12));
34

jButton1.setText("CANCEL");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(320,
290, 90, -1));
jButton2.setFont(new java.awt.Font("Times New Roman", 3, 14));
jButton2.setText("LOGIN");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(160,
290, 90, -1));
jLabel3.setFont(new java.awt.Font("Tahoma", 3, 12));
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("PASS WORD

:");

getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(120,


180, 120, 30));
getContentPane().add(jPasswordField1, new
org.netbeans.lib.awtextra.AbsoluteConstraints(300, 180, 160, 30));
jLabel1.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/greendata/images/ig.png"))); // NOI18N
jLabel1.setToolTipText("");
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0,
-20, 900, 640));
getAccessibleContext().setAccessibleParent(this);
35

pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String user1=jTextField1.getText();
String pass1=jPasswordField1.getText();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c = DriverManager.getConnection("jdbc:odbc:sensor");
Statement st = c.createStatement();
ResultSet rs = st.executeQuery("select * from login");
while (rs.next()) {
String user = rs.getString("user");
String pass = rs.getString("pass");
if(user.equals(user1)&&pass.equals(pass1))
{ hide();
new mainform().setVisible(true);
}
}
rs.close();
c.close();
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
36

}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Login().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JOptionPane jOptionPane1;
private javax.swing.JPasswordField jPasswordField1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
Sensor.java
package greendata;
//Sensor.java
import java.lang.*;
37

import java.io.*;
public class Sensor
{
private int ID;
private int X;
private int Y;
//constructors
Sensor()
{
ID=0;
X=0;
Y=0;
}
Sensor(int tX,int tY)
{
ID=Globals.CurrentSensorID;
X=tX;
Y=tY;
Globals.CurrentSensorID++;
}
//get functions
public int getID()
{
return(ID);
}
public int getX()
{
return(X);
}
38

public int getY()


{
return(Y);
}
//set functions
public void setX(int tX)
{
X=tX;
}
public void setY(int tY)
{
Y=tY;
}
}
SensorDataPrediction.java
package greendata;
//AdaptiveDataFusion.java
import java.io.*;
import java.util.*;
import java.util.Date;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import jist.runtime.JistAPI;
import jist.runtime.Node;
39

import jist.runtime.guilog.GuiLog;
import java.io.IOException;
import jist.runtime.JistAPI;
import jist.swans.Constants;
import jist.swans.misc.Util;
import jist.swans.misc.Mapper;
import jist.swans.net.NetAddress;
import jist.swans.net.NetIp;
import jist.swans.net.PacketLoss;
import jist.swans.trans.TransUdp;
import jist.swans.app.AppJava;
import java.net.InetAddress;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.util.logging.Level;
import java.util.logging.Logger;
//import jist.minisim.block;
//import jist.swans.misc.Node;
import java.sql.*;
import javax.imageio.ImageIO;
class SensorDataprediction extends JFrame implements
ActionListener,MouseMotionListener,MouseListener
{
//ui
sens frmMain=new sens();
JLabel lblSensorCount=new JLabel("");
JLabel lblXY=new JLabel("");
JLabel lblCurrentSensor=new JLabel("");
JLabel lblMovements=new JLabel("");
JTextArea txtSensorList=new JTextArea("");
JScrollPane spSensorList=new JScrollPane(txtSensorList);

40

JButton btDataTransfer=new JButton("Data Transfer");


JButton sensor=new JButton("Network");
JButton btExisting=new JButton("Network Nodes");
JButton btExisting1=new JButton("Cloaked Area");
JButton proposed=new JButton("");
JLabel lblUnitDataSize=new JLabel("Send Data :");
JTextField txtUnitDataSize=new JTextField("12");
JLabel lblGroupCount=new JLabel("Group Count:");
JTextField txtGroupCount=new JTextField("6");
JComboBox jc = new JComboBox();
JTextArea txtdata=new JTextArea("");
JScrollPane spSensorList1=new JScrollPane(txtdata);

//ui parameters
int frmLeft=60,frmTop=60;
int frmWidth=900,frmHeight=640;
int mapWidth=frmWidth-260,mapHeight=frmHeight-100;
//system parameters
int CurrentSensor=-1,CurrentSensor1=-1,cpw,cph;
int nSensorsPerRegion=5;
int TransmissionRange=100;
int SensorRadius=10;
int SourceSensor=100;
int DestSensor=-1;
int cloakedarea=0,port1,port2;
String Hacker="Hacker Not Attacked";
Map map=new Map();
Region[] MapRegions=map.getMapRegions();
Graphics g;
41

//constructor
SensorDataprediction()
{
//get user-paramters
//nSensorsPerRegion=Integer.parseInt(JOptionPane.showInputDialog("Enter
SensorNodeCount per Cluster: ",""+nSensorsPerRegion));
//setup frmMain
frmMain.setResizable(false);
// frmMain.getContentPane().imageUpdate(null, frmLeft, WIDTH, WIDTH,
WIDTH, WIDTH);
//Image img=new Image();
//"D:/uis
staff/veeramani/slm/sec/sensornetwork/src/sensornetwork/images/cbe_district_map.gif") ;
//frmMain.setIconImage(img);
//setIconImage("Lake.jpg");
frmMain.setBounds(frmLeft,frmTop,frmWidth,frmHeight);
frmMain.getContentPane().setLayout(null);
frmMain.addMouseMotionListener(this);
frmMain.addMouseListener(this);
lblSensorCount.setBounds(30,frmHeight-65,150,20);
frmMain.getContentPane().add(lblSensorCount);
lblXY.setBounds(30,10,100,20);
frmMain.getContentPane().add(lblXY);
lblCurrentSensor.setBounds(frmWidth-330,frmHeight-65,150,20);
frmMain.getContentPane().add(lblCurrentSensor);
lblMovements.setBounds(frmWidth-330,frmHeight-65,150,20);
frmMain.getContentPane().add(lblMovements);
frmMain.getContentPane().setBackground(Color.gray);
txtSensorList.setEditable(false);
spSensorList.setBounds(frmWidth-180-40,30,200,120);
spSensorList.setColumnHeaderView(new JLabel("Network List"));
42

frmMain.getContentPane().add(spSensorList);

sensor.setBounds(frmWidth-180-40,160,200,22);
sensor.addActionListener(this);
// sensor.setForeground(Color.white);
//

//sensor.setBackground(Color.BLACK);

//
frmMain.getContentPane().add(sensor);
//
//
btExisting.setBounds(frmWidth-180-40,190,200,22);
btExisting.addActionListener(this);
frmMain.getContentPane().add(btExisting);
// jc.addItem("Predict Enable");
//

jc.addItem("Predict Disable");

//
//
//

jc.setBounds(frmWidth-180-40,220,200,22);
jc.addActionListener(this);

//

frmMain.getContentPane().add(jc);

//

//add(jc);
lblUnitDataSize.setBounds(frmWidth-180-40,220,100,22);

frmMain.getContentPane().add(lblUnitDataSize);
txtUnitDataSize.setBounds(frmWidth-180-40+90,220,100,22);
frmMain.getContentPane().add(txtUnitDataSize);
//
btDataTransfer.setBounds(frmWidth-180-40,250,200,22);
btDataTransfer.addActionListener(this);
43

frmMain.getContentPane().add(btDataTransfer);
btExisting1.setBounds(frmWidth-180-40,330,200,22);
btExisting1.addActionListener(this);
frmMain.getContentPane().add(btExisting1);
//

//setup frmQueryTable

//

proposed.setBounds(frmWidth-180-40,360,200,22);

// proposed.addActionListener(this);
// frmMain.getContentPane().add(proposed);
txtdata.setEditable(false);
spSensorList1.setBounds(frmWidth-180-40,360,200,120);
spSensorList1.setColumnHeaderView(new JLabel("Packet Datas"));
frmMain.getContentPane().add(spSensorList1);
frmMain.setVisible(true);
Globals.wait(1000);
g=frmMain.getGraphics();
Graphics2D g2d=(Graphics2D)g;
g2d.setStroke(new BasicStroke(4.0f));
g2d.drawRect(30,60,mapWidth,mapHeight);
udp up=new udp();
up.main1();
}
//events
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource()==btDataTransfer)
{
44

udp up=new udp();


up.main(txtUnitDataSize.getText());
}
else if(evt.getSource()==sensor)
{
map.draw(g);
map.drawSensorsLabel(g);

}
else if(evt.getSource()==btExisting)
{
addSensors();
txtSensorList.setText(map.getSensorListString());
}
else if(evt.getSource()==btExisting1)
{
cloackeareas();
}
else if(evt.getSource()==proposed)
{
// proposed();
}
}
//mouse motion listener events
public void mouseDragged(MouseEvent me)
45

{
//
}
public void mouseMoved(MouseEvent me)
{
int xposition=me.getX();
int yposition=me.getY();
lblXY.setText("("+xposition+","+yposition+")");
int n=map.findTotalSensorsCount();
int trad=SensorRadius-2;
boolean flag=false;
for(int i=0;i<map.getRegionCount();i++)
{
for(int j=0;j<MapRegions[i].getSensorCount();j++)
{
int x1=MapRegions[i].getSensorX(j)-trad+2;
int x2=MapRegions[i].getSensorX(j)+trad+2;
int y1=MapRegions[i].getSensorY(j)-trad+2;
int y2=MapRegions[i].getSensorY(j)+trad+2;
if(between(xposition,yposition,x1,y1,x2,y2)==true)
{
flag=true;
CurrentSensor=MapRegions[i].getSensorID(j);
}
}
}
//make sure sensorid is displayed only when mouse is over it
if(flag==false)
{
46

CurrentSensor=-1;
}
displayStatus();
}
//mouselistener events
public void mouseClicked(MouseEvent me)
{
if(CurrentSensor>=0)
{
if(SourceSensor==-1)
{
SourceSensor=CurrentSensor;
}
else
{
if(CurrentSensor!=SourceSensor)
{
DestSensor=CurrentSensor;
}
}
displayStatus();
}
}
public void mouseEntered(MouseEvent me)
{
//
}
public void mouseExited(MouseEvent me)
{
//
}
47

public void mousePressed(MouseEvent me)


{
//
}
public void mouseReleased(MouseEvent me)
{
//
}
//display functions
public void displayStatus()
{
lblSensorCount.setText("Total node: "+(map.findTotalSensorsCount()-1));
lblCurrentSensor.setText("Current node: "+CurrentSensor);
String tstr="Selected Aggregate: "+SourceSensor;
tstr+="\nDestination: BS";
//txtInput.setText(tstr);
}
void displayQueryTable()
{
String tstr="";
for(int t=0;t<map.RegionCount;t++)
{
int x1=MapRegions[t].getX();
int y1=MapRegions[t].getY();
int x2=x1+Globals.RegionWidth;
int y2=y1+Globals.RegionHeight;
tstr+="R"+t+": ("+x1+","+y1+")"+"-("+x2+","+y2+")"+"\n";
}
}
48

void displaySensorTable()
{
String tstr="";
for(int t=0;t<map.findTotalSensorsCount();t++)
{
int tx=findSensorX(t);
int ty=findSensorY(t);
tstr+="O"+t+": ("+tx+","+ty+")"+"\n";
}
}
//internal methods
private boolean between(int x,int y,int x1,int y1,int x2,int y2)
{
boolean flag=false;
if(x>=x1 && x<=x2)
{
if(y>=y1 && y<=y2)
{
flag=true;
}
}
return(flag);
}
//methods
void addSensors()
{
for(int t=0;t<map.getRegionCount();t++)
{
int tcount=nSensorsPerRegion;
if(t==map.getRegionCount()-1) tcount=nSensorsPerRegion-1;
49

for(int i=0;i<tcount;i++)
{
try
{
// frmMain.repaint();
int no=t;
//find random x,y
double random1=java.lang.Math.random();
int no1=(int)(((double)Globals.RegionWidth-5.0)*random1);
double random2=java.lang.Math.random();
int no2=(int)(((double)Globals.RegionHeight-5.0)*random2);
int tx=MapRegions[no].getX()+no1;
int ty=MapRegions[no].getY()+no2;
//draw sensor
Graphics2D g2d=(Graphics2D)g;
g2d.setStroke(new BasicStroke(4.0f));
g.setColor(new Color(255,0,0));
if(i==0){ g.setColor(new Color(0,128,0));
//color for aggregate sensor
g.drawOval(tx,ty,SensorRadius,SensorRadius);
// g.drawOval(tx+5*t,ty-5,SensorRadius,SensorRadius);
}else if(i==2)
{
g.setColor(new Color(200,23,253));
g.drawOval(tx,ty,SensorRadius,SensorRadius);
g.setColor(Color.WHITE);
g.drawString("User", tx, ty);
}
else
{
50

g.setColor(Color.RED);
g.drawOval(tx,ty,SensorRadius,SensorRadius);
}

MapRegions[no].addSensor(tx,ty);
Thread.sleep(200);
}
catch(Exception ex)
{
System.out.println("Error: "+ex.getMessage());
}
}
}
int tx=MapRegions[map.getRegionCount()-1].getX()+Globals.RegionWidth-10;
int ty=MapRegions[map.getRegionCount()-1].getY()+Globals.RegionHeight-12;
g.drawOval(tx,ty,SensorRadius,SensorRadius);
MapRegions[map.getRegionCount()-1].addSensor(tx,ty);
//add basestation
tx=MapRegions[map.getRegionCount()-1].getX()+Globals.RegionWidth+10;
ty=MapRegions[map.getRegionCount()-1].getY()+Globals.RegionHeight+5;
//draw basestation
Graphics2D g2d=(Graphics2D)g;
g2d.setStroke(new BasicStroke(2.0f));
g.setColor(new Color(255,0,0));
g.drawRect(tx,ty,SensorRadius,SensorRadius);
g.setColor(new Color(0,0,128));
g.drawString("BS",tx-6,ty+20);
MapRegions[map.getRegionCount()-1].addSensor(tx,ty);
DestSensor=map.findTotalSensorsCount()-1;
}
51

int findSensorX(int tSensorID)


{
int
tX=MapRegions[map.findRegionNoOfSensor(tSensorID)].getSensorX(map.findSensorIndex
InRegion(tSensorID));
return(tX);
}
int findSensorY(int tSensorID)
{
int
tY=MapRegions[map.findRegionNoOfSensor(tSensorID)].getSensorY(map.findSensorIndex
InRegion(tSensorID));
return(tY);
}
//path functions
public int getSensorX(int tSensorID)
{
int
tx=MapRegions[map.findRegionNoOfSensor(tSensorID)].getSensorX(map.findSensorIndexI
nRegion(tSensorID));
return(tx);
}
public int getSensorY(int tSensorID)
{
int
ty=MapRegions[map.findRegionNoOfSensor(tSensorID)].getSensorY(map.findSensorIndexI
nRegion(tSensorID));
return(ty);
}

52

int findDistance(int x1,int y1,int x2,int y2)


{
double d=Math.sqrt(Math.pow((double)(x2-x1),2.0)+Math.pow((double)(y2-y1),2.0));
return((int)d);
}
int findSensorDistance(int tSensorID1,int tSensorID2)
{

int x1=getSensorX(tSensorID1);
int y1=getSensorY(tSensorID1);
int x2=getSensorX(tSensorID2);
int y2=getSensorY(tSensorID2);
double tdistance=findDistance(x1,y1,x2,y2);
return((int)tdistance);
}
private void drawLine(int tindex1,int tindex2)
{
int x=findSensorX(tindex1);
int y=findSensorY(tindex1);
int x1=findSensorX(tindex2);
int y1=findSensorY(tindex2);
port1=x1;
port2=y1;
cloakedarea++;
//g.setColor(new Color(0,0,255));
if(tindex1%5==0 && tindex1!=100 && tindex2!=100){
try {
Graphics2D g2d=(Graphics2D)g;
g2d.setStroke(new BasicStroke(4.0f));
53

g.draw3DRect(x-25, y-25, 50, 50, true);


//ImageIcon img=new ImageIcon("arrows_e0.gif");
BufferedImage originalImage =
ImageIO.read(new File("C:/Documents and Settings/user/Desktop/Attackers in
Wireless Networks/src/sensornetwork/hacked.jpg"));
g.drawImage(originalImage, x-25, y-25, 50, 50, sensor);
Hacker="Hacker Attacked";
Thread.sleep(4000);
//JOptionPane.showMessageDialog(null, "sgsdegds");
} catch (InterruptedException ex) {
Logger.getLogger(SensorDataprediction.class.getName()).log(Level.SEVERE,
null, ex);
} catch (IOException ex) {
Logger.getLogger(SensorDataprediction.class.getName()).log(Level.SEVERE,
null, ex);
}
}
g.drawLine(x,y,x1,y1);
}
private Path findPath(int tsourcesensor,int tdestsensor)
{
Path tpath=new Path();
if(tsourcesensor==tdestsensor) return(tpath);
int x[],y[],distances[][];
int n=map.findTotalSensorsCount();
x=new int[n];
y=new int[n];
distances=new int[n][n];
int x1,x2,y1,y2;
54

for(int i=0;i<n;i++)
{
x[i]=findSensorX(i);
y[i]=findSensorY(i);
}
//find euclidean distance between each sensor and every other sensor (routing table)
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
x1=x[i]; x2=x[j];
y1=y[i]; y2=y[j];
distances[i][j]=findDistance(x1,y1,x2,y2);
}
}
int tsource=tsourcesensor;
int tdestination=tdestsensor;
int neighbors[]=new int[n];
int neighborCount=0;
tpath.addSensor(tsource); //add sourcesensor to path
boolean destReached=false;
while(destReached==false)
{
//find neighbor sensors that are within the transmission range
neighborCount=0;
for(int i=0;i<n;i++)
{
55

if(distances[tsource][i]<=TransmissionRange)
{
if(i!=tsource) //to ensure source itself is not taken as a neighbor
{
//find if this neighbor is already in path
boolean found=false;
for(int k=0;k<tpath.size();k++)
{
if(tpath.getSensor(k)==i)
{
found=true;
break;
}
}
if(found==false)
{
neighbors[neighborCount]=i;
neighborCount++;
}
}
}
}
if(neighborCount>0)
{
//check if DestinationSensor reached
for(int i=0;i<neighborCount;i++)
{
if(neighbors[i]==tdestsensor)
{
tpath.addSensor(tdestsensor);
destReached=true;
break;
56

}
}
if(destReached==true)
{
break;
}
//find the next-sensor as neighbor-sensor with shortest distance to the target sensor
int nextSensor=-1;
int tnext=0,tdist,shortestDist=0;
for(int i=0;i<neighborCount;i++)
{
int tsensor=neighbors[i];
x1=x[tsensor]; x2=x[tdestsensor];
y1=y[tsensor]; y2=y[tdestsensor];
tdist=findDistance(x1,y1,x2,y2);
if(i==0)
{
shortestDist=tdist;
tnext=tsensor;
}
else if(shortestDist>tdist)
{
shortestDist=tdist;
tnext=tsensor;
}
}
nextSensor=tnext;
tpath.addSensor(nextSensor);
tsource=nextSensor;
}
else
57

{
//if no neighbor found inside the transmission range
break;
}
}
//find path distance
double tdistance=0.0;
for(int t=0;t<tpath.size();t++)
{
if(t>0)
{
int sensor1=tpath.getSensor(t-1);
int sensor2=tpath.getSensor(t);
tdistance+=findSensorDistance(sensor1,sensor2);
}

}
tpath.setDistance(tdistance);
return(tpath);
}
private void drawPath(Path tpath)
{
String tstr="Data Transfer Path: ";
for(int t=0;t<tpath.size();t++)
{
tstr+=tpath.getSensor(t)+"-";
if(t>0)
{
int sensor1=tpath.getSensor(t-1);
58

int sensor2=tpath.getSensor(t);
System.out.println(sensor2);
drawLine(sensor1,sensor2);
}
Globals.wait(Globals.PathDrawingDelay);
}
//g.setColor(Color.pink);

tstr=tstr.substring(0,tstr.length()-1);
tstr+="(BS)\r\n\r\n";

displayStatus();
}

private Color getUniqueColor(int tid)


{
Color tColor=new Color(0,0,0);
if(tid==1)

tColor=new Color(255,0,0); //001

else if(tid==2) tColor=new Color(0,128,0); //010


else if(tid==3) tColor=new Color(0,0,255); //011
else if(tid==4) tColor=new Color(128,0,0); //100
else if(tid==5) tColor=new Color(128,0,128);

//101

else if(tid==6) tColor=new Color(128,128,0);

//110

else if(tid==7) tColor=new Color(128,128,128);

//111

else if(tid==8) tColor=new Color(0,0,255); //001


else if(tid==9) tColor=new Color(0,255,0); //010
else if(tid==10) tColor=new Color(0,255,255);

//011

else if(tid==11) tColor=new Color(255,0,0); //100


else if(tid==12) tColor=new Color(255,0,255);
59

//101

else if(tid==13) tColor=new Color(255,255,0);

//110

else if(tid==14) tColor=new Color(255,255,255); //111


return(tColor);
}
private ArrayList HeaderAggregates=new ArrayList();
private String setHeaderAggregates()
{
PointCollection pc1=new PointCollection();
for(int t=0;t<MapRegions.length;t++)
{
Sensor aggregate=MapRegions[t].getSensor(0);
Point pt1=new Point();
pt1.setx(aggregate.getX());
pt1.sety(aggregate.getY());
pt1.setid(aggregate.getID());
pc1.addPoint(pt1);
}
int groupcount=Integer.parseInt(txtGroupCount.getText());
Correlation grouping1=new Correlation();
grouping1.set_nGroups(groupcount);
grouping1.setPoints(pc1);
grouping1.FindCorrelation();
for(int t=0;t<groupcount;t++)
{
Color tcolor=getUniqueColor(t+1);
//highlight all aggregate sensors in this group
PointCollection tgroup=grouping1.getGroup(t);
for(int j=0;j<tgroup.get_nPoints();j++)
{
60

int tid=tgroup.getPoint(j).getid();
int tx=getSensorX(tid);
int ty=getSensorY(tid);
g.setColor(tcolor);
g.drawRect(tx,ty,SensorRadius,SensorRadius);
g.setFont(new Font("Verdana",Font.BOLD,10));
g.drawString(""+(t+1),tx+SensorRadius,ty);
}
//choose header aggregate as aggregate nearest to group's centroid
Point pt1=tgroup.getPointNearestToCentroid();
int tsensorid=pt1.getid();
HeaderAggregates.add(new Integer(tsensorid));
}
return(grouping1.toString());
}
private Result existing() throws ClassNotFoundException, SQLException
{
//GuiLog gl=new GuiLog(frmLeft);
String predict = null;
g.setColor(Color.yellow);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c = DriverManager.getConnection("jdbc:odbc:sensor");
Statement st = c.createStatement();
Statement st1 = c.createStatement();
st1.executeUpdate("delete from predict");
st1.close();
g.drawLine(55,75,67,75);
g.drawString(" : Prediction Enable", 70, 76);

g.setColor(new Color(128,0,0));
61

g.drawLine(250,75,260,75);
g.drawString(" : Prediction Disaable", 266, 76);
//g.drawLine(x1,y1,x2,y2);
Result tresult=new Result();
long tstart=System.currentTimeMillis();
long cond=tstart+2;
int totaldata=0,unitdatasize=Integer.parseInt(txtUnitDataSize.getText());
for(int t=0;t<MapRegions.length;t++)
{
Sensor aggregate=MapRegions[t].getSensor(0);
System.out.println(t);
for(int j=1;j<MapRegions[t].getSensorCount();j++)
{
if(JistAPI.getTime()<cond){
Sensor member=MapRegions[t].getSensor(j);
//System.out.println(member.getID());
//Node nd=new Node(member.getID());
//nd.getHost();
//System.out.println(nd);
if(member.getID()!=DestSensor)
{
totaldata+=unitdatasize;
int x1=aggregate.getX(),y1=aggregate.getY();
int x2=member.getX(),y2=member.getY();
if(JistAPI.getTime()<cond&&x1<x2&&y1<y2){
if(j!=2){
g.setColor(new Color(128,0,0));
g.drawLine(x1,y1,x2,y2);
predict="Predict Disable";
}
}
62

else{
if(j!=2){
g.setColor(Color.yellow);
g.drawLine(x1,y1,x2,y2);
predict="Predict Enable";
}
}
JistAPI.sleep(1000);
Globals.wait(200);
}
String a="Head : "+aggregate.getID();
String b="Member : "+member.getID();

st.executeUpdate("insert into predict values('"+a+"','"+b+"','"+predict+"')");


}
}
}
st.close();
tresult.method=0;
tresult.TotalDataSize=totaldata;
long tend=System.currentTimeMillis();
double tseconds=((double)(tend-tstart))/(double)1000;
tresult.TimeTaken=tseconds;
return(tresult);
}
private void proposed(String recive,String nopacket)
{
ResultSet res;
//String dest=String.valueOf(DestSensor);
String data=txtUnitDataSize.getText();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
63

Connection c = DriverManager.getConnection("jdbc:odbc:sensor");

Statement st = c.createStatement();
Date date=new Date();
String sens="";
st.executeUpdate("insert into propose
values('"+DestSensor+"','"+txtUnitDataSize.getText()
+"','"+nopacket+"','"+date+"','"+sens+"','"+Hacker+"')");
st.close();
c.close();
//g.drawLine(x1,y1,x2,y2);
} catch (SQLException ex) {
Logger.getLogger(SensorDataprediction.class.getName()).log(Level.SEVERE, null,
ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(SensorDataprediction.class.getName()).log(Level.SEVERE, null,
ex);
}

}
private void showResult(Result tresult)
{
String tstr="Result ["+(tresult.method==0?"Existing":"Proposed")+"]:\r\n";
tstr+="TotalDataSize: "+tresult.TotalDataSize+" KB\r\n";
tstr+="TimeTaken: "+tresult.TimeTaken+" seconds\r\n\r\n";
//txtResult.append(tstr);
}
64

//main
public static void main(String args[])
{
new SensorDataprediction();
}
public void cloackeareas(){
int num_of_sensnode=cloakedarea;
int cloackarea_with=num_of_sensnode*3;
int cloackarea_height=num_of_sensnode*3;
cpw=cloackarea_with;
cph=cloackarea_height;
Graphics2D g2d=(Graphics2D)g;
g2d.setStroke(new BasicStroke(4.0f));
g.setColor(Color.white);
g.draw3DRect(port1, port2, cloackarea_with, cloackarea_height,true);
histogram();

}
public void histogram(){
try {
String no_of_sensnode ="";
System.out.println(no_of_sensnode);
for(int p1=port2;p1<(port2+cph);p1=p1+18){
for(int p2=port1;p2<(port1+cpw);p2=p2+18){
System.out.println(p1+"

"+p2);

// System.out.println(port2+cph+"

"+port1+cpw);

int xposition=p2;
int yposition=p1;

65

int n=map.findTotalSensorsCount();
int trad=SensorRadius-2;
boolean flag=false;
for(int i=0;i<map.getRegionCount();i++)
{
for(int j=0;j<MapRegions[i].getSensorCount();j++)
{
int x1=MapRegions[i].getSensorX(j)-trad+2;
int x2=MapRegions[i].getSensorX(j)+trad+2;
int y1=MapRegions[i].getSensorY(j)-trad+2;
int y2=MapRegions[i].getSensorY(j)+trad+2;
if(between(xposition,yposition,x1,y1,x2,y2)==true)
{
flag=true;
CurrentSensor1=MapRegions[i].getSensorID(j);
no_of_sensnode+=CurrentSensor1+",";
}
}
}
//make sure sensorid is displayed only when mouse is over it
if(flag==false)
{
CurrentSensor=-1;
}
}
}
displayStatus();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c = DriverManager.getConnection("jdbc:odbc:sensor");
Statement st = c.createStatement();
66

st.executeUpdate("update propose set sens_nodes='"+no_of_sensnode+"' where


data='" + txtUnitDataSize.getText().toString()+ "' and userid='" + DestSensor+ "'");
st.close();
c.close();
} catch (SQLException ex) {
Logger.getLogger(SensorDataprediction.class.getName()).log(Level.SEVERE, null,
ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(SensorDataprediction.class.getName()).log(Level.SEVERE, null,
ex);
}
}
public class udp
{
/** default server address. */
public static final String HOST = "localhost";
/** default client-server port. */
public static final int PORT = 3001;
public void main1()
{
try
{
System.out.println("server starting at t="+JistAPI.getTime());
DatagramSocket socket = new DatagramSocket(PORT);
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
int received = 0;
int r1=250,g1=150,b1=0;
//StringBuffer sb=new StringBuffer("");
String data="";
do
{
67

socket.receive(packet);
received++;
data=data+(new String(packet.getData(), packet.getOffset(), packet.getLength()));
System.out.println("received at t="+System.currentTimeMillis()/1000+
" ("+packet.getLength()+" bytes) "
+(new String(packet.getData(), packet.getOffset(), packet.getLength())));
txtdata.append("\n");
txtdata.append("received at t="+System.currentTimeMillis()/1000+
" ("+packet.getLength()+" bytes) "
+(new String(packet.getData(), packet.getOffset(), packet.getLength())));
// long tstart=System.currentTimeMillis();
Path tpath=findPath(SourceSensor,DestSensor);
drawPath(tpath);
g.setColor(new Color(r1, g1, b1));
//

long tend=System.currentTimeMillis();

//

double tseconds=((double)(tend-tstart))/(double)1000;

//

g.setColor(new Color(i*10));

//

g.drawString("Existing : "+tseconds, 90, 385);


r1=r1-40;
b1=b1+40;
g1=g1-25;
}
while(packet.getLength()>0);
socket.close();
System.out.println("server received "+received+" packets.");
proposed(data,received+" Packets");
//JOptionPane.showMessageDialog(null, "node"+ DestSensor+"received "+received+"

packets.");
}
catch(Exception e)
{
e.printStackTrace();
}
68

}
public void main(String a)
{
String dat=a;
String dat1;
String dat2,dat3,dat4,dat5;
dat1=dat.substring(0, 4);
dat2=dat.substring(4, 10);
dat3=dat.substring(10, 15);
dat4=dat.substring(15, 20);
dat5=dat.substring(20, 25);
//

for(int i=0;i<dat.length();i++){

//

if(i<4){

//

dat1=

//
//

}
}
try {
System.out.println("client starting at t="+JistAPI.getTime());
DatagramSocket socket = new DatagramSocket();
byte[] buf = dat1.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length,

InetAddress.getByName(HOST), PORT);
byte[] buf1 =dat2.getBytes();
DatagramPacket packet1 = new DatagramPacket(buf1, buf.length,
InetAddress.getByName(HOST), PORT);
byte[] buf2 =dat3.getBytes();
DatagramPacket packet2 = new DatagramPacket(buf2, buf.length,
InetAddress.getByName(HOST), PORT);
byte[] buf3 =dat4.getBytes();
DatagramPacket packet3 = new DatagramPacket(buf3, buf.length,
InetAddress.getByName(HOST), PORT);
byte[] buf4 =dat5.getBytes();
DatagramPacket packet4 = new DatagramPacket(buf4, buf.length,
InetAddress.getByName(HOST), PORT);
69

for(int i=0; i<5; i++)


{
System.out.println("sent at t="+JistAPI.getTime());
System.out.flush();
if(i==0){
try {
socket.send(packet);
} catch (IOException ex) {
Logger.getLogger(udp.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if(i==1){
try {
socket.send(packet1);
} catch (IOException ex) {
Logger.getLogger(udp.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if(i==2){
try {
socket.send(packet2);
} catch (IOException ex) {
Logger.getLogger(udp.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if(i==3){
try {
socket.send(packet3);
} catch (IOException ex) {
70

Logger.getLogger(udp.class.getName()).log(Level.SEVERE, null, ex);


}
} else if(i==4){
try {
socket.send(packet4);
} catch (IOException ex) {
Logger.getLogger(udp.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Thread.sleep(2000);
}
// sending final packet
System.out.println("terminate packet sent at t="+JistAPI.getTime());
System.out.flush();
buf = new byte[0];
packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(HOST),
PORT);
socket.send(packet);
socket.close();
} catch (IOException ex) {
Logger.getLogger(udp.class.getName()).log(Level.SEVERE, null, ex);
//

} catch (InterruptedException ex) {

//

Logger.getLogger(udp.class.getName()).log(Level.SEVERE, null, ex);

//
}
catch(Exception e)
{
e.printStackTrace();
}
}
// class: Client
71

/**
* Program entry point: small UDP test that can be run
* inside and outside of JiST.
*
* @param args command-line parameters
*/
public void m()
{
try
{
// protocol mapper
Mapper protMap = new Mapper(Constants.NET_PROTOCOL_MAX);
protMap.mapToNext(Constants.NET_PROTOCOL_UDP);
// net
PacketLoss pl = new PacketLoss.Zero();
NetIp net = new NetIp(NetAddress.LOCAL, protMap, pl, pl);
// trans
TransUdp udp = new TransUdp();
// hookup
net.setProtocolHandler(Constants.NET_PROTOCOL_UDP, udp.getProxy());
udp.setNetEntity(net.getProxy());
// applications
AppJava server = new AppJava(udp.class);
server.setUdpEntity(udp.getProxy());
AppJava client = new AppJava(udp.class);
client.setUdpEntity(udp.getProxy());
// run apps
server.getProxy().run(null);
JistAPI.sleep(1);
72

client.getProxy().run(null);
}
catch(Exception e)
{
e.printStackTrace();
}
}
} // class: udp

}
SensorNetwork.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package greendata;
//import jist.runtime.JistAPI;
import java.net.*;
import java.util.Scanner;
import jist.runtime.JistAPI;
/**
*
* @author admin
*/
public class Sensornetwork {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws UnknownHostException {
// new Login().setVisible(true);
new SensorDataprediction();
73

}
}
Mainform.java
package greendata;
import java.awt.Color;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author Admin
*/
public class mainform extends javax.swing.JFrame {
/** Creates new form mainframe */
public mainform() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GENBEGIN:initComponents
private void initComponents() {
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
74

jLabel1 = new javax.swing.JLabel();


jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
//

jMenuItem4 = new javax.swing.JMenuItem();


jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel2.setFont(new java.awt.Font("Algerian", 3, 18)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("PROTECTING POSITION SUPERVISE SYSTEM ");
getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(120,

160, 430, 60));


jLabel3.setFont(new java.awt.Font("Vivaldi", 3, 36)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Welcome to....");
getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20,
100, 210, 40));
//jLabel1.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/sensornetwork/image/ig.png"))); // NOI18N
// getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0,
0, 610, 450));
jMenu1.setText("File");
jMenuItem1.setText("Logout");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
75

public void actionPerformed(java.awt.event.ActionEvent evt) {


jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);

//
jMenuItem3.setText("Report");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem3);
//

jMenuItem4.setText("Start Agregation");

//

jMenuItem4.addActionListener(new java.awt.event.ActionListener() {

//

public void actionPerformed(java.awt.event.ActionEvent evt) {

//
//

jMenuItem4ActionPerformed(evt);
}

//

});

//

jMenu1.add(jMenuItem4);
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
pack();
}// </editor-fold>//GEN-END:initComponents

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN76

FIRST:event_jMenuItem1ActionPerformed
this.setVisible(false);
dispose();
new Login().setVisible(true);
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_jMenuItem1ActionPerformed
new reports().setVisible(true);
}

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_jMenuItem2ActionPerformed

}//GEN-LAST:event_jMenuItem2ActionPerformed

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and
feel.
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
77

javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(mainform.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(mainform.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(mainform.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(mainform.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new mainform().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
78

private javax.swing.JLabel jLabel3;


private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
//

private javax.swing.JMenuItem jMenuItem4;


// End of variables declaration//GEN-END:variables

}
Report.java
package greendata;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.*;
/**
*
* @author Admin
*/
public class reports extends javax.swing.JFrame
{
Socket s;
DataInputStream din;
String s1;

79

/** Creates new form RECEIVER */


public reports()
{
initComponents();
proposed1();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jOptionPane1 = new javax.swing.JOptionPane();
jLabel4 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();

setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(400, 400));
setName("RECEIVER"); // NOI18N
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel4.setFont(new java.awt.Font("Elephant", 3, 48));
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText(" REPORT");
getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(160,
20, 300, 50));

80

jTable1.setFont(new java.awt.Font("Rockwell", 1, 14));


jTable1.setForeground(new java.awt.Color(0, 51, 204));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
81

{null, null, null, null, null},


{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
},
new String [] {
"Userid", "Data", "No_Of_packets", "Date_and_Time", "Sensing_nodes"
}
));
jScrollPane1.setViewportView(jTable1);
jTable1.getColumnModel().getColumn(0).setPreferredWidth(3);
getContentPane().add(jScrollPane1, new
org.netbeans.lib.awtextra.AbsoluteConstraints(40, 150, 770, 280));
getAccessibleContext().setAccessibleParent(this);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public void proposed1()
{
int cut=0;
82

//String user=(String) jc.getSelectedItem();


Connection c=null;
//boolean b=true;
int i=0;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c = DriverManager.getConnection("jdbc:odbc:sensor");
//st=c.createStatement();
System.out.println("dFadf");
PreparedStatement stt = c.prepareStatement("select * from propose");
ResultSet rs=stt.executeQuery();
while (rs.next()) {
cut++;
int j=0;
String userid = rs.getString("userid");
String data = rs.getString("data");
String no_of_packet = rs.getString("no_of_packet");
String data_and_time = rs.getString("data_and_time");
String sens_nodes = rs.getString("sens_nodes");
// String hacking = rs.getString("hacking");
jTable1.setValueAt(userid, i, j);
jTable1.setValueAt(data, i, j+1);
jTable1.setValueAt(no_of_packet, i, j+2);
jTable1.setValueAt(data_and_time, i, j+3);
jTable1.setValueAt(sens_nodes, i, j+4);
//jTable1.setValueAt(hacking, i, j+5);
i++;
}stt.close();
83

c.close();
}
catch (Exception ex)
{
}}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new reports().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel4;
private javax.swing.JOptionPane jOptionPane1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
}

Sens.java
package greendata;
public class sens extends javax.swing.JFrame {
/** Creates new form NewJFrame */
public sens() {
initComponents();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
84

public void run() {


new sens().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JFrame jFrame1;
private javax.swing.JLabel jLabel2;
// End of variables declaration
}

85

C. SAMPLE INPUT AND OUTPUT

GREEN DATA CENTER

86

WELCOME SCREEN

87

NETWORK LIST

88

CREATE TABLE OF NETWORK LIST

89

INPUT NETWORK LIST

90

DATA TRANSFER

91

NETWORK NODES -1

92

NETWORK NODES -2

93

LOGOUT SCREEN

94

You might also like