You are on page 1of 158

Study Material and Syllabus

review/scope of CBGS syllabus


for TYBSc Computer Science
w.e.f 2!"#!$%
Compiled and &resented
by
Syllabus Committee and B'S
Members
at
Mulund Colle(e of Commerce
TYBSC
Computer Science
USCS501 & USCS601
Paper 1
Data Communication,
Networking &
Security
17Jul2013
1
Workshop on
T Y B S C t S i T.Y. B.Sc. Computer Science
Credit Based Syllabus
USCS501 ,USCS601
Semester V
17Jul2013
2
Reference Books
Reference1 (All Units)
Data Communication &Networkingg
Behrouz A Forouzan
3
UNIT I
Introduction - Data Communication, Networks,
Internet, Intranet, Protocols, OSI & TCP/IP Models,
Addressing. (Chapter 1, 2) (3 lectures) Addressing. (Chapter 1, 2) (3 lectures)
Physical Layer Signals, Analog, Digital, Analog VS
Digital, Transmission Impairment, Data Rate Limits,
Performance (Chapter 3) (3 lectures)
Di i l T i i Li C di (U i l P l Digital Transmission Line Coding (Unipolar, Polar,
Biphase), Block Coding(4B/5B Encoding), Analog to
digital conversion, PCM, Transmission Modes.
(Chapter 3 Pg 101-110, 115-117, 120-135) (4 lectures)
4
17Jul2013
3
UNIT I contd
Analog Transmission Digital to analog
conversion(ASK,FSK,PSK, QAM), Analog to Analog
conversion (Chapter 5) (4 lectures) conversion (Chapter 5) (4 lectures)
5
Line Coding schemes
Encoding of 0 and 1 bit
Polarity Polarity
DC component
Synchronization
Bandwidth requirement
6
17Jul2013
4
Guided media
Structure
Sub-Types
Connector
Application
Performance
Interference
Noise
Attenuation Attenuation
7
UNIT II
Multiplexing FDM, WDM, Synchronous TDM(time slots &frames,
interleaving, data rate management) (4 lectures)
SpreadSpectrum FHSS, DSSS p p ,
(Chapter 6 Pg 161-175, 180-185) (2 lectures)
TransmissionMedia Guided &Unguided
(Chapter 7) (5 lectures)
Switching Switching, Circuit-Switched Networks, Datagram
f f networks, Concept of Virtual circuit networks, structure of circuit
switch & packet switch, Concepts of DSL & ADSL
(Chapter 8, Pg 213-223, 227-235, Chapter 9 - Pg 251-254)
(5 lectures)
8
17Jul2013
5
UNIT III
Data Link Layer Error correction & detection, Types of errors,
Detection VS Correction, Block Coding, Hamming Distance, Linear
Block codes(single parity check, hamming codes), Cyclic codes, CRC
Encoder & Decoder, CRC Polynomial & its degree, Checksum
(Chapter 10 - Pg 267-292, 298-301) (5 lectures)
Data Link Control & Protocols Framing, Flow & Error Control,
Simplest, Stop-N-Wait, Stop-N-Wait ARQ, Go Back N ARQ, Selective
Repeat ARQ, Piggybacking
(Chapter 11 Pg 307-340) (5 lectures)
HDLC & PPP HDLC Modes, HDLC Frames, PPP, PPP Transition
states (Chapter 11 Pg 340-350) (3 lectures)
9
UNIT IV
Multiple Access Random(CSMA), Controlled(Reservation, Polling,
Token Passing), Channelization(FDMA, TDMA, CDMA),
(Chapter 12) (5 lectures)
Wired LAN LLC, MAC, Ethernet, Ethernet frame, Addressing,
Concept of MBaseN Ethernet, Bridged, Switched, Full Duplex
Ethernet, Concept of Fast(purpose & goals) & Gigabit
Ethernet(purpose &goals),
(Chapter 13 Pg 395-409) (2 lectures)
Wireless LAN - Introduction to WLAN(Architecture, Hidden,
Exposed Station Problem), Introduction to Bluetooth & Architecture,
Cellular telephony, Concept of 1G, 2G, 3G cellular telephony
(Chapter 13 Pg 421-426, 429-431, Chapter 14 Pg 434-436,
Chapter 16 Pg 467-469, 470 (last para.), 477) (4 lectures)
10
17Jul2013
6
UNIT IV
Connecting Devices Repeaters, Hubs, Bridges, Spanning tree
algorithm, Two & Three layer Switches, Routers, Gateways,
Backbone networks, Concept of VLAN
(Chapter 15 Pg 445-460) (3 lectures)
11
Semester VI
17Jul2013
7
Reference Books
Reference 1 (Unit I &II)
Data Communication &Networking
Behrouz A Forouzan Behrouz A Forouzan
Reference 2 (Unit III)
Network Security Essentials: Applications And
Standards (3
rd
Edition)
WilliamStallings
Reference 3 (Unit IV)
Cryptography &network security
Behrouz A. Forouzan, Debdeep Mukhopadhyay
13
UNIT I
Network Layer Logical addressing, IPv4 Addresses, Classful &
Classless addresses, NAT, IPv6 Addressing
(Chapter 19 Pg 549-558, 563-572) (3 lectures)
Network Layer Protocol Internetworking, IPv4, IPv4 protocol
packet format, IPv6 Protocol & Packet format, IPv4 VS IPv6,
Transition from IPv4 to IPv6, Address Resolution protocols(ARP,
RARP), BOOTP, DHCP
(Chapter 20, Chapter 21 Pg 611-620) (7 lectures)
Routing Protocols - Delivery, forwarding, routing, types of
routing, routing tables, Unicast Routing, Unicast Routing protocols,
RIP, Concepts of OSPF, BGP &Multicast Routing (up to applications)
(Chapter 22 Pg 647-671, 676-682) (6 lectures)
14
17Jul2013
8
UNIT II
Transport Layer - Process to process delivery, UDP, TCP
(Chapter 23 Pg 703-735) (7 lectures)
Congestion Control & Quality of Service Data traffic,
Congestion, Congestion Control(Open Loop, Closed Loop &
Congestion control in TCP), QoS and Flow Characteristics
(Chapter 24 Pg 761-773, 775-776) (4 lecture)
Application Layer - DNS, Remote Logging(Telnet), SMTP, FTP,
WWW HTTP (Chapter 25 26 27) (6 lectures) WWW, HTTP (Chapter 25, 26, 27) (6 lectures)
15
UNIT III
Introduction Introduction to system and network security,
security attacks, security services and mechanisms.
Chapter 1 (1.1 to 1.6), (2 lectures)
Malicious Software And Internet Security viruses and related
threats, virus countermeasures, denial of service attacks, Hacking,
Security policies and plan, Strategies for a secure network.
Chapter 10, (3 lectures)
16
17Jul2013
9
UNIT III
Firewall and I ntrusion Detection: Firewalls and their
types, DMZ, Limitations of firewalls
Chapter 11(11 1) (2 lectures) Chapter 11(11.1) (2 lectures)
Intruders, Intrusion detection (Host based, Networked,
Distributed), IDS.
Chapter 9 (9.1 and 9.2) (2 lectures)
17
Reference Books
Reference3 (Unit IV)
Cryptography &network security yp g p y y
Behrouz A. Forouzan, Debdeep
Mukhopadhyay-second edition
18
17Jul2013
10
UNIT IV
Cryptography Traditional and Modern Symmetric-Key
Ciphers
Additive multiplicative affine autokey transposition Additive, multiplicative, affine, autokey, transposition,
stream, block cipher
Chapter 3 (3.1,3.2(till pg 57),3.4)
Chapter 5( 5.1-5.2)
(3 lectures)
DES
BASICDES structure
Chapter 6 ( 6.1-6.2)
19
UNIT IV
AES
Basic AES structure
Chapter 7 (71 73) Chapter 7 (7.1-7.3)
3 lectures
Asymmetric Key Cryptography, RSA and ELGAMAL
cryptosystems
Introduction, RSA key generation, Elgamal algorithm odu o , y g a o , ga a ago
Chapter 10 (10.1(till 10.2.3) ,10.2, 10.4) (3 lectures)
Message Digest
Chapter 11 (11.1, 11.3) (2 lectures)
20
17Jul2013
11
UNIT IV
Digital Signature
Comparison, process and services, attacks
Digital schemes excluded
Chapter 13(13.1 -13.4) (2 lectures)
Key Management
Symmetric key distributions, kerberos, symmetric key
agreement public key distributions agreement, public key distributions
Otway rees and needhamprotocol excluded
Chapter 15(15.1-15.4) (2 lectures)
21
UNIT IV
Security at Application Layer (E-MAIL, PGP and
S/MIME)
PGP packets excluded PGP packets excluded
Chapter 16 (16.1,16.2(till 16.2.6), 16.3) (3 lectures)
Security at Transport Layer (SSL and TLS)
SSL message formats excluded
Chapter 17 (171-172 174) (2 lectures) Chapter 17 (17.1 17.2,17.4) (2 lectures)
Security at Network Layer (IPSec)
Chapter 18 (18.1 -18.4) (2 lectures)
22
17Jul2013
12
Thank you !!!
Ms. Megha Sawant - Ruia College
23
TYBSC CS, Sem V
(2013-2014)

Handbook for USCSP05
(Practicals based on USCS501)

University list of experiments:
1. Study of URL, InetAddress and its members
2. Study of URLConnection & read the contents
3. Study of URLConnection & write to it
4. Study of Connection-less approach using datagram
5. Study of connection-oriented approach using ServerSocket
6. Creating server process using ServerSocket
7. Sending Email through Java
8. Designing RMI Application

The Java platform is extremely preferable to write an application program require to communicate with
the resources on network. Java, mainly focuses on the networking relating the description of the
networking capabilities of the Java platform and second one is describes a brief summary of networking
in a very simple manner that how to use URLs, sockets, and datagrams.
In Java, there is a java.net package provides the network support. All the classes for making a network
program are available in the java.net package.

Basic concepts of Networking:

The java.net package provides powerful and easy-to-use networking capabilities. The classes of java.net
falls into two categories: the socket API and tools for working with Uniform Resource Locators (URLs).
Java sockets API provides access to the standard network protocols used for communications between
hosts on the Internet. Sockets are the mechanism underlying all other kinds of portable networked
communications. They send streams of data between applications that may or may not be on the same
host.

Using the socket classes, you can communicate with any server on the Internet or implement your own
Internet server. A number of classes are provided to make it convenient to use Uniform Resource
Locators (URLs) to retrieve data on the Internet. Computers running on the Internet communicate to
each other using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP).

When you write Java programs that communicate over the network, you are programming at the
application layer. Typically, you don't need to concern yourself with the TCP and UDP layers. Instead,
you can use the classes in the java.net package. These classes provide system-independent network
communication. However, to decide which Java classes your programs should use, you do need to
understand how TCP and UDP differ.

URL is the acronym for Uniform Resource Locator. It is a reference (an address) to a resource on the
Internet. You provide URLs to your favorite Web browser so that it can locate files on the Internet in the
2

same way that you provide addresses on letters so that the post office can locate your correspondents.
The easiest way to create a URL object is from a String that represents the human-readable form of the
URL address. This is typically the form that another person will use for a URL.

What Is a URL?

If you've been surfing the Web, you have undoubtedly heard the term URL and have used URLs to
access HTML pages from the Web.
It's often easiest, although not entirely accurate, to think of a URL as the name of a file on the World
Wide Web because most URLs refer to a file on some machine on the network. However, remember that
URLs also can point to other resources on the network, such as database queries and command output.

Definition:
URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the
Internet.

A URL has two main components:
Protocol identifier: For the URL http://example.com, the protocol identifier is http.
Resource name: For the URL http://example.com, the resource name is example.com.
Note that the protocol identifier and the resource name are separated by a colon and two forward slashes.
The protocol identifier indicates the name of the protocol to be used to fetch the resource. The example
uses the Hypertext Transfer Protocol (HTTP), which is typically used to serve up hypertext documents.
HTTP is just one of many different protocols used to access different types of resources on the net.
Other protocols include File Transfer Protocol (FTP), Gopher, File, and News.
The resource name is the complete address to the resource. The format of the resource name depends
entirely on the protocol used, but for many protocols, including HTTP, the resource name contains one
or more of the following components:
Host Name
The name of the machine on which the resource lives.
Filename
The pathname to the file on the machine.
Port Number
The port number to which to connect (typically optional).
Reference
A reference to a named anchor within a resource that usually identifies a specific location within
a file (typically optional).
For many protocols, the host name and the filename are required, while the port number and reference
are optional. For example, the resource name for an HTTP URL must specify a server on the network
(Host Name) and the path to the document on that machine (Filename); it also can specify a port number
and a reference.
3

Socket Programming

A socket is one end-point of a two-way communication link between two programs running on the
network. Socket classes are used to represent the connection between a client program and a server
program. The java.net package provides two classes--Socket and ServerSocket--that implement the
client side of the connection and the server side of the connection, respectively.

Reading from and Writing to a Socket
1. Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream according to the server's protocol.
4. Close the streams.
5. Close the socket.

In contrast, applications that communicate via datagrams send and receive completely independent
packets of information. These clients and servers do not have and do not need a dedicated point-to-point
channel. The delivery of datagrams to their destinations is not guaranteed. Nor is the order of their
arrival.

When two applications want to communicate to each other reliably, they establish a connection and send
data back and forth over that connection. This is analogous to making a telephone call. If you want to
speak to Aunt Beatrice in Kentucky, a connection is established when you dial her phone number and
she answers. You send data back and forth over the connection by speaking to one another over the
phone lines. Like the phone company, TCP guarantees that data sent from one end of the connection
actually gets to the other end and in the same order it was sent. Otherwise, an error is reported.

Definition: TCP (Transmission Control Protocol) is a connection-based protocol that provides a
reliable flow of data between two computers.

The UDP protocol provides for communication that is not guaranteed between two applications on the
network. UDP is not connection-based like TCP. Rather, it sends independent packets of data, called
datagrams, from one application to another. Sending datagrams is much like sending a letter through the
postal service: The order of delivery is not important and is not guaranteed, and each message is
independent of any other.

Definition: UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called
datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based
like TCP.

Experiment 1: Study of URL, InetAddress and its members

1.1 GetURL.java
package je3.net;
4

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

/**
* This simple program uses the URL class and its openStream() method to
* download the contents of a URL and copy them to a file or to the console.
**/
public class GetURL {
public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
try {
// Check the arguments
if ((args.length != 1)&& (args.length != 2))
throw new IllegalArgumentException("Wrong number of args");

// Set up the streams
URL url = new URL(args[0]); // Create the URL
in = url.openStream(); // Open a stream to it
if (args.length == 2) // Get an appropriate output stream
out = new FileOutputStream(args[1]);
else out = System.out;

// Now copy bytes from the URL to the output stream
byte[] buffer = new byte[4096];
int bytes_read;
while((bytes_read = in.read(buffer)) != -1)
out.write(buffer, 0, bytes_read);
}
// On exceptions, print error message and usage message.
catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java GetURL <URL> [<filename>]");
}
finally { // Always close the streams, no matter what.
try { in.close(); out.close(); } catch (Exception e) {}
}
}
}

Complete following steps:
1. Compile Program.
2. Run Program with following commands.

5






Note:

URL is given as command line argument to Java program. It can be in any of the following forms:

file:///C:/hello.html
(make sure that hello.html is kept in C:\)

http://localhost:9090/Girish/hello.html
(make sure that Tomcat is started and hello.html is kept in webapps\Girish folder)

http://myserver:9090/Girish/hello.html
(make sure that in hosts file following entry is done
127.0.0.1 myserver
and Tomcat is started and hello.html is kept in webapps\Girish folder)

http://localhost:/Girish/hello.html
(make sure that WAMP server is started and hello.html is kept in C:\wamp\www folder)

http://myserver:/Girish/hello.html
(make sure that WAMP server is started and hello.html is kept in C:\wamp\www\Girish folder)
6

Create virtual server myserver with the following additions in httpd.conf file
Edit the C:\wamp\bin\apache\Apache2.2.11\conf\httpd.conf (add following content)


</Directory>

NameVirtualHost 127.0.0.1
<VirtualHost 127.0.0.1>
ServerName localhost
DocumentRoot 'C:\wamp\www'
</VirtualHost>
<VirtualHost 127.0.0.1>
ServerName myserver
DocumentRoot 'C:\wamp\www\Girish'
</VirtualHost>

Make sure that
127.0.0.1 myserver
is added in hosts file. C:\WINDOWS\system32\drivers\etc\hosts


1.2 GetURLInfo.java

package je3.net;
import java.net.*;
import java.io.*;
import java.util.Date;

/**
* A class that displays information about a URL.
**/
public class GetURLInfo {
/** Use the URLConnection class to get info about the URL */
public static void printinfo(URL url) throws IOException {
URLConnection c = url.openConnection(); // Get URLConnection from URL
c.connect(); // Open a connection to URL

// Display some information about the URL contents
System.out.println(" Content Type: " + c.getContentType());
System.out.println(" Content Encoding: " + c.getContentEncoding());
System.out.println(" Content Length: " + c.getContentLength());
System.out.println(" Date: " + new Date(c.getDate()));
System.out.println(" Last Modified: " +new
Date(c.getLastModified()));
System.out.println(" Expiration: " + new Date(c.getExpiration()));

// If it is an HTTP connection, display some additional information.
if (c instanceof HttpURLConnection) {
HttpURLConnection h = (HttpURLConnection) c;
System.out.println(" Request Method: " + h.getRequestMethod());
System.out.println(" Response Message: " +h.getResponseMessage());
System.out.println(" Response Code: " + h.getResponseCode());
7

}
}

/** Create a URL, call printinfo() to display information about it. */
public static void main(String[] args) {
try
{ printinfo(new URL(args[0])); }
catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java GetURLInfo <url>");
}
}
}







1.3 InetTest.java

package je3.net;
import java.net.*;
class InetTest
{
public static void main(String[] args)
{
try
{
8

InetAddress i = InetAddress.getByName(args[0]);
System.out.println(i.getHostAddress());
}
catch(Exception e)
{
e.printStackTrace();
}
InetTest i = new InetTest();
}
}



1.4 InetTest1.java

package je3.net;
import java.net.*;

class InetTest1
{
public static void main(String[] args)
{
try
{
InetAddress i = InetAddress.getLocalHost();
System.out.println(i.getHostAddress());
}
catch(Exception e)
{
e.printStackTrace();
}
InetTest1 j1 = new InetTest1();
}
}




9

1.5 URLDemo.java

package je3.net;

import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.util.Date;

class URLDemo
{
long d;
public static void main(String args[])throws Exception
{
URL u=new URL("http://127.0.0.1:9090/Girish/hello.html");
URLConnection uc=u.openConnection();
HttpURLConnection huc=(HttpURLConnection)uc;

Date d=new Date(uc.getDate());
System.out.println("File Name = "+u.getFile());
System.out.println("Host Name= "+u.getHost());
System.out.println("Path Name= "+u.getPath());
System.out.println("Port Name= "+u.getPort());
System.out.println("Protocol Name= "+u.getProtocol());
System.out.println("Reference Name= "+u.getRef());
System.out.println("User Info= "+u.getUserInfo());
System.out.println("Content Name= "+u.getContent());
System.out.println("Authority Name= "+u.getAuthority());

System.out.println("Content Type= "+uc.getContentType());
System.out.println("Length= "+uc.getContentLength());
System.out.println("Expiration Date= "+uc.getExpiration());
System.out.println("Encoding Type= "+uc.getContentEncoding());
System.out.println("Last Modified Date= "+uc.getLastModified());
System.out.println("Date= "+d.toString());

System.out.println("Request Method= "+huc.getRequestMethod());
System.out.println("Response Message= "+huc.getResponseMessage());
System.out.println("Response Code= "+huc.getResponseCode());
}
}

10



1.6 InetAddressTest.java

// Demonstrate InetAddress

import java.net.*;

class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("osborne.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}




11

JAVA - URL PROCESSING
URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a
Web page or FTP directory. How to write Java programs that communicate with a URL are explained
here. A URL can be broken down into parts, as follows:
protocol://host:port/path?query#ref
Examples of protocols include HTTP, HTTPS, FTP, and File. The path is also referred to as the
filename, and the host is also called the authority.
The following is a URL to a Web page whose protocol is HTTP:
http://www.amrood.com/index.htm?language=en#j2se
Notice that this URL does not specify a port, in which case the default port for the protocol is used. With
HTTP, the default port is 80.
URL Class Methods:
The java.net.URL class represents a URL and has complete set of methods to manipulate URL in Java.
The URL class has several constructors for creating URLs, including the following:
SN Methods with Description
1 public URL(String protocol, String host, int port, String file) throws
MalformedURLException.
Creates a URL by putting together the given parts.
2 public URL(String protocol, String host, String file) throws MalformedURLException
Identical to the previous constructor, except that the default port for the given protocol is used.
12

3 public URL(String url) throws MalformedURLException
Creates a URL from the given String
4 public URL(URL context, String url) throws MalformedURLException
Creates a URL by parsing the together the URL and String arguments
The URL class contains many methods for accessing the various parts of the URL being represented.
Some of the methods in the URL class include the following:
SN Methods with Description
1 public String getPath()
Returns the path of the URL.
2 public String getQuery()
Returns the query part of the URL.
3 public String getAuthority()
Returns the authority of the URL.
4 public int getPort()
Returns the port of the URL.
13

5 public int getDefaultPort()
Returns the default port for the protocol of the URL.
6 public String getProtocol()
Returns the protocol of the URL.
7 public String getHost()
Returns the host of the URL.
8 public String getHost()
Returns the host of the URL.
9 public String getFile()
Returns the filename of the URL.
10 public String getRef()
Returns the reference part of the URL.
11 public URLConnection openConnection() throws IOException
Opens a connection to the URL, allowing a client to communicate with the resource.
14

Example:
The following URLDemo program demonstrates the various parts of a URL. A URL is entered on the
command line, and the URLDemo program outputs each part of the given URL.
1.7 URLDemo.java

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

public class URLDemo
{
public static void main(String [] args)
{
try
{
URL url = new URL(args[0]);
System.out.println("URL is " + url.toString());
System.out.println("protocol is "
+ url.getProtocol());
System.out.println("authority is "
+ url.getAuthority());
System.out.println("file name is " + url.getFile());
System.out.println("host is " + url.getHost());
System.out.println("path is " + url.getPath());
System.out.println("port is " + url.getPort());
System.out.println("default port is "
+ url.getDefaultPort());
System.out.println("query is " + url.getQuery());
System.out.println("ref is " + url.getRef());
}catch(IOException e)
{
e.printStackTrace();
}
}
}
A sample run of the third program would produce following result:

15

URLConnections Class Methods:
The openConnection() method returns a java.net.URLConnection, an abstract class whose subclasses
represent the various types of URL connections.
For example:
If you connect to a URL whose protocol is HTTP, the openConnection() method returns an
HttpURLConnection object.
If you connect to a URL that represents a JAR file, the openConnection() method returns a
JarURLConnection object.
etc...
The URLConnection class has many methods for setting or determining information about the
connection, including the following:
SN Methods with Description
1 Object getContent()
Retrieves the contents of this URL connection.
2 Object getContent(Class[] classes)
Retrieves the contents of this URL connection.
3 String getContentEncoding()
Returns the value of the content-encoding header field.
4 int getContentLength()
16

Returns the value of the content-length header field.
5 String getContentType()
Returns the value of the content-type header field.
6 int getLastModified()
Returns the value of the last-modified header field.
7 long getExpiration()
Returns the value of the expires header field.
8 long getIfModifiedSince()
Returns the value of this object's ifModifiedSince field.
9 public void setDoInput(boolean input)
Passes in true to denote that the connection will be used for input. The default value is
true because clients typically read from a URLConnection.
10 public void setDoOutput(boolean output)
Passes in true to denote that the connection will be used for output. The default value is
false because many types of URLs do not support being written to.
17

11 public InputStream getInputStream() throws IOException
Returns the input stream of the URL connection for reading from the resource.
12 public OutputStream getOutputStream() throws IOException
Returns the output stream of the URL connection for writing to the resource
13 public URL getURL()
Returns the URL that this URLConnection object is connected to
Example:
The following URLConnectionDemo program connects to a URL entered from the command line.
If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and the data in
the resource is read one line at a time.
1.8 URLConnDemo.java

import java.net.*;
import java.io.*;
public class URLConnDemo
{
public static void main(String [] args)
{
try
{
URL url = new URL(args[0]);
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection)
{
connection = (HttpURLConnection) urlConnection;
}
else
{
System.out.println("Please enter an HTTP URL.");
return;
}
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
18

String urlString = "";
String current;
while((current = in.readLine()) != null)
{
urlString += current;
}
System.out.println(urlString);
}catch(IOException e)
{
e.printStackTrace();
}
}
}
A sample run of the third program would produce following result:






















19

Experiment 2: Study of URLConnection & read from URLConnection

The URLConnection class contains many methods that let you communicate with the URL over the
network. URLConnection is an HTTP-centric class; that is, many of its methods are useful only when
you are working with HTTP URLs. However, most URL protocols allow you to read from and write to
the connection. This section describes both functions.

Reading from a URLConnection

The following program performs the same function as the URLReader program shown in Reading
Directly from a URL.
However, rather than getting an input stream directly from the URL, this program explicitly retrieves
a URLConnection object and gets an input stream from the connection. The connection is opened
implicitly by calling getInputStream. Then, like URLReader, this program creates a BufferedReader on
the input stream and reads from it. The bold statements highlight the differences between this example
and the previous:

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

public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}

Compile the program and run it. (Internet connectivity is required)
20


The output from this program is identical to the output from the program that opens a stream directly
from the URL. You can use either way to read from a URL. However, reading from
a URLConnection instead of reading directly from a URL might be more useful. This is because you can
use the URLConnection object for other tasks (like writing to the URL) at the same time.
2. URLConnection is a general-purpose class for accessing the attributes of a remote resource. Once
you make a connection to a remote server, you can use URLConnection to inspect the properties of
the remote object before actually transporting it locally. These attributes are exposed by the HTTP
protocol specification and, as such, only make sense for URL objects that are using the HTTP
protocol. We'll examine the most useful elements of URLConnection here.

In the following example, we create a URLConnection using the openConnection( ) method of
a URLobject and then use it to examine the document's properties and content:

package je3.net;

// Demonstrate URLConnection.
import java.net.*;
import java.io.*;
import java.util.Date;
class UCDemo
{
public static void main(String args[]) throws Exception {
int c;
21

URL hp = new URL("http://www.java-samples.com/testpapers/index.php/");
URLConnection hpCon = hp.openConnection();
System.out.println("Date: " + new Date(hpCon.getDate()));
System.out.println("Content-Type: " +
hpCon.getContentType());
System.out.println("Expires: " + hpCon.getExpiration());
System.out.println("Last-Modified: " +
new Date(hpCon.getLastModified()));
int len = hpCon.getContentLength();
System.out.println("Content-Length: " + len);

if (len > 0) {
System.out.println("=== Content ===");
InputStream input = hpCon.getInputStream();
int i = len;
while ((c = input.read()) != -1) {
System.out.print((char) c);
}
input.close();
} else {
System.out.println("No Content Available");
}
}
}



The program establishes an HTTP connection to http://www.java-samples.com over port 80
and requests the document /testpapers/index.php/. We then list out the header values and retrieve
the content.
The URL and URLConnection classes are good enough for simple programs that want to connect
to HTTP servers to fetch content. For more complex applications, you'll probably find that you are
better off studying the specification of the HTTP protocol and implementing your own wrappers.

3. URL Connection Reader

Using this example, you will learn about the url connection reader. Here, first of all we are going to
define class named "URLConnectionReader". After that we make a URL object passing a url
"http://www.javajazzup.com" as string in its constructor.

openConnection():
This is the method that returns a URLConnection object that represents a connection to the remote
22

object referred to by the URL. A new connection is opened every time by calling
the openConnection()method of the protocol handler for this URL.

InputStreamReader(): An InputStreamReader is a bridge from byte stream to character stream, It
reads bytes and decodes them into character using a specified charset.

BufferedReader: This constructor reads text from a character-input stream, buffering characters so
as to provide for the efficient reading of characters. A BufferedReader creates a buffering character-
input stream that uses a default sized input buffer.

Package je3.net;
import java.net.*;
import java.io.*;

public class URLConnectionReader{
public static void main(String[] args) throws Exception {
URL javajazzup = new URL("http://www.javajazzup.com/");

URLConnection javajazzupConnection = javajazzup.openConnection();
System.out.println(javajazzupConnection);
InputStreamReader inp=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
System.out.print("Enter the text: ");
String str = br.readLine();
System.out.println("You entered String is: ");
System.out.println(str);
}
}




4. Using java.net.URLConnection class in Networking

The java.net.URLConnection class establishes a link between your Java program and a resource on the
network, a URL. Here is a program on how we can get various details regarding a URL such as its
content type, the last modified date etc.

package je3.net;
import java.net.*;
import java.io.*;
import java.util.*;
import java.text.*;
class Connect {
23

public static void main(String args[])
{
// The url may not well formed, So MalformedURLException
try
{
// URL pointing to java-demos.blogspot.com
URL u=new URL("http://java-demos.blogspot.com");
// IOException might occur, when the URL is not
// available/readable etc.
try
{
// Create URLConnection object
URLConnection con=u.openConnection();
// Connect to the url
con.connect();
// Print the url
System.out.println("URL: "+con.getURL());
// Print the type of content
System.out.println("Content type: "+con.getContentType());
// Get date (long)
long d=con.getDate();
// Create date object for above value
Date date=new Date(d);
// Create SimpleDateFormat for above Date object
SimpleDateFormat sd=new SimpleDateFormat("dd/MM/yyyy");
// Print the date
System.out.println("Date: "+sd.format(date));
// Get the last modified date
date=new Date(con.getLastModified());
// Print the last modified date
System.out.println("Last Modified: "+sd.format(date));
// Print the content of URL (returns Object)
System.out.println("Content: "+con.getContent());
}
catch(IOException e){
System.out.println("Unable to connect to the url");
}
}
catch(MalformedURLException e){
System.out.println("The given url is not well formed.");
}
}
}



24

Notes
The constructor of java.net.URL used here takes a String which is the url of the resource.
http://java-demos.blogspot.com/index.html

In order to get the details of the resource we need a URLConnection object here. So it is created
using openConnection() method in the URL class. The connect() method is used to interact with the
resource. Note that, the above works (i.e. the program's output is one and the same) even when you don't
call this connect() method.

Classes and their presence
URL, URLConnection, MalformedURLException classes are from java.net package.
Date class is from java.util package.
SimpleDateFormat is from java.text package.
IOException is from java.io package.

Exception clauses
The first exception clause is for the URL constructor. This might thrown an exception called
the MalformedURLException. The name itself says that it occurs when the URL is not correctly formed.
For example htp: instead of http: etc. This try clause is the outer clause.

The inner try clause is for the openConnection() method which might throw an exception which is
nothing but IOException. You might be familiar with this. This exception occurs when the resource is
unable to read/write. Here, the URL points to the resource (http://java-demos.blogspot.com/index.html).
If the index.html file here is unable to be read, then this exception occurs. It is obvious that this might
occur when there is no internet connection. The inner clause is declared here because if there is
no URL object i.e. if u is null, then there will be no URLConnection object since u is null
and openConnection() cannot be called.



















25

Experiment 3: Study of URLConnection & writing to URLConnection

A static HTML page cannot be written to using HTTP. If you want to alter a server-side file, you either
need an active server component. (Like a servlet or server side PHP script), or you need to somehow
obtain file access to it, so that you can use the java.io classes like File and FileOutputStream.
3.1 Writing to a URLConnection (First Example)
Many HTML pages contain forms text fields and other GUI objects that let you enter data to send to
the server. After you type in the required information and initiate the query by clicking a button, your
Web browser writes the data to the URL over the network. At the other end the server receives the data,
processes it, and then sends you a response, usually in the form of a new HTML page. Many of these
HTML forms use the HTTP POST METHOD to send data to the server. Thus writing to a URL is often
called posting to a URL. The server recognizes the POST request and reads the data sent from the client.

For a Java program to interact with a server-side process it simply must be able to write to a URL, thus
providing data to the server. It can do this by following these steps:
1. Create a URL.
2. Retrieve the URLConnection object.
3. Set output capability on the URLConnection.
4. Open a connection to the resource.
5. Get an output stream from the connection.
6. Write to the output stream.
7. Close the output stream.
Create temp2.php as follows and store it in folder C:\wamp\www\temp1\

temp2.php

<?php

$first = $_POST["first"];
$last = $_POST["last"];

echo "Welcome friend! ";
echo "$first";
echo "$last";

?>

WritingToURLConnection.java

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

public class WritingToURLConnection {
public static void main( String[] args ) {

26

try {

String data1 = URLEncoder.encode("first", "UTF-8") + "=" +
URLEncoder.encode("Girish ", "UTF-8");
String data2 = URLEncoder.encode("last", "UTF-8") + "=" +
URLEncoder.encode("Tere", "UTF-8");
String data = data1 +"&" +data2;

String inLine;

URL u1 = new URL("http://localhost/test1/test2.php");
URLConnection uc1 = u1.openConnection();

uc1.setDoOutput(true);
OutputStreamWriter out = new
OutputStreamWriter(uc1.getOutputStream());
out.write(data);
out.flush();

BufferedReader in = new BufferedReader( new InputStreamReader(
uc1.getInputStream() ) );

// The readLine() method reads the output of the php script
while ((inLine = in.readLine()) != null) {
System.out.println(inLine);
}

in.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}

Now perform following steps:
1. Compile WritingToURLConnection.java
2. Start WAMP server (Be sure that you have created test2.php file and stored it at
C:\wamp\www\test1\test2.php)
3. Run WritingToURLConnection.class




27

3.2 Writing to a URLConnection (Second Example)
ReverseServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.*;

public class ReverseServlet extends HttpServlet
{
private static String message = "Error during Servlet processing";

public void doPost(HttpServletRequest req, HttpServletResponse resp) {
try {
int len = req.getContentLength();
byte[] input = new byte[len];

ServletInputStream sin = req.getInputStream();
int c, count = 0 ;
while ((c = sin.read(input, count, input.length-count)) != -1) {
count +=c;
}
sin.close();

String inString = new String(input);
int index = inString.indexOf("=");
if (index == -1) {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().print(message);
resp.getWriter().close();
return;
}
String value = inString.substring(index + 1);

//decode application/x-www-form-urlencoded string
String decodedString = URLDecoder.decode(value, "UTF-8");

//reverse the String
String reverseStr = (new StringBuffer(decodedString)).reverse().toString();

// set the response code and write the response data
resp.setStatus(HttpServletResponse.SC_OK);
OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream());

writer.write(reverseStr);
writer.flush();
writer.close();
} catch (IOException e) {
try{
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().print(e.getMessage());
resp.getWriter().close();
} catch (IOException ioe) {
}
}

}

}

28

Perform following steps:

1. Compile ResverseServlet.java
2. Create test folder in webapps in Tomcat.
3. In test create WEB-INF folder
4. In WEB-INF create classes folder
5. In classes folder keep ReverseServlet.class
6. Go back to WEB-INF folder. Create web.xml file in it. It is deployment descriptor for a servlet.
7. Start Tomcat container

web.xml

<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>ReverseServlet</servlet-name>
<display-name>ReverseServlet</display-name>
<servlet-class>ReverseServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReverseServlet</servlet-name>
<url-pattern>/ReverseServlet</url-pattern>
</servlet-mapping>
</web-app>

Next step is to create a client program, Reverse.java program in your working directory.

Reverse.java

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

public class Reverse {
public static void main(String[] args) throws Exception {

if (args.length != 2) {
System.err.println("Usage: java Reverse "
+ "http://<location of your servlet/script>"
+ " string_to_reverse");
System.exit(1);
}

String stringToReverse = URLEncoder.encode(args[1], "UTF-8");

URL url = new URL(args[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);

OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();

BufferedReader in = new BufferedReader(
29

new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}

Perform following steps:

1. Compile Resverse.java
2. Run Reverse class using java command as shown below.



























30

Experiment 4: Study of Connectionless approach using datagram

Datagram

Datagram is a type of packet that represents an entire communication. There is no necessity to have
connection or disconnection stages when communicating using datagrams. This is less reliable than
TCP/IP.

There are two classes in Java, which enables communication-using datagrams.

- DatagramPacket is the class, which acts as the data container, and
- DatagramSocket is a mechanism used to send or receive DatagramPackets.

DatagramPacket

The constructors for the DatagramPacket

- takes a byte array and its size as its parameters
- and another constructor, which takes the InetAddress and port as its parameters.

Represents datagram packet

Data buffer
packet length
IP address, port

Sender creates a DatagramPacket with the data, length, destination IP address and port number

DatagramSocket

The DatagramPacket does not provide methods to send or receive data. This job is taken up by the
DatagramSocket class. The creation of DatagramSocket object throws a SocketException. The
Constructors are:

- No parameters and
- second one takes an int port.

The important methods are:

send (DatagramPacket p) - Dispatches the given DatagramPacket
receive(DatagramPacket p) - Receives the given DatagramPacket
close() - Closes the socket connection

The send and receive methods throws IOException and must be caught.

4.1 Connection-less communication between Server and client using datagram
31


UDPServer.java


//Server Side:

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

class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
//Server Socekt Created

byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);

InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();

String capitalizedSentence = sentence.toUpperCase();
//Change sentence to Capital letter
sendData = capitalizedSentence.getBytes();

DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
//Send Capitalized data back to client
}
}
}


UDPClient.java

//Client Side:

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

class UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));

DatagramSocket clientSocket = new DatagramSocket();
//Client Socket is created

InetAddress IPAddress = InetAddress.getByName("localhost");
32

//Gets the IP Address

byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();

sendData = sentence.getBytes();
//sends data

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,
9876);
clientSocket.send(sendPacket);

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);

String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}


Perform following steps:

1. Open command window
2. Go to appropriate directory
3. Compile both UDPServer.java and UDPClient.java program
4. Run UDPServer class using java command
5. Open other command window
6. Go to appropriate directory
7. Run UDPClient class using java command
8. Type some text at client and press Enter.
9. UDPServer will send the same text in capital to client as shown in following figures.



33





4.2 One way Connection-less communication between Server and client using datagram

UDPServer.java

import java.net.*;
import java.io.*;
class UDPServer extends Thread
{
DatagramSocket ds2;
DatagramPacket dp2;
UDPServer()
{
try
{
ds2=new DatagramSocket(1600);
start();
System.out.println("UDPServer");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
try
{
while(true)
{
byte b[]=new byte[1024];
dp2=new DatagramPacket(b,b.length);
ds2.receive(dp2);
String s=new String(b,0,b.length);
34

System.out.println("Message from Client: " +s.trim());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

public static void main(String[] args)
{
UDPServer s = new UDPServer();
}
}


UDPClient.java

import java.net.*;
import java.io.*;
class UDPClient extends Thread
{
DatagramSocket ds1;
BufferedReader br;
DatagramPacket dp1;
UDPClient()
{
try
{
InputStreamReader i=new InputStreamReader(System.in);
br=new BufferedReader(i);
ds1=new DatagramSocket(1400);
start();
System.out.println("UDPCLient");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
try
{
while(true)
{
String s=br.readLine();
byte b[]=s.getBytes();
dp1=new
DatagramPacket(b,b.length,InetAddress.getLocalHost(),1600);
ds1.send(dp1);
}
}

catch(Exception e)
{
35

e.printStackTrace();
}
}
public static void main(String[] args)
{
UDPClient u = new UDPClient();
}
}

Output:





4.3 Two way Connection-less communication between Server and client using datagram

UDPServerOuter.java

import java.net.*;
import java.io.*;
class UDPServerOuter extends Thread
{
DatagramSocket ds2;
DatagramPacket dp2;
UDPServerOuter()
{
try
{
ds2=new DatagramSocket(1600);
start();
System.out.println("UDPServer");
UDPServerInner si= new UDPServerInner();
}
catch(Exception e)
{
e.printStackTrace();
}
}
36

public void run()
{
try
{
while(true)
{
byte b[]=new byte[1024];
dp2=new DatagramPacket(b,b.length);
ds2.receive(dp2);
String s=new String(b,0,b.length);
System.out.println("Message from Client: " +s.trim());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

public static void main(String[] args)
{
UDPServerOuter s = new UDPServerOuter();
}

class UDPServerInner extends Thread
{
BufferedReader br;
DatagramPacket dp1;
UDPServerInner()
{
try
{
InputStreamReader i=new InputStreamReader(System.in);
br=new BufferedReader(i);
start();

UDPClientInner ci = new UDPClientInner();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
try
{
while(true)
{
String s=br.readLine();
byte b[]=s.getBytes();
dp1=new
DatagramPacket(b,b.length,InetAddress.getLocalHost(),1400);
ds2.send(dp1);
}
}

37

catch(Exception e)
{
e.printStackTrace();
}
}


class UDPClientInner extends Thread
{
DatagramPacket dp2;
UDPClientInner()
{
try
{
start();

}
catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
try
{
while(true)
{
byte b[]=new byte[1024];
dp2=new DatagramPacket(b,b.length);
ds2.receive(dp2);
String s=new String(b,0,b.length);
System.out.println("Message from Server: " +s.trim());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
};
};
}


UDPClientOuter.java

import java.net.*;
import java.io.*;
class UDPClientOuter extends Thread
{
DatagramSocket ds1;
BufferedReader br;
DatagramPacket dp1;
UDPClientOuter()
{
38

try
{
InputStreamReader j=new InputStreamReader(System.in);
br=new BufferedReader(j);
ds1=new DatagramSocket(1400);
start();
System.out.println("UDPCLient");
UDPClientInner ci = new UDPClientInner();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
try
{
while(true)
{
String s=br.readLine();
byte b[]=s.getBytes();
dp1=new
DatagramPacket(b,b.length,InetAddress.getLocalHost(),1600);
ds1.send(dp1);
}
}

catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
UDPClientOuter u = new UDPClientOuter ();
}

class UDPClientInner extends Thread
{
DatagramPacket dp2;
UDPClientInner()
{
try
{
start();

}
catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
try
{
39

while(true)
{
byte b[]=new byte[1024];
dp2=new DatagramPacket(b,b.length);
ds1.receive(dp2);
String s=new String(b,0,b.length);
System.out.println("Message from Server: " +s.trim());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
};
}

Output:


















40

Experiment 5: Study of Connection-oriented approach using ServerSocket

TCP/IP

There are two kinds of sockets in Java a Server and a Client. The ServerSocket class is used by the
server to wait for the client and the client connects to the server using Socket Class.

Socket Class

The first constructor takes a hostname and a port as its parameters to create a Socket Object and it can
throw a UnknownHostException or an IOException, which must be caught.

The second constructor takes a InetAddress and port number as its parameters to create a Socket object.
The Important Methods are:

InetAddress - getInetAdress() returns a InetAddress associated with Socket object

Int - getPort() returns remote port to which this Socket object is connected.

Int - getLocalPort() returns the local port

InputStream - getInputStream() returns the IS

OS - getOutputStream()- returns the OS

Void - close() closes both the IS and OS

ServerSocket Class

The ServerSocket waits for the client to make a connection. An object of this class registers itself as
having an interest in client connection. Apart from using the methods listed, this class has accept()
which is used to wait for a client to initiate communications. The normal Socket object is used for
further transfer of data.

The first constructor takes a part and the second a maximum queue length as parameters. The queue
length indicates the maximum number of client connections that the client can have before refusing
further connection.

Socket Programming:
Sockets provide the communication mechanism between two computers using TCP. A client program
creates a socket on its end of the communication and attempts to connect that socket to a server. When
the connection is made, the server creates a socket object on its end of the communication. The client
and server can now communicate by writing to and reading from the socket. The java.net.Socket class
represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to
listen for clients and establish connections with them.

The following steps occur when establishing a TCP connection between two computers using sockets:
41

The server instantiates a ServerSocket object, denoting which port number communication is to
occur on.
The server invokes the accept() method of the ServerSocket class. This method waits until a
client connects to the server on the given port.
After the server is waiting, a client instantiates a Socket object, specifying the server name and
port number to connect to.
The constructor of the Socket class attempts to connect the client to the specified server and port
number. If communication is established, the client now has a Socket object capable of
communicating with the server.
On the server side, the accept() method returns a reference to a new socket on the server that is
connected to the client's socket.


After the connections are established, communication can occur using I/O streams. Each socket has both
an OutputStream and an InputStream. The client's OutputStream is connected to the server's
InputStream, and the client's InputStream is connected to the server's OutputStream. TCP is a two way
communication protocol, so data can be sent across both streams at the same time. There are following
usefull classes providing complete set of methods to implement sockets.

ServerSocket Class Methods:
The java.net.ServerSocket class is used by server applications to obtain a port and listen for client
requests
The ServerSocket class has four constructors:
1. 1 public ServerSocket(int port) throws IOException
Attempts to create a server socket bound to the specified port. An exception occurs if the port is
already bound by another application.
2. public ServerSocket(int port, int backlog) throws IOException
Similar to the previous constructor, the backlog parameter specifies how many incoming clients
to store in a wait queue.
3. public ServerSocket(int port, int backlog, InetAddress address) throws IOException
Similar to the previous constructor, the InetAddress parameter specifies the local IP address to
bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the
server to specify which of its IP addresses to accept client requests on
4. public ServerSocket() throws IOException
Creates an unbound server socket. When using this constructor, use the bind() method when you
are ready to bind the server socket

If the ServerSocket constructor does not throw an exception, it means that your application has
successfully bound to the specified port and is ready for client requests.

Here are some of the common methods of the ServerSocket class:
1. public int getLocalPort()
Returns the port that the server socket is listening on. This method is useful if you passed in 0 as
the port number in a constructor and let the server find a port for you.
2. public Socket accept() throws IOException
42

Waits for an incoming client. This method blocks until either a client connects to the server on
the specified port or the socket times out, assuming that the time-out value has been set using the
setSoTimeout() method. Otherwise, this method blocks indefinitely
3. public void setSoTimeout(int timeout)
Sets the time-out value for how long the server socket waits for a client during the accept().
4. public void bind(SocketAddress host, int backlog)
Binds the socket to the specified server and port in the SocketAddress object. Use this method if
you instantiated the ServerSocket using the no-argument constructor.

When the ServerSocket invokes accept(), the method does not return until a client connects. After a
client does connect, the ServerSocket creates a new Socket on an unspecified port and returns a
reference to this new Socket. A TCP connection now exists between the client and server, and
communication can begin.

Socket Class Methods:
The java.net.Socket class represents the socket that both the client and server use to communicate with
each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket
object from the return value of the accept() method.

The Socket class has five constructors that a client uses to connect to a server:

1. public Socket(String host, int port) throws UnknownHostException, IOException.
This method attempts to connect to the specified server at the specified port. If this constructor
does not throw an exception, the connection is successful and the client is connected to the
server.
2. public Socket(InetAddress host, int port) throws IOException
This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object.
3. public Socket(String host, int port, InetAddress localAddress, int localPort)
throws IOException.
Connects to the specified host and port, creating a socket on the local host at the specified
address and port.
4. public Socket(InetAddress host, int port, InetAddress localAddress, int localPort)
throws IOException.
This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object instead of a String
5. public Socket()
Creates an unconnected socket. Use the connect() method to connect this socket to a server.
When the Socket constructor returns, it does not simply instantiate a Socket object but it actually
attempts to connect to the specified server and port.

Some methods of interest in the Socket class are listed here. Notice that both the client and server have a
Socket object, so these methods can be invoked by both the client and server.

1. public void connect(SocketAddress host, int timeout) throws IOException
43

This method connects the socket to the specified host. This method is needed only when you
instantiated the Socket using the no-argument constructor.
2. public InetAddress getInetAddress()
This method returns the address of the other computer that this socket is connected to.
3. public int getPort()
Returns the port the socket is bound to on the remote machine.
4. public int getLocalPort()
Returns the port the socket is bound to on the local machine.
5. public SocketAddress getRemoteSocketAddress()
Returns the address of the remote socket.
6. public InputStream getInputStream() throws IOException
Returns the input stream of the socket. The input stream is connected to the output stream of the
remote socket.
7. public OutputStream getOutputStream() throws IOException
Returns the output stream of the socket. The output stream is connected to the input stream of the
remote socket
8. public void close() throws IOException
Closes the socket, which makes this Socket object no longer capable of connecting again to any
server

5.1 : First example using socket programming

// File Name GreetingServer.java
import java.net.*;
import java.io.*;

public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}

public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " +
server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new
DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
44

System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}

public static void main(String [] args)
{
int port = Integer.parseInt(args[0]);
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}


// File Name GreetingClient.java

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

public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " +
client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Output:

45






5.2 One more example using socket programming

Server.java

import java.net.*;
import java.io.*;
class Server extends Thread
{
BufferedReader br;
Socket s1;
ServerSocket ss;
Server()
{
try
{
ss=new ServerSocket(7200);
s1=ss.accept();
InputStreamReader i = new
InputStreamReader(s1.getInputStream());
br=new BufferedReader(i);
start();
System.out.println("Server");
ServerInner ci = new ServerInner();
}
catch(Exception e)
{
e.printStackTrace();
}
}

46

public void run()
{ try
{
while(true)
{
String s2=br.readLine();
System.out.println("Msg from Client: "+s2);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

public static void main(String[] args)
{
Server c = new Server();
}
class ServerInner extends Thread
{
BufferedReader br1;
PrintWriter pw;
ServerInner()
{
try
{
InputStreamReader i = new InputStreamReader(System.in);
br=new BufferedReader(i);
pw = new PrintWriter(s1.getOutputStream(),true);
start();
}
catch(Exception e)
{
e.printStackTrace();
}

}
public void run()
{
try
{
while(true)
{
String s=br.readLine();
pw.println(s);
}
}
catch(Exception e)
{
e.printStackTrace();
}

}

}
}
47



Client.java

import java.net.*;
import java.io.*;
class Client extends Thread
{
BufferedReader br;
Socket s;
PrintWriter pw;
Client()
{
try
{
InputStreamReader i = new InputStreamReader(System.in);
br=new BufferedReader(i);
s=new Socket(InetAddress.getLocalHost(),7200);
pw = new PrintWriter(s.getOutputStream(),true);
start();
System.out.println("Client");
ClientInner ci = new ClientInner();
}
catch(Exception e)
{
e.printStackTrace();
}
}

public void run()
{ try
{
while(true)
{
String s=br.readLine();
pw.println(s);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

public static void main(String[] args)
{
Client c = new Client();
}
class ClientInner extends Thread
{
BufferedReader br1;
ClientInner()
{ try
{
InputStreamReader i = new
InputStreamReader(s.getInputStream());
48

br1=new BufferedReader(i);
start();
}
catch(Exception e)
{
e.printStackTrace();
}

}
public void run()
{
try
{
while(true)
{
String s2=br1.readLine();
System.out.println("Msg from Server: "+s2);
}
}
catch(Exception e)
{
e.printStackTrace();
}

}

}
}


Output:




49



































50

Experiment 6: Creating Server Process using ServerSocket

Building your own server

When a browser connects to a server and server sends the response, there is a specific format in
which the information is exchanged. It contains three parts:

- the request or response line
- a header section
- the entire body

The client sends request to a host on specific port. The first request line contains to HTTP command,
document address and HTTP version number. For example -

GET /index.html HTTP/1.0

Header are sent using format -
Keyword: Value

For example

User-Agent : Lynx/2.4 ,MSIE/5.0
Accept : text/html ,image/gif ,*/*

HTTP response contains similar format. The first line of reply from a server contains Http version, status
code and description. For example,

HTTP/1.0 200 OK

Here 200 indicate that the client request was successful. By reading the contents of clients request, one
can process it and sends appropriate response.

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

class myserver
{
public static void main(String args[]) throws Exception
{
ServerSocket soc=new ServerSocket(8400);
while(true)
try
{
Socket client=soc.accept();
BufferedReader br=new BufferedReader(new
InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());

String l = null;
String t1 = br.readLine();
51

System.out.println(t1);

while((l=br.readLine())!= null)
{
if(l.length()==0)
break;
System.out.println(l);
}

String t2 = t1.substring(t1.indexOf("/")+1);
String filename=null;
try
{
filename = t2.substring(0,t2.indexOf("?"));
}
catch(Exception e)
{
filename = t2.substring(0,t2.indexOf(" "));
}

BufferedReader br2 = new BufferedReader(new FileReader(filename));

while((l=br2.readLine())!=null)
{
out.println(l);
}

out.println("</html>");
out.close();
br.close();
br2.close();
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

To run the above application

1. Run this program using
java myserver
2. Open Browser and type the following url:
http://localhost:8400/file1.html

where file1.html is a file which exists in the directory from where you run myserver.class.

52





























53

Experiment 7: Sending email through Java

For demo purpose we have selected Gmail SMTP server. Following program show the demonstration of
how to send emails from a Gmail Id to any other Email ids through Java code using Secure Socket Layer
(SSL) connection.

Add following jar files to JDK_HOME\jre\lib\ext

mail-1.4
activation-1.0.2


Set up POP in mail clients
Standard configuration instructions:

Incoming Mail (POP3) Server - requires SSL: pop.gmail.com
Use SSL: Yes
Port: 995
Outgoing Mail (SMTP) Server - requires TLS or
SSL:
smtp.gmail.com
Use Authentication: Yes
Port for TLS/STARTTLS: 587
Port for SSL: 465
Server timeouts Greater than 1 minute, we recommend 5
Full Name or Display Name: [your name]
Account Name or User Name: your full email address (including @gmail.com or
@your_domain.com)
Email Address: your email address (username@gmail.com or
username@your_domain.com)
Password: your Gmail password

Example 7.1:

JavaMailEx.java

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class JavaMailEx {

public static void main(String[] args)throws MessagingException {
String sender_email = "girish.tere@gmail.com",
sender_password = "aaaaaaaa",
sender_host = "smtp.gmail.com",
sender_port = "465",
reciever_id = "atharva.tere0307@gmail.com",
54

subject_to_be_given = "Greeting...",
message_mi = "Hi, Athu...";

Properties props = new Properties();
props.put("mail.smtp.user", sender_email);
props.put("mail.smtp.host", sender_host);
props.put("mail.smtp.port", sender_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
//props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port",sender_port);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallb","false");

SecurityManager security = System.getSecurityManager();

try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
//session.setDebug(true);

MimeMessage msg = new MimeMessage(session);
msg.setText(message_mi);
msg.setSubject(subject_to_be_given);
msg.setFrom(new InternetAddress(sender_email));
msg.addRecipient(Message.RecipientType.TO,new
InternetAddress(reciever_id));
Transport.send(msg);
}
catch (Exception mex)
{
mex.printStackTrace();
}

}

}
class SMTPAuthenticator extends javax.mail.Authenticator
{
String sender_email = "girish.tere@gmail.com",
sender_password = "aaaaaaaaaaa",
sender_host = "smtp.gmail.com",
sender_port = "465",
reciever_id = "atharva.tere0307@gmail.com",
subject_to_be_given = "Greeting...",
message_mi = "Hello Athu!";
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(sender_email, sender_password);
}
}



55

Example 7.2: (Using SSL connection)

SendMailSSL.java

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailSSL {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication
getPasswordAuthentication() {
return new
PasswordAuthentication("girish.tere@gmail.com","abcdefgh");
}
});

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("girish.tere@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("atharva.tere0307@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Hi Athu, congratulations and all the best!");

Transport.send(message);

System.out.println("Done");

} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}


56





Example 7.3: (Using Transport Layer Security, TLS connection)


SendMailTLS.java

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailTLS {

public static void main(String[] args) {

final String username = "girish.tere@gmail.com";
final String password = "password123456";

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("girish.tere@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("atharva.tere0307@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Athu, congratulations!\n Keep up the good
work!");
57


Transport.send(message);

System.out.println("Done");

} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}






































58

Experiment 8: Designing RMI Application

The Java RMI (Remote Method Invocation) is a package for writing and executing distributed Java
programs. The Java RMI provides a framework for developing and running servers (server objects). The
services (methods) provided by those server objects can be accessed by clients in a way similar to
method invocation. I.e. Java RMI hides almost all aspects of the distribution and provides a uniform way
by which objects (distributed or not) may be accessed.

Writing Java programs using RMI can be described by the following steps:
write server interface(s),
write server implementation,
generate server skeleton and client stub,
write client implementation.

Executing distributed Java programs using RMI can be described by the following steps:
start the rmi registry,
start the server object,
run the client(s).

8.1 Simple RMI Application

HelloImpl.java

import java.rmi.*;

public interface HelloImpl extends Remote
{
String sayHello(String a) throws RemoteException;
}

RMIHelloServer.java

import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
public class RMIHelloServer extends UnicastRemoteObject implements HelloImpl
{
public RMIHelloServer() throws RemoteException
{
System.out.println("The server is instantiated");
}
public String sayHello(String a)
{
// Returns the square root of the number passed as argument
String s;
s="Hello, "+a;
return s;
}
public static void main(String[] arguments)
{
try
59

{
// Instantiates the RMIServer object
RMIHelloServer server = new RMIHelloServer();

/* The rebind() method takes two arguments, URL name and the
Remote object which binds the remote object to the remote
registry */

Naming.rebind("call1", server);

/* The name call1 is a bind name given to the remote object,
which gets registered with the RMI registry through which
remote calls are made */
}
catch (Exception exce)
{
System.out.println("Error -- " +exce.toString());
exce.printStackTrace();
}
} // End of main() method
} // End of RMIServer class

RMIHelloClient.java

import java.rmi.*;
import java.rmi.registry.*;

public class RMIHelloClient
{
public static void main(String[] arguments)
{
try
{
HelloImpl mthdIp =
HelloImpl)Naming.lookup("rmi://127.0.0.1/call1");

/* '127.0.0.1' is the IP address of the Server machine
and call1 is the name with which the Server Object is
registered. */

String s = mthdIp.sayHello(arguments[0]);
System.out.println(s);
}
catch (Exception exec)
{
System.out.println("Error -- " + exec.toString());
exec.printStackTrace();
}
} //End of main() method
} // End of RMIClient class



Complete following steps:

1. Go to your working directory (F:\RMI\Hello)
60

2. Write all Java programs. (Interface, server, client)
3. Compile all java programs
4. Once this has been completed, the stubs and skeletons for the Remote interfaces should be compiled
by using the rmic stub compiler. The stub and skeleton of the example Remote interface are
compiled with the command:

rmic RMIHelloServer

5. Open other command window. Go to directory where server files are kept and run server

java RMIHelloServer

6. Open other command window. Go to directory where client files are kept and run client

java RMIHelloClient Girish


Screen shots are shown below:













61

8.2 Simple RMI Calculator Application

CalcImpl.java

import java.rmi.*;

public interface CalcImpl extends Remote
{
double add(int a, int b) throws RemoteException;
double sub(int a, int b) throws RemoteException;
double mul(int a, int b) throws RemoteException;
double div(int a, int b) throws RemoteException;
}

RMICalcServer.java

import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;

public class RMICalcServer extends UnicastRemoteObject implements CalcImpl
{
public RMICalcServer() throws RemoteException
{
System.out.println("The server is instantiated");
}
public double add(int a, int b)
{
return a+b;
}

public double sub(int a, int b)
{
return a-b;
}
public double mul(int a, int b)
{
return a*b;
}
public double div(int a, int b)
{
return (double)a/b;
}

public static void main(String[] arguments)
{
try
{
// Instantiates the RMIServer object
RMICalcServer server = new RMICalcServer();

/* The rebind() method takes two arguments, URL name and the
Remote object which binds the remote object to the remote
registry */

Naming.rebind("call12", server);
62


/* The name call1 is a bind name given to the remote object,
which gets registered with the RMI registry through which
remote calls are made */
}
catch (Exception exce)
{
System.out.println("Error -- " +exce.toString());
exce.printStackTrace();
}
} // End of main() method
} // End of RMIServer class


RMICalcClient.java

import java.rmi.*;
import java.rmi.registry.*;

public class RMICalcClient
{
public static void main(String[] arguments)
{
try
{
CalcImpl mthdIp =
(CalcImpl)Naming.lookup("rmi://localhost/call12");
int a = Integer.parseInt(arguments[0]);
int b = Integer.parseInt(arguments[1]);
double ans;

ans = mthdIp.add(a,b);
System.out.println(a+"+"+b+" = "+ans);

ans = mthdIp.sub(a,b);
System.out.println(a+"-"+b+" = "+ans);

ans = mthdIp.mul(a,b);
System.out.println(a+"*"+b+" = "+ans);

ans = mthdIp.div(a,b);
System.out.println(a+"/"+b+" = "+ans);
}
catch (Exception exec)
{
System.out.println("Error -- " + exec.toString());
exec.printStackTrace();
}
} //End of main() method
} // End of RMIClient class

Output is shown below:
63




All the best!

TYBSC
Computer Science
USCS502 & USCS602
Paper 2
Advanced Java
17Jul2013
1
SCS 02 USCS502
Advanced JAVA - I
Unit I
Introduction to J FC and Swingg
Features of the J ava Foundation Classes
Swing API Components
J Component Class
Windows, Dialog Boxes, and Panels: , g ,
(Container, JDialog, JFrame, JWindow,
JDesktopPane, JInternalFrame,
JOptionPane, JPanel)
17Jul2013
2
Unit I
Labels, Buttons, Check Boxes:
(JLabel, JButton, JToggleButton,
JCheckBox, JRadioButton, ButtonGroup)
Pane, JScrollPane, DesktopPane
(RootPane, GlassPane, LayeredPane,
JTabbedPane JSplitPane) JScrollPane JTabbedPane, JSplitPane), JScrollPane
Scrollbars
(JScrollBar)
Unit I
Lists and Combo Boxes
(JList, JComboBox)
Text-Entry Components
(JTextField, JPasswordField, JTextArea,
JEditorPane, JTextPane)
References:
1. JAVA Tutorial (Preferable)
2. JPAT
17Jul2013
3
U nit II
Menus, Toolbars, Implementing Action p g
interface
(JMenuBar, JMenuItem, JMenu,
JPopupMenu, JCheckboxMeuItem,
JRadioButtonMenuItem, JToolBar,
AbstractAction
Colors and File Choosers
(JColorChooser, JFileChooser)
Tables and Trees
(JTable, JTree)
Unit II
Printing with 2D API and Java Print g
Service API.
References
1. JAVA Tutorial (Preferable)
2. JPAT
17Jul2013
4
Unit II
Threads and Multithreading - The g
Lifecycle of a thread
(newly created, runnable, blocked, or dead)
Creating and running threads
(Using Thread Class , Runnable interface,
St i th th d) Stopping the thread)
Creating the Service Threads
(Daemon threads)
Unit II
Schedules Tasks using JVM g
(using thread priority)
Thread-safe code, Synchronizing threads,
Communication between threads.
References:
1. JPAT
17Jul2013
5
Unit III
J DBC Introduction
J DBC Architecture
References:
1. J AVA Tutorial
J DBC Drivers
References
1. J PAT/Core J AVA-Volume II
Unit III
The Connectivity Model y
The java.sql package
Navigating the ResultSet objects contents,
Manipulating records of a ResultSet object
through User Interface
The J DBC Exception classes
Database Connectivity
17Jul2013
6
Unit I
Data Manipulation (using Prepared p ( g p
Statements, J oins, Transactions, Stored
Procedures)
Data navigation
References
1. J AVA Tutorial (Preferable)
2. Ivan Bayross, Web Enabled Commercial
Applications Development Using J ava 2,
BPB Publications, Revised Edition, 2006
Unit IV
Working with URL g
(What is URL, Creating URL, Parsing URL,
Reading from URL using openStream())
Reference: JAVA Tutorial/J2CR
Connecting to a Server, Implementing
Servers Serving multiple Clients Servers, Serving multiple Clients,
Sending E-Mail, Socket Programming
Reference: Core JAVA Volume - II
17Jul2013
7
Unit IV
Inet Addresses
Reference: J2CR
URL Connections, Posting Form Data,
Accessing Network interface parameters,
Cookies, Overview of Understanding the
S k Di P l Sockets Direct Protocol.
Reference :
1. JAVA Tutorial
Unit IV
Introduction to distributed object system
Distributed Object Technologies
RMI for distributed computing
RMI Architecture
RMI Registry Service
CreatingRMI application Creating RMI application
Steps involved in running the RMI application
Reference:
1 . Ivan Bayross
17Jul2013
8
Unit IV
Parameter Passing in Remote Methods g
Using RMI with Applets
Reference:
1. J AVA Tutorial
SCS602 USCS602
Advanced JAVA-II
17Jul2013
9
Unit I
What Is a Servlet? The Example Servlets, p
Servlet Life Cycle, Sharing Information,
Initializing a Servlet, Writing Service
Methods,
Filtering Requests and Responses,
Invoking Other Web Resources,
Accessing the Web Context,
Unit I
Maintaining Client State, g
Finalizing a Servlet.
Reference:
The J ava EE 6Tutorial (Preferable) ( )
Head First Servletsand J SP
17Jul2013
10
Unit II
What Is a J SP Page?, The Example J SP g p
Pages,
The Life Cycle of a J SP Page,
Creating Static Content, Creating Dynamic
Content, Unified Expression Language
Reference:
The J ava EE 6Tutorial (Preferable)
Head First Servletsand J SP
Unit II
J avaBeans Components, J avaBeans p
Concepts,
Using NetBeansGUI Builder
Writing a Simple Bean, Properties: Simple
Properties
Reference:
1 . J AVA Tutorial
17Jul2013
11
Unit II
Using Custom tags, Reusing content in J SP g g g
Pages
Transferring Control to Another Web
Component, Including an Applet.
Reference:
The J ava EE 6Tutorial (Preferable)
Head First Servletsand J SP
Unit - III
Introduction to EJ B, Benefits of EJ B, Types yp
of EJ B,
Session Bean: State Management Modes;
Message-Driven Bean, Differences between
Session Beans and Message-Driven Beans,
The Contents of an Enterprise Bean,
Naming Conventions for Enterprise Beans,
The Life Cycles of Enterprise Beans,
17Jul2013
12
Unit III
The Life Cycle of a Stateful Session Bean, y
The Life Cycle of a Stateless Session Bean,
The Life Cycle of a Message-Driven Bean
Reference:
1. The J ava EE 6 Tutorial
Unit - IV
Defining Client Access with Interfaces: g
Remote Access, Local Access,
Local Interfaces and Container-Managed
Relationships, Deciding on Remote or
Local Access,
W bS i Cli M h dP Web Service Clients, Method Parameters
and Access.
17Jul2013
13
Unit IV
Building Web Services with J AX-WS: g
Setting the Port, Creating a Simple Web
Service and Client with J AX-WS.
Reference:
1. J AVA EE 6 Tutorial
17-J ul-2013
1
USCSP05 + USCSP07
Paper 2 Sample Practical List
Advance Java Practicals
SEM V - Topic List
1. Using Basic Swing Controls
2 UsingJ ScrollPane J TabbedPane J DesktopPane 2. Using J ScrollPane, J TabbedPane, J DesktopPane
3. Using Common Dialog Boxes
4. Using J Table and J Tree
5. Creating Table in database
6. Inserting data in tables & Displaying data
7. Using ResultSetMetaData
8 U i P dS 8. Using Prepared Statements
17-J ul-2013
2
1. Using Basic Swing Controls
Write a program to create a form to enter bio-data of student. Use various
components such as JLabel, JButton, JTextField, JTextArea, JComboBox, p J , J , J , J , J ,
JTable, JRadioButton, and JCheckBox. Also add validations for textbox if it is
empty, for radio button and checkboxes at least one should be selected.
Create an application for PHIZZAHUUT where the user can place the order
for pizza. Accept user name, address and mobile number who places the
order. Give the options for four types of pizzas(basic, thick and chewy, thin
and crispy, Chicago deep dish). Also provide the options for multiple
t i ( i h ill d hi k h toppings (pepperoni, sausage, ham, grilled chicken, mushrooms, green
peppers, hot peppers, black olives, tomato slices, sun-dried tomatoes, extra
cheese, pineapple, anchovies). Confirm the order by displaying all the details
on messagebox.
2. Using JScrollPane, JTabbedPane,
JDesktopPane
((Creating MDI Form in SWING) Design a class, which extends JFrame and has
three objects of three classes whose name are ColorPanel, CitiesPanel, and
FlavourPanel. All the three classes (ColorPanel: Names of colors as radio buttons,
CitiesPanel: Names of cities in combobox, and FlavourPanel- Names of Icecream
flavours as checkboxes) extends JPanel and have a method, which makes the Panel
visible.The main JFrame has an object of JDesktopPane and this object holds the
three panels, which are displayed on the click of the menu bar item.
Write a java program to create three tabbed panes.
First tab pane contains a button and a textfield. On click of the button the
textfield is either enabled or disabled
Second tab pane contains two radio buttons (first and second) and text field, on
selecting the radio buttons label is displayed in the textfield.
Third tab pane contains a combo box, textfield and a button. On click of the
button the text from text field is added to the combobox.
17-J ul-2013
3
2. Using JScrollPane, JTabbedPane,
JDesktopPane
Create an application, which is a subclass of the JFrame class which
will have a text box button image and a scroll pane The user will will have a text box, button, image and a scroll pane. The user will
input the image path in the text field. On click of the button the image
should be display inside the scroll pane.
3. Using Common Dialog Boxes
Create an application that will select a text file using the Open
Dialog Box and display the contents of the file in the JTextArea Dialog Box and display the contents of the file in the JTextArea.
Create an application that will have a text area and a button. On
click of button Color Dialog Box will be shown. The color
selected by the user will be applied to the foreground.
17-J ul-2013
4
4. Using JTable and JTree
Design a JTree showing the name of a book as root node.
Chapter number along with Chapter name will be child nodes of Chapter number along with Chapter name will be child nodes of
book node(For example 1.Introduction). Each Chapter node
will have topic names as child nodes. When you click on any
node, some information should be displayed in the message box.
Create a JTable to display the records of 5 employees. The titles
of the columns should be Employee Number, Employee
Name, Designnation & Salary. Accept the data of employees
from a file.
5. Creating Table in database
Write a JDBC program that will create a Emp table. The emp
table will have EmpNo EmpName Salary and Location table will have EmpNo, EmpName, Salary and Location.
Write a JDBC program that will create a Student table. The emp
table will have StudentRollNo, StudentName, MarksSSC and
MarksHSC.
17-J ul-2013
5
6. Inserting data in tables & Displaying
data
Write a JDBC program that will insert 5 records in the Emp
table and display all the records table and display all the records.
Write a JDBC program that will insert 5 records in the
Student table and display all the records.
7. Using ResultSetMetaData
Create a JFrame, which will add data of Friends (Name, DOB,
Address and Tel No ) to the database and on click of Show All Address and Tel. No.) to the database and on click of Show All
button, display the records from the database in a scrollable
JTextArea.
Write a program to create a user interface to accept a SQL query
in a textbox and on click of the Execute button the result should
be displayed in any control.
17-J ul-2013
6
8. Using Prepared Statements
Write a JDBC program that accepts share account number, share
company name type of transaction(buy/sell) number of shares company name, type of transaction(buy/sell), number of shares
and current date from user using loop and inserts all these
records in sharetrans table(accountno, company, transtype, qty,
date). Use prepared statement.
Write a JDBC program that insert values in the Dept table using
Prepared Statements. The Dept table has DeptNo, DeptName
and Location.
SEM VI - Topic List
1. Simple Server-Side Programming using Servlets
2 Ad S Sid P i i S l 2. Advance Server-Side Programming using Servlets
3. Simple Server-side programming using JSP
4. Advance Server-side programming using JSP
5. Developing Simple Enterprise Java Beans
6. Developing Advance Enterprise Java Beans
7. Developing Simple Web services in Java
8. Developing Advance Web services in Java
17-J ul-2013
7
1. Simple Server-Side Programming using
Servlets
Write a servlet that accepts single-valued (Name, Mobile No.) as
well as multi valued (Languages known Hobbies) parameters well as multi-valued (Languages known, Hobbies) parameters
like check boxes and multiple selection list boxes from an HTML
document and outputs them to the screen.
Write a servlet program that accepts an integer n from html
form calculates and displays the factorial of n. If the number is
negative, it should redirect to a different error page having link
to the html form.
2. Advance Server-Side Programming
using Servlets
Write two servlets in which one servlet will display a form in
which data entry can be done for the fields dept no dept name which data entry can be done for the field s dept-no, dept-name
and location. In the same form place a button called as submit
and on click of that button this record should be posted to the
table called as DEPT in the database. This inserting of record
should be done in another servlet. The second servlet should also
display all the previous record entered in the database.
Write a Servlet that accepts a User Name from a HTML form
and stores it as a session variable. Write another Servlet that
returns the value of this session variable and displays it.
17-J ul-2013
8
3. Simple Server-side programming using
JSP
Write JSP files that accept a number from the HTML form and
Di l h th it dd Displays whether it s even or odd
Its factorial.
Multiplication Table.
Write a JSP page to accept two numbers (m,n) from the user, on
click of the submit button display on a new JSP page all prime
numbers between m and n. If the number m is not less than n
(m<n), it should redirect to a different error page having link to
the JSP form.
4. Advance Server-side programming
using JSP
Write a JSP page, which displays three text boxes for user name,
password, and email. On click of the submit button call another JSP p , J
page which will enter the values in the database with the help of
PreparedStatement class. Also use jspInit() and jspDestroy() to open
and close the connection.
Create a java bean that gives information about the current time. The
bean has getter properties for time, hour, minute, and second. Write a
JSP page that uses the bean and display all the information.
W it HTML t t d t b t bl f th Write a HTML page to accept a database table name from the user on
click of the submit button display a JSP to connect to a database and
display the total number of records followed by the contents of the
database table using the HTML TABLE tag, The column names should
be fetched from the database.
17-J ul-2013
9
5. Developing Simple Enterprise Java
Beans
Develop Converter Stateless Session Bean. Write Enterprise
application for converting Japanese yen currency to Eurodollars application for converting Japanese yen currency to Eurodollars
currency. Converter consists of an enterprise bean, which
performs the calculations, and a web client (JSP/Servlet) or
Application client.
Develop Calculator Stateless Session Bean. Write Enterprise
application for adding, subtracting, multiplying and dividing two
numbers. Calculator consists of an enterprise bean, which
performs the calculations, and a web client (JSP/Servlet) or
Application client.
6. Developing Advance Enterprise Java
Beans
Develop CommonDivMul Stateless Session Bean. Write
Enterprise application for calculating the GCD and LCM of two Enterprise application for calculating the GCD and LCM of two
numbers. CommonDivMul consists of an enterprise bean, which
performs the calculations, and a web client (JSP/Servlet) or
Application client.
Design a Mobile Bean as a Stateful EJB containing a variable
representing modelname and three functions setModelName,
getPrice, getFeatures. setModelName accepts a string g , g p g
parameter, getPrice & getFeatures dont have any parameter but
return types. Design a servlet that accepts mobile name from
HTML page and shows mobile price and features to user by
accessing mobile bean.
17-J ul-2013
10
7. Developing Simple Web services in
Java
Create a web service that gives (i) NSE Index, (ii) BSE Index,
(iii) Gold Rate The values are stored in database Also create a (iii) Gold Rate. The values are stored in database. Also create a
web client for a share trading firm that displays these values on
its home page.
Design a web service for college containing 2 functions- 1
st
function getCutoff accepts coursename as parameter and returns
last years cutoff for that course as floating point number, 2
nd
function getFees accepts coursename as parameter and returns
this years fee for that course as floating point number. Design a
client to test the above web service.
8. Developing Advance Web services in
Java
Create a web service for UGC that contains a method which
accepts college name as parameter and returns the NAAC accepts college name as parameter and returns the NAAC
rating. The college names and their ratings are stored in
database. Design a web client to test the above web service
Design a web service for a channel containing 2 functions 1
st
function called getBreakingNews which accepts date as string
parameter and returns special news of that day, 2
nd
function
accepts sunsign name as string parameter and returns predictions
as string. Design a client to test the above web service.
TYBSC
Computer Science
USCS503 & USCS603
Paper 3
Operating Systems &
Linux
17-J ul-2013
1
TYBSc Comp Sci Syllabus Workshop
@MCC College
17
th
July 2013
Operating Systems(SemV)
and
Linux OS(SemVI)
OperatingSystem SemV
17-J ul-2013
2
OperatingSystemsTheory
OperatingSystemPrinciples VIIEdition
Silberschatz,GalvinandGagne(WileyIndiaEdition)
Chapter1 IntroductiontoOS
P 3 35 Page3 35
Chapter2:SystemStructures
Page3965
Chapter3:ProcessConcept
Page79 99
Chapter4:MultithreadedProgramming
Page123 127
Chapter5:ProcessScheduling
Page149 165,Page177178
OperatingSystemsTheory
OperatingSystemPrinciples VIIEdition
Silberschatz,GalvinandGagne(WileyIndiaEdition)
Chapter6:Synchronization p y
Page187213
Chapter7:Deadlocks
Page237259
Chapter 8 : Memory Mgmt Strategies Chapter8:MemoryMgmtStrategies
Page265 295
Chapter9:VirtualMemorymgmt
Page303 333
17-J ul-2013
3
OperatingSystemsTheory
OperatingSystemPrinciples VIIEdition
Silberschatz,GalvinandGagne(WileyIndiaEdition)
Chapter10:FileSystem
Page359 376
Chapter13:I/OSystems
Page477489
Chapter12:SecondaryStorageStructure p y g
Page435443
Chapter18 OSSecurity
Page623639
OSPractical
17-J ul-2013
4
GeneralInstructions
ShouldbedoneinJava
Shouldbedoneusingthreadsasnecessary
CanchangetheorderofOStheorytopicsto
complementOSPractical
For example 1,2,3,6,7,8,4,5 Forexample 1,2,3,6,7,8,4,5
CanteachJavathreadsinOSPractical
Avoidlengthypracticalinexam
1.Demonstrateroundrobin
schedulingusingthreads
Createathread
Jobcanbetocountnumbersfrom1ton
wherenrepresentsnumberofinstr
Acceptn,timequantum,processidfromuser
ActualRoundRobinalgorithmprocessesthe
jobs in FCFS manner But when you are using jobsinFCFSmanner.Butwhenyouareusing
Javathreads,theymaynotbeinFCFSmanner
sinceyoucannotcontrolorderofexecutionof
threads.
17-J ul-2013
5
1.Demonstratepriorityscheduling
usingthreads
Createathread
Jobcanbetocountnumbersfrom1ton
wherenrepresentsnumberofinstr
Acceptn,timequantum,processid,priority
fromuser
High priority job gets over first provided low Highpriorityjobgetsoverfirstprovidedlow
priorityjobsarenottoosmallandiftheystart
first
Output
Enterauserprocessstartingnumber:
500
Enteratimequantum(inmillis):
100
Executinginstr no5ofprocess503
Executinginstr no5ofprocess501
100
Executinginstr no1ofprocess502
Executinginstr no1ofprocess501
Executinginstr no1ofprocess503
Executinginstr no2ofprocess502
Executinginstr no2ofprocess503
Executinginstr no2ofprocess501
Executinginstr no3ofprocess501
Executinginstr no6ofprocess501
Executinginstr no6ofprocess503
Executinginstr no6ofprocess502
Executinginstr no7ofprocess503
Executinginstr no7ofprocess502
Executinginstr no7ofprocess501
Executing instr no 8 of process 501
xecuting instr no 3 of process 50
Executinginstr no3ofprocess503
Executinginstr no3ofprocess502
Executinginstr no4ofprocess503
Executinginstr no4ofprocess502
Executinginstr no4ofprocess501
Executinginstr no5ofprocess502
Executinginstr no8ofprocess501
Executinginstr no8ofprocess503
Executinginstr no8ofprocess502
Job503isover
Job502isover
Job501isover
17-J ul-2013
6
2.Foranyschedulingalgorithm,
calculateturnaroundtime
Useany1ofthepreviousprogram
Recordtimewhenthejobstarts
Recordtimewhenthejobends
DifferenceinTurnaroundtime
Addallturnaroundtimes&calculateavg
Output
Enterauserprocessstartingnumber:
500 500
Enteratimequantum(inmillis):
100
Job503with9instructionshascompletedin922
milliseconds
Job502with15instructionshascompletedin1531 Job 50 with 5 instructions has completed in 53
milliseconds
Job501with25instructionshascompletedin2547
milliseconds
Averageturnaroundtime=1666.6666
17-J ul-2013
7
3.Demonstratetheconceptof
synchronizedaccesstosharedresource
Sharedresourcecanrepresentobjectof
thi fil i t anything file,room,printer
Include1ormorefunctionstouseresource
Create2ormoreuserjobstoaccessthis
resource&callfunctionsatthesametime
Test the above program with/without Testtheaboveprogramwith/without
synchronizedkeyword
Output(withoutsynchronized)
Kamlakar Sirenters...
P ji h M d t Prajisha Madamenters...
Madhavi Madamenters...
Kamlakar Sirstartslecture...
Prajisha Madamstartslecture...
Madhavi Madam starts lecture Madhavi Madamstartslecture...
Kamlakar Sirexits...
Prajisha Madamexits...
Madhavi Madamexits...
17-J ul-2013
8
Output(withsynchronized)
Kamlakar Sirenters...
K l k Si t t l t Kamlakar Sirstartslecture...
Kamlakar Sirexits...
Prajisha Madamenters...
Prajisha Madamstartslecture...
Prajisha Madam exits Prajisha Madamexits...
Madhavi Madamenters...
Madhavi Madamstartslecture...
Madhavi Madamexits...
4.Demonstratetheuseofinter
processcommunication
ProducerConsumerproblem
o FromJavaCompleteReference
o Dining Philosopherproblem
Maynotgetoverin1.5hours
17-J ul-2013
9
5.Demonstrateany1ofdeadlock
avoidancealgorithm
UsingBankersalgorithmasgivenintextbook
I l d f l i h Includessafetyalgorithm
Resourcerequestalgorithm
Output
Applyingsafetyalgorithm...
Process0canbecompleted
b l d Process1canbecompleted
Process2canbecompleted
Process3canbecompleted
Process4canbecompleted
Thesystemisinsafestate...
l i l Applyingresourcerequestalgo...
Process2hasexceededrequestforresource3hence
isunsafe
thesystemisunsafe...
17-J ul-2013
10
6.Demonstratememorymanagement
usingfirst/best/worstfitusingarrays
CreateabigarrayrepresentingMemory(RAM)
Createjobwhereeachjobwitharray
representingsizeofjob
Forshowingexecutionofjobs,copythejob
arraystobigarray.
Apply first fit/worst fit/best fit technique Applyfirstfit/worstfit/bestfittechnique
Addthejobsinvectorinincreasing/
decreasingorderofsize
Output
Initialmemorylayout...
|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|
Enterpolicy:
1:FirstFit
2:BestFit
3:WorstFit
2
ApplyingBestFitPolicy...
copying2instructionsatlocation0
|201|202|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|
copying6instructionsatlocation2
|201|202|901|902|903|904|905|906|0|0|0|0|0|0|0|0|0|0|0|0|
copying9instructionsatlocation8
|201|202|901|902|903|904|905|906|501|502|503|504|505|506|507|
508|509|0|0|0|
17-J ul-2013
11
7.Demonstratepagereplacement
algorithm
Createaarrayofsomeblocksizeasspecified
bbyuser
Acceptframesequencefromuser
Applyvarioustechniquesontheframe
sequenceandshowtheoutput
Calculate number of page faults Calculatenumberofpagefaults
Output
OptimalPage
Replacement
InitialMemorylayout...
Loading page no.6:3
|2|0|3|
Loading page no.7:0
|2|0|3|
Loading page no.15:2
|2|0|1|
Loading page no.16:0
|1|1|1|
Loadingpageno.1:7
|7|1|1|
Loadingpageno.2:0
|7|0|1|
Loadingpageno.3:1
| |0|1|
Loading page no.8:4
|2|4|3|
Loading page no.9:2
|2|4|3|
Loading page no.10:3
|2|4|3|
Loadingpageno.11:0
|2|0|3|
|2|0|1|
Loadingpageno.17:1
|2|0|1|
Loadingpageno.18:7
|7|0|1|
Loadingpageno.19:0
|7|0|1| |7|0|1|
Loadingpageno.4:2
|2|0|1|
Loadingpageno.5:0
|2|0|1|
Loadingpageno.12:3
|2|0|3|
Loadingpageno.13:2
|2|0|3|
Loadingpageno.14:1
|2|0|1|
|7|0|1|
Loadingpageno.20:1
|7|0|1|
TotalNumberofpage
faults:9
17-J ul-2013
12
8.Demonstratepagereplacement
algorithm
Enterdiskframesequence
Startingtracknumber
Additionallyyoucantakealgo.Specification
Showstartingtrack,newtrackpositions&
totalcylinderstraversed
Output
=======SHORTESTSEEKTIMEFIRST===========
Traversingfrom:53
to track : 65 totrack:65
totrack:67
totrack:37
totrack:14
totrack:98
to track : 122 totrack:122
totrack:124
totrack:183
Totalcylinderstraversed=236
17-J ul-2013
13
Linux
LinuxTheory #Unit1
Linux System: History, Design Principles,
K l M d l P M t Kernel Modules, Process Management,
Scheduling, Memory Management, File
system, I/O (SGG: 20.1 to 20.8)
Linux Basics: Looking into the Linux Kernel,
GNU Utilities, Desktop environments. (RB: , p (
Chapter1) , The Linux console (RB: Chapter2)
The Unix/Linux architecture, Features of
Unix/Linux. . (SD: 2.1, 2.2)
17-J ul-2013
14
#Unit1
Basicbashshellcommands: Startingtheshell,
Sh ll t Fil t N i ti Fil d Shellprompt,FilesystemNavigation,Fileand
directorylisting,Filehandling,Directory
handling,Viewingfilecontents.(RB:Chapter
3)Directorystructure,differenttypesof
shells,commandslikels,md,cd,rd,cat,cp,
mv,rmetc
#Unit1
Morebashshellcommands: Monitoring
programs Monitoring disk space Working with programs,Monitoringdiskspace,Workingwith
datafiles:Sorting,Searching,Compressing,
Archiving. (RB:Chapter4)Fromthe
followingcommandsthatarecoveredinchapter
4likejobs,ps,du,sort,find,zip,unzip,zcat,tar
etc
FilterCommands:more,head,tail,comm,diff,
cmp,sort,tee,grep,egrep,fgrep,cut,tr,wc,split,
paste.(SDIVEdition:229242)
17-J ul-2013
15
#Unit1
TheLinuxenvironmentvariable:Environment
variables,settingenvironmentvariables,
Removingenvironmentvariables,Defaultshell
environmentvariables,settingthePATH
environmentvariables,Locatingsystem
environmentvariables,Variablearrays,Using
command aliases (RB: Chapter5) (SD 194 commandaliases.(RB:Chapter 5)(SD194
201)
likePATH,HOME,PS1etc,Commandslikeset,
env,export,fileslike.profile,.bash_profile,
.bash_login,.bashrc,.bash_logout
#Unit2
UnderstandingLinuxfilepermission: Linux
it U i Li D di fil security,UsingLinuxgroups,Decodingfile
permissions,Changingsecuritysettings,
Sharingfiles. (RB:Chapter6)(SD110117)
[Users&Groups,chmodcommand,setting
permissionsusingrwx&binarymask,user p g y ,
representationsuchasuaga,useridand
groupidpermission,creatinglinks(soft/hard)]
17-J ul-2013
16
#Unit2
Basicscriptbuilding: Usingmultiple
d C ti i t fil Di l i commands,Creatingascriptfile,Displaying
messages,Usingvariables,RedirectingInput
andOutput,Pipes,Performingmath,Exiting
thescript..(RB:Chapter8)
[Usingecho,declaringvariables,using>,>>,< [ g , g , g , ,
,|,exprandletstatements,shcommandetc]
#Unit2
Usingstructuredcommands:Workingwith
th if th if th l d ti if theifthen,ifthenelseandnestingif
statements,testcommand,Compound
conditiontesting,advancedifthenfeatures,
thecasecommand.(RB:Chapter9)
17-J ul-2013
17
#Unit2
Morestructuredcommands:forcommand,C
t l f d hil d til styleforcommand,whilecommand,until
command,nestingloops,Loopingonfiledata,
controllingtheloop,processingtheo/pofa
loop.(RB:Chapter10)
#Unit2
Handlinguserinput: Commandline
t S i l t i bl hift parameters,Specialparametervariables,shift
command,workingwithoptions,
Standardizingoptions,GettinguserI/P.(RB:
Chapter11)[Using$@,$*,$#,Usingshiftto
changepositionofcommandlinearguments
etc]
17-J ul-2013
18
#Unit3
Presentingdata: UnderstandingI/O,
R di ti O/ i i t R di ti I/ i RedirectingO/pinscripts,RedirectingI/pin
scripts,Creatingyourownredirection,Listing
openfiledescriptors,Suppressingcommand
o/p,Usingtemporaryfiles,LoggingMessages.
(RB:Chapter12)[Usinglscommand,
/dev/null,using/var/log/messagefile]
#Unit3
Scriptcontrol:Handlingsignals,Runningscripts
in background mode Running scripts without a inbackgroundmode,Runningscriptswithouta
console,Jobcontrol,JobSchedulingCommands:
nice,renice,at,batch,cron table,Runningthe
scriptatboot.(RB:Chapter13)[commandslike
fg,bg,jobs,crontab,at](SD:chapter9)
Editors:sed andawk (RB:Chapter16)(SD:255
265,382390)
17-J ul-2013
19
#Unit3
TCP/IPnetworking: TCP/IPBasics,TCP/IP
M d l R l i IP dd A li ti Model,ResolvingIPaddresses,Applications,
telnet,ftp,Berkeleycommands.(SD:Chapter
17)[commandslikeifconfig,ping,traceroute,
host,nslookup,netstat,wall,talk,etc]
#Unit4
LinuxFirewall:Introductiontofirewall,
Di l i t t f fi ll T i Displayingstatusoffirewall,Turningan
iptablesFirewallon/off,Testingfirewall,
ConfiguringthefirewallforRemoteSSH
Administration.(CS:3.0,3.73.11)
17-J ul-2013
20
#Unit4
EssentialSystemAdministration: root:The
t d i i t t l i Th systemadministratorslogin,The
administratorsprivileges,Startup&
Shutdown.(SD:15.1,15.2,15.5)
Suchasmountingdevices,managingusers/
groups,installingsoftwares,sucommand g p , g ,
#Unit4
AdvancedSystemAdministration: Partitions
& fil t / t /f t b f k S t t t &filesystems,/etc/fstab,fsck,Systemstartup
andinit,Shutdown&syncoperation.(SD:
25.2,25.6.3,25.7,25.8,25.9)
[commandslikefdisk,mountetc]
17-J ul-2013
21
LinuxPractical
BasicLinuxCommandssuchasfileanddirectory
manipulation,redirectionandpiping
Basic Filter commands such as BasicFiltercommandssuchas
head,tail,more,cat,sort,cut,grep(withoptionse,
f),paste
AdvancedFiltersuchasegrep,fgrep,tr,sed,awk
FileOperationCommandssuchas
split tar find zip ln touch chmod split,tar,find,zip,ln,touch,chmod
BasicShellscriptingsuchas defining
variables,readinguserinput,conditions,loops,string
operations,arithmaticoperartions
LinuxPractical
AdvancedShellScriptingsuchas
environmentvariables,shell
features command line arguments file test features,commandlinearguments,filetest,
backticks
ProcessManagement ps,jobs,nice,fg,bg,
at,sleep(forusermanagementshellscripts)
LinuxSystemAdministration User y
Management,Mounting,Jobcontrol(crontab),
chown,chgrp
17-J ul-2013
22
Thankyou.
Any?????
OSPRACTICALS

1. Demonstrateroundrobin/priorityschedulingusingthreads.

RoundRobin

importjava.io.*;

classjobimplementsRunnable
{
intprocess_id,no_of_instr,time_quantum;
Threadt;
job(intpid,intinstr,inttq)
{
process_id=pid;
no_of_instr=instr;
time_quantum=tq;
t=newThread(this);
t.start();
}
publicvoidrun()
{
try
{
for(inti=1;i<=no_of_instr;i++)
{
System.out.println("Executinginstrno"+i+"ofprocess"+process_id);
Thread.sleep(time_quantum);
}
System.out.println("Job"+process_id+"isover");
}
catch(InterruptedExceptione)
{
System.out.println("Thejobhasbeeninterrupted...");
}
}
}
classos
{
publicstaticvoidmain(Stringargs[])
{
try
{
intprocess_id=100,time_quantum=100;
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
System.out.println("Enterauserprocessstartingnumber:");
process_id=Integer.parseInt(br.readLine());
System.out.println("Enteratimequantum(inmillis):");
time_quantum=Integer.parseInt(br.readLine());
jobj1=newjob(++process_id,10,time_quantum);
jobj2=newjob(++process_id,6,time_quantum);
jobj3=newjob(++process_id,8,time_quantum);
}
catch(Exceptione)
{
System.out.println("Someprocessfailedtocomplete...");
System.out.println("Plzcontactsystemadmin...");
}
}
}
Output
Enterauserprocessstartingnumber:
500
Enteratimequantum(inmillis):
100
Executinginstrno1ofprocess501
Executinginstrno1ofprocess502
Executinginstrno1ofprocess503
Executinginstrno2ofprocess502
Executinginstrno2ofprocess501
Executinginstrno2ofprocess503
Executinginstrno3ofprocess502
Executinginstrno3ofprocess501
Executinginstrno3ofprocess503
Executinginstrno4ofprocess502
Executinginstrno4ofprocess501
Executinginstrno4ofprocess503
Executinginstrno5ofprocess502
Executinginstrno5ofprocess501
Executinginstrno5ofprocess503
Executinginstrno6ofprocess502
Executinginstrno6ofprocess501
Executinginstrno6ofprocess503
Job502isover
Executinginstrno7ofprocess501
Executinginstrno7ofprocess503
Executinginstrno8ofprocess501
Executinginstrno8ofprocess503
Executinginstrno9ofprocess501
Job503isover
Executinginstrno10ofprocess501
Job501isover

Priority

importjava.io.*;

classjobimplementsRunnable
{
intprocess_id,no_of_instr,priority_value,time_quantum;
Threadt;
job(intpid,intinstr,intprio,inttq)
{
process_id=pid;
no_of_instr=instr;
time_quantum=tq;
priority_value=prio;
t=newThread(this);
t.setPriority(priority_value);
t.start();

}
publicvoidrun()
{
try
{
for(inti=1;i<=no_of_instr;i++)
{
System.out.println("Executinginstrno"+i+"ofprocess"+process_id);
Thread.sleep(time_quantum);
}
System.out.println("Job"+process_id+"isover");
}
catch(InterruptedExceptione)
{
System.out.println("Thejobhasbeeninterrupted...");
}
}
}

classos
{
publicstaticvoidmain(Stringargs[])
{
try
{
intprocess_id=100,time_quantum=100;
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
System.out.println("Enterauserprocessstartingnumber:");
process_id=Integer.parseInt(br.readLine());
System.out.println("Enteratimequantum(inmillis):");
time_quantum=Integer.parseInt(br.readLine());
jobj1=newjob(++process_id,8,9,time_quantum);
jobj2=newjob(++process_id,8,1,time_quantum);
jobj3=newjob(++process_id,8,2,time_quantum);
}
catch(Exceptione)
{
System.out.println("Someprocessfailedtocomplete...");
System.out.println("Plzcontactsystemadmin...");
}
}
}
Output

Enterauserprocessstartingnumber:
500
Enteratimequantum(inmillis):
100
Executinginstrno1ofprocess502
Executinginstrno1ofprocess501
Executinginstrno1ofprocess503
Executinginstrno2ofprocess502
Executinginstrno2ofprocess503
Executinginstrno2ofprocess501
Executinginstrno3ofprocess501
Executinginstrno3ofprocess503
Executinginstrno3ofprocess502
Executinginstrno4ofprocess503
Executinginstrno4ofprocess502
Executinginstrno4ofprocess501
Executinginstrno5ofprocess502
Executinginstrno5ofprocess503
Executinginstrno5ofprocess501
Executinginstrno6ofprocess501
Executinginstrno6ofprocess503
Executinginstrno6ofprocess502
Executinginstrno7ofprocess503
Executinginstrno7ofprocess502
Executinginstrno7ofprocess501
Executinginstrno8ofprocess501
Executinginstrno8ofprocess503
Executinginstrno8ofprocess502
Job503isover
Job502isover
Job501isover

2. Foranyschedulingalgorithm,calculateturnaroundtime.

importjava.io.*;
importjava.util.*;

//classjobrepresentsosprocess
//eachjobhassomenumberofinstructions
//OSassignsprocessidandtimequantum
classjobimplementsRunnable
{
intprocess_id,no_of_instr,time_quantum;
longmillis;
Threadt;
job(intpid,intinstr,inttq)
{
millis=System.currentTimeMillis();
process_id=pid;
no_of_instr=instr;
time_quantum=tq;
t=newThread(this);
t.start();
}
publicvoidrun()
{
try
{
for(inti=1;i<=no_of_instr;i++)
{
//System.out.println("Executinginstrno"+i+"ofprocess"+process_id);
Thread.sleep(time_quantum);
}
millis=System.currentTimeMillis()millis;
os.millitime=os.millitime+millis;
System.out.println("Job"+process_id+"with"+no_of_instr+"instructionshascompletedin"+
millis+"milliseconds");
}
catch(InterruptedExceptione)
{
System.out.println("Thejobhasbeeninterrupted...");
}
}
}
classos
{
staticlongmillitime=0;
staticintprocess_id=100,time_quantum=100;
publicstaticvoidmain(Stringargs[])
{
try
{
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
System.out.println("Enterauserprocessstartingnumber:");
process_id=Integer.parseInt(br.readLine());
System.out.println("Enteratimequantum(inmillis):");
time_quantum=Integer.parseInt(br.readLine());
jobj1=newjob(++process_id,25,time_quantum);
jobj2=newjob(++process_id,15,time_quantum);
jobj3=newjob(++process_id,9,time_quantum);
Threadmainthread=Thread.currentThread();
mainthread.sleep(3000);
System.out.println("Averageturnaroundtime="+(millitime)/3.0f);
}
catch(Exceptione)
{
System.out.println("Someprocessfailedtocomplete...");
System.out.println("Plzcontactsystemadmin...");
}
}
}
Output
Enterauserprocessstartingnumber:
500
Enteratimequantum(inmillis):
100
Job503with9instructionshascompletedin922milliseconds
Job502with15instructionshascompletedin1531milliseconds
Job501with25instructionshascompletedin2547milliseconds
Averageturnaroundtime=1666.6666

3. Demonstratetheconceptofsynchronizedaccesstosharedresource

classroom
{
publicsynchronizedvoidtakesLecture(Stringname)throwsInterruptedException
{
System.out.println(name+"enters...");
Thread.sleep(250);
System.out.println(name+"startslecture...");
Thread.sleep(500);
System.out.println(name+"exits...");
Thread.sleep(250);
}
}

classlecturerimplementsRunnable
{
Stringname;
roomr;
Threadt;
lecturer(Stringn,roomr)
{
name=n;
t=newThread(this,n);
this.r=r;
}
publicvoidstart()
{
t.start();
}
publicvoidrun()
{
try
{
r.takesLecture(name);
}
catch(InterruptedExceptione)
{
System.out.println(name+"operationinterrupted...");
}
}
}

classos
{
publicstaticvoidmain(Stringargs[])
{
roomr=newroom();
lecturerkamlakar=newlecturer("KamlakarSir",r);
lecturermadhavi=newlecturer("MadhaviMadam",r);
lecturerprajisha=newlecturer("PrajishaMadam",r);
kamlakar.start();
madhavi.start();
prajisha.start();
}
}
Output
KamlakarSirenters...
KamlakarSirstartslecture...
KamlakarSirexits...
PrajishaMadamenters...
PrajishaMadamstartslecture...
PrajishaMadamexits...
MadhaviMadamenters...
MadhaviMadamstartslecture...
MadhaviMadamexits...

4. Demonstratetheuseofinterprocesscommunication

ProducerConsumerproblemFromJ2CR
DiningPhilosopherproblemtobesolved

5. Demonstrateany1ofdeadlockavoidancealgorithm

importjava.io.*;

classBanker
{
intavail[];
intmax[][]={{3,2,2,1},{8,12,0,0},{2,1,0,0},{4,3,0,0},{2,0,3,1}};
intalloc[][]={{1,1,1,0},{2,1,0,0},{1,0,0,0},{2,1,0,0},{1,0,0,0}};
intneed[][];
intm,n;
Banker()
{
m=4;
n=5;
avail=newint[4];
avail[0]=16;//NumberofRegisters
avail[1]=50;//NumberofFiles
avail[2]=5;//NumberofPorts
avail[3]=2;//NumberofPrinter

need=newint[5][4];

for(inti=0;i<5;i++)
for(intj=0;j<4;j++)
need[i][j]=max[i][j]alloc[i][j];
}
booleanisSafe()
{
intwork[]=newint[m];
booleanfinish[]=newboolean[n];
for(inti=0;i<m;i++)
work[i]=avail[i];

for(inti=0;i<n;i++)
finish[i]=false;

for(inti=0;i<n;i++)
{
if(finish[i]==false)
{
booleanincomplete=false;
for(intj=0;j<m;j++)
{
if(need[i][j]>work[j])
{
incomplete=true;
//System.out.println(i+":"+j+":"+need[i][j]+":"+work[j]);
}
if(need[i][j]!=0&&need[i][j]<=work[j])
{
work[j]=work[j]need[i][j];
}
}
if(!incomplete)
{
finish[i]=true;
}
if(finish[i])
System.out.println("Process"+i+"canbecompleted");
else
System.out.println("Process"+i+"can'tbecompleted");
}
}
for(inti=0;i<n;i++)
{
if(!finish[i])
{
returnfalse;
}
}
returntrue;
}
voidresourceRequest()
{
intrequest[][]={{1,1,1,0},{2,2,0,0},{1,1,0,1},{1,1,0,0},{1,0,0,0}};
booleansafe=true;
for(inti=0;i<n;i++)
{
for(intj=0;j<m;j++)
{
if(request[i][j]<=need[i][j])
{
if(request[i][j]<=avail[j])
{
avail[j]=avail[j]request[i][j];
alloc[i][j]=alloc[i][j]+request[i][j];
need[i][j]=need[i][j]request[i][j];
}
else
{
System.out.println("Heyprocess"+i+"!resource"+j+"isnotavailablenow...tryagain
later...");
}
}
else
{
System.out.println("Process"+i+"hasexceededrequestforresource"+j+"henceis
unsafe");
safe=false;
}
}
}
if(safe)
{
System.out.println("thesystemissafe...");
}
else
{
System.out.println("thesystemisunsafe...");
}
}
}
classos
{
publicstaticvoidmain(Stringargs[])throwsException
{
Bankerb=newBanker();
System.out.println("Applyingsafetyalgorithm...");
if(b.isSafe())
{
System.out.println("Thesystemisinsafestate...");
}
else
{
System.out.println("Thesystemisnotinsafestate....");
}
System.out.println("Applyingresourcerequestalgo...");
b.resourceRequest();
}
}
Ouput
Applyingsafetyalgorithm...
Process0canbecompleted
Process1canbecompleted
Process2canbecompleted
Process3canbecompleted
Process4canbecompleted
Thesystemisinsafestate...
Applyingresourcerequestalgo...
Process2hasexceededrequestforresource3henceisunsafe
thesystemisunsafe...

6. Demonstratememorymanagementusingfirst/best/worstfit

importjava.util.*;
importjava.io.*;

classJob
{
intinstr[];
intprocess_id,size;
Job(intpid,intn)
{
process_id=pid;
size=n;
instr=newint[size];
for(inti=0;i<size;i++)
{
instr[i]=process_id+i+1;
}
}
intgetSize()
{
returnsize;
}
int[]getInstr()
{
returninstr;
}
intgetProcessId()
{
returnprocess_id;
}
}

classMemMgmt
{
intmemory_array[];
Vectorjobqueue;
MemMgmt(Vectorv)
{
jobqueue=v;
memory_array=newint[20];
for(inti=0;i<20;i++)
{
memory_array[i]=0;
}
System.out.println("Initialmemorylayout...");
printArray();
}
voidaddJob(Jobnewjob)
{
jobqueue.add(newjob);
}
voidaddSortedJob(Jobnewjob)
{
if(jobqueue.size()==0)
{
jobqueue.add(newjob);
return;
}
for(inti=0;i<jobqueue.size();i++)
{
Jobj=(Job)jobqueue.elementAt(i);
if(j.getSize()>=newjob.getSize())
{
jobqueue.insertElementAt(newjob,i);
return;
}
}
jobqueue.add(newjob);
}
voidprintArray()
{
System.out.println();
System.out.print("|");
for(inti=0;i<20;i++)
{
System.out.print(memory_array[i]+"|");
}
}

voidfirstFit()
{
intmem_arr_index=0;
for(inti=0;i<jobqueue.size();i++)
{
Jobjob=(Job)jobqueue.elementAt(i);
intinstr_array[]=job.getInstr();
if(20mem_arr_index>=instr_array.length)
{
System.out.print("\n\ncopying"+instr_array.length+"instructionsatlocation"+
mem_arr_index);
for(intj=0;j<instr_array.length;j++)
{
memory_array[mem_arr_index]=instr_array[j];
mem_arr_index++;
}
printArray();
}
else
{
System.out.println("\nJobwithprocessid"+job.getProcessId()+"istoobig!");
}
}
}
voidworstFit()
{
intmem_arr_index=0;
for(inti=jobqueue.size()1;i>=0;i)
{
Jobjob=(Job)jobqueue.elementAt(i);
intinstr_array[]=job.getInstr();
if(20mem_arr_index>=instr_array.length)
{
System.out.print("\n\ncopying"+instr_array.length+"instructionsatlocation"+
mem_arr_index);
for(intj=0;j<instr_array.length;j++)
{
memory_array[mem_arr_index]=instr_array[j];
mem_arr_index++;
}
printArray();
}
else
{
System.out.println("\nJobwithprocessid"+job.getProcessId()+"istoobig!");
}
}
}
}

classos
{
publicstaticvoidmain(Stringargs[])throwsException
{
Vectorv=newVector();
MemMgmtm=newMemMgmt(v);

Jobjob1=newJob(500,9);
Jobjob2=newJob(200,2);
Jobjob3=newJob(900,6);

System.out.println("\n\nEnterpolicy:\n1:FirstFit\n2:BestFit\n3:WorstFit");
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
intpolicy=Integer.parseInt(br.readLine());

if(policy==1)
{
System.out.println("\nApplyingFirstFitPolicy...");
m.addJob(job1);
m.addJob(job2);
m.addJob(job3);
m.firstFit();
}
else
if(policy==2)
{
System.out.println("\nApplyingBestFitPolicy...");
m.addSortedJob(job1);
m.addSortedJob(job2);
m.addSortedJob(job3);
m.bestFit();
}
else
if(policy==3)
{
System.out.println("\nApplyingWorstFitPolicy...");
m.addSortedJob(job1);
m.addSortedJob(job2);
m.addSortedJob(job3);
m.worstFit();
}
}
}
Output
Initialmemorylayout...

|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|

Enterpolicy:
1:FirstFit
2:BestFit
3:WorstFit

ApplyingBestFitPolicy...

copying2instructionsatlocation0
|201|202|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|

copying6instructionsatlocation2
|201|202|901|902|903|904|905|906|0|0|0|0|0|0|0|0|0|0|0|0|

copying9instructionsatlocation8
|201|202|901|902|903|904|905|906|501|502|503|504|505|506|507|508|509|0|0|0|

7. Demonstratepagereplacementalgorithm

importjava.io.*;

classMemMgmt
{
Stringframe_sequence;
intmem_block[];
MemMgmt(Stringfs,intn)
{
frame_sequence=fs;
mem_block=newint[n];
for(inti=0;i<n;i++)
mem_block[i]=1;
}
voiddispMemBlock()
{
System.out.print("|");
for(inti=0;i<mem_block.length;i++)
{
System.out.print(mem_block[i]+"|");
}
System.out.println();
}
voidfcfs()
{
System.out.println("=======FCFS===========");
Stringstrpages[]=frame_sequence.split("");
intpages[]=newint[strpages.length];
for(inti=0;i<strpages.length;i++)
pages[i]=Integer.parseInt(strpages[i]);
intmem_block_num=0,page_faults=0;
System.out.println("InitialMemorylayout...");
dispMemBlock();
for(inti=0;i<pages.length;i++)
{
booleanpresent=false;
for(intj=0;j<mem_block.length;j++)
{
if(mem_block[j]==pages[i])
{
present=true;
break;
}
}
if(!present)
{
mem_block[mem_block_num]=pages[i];
mem_block_num++;
page_faults++;
}
if(mem_block_num==mem_block.length)
mem_block_num=0;
System.out.println("Loadingpageno."+(i+1)+":"+pages[i]);
dispMemBlock();
}
System.out.println("TotalNumberofpagefaults:"+page_faults);
}

voidoppr()
{
System.out.println("=======OptimalPageReplacement===========");
Stringstrpages[]=frame_sequence.split("");
intpages[]=newint[strpages.length];
inti=0;
for(i=0;i<strpages.length;i++)
pages[i]=Integer.parseInt(strpages[i]);
intmem_block_num=0,page_faults=0;
System.out.println("InitialMemorylayout...");
dispMemBlock();
for(i=0;i<mem_block.length;i++)
{
booleanpresent=false;
for(intj=0;j<mem_block.length;j++)
{
if(mem_block[j]==pages[i])
{
present=true;
break;
}
}
if(!present)
{
mem_block[mem_block_num]=pages[i];
mem_block_num++;
page_faults++;
}
System.out.println("Loadingpageno."+(i+1)+":"+pages[i]);
dispMemBlock();
}
for(;i<pages.length;i++)
{
booleanpresent=false;
for(intj=0;j<mem_block.length;j++)
{
if(mem_block[j]==pages[i])
{
present=true;
break;
}
}
if(!present)
{
mem_block_num=1;
intlongest_page=1;
for(intj=0;j<mem_block.length;j++)
{
intk=0;
for(k=i+1;k<pages.length;k++)
{
if(mem_block[j]==pages[k])
{
if(k>longest_page)
{
longest_page=k;
mem_block_num=j;
}
break;
}
}
if(k==pages.length)
{
longest_page=pages.length;
mem_block_num=j;
}
}
mem_block[mem_block_num]=pages[i];
page_faults++;
}
System.out.println("Loadingpageno."+(i+1)+":"+pages[i]);
dispMemBlock();
}
System.out.println("TotalNumberofpagefaults:"+page_faults);
}
}
classos
{
publicstaticvoidmain(Stringargs[])throwsException
{
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
System.out.println("Enterpageframesequence(separatedbyspace):");
//Stringframe_sequence=br.readLine();
Stringframe_sequence="70120304230321201701";
System.out.println("Enterpagereplacementalgo:");
inti=Integer.parseInt(br.readLine());
MemMgmtm=newMemMgmt(frame_sequence,3);
if(i==1)
m.fcfs();
else
if(i==2)
m.oppr();
}
}
Output
Enterpageframesequence(separatedbyspace):
Enterpagereplacementalgo:
=======OptimalPageReplacement===========
InitialMemorylayout...
|1|1|1|
Loadingpageno.1:7
|7|1|1|
Loadingpageno.2:0
|7|0|1|
Loadingpageno.3:1
|7|0|1|
Loadingpageno.4:2
|2|0|1|
Loadingpageno.5:0
|2|0|1|
Loadingpageno.6:3
|2|0|3|
Loadingpageno.7:0
|2|0|3|
Loadingpageno.8:4
|2|4|3|
Loadingpageno.9:2
|2|4|3|
Loadingpageno.10:3
|2|4|3|
Loadingpageno.11:0
|2|0|3|
Loadingpageno.12:3
|2|0|3|
Loadingpageno.13:2
|2|0|3|
Loadingpageno.14:1
|2|0|1|
Loadingpageno.15:2
|2|0|1|
Loadingpageno.16:0
|2|0|1|
Loadingpageno.17:1
|2|0|1|
Loadingpageno.18:7
|7|0|1|
Loadingpageno.19:0
|7|0|1|
Loadingpageno.20:1
|7|0|1|
TotalNumberofpagefaults:9

8. Demonstratediskschedulingalgorithm

importjava.io.*;

classDevMgmt
{
Stringdisk_sequence;
DevMgmt(Stringfs)
{
disk_sequence=fs;
}
voidsstf(intstart_track)
{
System.out.println("=======SHORTESTSEEKTIMEFIRST===========");
Stringdisknums[]=disk_sequence.split("");
inttracks[]=newint[disknums.length];
booleantracks_bool[]=newboolean[disknums.length];
intmin_dist=0,max_dist=0;
for(inti=0;i<disknums.length;i++)
{
tracks[i]=Integer.parseInt(disknums[i]);
tracks_bool[i]=false;
max_dist=max_dist+tracks[i];
}
min_dist=max_dist;
for(inti=0;i<disknums.length;i++)
{
//System.out.println(tracks[i]+":"+tracks_bool[i]);
}
//System.out.println(min_dist);

inttotal_cylinders=0,from_track=start_track,current_track_index=1;
System.out.println("Traversingfrom:"+from_track);
for(inti=0;i<tracks.length;i++)
{
//System.out.println("i="+i+",from_track:"+from_track);
intto_track_index=0;
for(intt=0;t<tracks.length;t++)
{
if((!tracks_bool[t])&&(Math.abs(from_tracktracks[t])<min_dist)&&(t!=current_track_index))
{
to_track_index=t;
min_dist=Math.abs(from_tracktracks[t]);
//System.out.println("*fromtrack:"+from_track+":"+tracks[t]);
}
}
System.out.println("totrack:"+tracks[to_track_index]);//":"+min_dist);
total_cylinders+=Math.abs(from_tracktracks[to_track_index]);
tracks_bool[to_track_index]=true;
from_track=tracks[to_track_index];
current_track_index=to_track_index;
min_dist=max_dist;
}
System.out.println("Totalcylinderstraversed="+total_cylinders);
}
voidlook(intstart_track)
{
System.out.println("=======LOOK===========");
Stringdisknums[]=disk_sequence.split("");
inttracks[]=newint[disknums.length+1];
intp=0;
for(p=0;p<disknums.length;p++)
{
tracks[p]=Integer.parseInt(disknums[p]);
}
tracks[p]=start_track;
for(inti=0;i<tracks.length;i++)
{
for(intj=0;j<tracks.length1;j++)
{
if(tracks[j]>tracks[j+1])
{
inttemp=tracks[j];
tracks[j]=tracks[j+1];
tracks[j+1]=temp;
}
}
}
System.out.println("Aftersorting...");
inttotal_cylinders=0,from_track=start_track,to_track=0;
System.out.println("Traversingfrom:"+from_track);
inti=0;
for(i=0;i<tracks.length;i++)
{
if(tracks[i]==start_track)
break;
}
for(intx=i1;x>=0;x)
{
System.out.println("Totrack:"+tracks[x]);
to_track=tracks[x];
total_cylinders=total_cylinders+Math.abs(from_trackto_track);
from_track=to_track;
}
for(intx=i+1;x<tracks.length;x++)
{
System.out.println("Totrack:"+tracks[x]);
to_track=tracks[x];
total_cylinders=total_cylinders+Math.abs(from_trackto_track);
from_track=to_track;
}
System.out.println("Totalcylinderstraversed="+total_cylinders);
}
}

classos
{
publicstaticvoidmain(Stringargs[])throwsException
{
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
System.out.println("Enterdiskframesequence(separatedbyspace):");
//Stringframe_sequence=br.readLine();
Stringdisk_sequence="9818337122141246567";
System.out.println("Enterscanschedulingalgo:");
inti=Integer.parseInt(br.readLine());
System.out.println("Enterstartingtracknumber:");
inttrack=53;//Integer.parseInt(br.readLine());

DevMgmtm=newDevMgmt(disk_sequence);
if(i==1)
m.sstf(track);
else
if(i==2)
m.look(track);
}
}
Output
Enterdiskframesequence(separatedbyspace):
Enterscanschedulingalgo:
Enterstartingtracknumber:
=======SHORTESTSEEKTIMEFIRST===========
Traversingfrom:53
totrack:65
totrack:67
totrack:37
totrack:14
totrack:98
totrack:122
totrack:124
totrack:183
Totalcylinderstraversed=236

TYBSC
Computer Science
USCS504 & USCS604
Paper 4
Database Management
System & Softare
!ngineering
17Jul2013
1
PaperIV
DBMSII&SoftwareEngineering
SEMESTER V
DBMSII
17Jul2013
2
UNITI
Decomposition: Functional dependency, Closure of a
set of functional dependency, LosslessJoin set of functional dependency, Lossless Join
decomposition, Multi valued dependency and fourth
normal form, Join dependency, Fifth normal form.
Ref: [Ramakrishnam: 19.119.3, 19.5, 19.8]
Concurrency Control: Concept of a transaction, ACID
properties Serial and serializable schedules Conflict properties, Serial and serializable schedules, Conflict
and View serializabilty, Precedence graphs and test for
conflict seralizability.
Ref: [Ramakrishnam: 16.116.3, 17.1]
UNITII
Enforcing serializability by locks: Concept of locks, the
locking scheduler, Two phase Locking, upgrading and down
di l k C f d d l k C l grading locks, Concept of dead locks, Concurrency control
by time stamps, The Thomos Write rule.
Ref: [Ramakrishnam: 16.4, 17.1, 17.3, 17.4, 17.6]
Crash Recovery: ARIES algorithm. The log based
recovery, recovery related structures like transaction
and dirty page table, Writeahead log protocol, check y p g , g p ,
points, recovery from a system crash, Redo and Undo
phases.
Ref: [Ramakrishnam: 18.118.6]
17Jul2013
3
UNITIII
Fundamentals of PL/SQL: Defining variables and constants,
PL/SQL expressions and comparisons: Logical Operators,
Boolean Expressions, CASE Expressions Handling, Null
Values in Comparisons and Conditional Statements PL/SQL Values in Comparisons and Conditional Statements, PL/SQL
Datatypes: Number Types, Character Types, Boolean Type,
Datetime and Interval Types.
Ref: [Ivan Bayross: Chap 15]
Overview of PL/SQL Control Structures: Conditional
Control: IF and CASE Statements, IFTHEN Statement, IF
THENELSE Statement IFTHEN ELSIF Statement CASE THENELSE Statement, IFTHEN ELSIF Statement, CASE
Statement, Iterative Control: LOOP and EXIT Statements,
WHILELOOP, FORLOOP, Sequential Control: GOTO and
NULL Statements, Concept of nested tables.
Ref: [Ivan Bayross: Chap 15]
UNITIV
Sequences: creating sequences, referencing, altering and dropping a
sequence.
Ref: [Ivan Bayross: Chap 11]
Query evaluation: System Catalog, Evaluation of relational operators
like selection projection join and set introduction to query like selection, projection, join and set, introduction to query
optimization.
Ref: [Ramakrishnam: 12.112.4]
Cursors: Concept of a cursor, types of cursors: implicit cursors;
explicit cursor, Cursor for loops, Cursor variables, parameterized
cursors,
Ref: [Ivan Bayross: Chap 16] Ref: [Ivan Bayross: Chap 16]
Transactions in SQL: Defining a transaction, Making Changes
Permanent with COMMIT, Undoing Changes with ROLLBACK, Undoing
Partial Changes with SAVEPOINT and ROLLBACK, Defining read only
transactions, explicit locks: transaction and system level, Choosing a
Locking Strategy: ROW SHARE and ROW EXCLUSIVE Mode.
Ref: [Ivan Bayross: Chap 16,17]
17Jul2013
4
References
1) Ramakrishnam, Gehrke, Database Management Systems, McGraw Hill.
2) Ivan Bayross, SQL,PL/SQL The Programming language of Oracle,
B.P.B. Publications
3) Michael Abbey, Michael J. Corey, Ian Abramson, Oracle 8i A
Beginners Guide, Tata McGrawHill.
Addi i l f Additional Reference
1) Elsmasri and Navathe, Fundamentals of Database Systems, Pearson
Education.
2) Peter Rob and Coronel, Database Systems, Design, Implementation
and Management, Thomson Learning
3) C.J.Date, Longman, Introduction to database Systems, Pearson
Education.
4) Jeffrey D. Ullman, Jennifer Widom, A First Course in Database
Systems, Pearson Education.
5) Martin Gruber, Understanding SQL,B.P.B. Publications.
6) George Koch and Kevin Loney ,ORACLE The Complete Reference, Tata
McGraw Hill,New Delhi
7) P. S Deshpande Oracle SQL PL/SQL Black Book
SQL PL/SQLPracticals
Practical1: WritingPL/SQLblockswithbasic
programmingconstructsby
a.Sequentialstatement
b.unconstrainedloop
c.If..then..else,ifelsifelse..endif
Practical2: WritingPL/SQLblockswithbasic
programmingconstructs
a.casewhen
b.usingGOTOtojumpoutofloop
17Jul2013
5
DBMSIIPracticalProblems
Practical3:ProceduresinPL/SQL
a.Createanemptyprocedure
b Create a stored procedure and call it b.Createastoredprocedureandcallit
c.Defineproceduretoinsertdata
d.aforwarddeclarationofprocedure
Practical4:FunctionsinPL/SQL
D fi d ll f ti a.Defineandcallafunction
b.Defineandusefunctionsinselect/printstmt
c.Recursivefunction
d.callfunctionandstorereturntoavariable
DBMSIIPracticalProblems
Practical5:cursorswith
a.CursorAttributesforImplicitandExplicit
b.Types:ImplicitandExplicit
c.CursorForLoop
d.declare,open,fetchvaluesandclosecursor
Practical6:Cursorswith
a.Subqueries
b.Joins
c.Clauseslikegroupbywithhaving,orderby
withwhere
17Jul2013
6
DBMSIIPracticalProblems
Practical7:ExecutionofSequenceCommand
Usingalloptionsincludingcycle/nocycleand
nextvalandcurrval
Practical8:StudyofTransactionsandlocks
a.Commit,Rollback
b.Savepoint
SampleListofPracticalonGroup1
1.Createatablestudent_list(rollno,name,marks)
andgeneratethesequenceonrollno &display
2 Q i it llb k d 2.Queriesoncommit,rollbackcommands.
Sequences
3.WriteaPL/SQLblocktoupdatethepriceofthe
bookbyitstitle,ifprice>300thenupdateitby
10%,elseupdateitspriceby5%.Raisean
exception if book title not available exceptionifbooktitlenotavailable.
4.Writeapl/sqlblocktocallacursorinaprocedure.
Thisprocedureiscalledfromthepl/sqlblockand
resultisdisplayed.
17Jul2013
7
Questions???
SEMESTER VI
SoftwareEngineering
17Jul2013
8
WhatisinTY???
InSY,wecoveredphasesofSDLC,SSAD&
OOADApproach
In TY(Sem VI) we will be covering Project InTY(SemVI),wewillbecoveringProject
Management,ChangingtrendsinSoftware
Engineering&Testing
Testingshouldbecoveredinsuchawaythat
fortheprojectsitwillbeuseful(forex.Test
casesetc)AsSTLCstartsalongwithSDLC
Studentsshouldbetoldtosearchforprojects
fromthemonthofAugust
UNITI
RevisionofProjectManagementProcess
[Jalote2.4.1],RoleofProjectManager,Project
M t K l d A [S t i Ch 3 ManagementKnowledgeAreas[SatzingerChap3
(Pg99100,104)]
ManagingChangesinrequirements
[Jalote2.4.4]
RoleofsoftwareMetrics
[Jalote1.3.2,Pressman23.1.5]
ProjectScheduling:BuildingWBS,UseofGantt
andPERT/CPMChart
17Jul2013
9
UNITII
ConfigurationManagementProcess&Functionality&
Mechanism[Jalote2.4.3]
ProcessManagement,CMM&itslevels[Jalote2.4.5]
Risk Management & activities [Jalote5 6 15 6 3] RiskManagement&activities[Jalote 5.6.1 5.6.3]
ManagementofOOsoftwareProjects Objectorientedmetrics,
UseCaseEstimation[Pressman23.3.3(CKMetric
Suite),25.2.5,26.6.726.6.8,27.5.3][Somepartisrelatedto
testing*]
Selectingdevelopmenttools,IntroductiontoCASE[Satzinger
Chap2(Pg85 86 Pg 341)] Chap2(Pg8586,Pg341)]
UnifiedProcess,Itsphases&disciplines,
AgileDevelopment Principles&Practices,Extreme
programming Corevalues&Practices
[SatzingerChap16(Pg692705)]
UNITIII
SoftwareTesting:IntroductiontoQualityAssurance,SixSigma
[Pressman14.4.4,16.2,16.5.2]
TestingFundamentals,CommonTerms(likeError,Fault,
Failure,Bug,Crash)Objectivesoftesting,Challengesin
Testing Principles of Testing [Mustafa1 2 1 2 1 1 2 3 1 2 4 Testing,PrinciplesofTesting[Mustafa 1.2,1.2.1,1.2.3,1.2.4,
1.5],
StaticTesting Introduction&Principles
[Mustafa3.1,3.2]
TypesofTesting LevelsoftestingsuchasUnittesting,
Systemtesting,ValidationTesting,Acceptancetesting,
TypesoftestingsuchasBlackbox,WhiteBox,Functional,
Performance,Regression,Acceptance,Volume,Stress,Alpha,
Betatesting[Mustafa1.4]
PlanningSoftwareTesting TestPlan,TestPlanSpecification,
TestCaseExecutionandAnalysis,Defectloggingandtracking
[Jalote10.4.210.4.5]
17Jul2013
10
UNITIV
BlackBoxTesting:Introduction,Equivalencepartitioning,
Boundaryvalue analysis, Robustness testing, Cause Effect Boundary valueanalysis,Robustnesstesting,CauseEffect
Graph,[Mustafa4.14.5,Jalote10.2.3]
WhiteBoxTesting :StatementCoverage,Branch/Decision
Coverage,ConditionCoverage,GraphMatrix,Cyclomatic
complexity,MutationTesting
[Mustafa5.15.6]
Object Oriented Testing & Web site testing Object Oriented ObjectOrientedTesting&Websitetesting ObjectOriented
TestingStrategies(*),Testingmethods,[Pressman19.3,
19.4.3,19.4.5,Mustafa11.2]Overviewofwebsite
testing[Pressman20.1.1]
References
1.SystemAnalysis&Design Satzinger,Jackson,Burd,Cengage Learning,
IndiaEd.
2.SoftwareEngineering APractitionersApproach,7
th
Edition,McGraw
HillInt.
3.IntegratedApproachtoSoftwareEngineering Pankaj Jalote (Narosa),
3
rd
Edition
4.DesignPatterns ElementsofReusableObjectOrientedSoftware,
PearsonBy ErichGamma,RichardHelm,RalphJohnson,JohnVlissides,
5.SoftwareTesting Concepts&Practices,Narosa,
Additional Reference
1) Design Patterns Elements of Reusable ObjectOriented Software, Pearson By
h Erich
Gamma, Richard Helm, Ralph Johnson, John Vlissides,
2) Software Engineering: Waman Jawadekar, TMH
3) Software Engineering : Sommerville, Pearson Education
17Jul2013
11
AdditionalReferencesforprojects
UMLForJavaProgrammers RobertMartin
DesigningFlexibleObjectOrientedSystems
withUML CharlesRichter
BuildingWebApplicationswithUML Jim
Connalen
ASPNET 3 5 Application Architecture & ASP.NET3.5ApplicationArchitecture&
Design VivekThakur
ProjectDiscussion
?????
17Jul2013
12
Questions???
ThankYou!!