MCC Workshop Booklet

158
“Study Material and Syllabus review/scope of CBGS syllabus for TYBSc Computer Science w.e.f 2013_14" Compiled and Presented by Syllabus Committee and BOS Members at Mulund College of Commerce

Transcript of MCC Workshop Booklet

Page 1: MCC Workshop Booklet

“Study Material and Syllabus

review/scope of CBGS syllabus

for TYBSc Computer Science

w.e.f 2013_14"

Compiled and Presented

by

Syllabus Committee and BOS

Members

at

Mulund College of Commerce

Page 2: MCC Workshop Booklet

TYBSC

Computer Science

USCS501 & USCS601

Paper 1

Data Communication,

Networking &

Security

Page 3: MCC Workshop Booklet

17‐Jul‐2013

1

Workshop on T Y B S C t S iT.Y. B.Sc. Computer Science

Credit Based SyllabusUSCS501 ,USCS601

Semester V

Page 4: MCC Workshop Booklet

17‐Jul‐2013

2

Reference Books

• Reference 1 (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 VSDigital, 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 todigital conversion, PCM, Transmission Modes.(Chapter 3 – Pg 101-110, 115-117, 120-135) (4 lectures)

4

Page 5: MCC Workshop Booklet

17‐Jul‐2013

3

UNIT I – contd…

• Analog Transmission – Digital to analogconversion(ASK,FSK,PSK, QAM), Analog to Analogconversion (Chapter 5) (4 lectures)conversion (Chapter 5) (4 lectures)

5

Line Coding schemes

• Encoding of 0 and 1 bit• PolarityPolarity• DC component• Synchronization• Bandwidth requirement

6

Page 6: MCC Workshop Booklet

17‐Jul‐2013

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)• Spread Spectrum – FHSS, DSSSp p ,

(Chapter 6 – Pg 161-175, 180-185) (2 lectures)

• Transmission Media – Guided & Unguided(Chapter 7) (5 lectures)

• Switching – Switching, Circuit-Switched Networks, Datagramf fnetworks, 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

Page 7: MCC Workshop Booklet

17‐Jul‐2013

5

UNIT III• Data Link Layer – Error correction & detection, Types of errors,

Detection VS Correction, Block Coding, Hamming Distance, LinearBlock codes(single parity check, hamming codes), Cyclic codes, CRCEncoder & 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 Transitionstates (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 DuplexEthernet, Concept of Fast(purpose & goals) & GigabitEthernet(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

Page 8: MCC Workshop Booklet

17‐Jul‐2013

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

Page 9: MCC Workshop Booklet

17‐Jul‐2013

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 (3rd Edition)– William Stallings

• 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 protocolpacket 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 ofrouting, 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

Page 10: MCC Workshop Booklet

17‐Jul‐2013

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 relatedthreats, virus countermeasures, denial of service attacks, Hacking,Security policies and plan, Strategies for a secure network.– Chapter 10, (3 lectures)

16

Page 11: MCC Workshop Booklet

17‐Jul‐2013

9

UNIT III

• Firewall and Intrusion Detection: Firewalls and theirtypes, 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

• Reference 3 (Unit IV) –– Cryptography & network securityyp g p y y– Behrouz A. Forouzan, Debdeep

Mukhopadhyay-second edition

18

Page 12: MCC Workshop Booklet

17‐Jul‐2013

10

UNIT IV

• Cryptography – Traditional and Modern Symmetric-KeyCiphers

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– BASIC DES structure– Chapter 6 ( 6.1-6.2)

19

UNIT IV• AES

– Basic AES structureChapter 7 (7 1 7 3)– Chapter 7 (7.1-7.3)

– 3 lectures

• Asymmetric –Key Cryptography, RSA and ELGAMALcryptosystems– Introduction, RSA key generation, Elgamal algorithmodu o , y g a o , ga a a go– 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

Page 13: MCC Workshop Booklet

17‐Jul‐2013

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 distributionsagreement, public key distributions– Otway rees and needham protocol excluded– Chapter 15(15.1-15.4) (2 lectures)

21

UNIT IV

• Security at Application Layer (E-MAIL, PGP andS/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 (17 1-17 2 17 4) (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

Page 14: MCC Workshop Booklet

17‐Jul‐2013

12

Thank you !!!

Ms. Megha Sawant - Ruia College 23

Page 15: MCC Workshop Booklet

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

Page 16: MCC Workshop Booklet

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.

Page 17: MCC Workshop Booklet

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;

Page 18: MCC Workshop Booklet

4

import java.io.*; import java.net.*; /** * This simple program uses the URL class and its o penStream() 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 o utput 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 u sage 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.

Page 19: MCC Workshop Booklet

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)

Page 20: MCC Workshop Booklet

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 abo ut the URL */ public static void printinfo(URL url) throws IO Exception { URLConnection c = url.openConnection(); // Get URLConnection from URL c.connect(); // Open a connection to URL // Display some information about the URL c ontents System.out.println(" Content Type: " + c.g etContentType()); 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.getLastModifie d())); System.out.println(" Expiration: " + new D ate(c.getExpiration())); // If it is an HTTP connection, display som e additional information. if (c instanceof HttpURLConnection) { HttpURLConnection h = (HttpURLConnectio n) c; System.out.println(" Request Method: " + h.getRequestMethod()); System.out.println(" Response Message: " +h.getResponseMessage()); System.out.println(" Response Code: " + h.getResponseCode());

Page 21: MCC Workshop Booklet

7

} } /** Create a URL, call printinfo() to display i nformation 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 GetURLI nfo <url>"); } } }

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

Page 22: MCC Workshop Booklet

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(); } }

Page 23: MCC Workshop Booklet

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 Excep tion { 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.getProtoc ol()); 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.getAutho rity()); System.out.println("Content Type= "+uc.getConten tType()); System.out.println("Length= "+uc.getContentLengt h()); System.out.println("Expiration Date= "+uc.getExp iration()); System.out.println("Encoding Type= "+uc.getConte ntEncoding()); System.out.println("Last Modified Date= "+uc.get LastModified()); System.out.println("Date= "+d.toString()); System.out.println("Request Method= "+huc.getReq uestMethod()); System.out.println("Response Message= "+huc.getR esponseMessage()); System.out.println("Response Code= "+huc.getResp onseCode()); } }

Page 24: MCC Workshop Booklet

10

1.6 InetAddressTest.java // Demonstrate InetAddress import java.net.*; class InetAddressTest { public static void main(String args[]) throws Unk nownHostException { InetAddress Address = InetAddress.getLocalHost( ); System.out.println(Address); Address = InetAddress.getByName("osborne.com"); System.out.println(Address); InetAddress SW[] = InetAddress.getAllByName("ww w.nba.com"); for (int i=0; i<SW.length; i++) System.out.println(SW[i]); } }

Page 25: MCC Workshop Booklet

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 fil e) throws MalformedURLException Identical to the previous constructor, except that the default port for the given protocol is used.

Page 26: MCC Workshop Booklet

12

3 public URL(String url) throws MalformedURLException Creates a URL from the given String

4 public URL(URL context, String url) throws Malforme dURLException 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.

Page 27: MCC Workshop Booklet

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.

Page 28: MCC Workshop Booklet

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.toStrin g()); System.out.println("protocol is " + url.getProtoc ol()); System.out.println("authority is " + url.getAuthor ity()); System.out.println("file name is " + url.g etFile()); System.out.println("host is " + url.getHos t()); System.out.println("path is " + url.getPat h()); System.out.println("port is " + url.getPor t()); System.out.println("default port is " + url.getDefault Port()); System.out.println("query is " + url.getQu ery()); System.out.println("ref is " + url.getRef( )); }catch(IOException e) { e.printStackTrace(); } } }

A sample run of the third program would produce following result:

Page 29: MCC Workshop Booklet

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()

Page 30: MCC Workshop Booklet

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.

Page 31: MCC Workshop Booklet

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.openConn ection(); HttpURLConnection connection = null; if(urlConnection instanceof HttpURLConnect ion) { connection = (HttpURLConnection) urlCon nection; } else { System.out.println("Please enter an HTT P URL."); return; } BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputS tream()));

Page 32: MCC Workshop Booklet

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:

Page 33: MCC Workshop Booklet

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 E xception { 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)

Page 34: MCC Workshop Booklet

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 Exce ption { int c;

Page 35: MCC Workshop Booklet

21

URL hp = new URL("http://www.java-samples.com/tes tpapers/index.php/"); URLConnection hpCon = hp.openConnection(); System.out.println("Date: " + new Date(hpCon.getD ate())); System.out.println("Content-Type: " + hpCon.getContentType()); System.out.println("Expires: " + hpCon.getExpirat ion()); 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

Page 36: MCC Workshop Booklet

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.ope nConnection(); 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 {

Page 37: MCC Workshop Booklet

23

public static void main(String args[]) { // The url may not well formed, So MalformedURLEx ception 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.getCont entType()); // Get date (long) long d=con.getDate(); // Create date object for above value Date date=new Date(d); // Create SimpleDateFormat for above Date objec t 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 ur l"); } } catch(MalformedURLException e){ System.out.println("The given url is not well fo rmed."); } } }

Page 38: MCC Workshop Booklet

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.

Page 39: MCC Workshop Booklet

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 ) {

Page 40: MCC Workshop Booklet

26

try { String data1 = URLEncoder.encode("first ", "UTF-8") + "=" + URLEncoder.encode("Girish ", "UT F-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/test 1/test2.php"); URLConnection uc1 = u1.openConnection() ; uc1.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(u c1.getOutputStream()); out.write(data); out.flush(); BufferedReader in = new BufferedReader( new InputStreamReader( uc1.getInputStream() ) ) ; // The readLine() method reads the outp ut 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

Page 41: MCC Workshop Booklet

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 S ervlet processing"; public void doPost(HttpServletRequest req, Http ServletResponse resp) { try { int len = req.getContentLength(); byte[] input = new byte[len]; ServletInputStream sin = req.getInputSt ream(); int c, count = 0 ; while ((c = sin.read(input, count, inpu t.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-urlenco ded string String decodedString = URLDecoder.decod e(value, "UTF-8"); //reverse the String String reverseStr = (new StringBuffer(d ecodedString)).reverse().toString(); // set the response code and write the response data resp.setStatus(HttpServletResponse.SC_O K); OutputStreamWriter writer = new OutputS treamWriter(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) { } } } }

Page 42: MCC Workshop Booklet

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 E xception { if (args.length != 2) { System.err.println("Usage: java Revers e " + "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.openConnecti on(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWr iter( connection .getOutputStream()); out.write("string=" + stringToReverse); out.close(); BufferedReader in = new BufferedReader(

Page 43: MCC Workshop Booklet

29

new InputStream Reader( connection.getI nputStream())); String decodedString; while ((decodedString = in.readLine()) != n ull) { System.out.println(decodedString); } in.close(); } }

Perform following steps:

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

Page 44: MCC Workshop Booklet

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

Page 45: MCC Workshop Booklet

31

UDPServer.java //Server Side: import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Ex ception { DatagramSocket serverSocket = new Datagram Socket(9876); //Server Socekt Created byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = ne w DatagramPacket(receiveData, receiveData.length ); serverSocket.receive(receivePacke t); String sentence = new String( rec eivePacket.getData()); System.out.println("RECEIVED: " + sentence); InetAddress IPAddress = receivePa cket.getAddress(); int port = receivePacket.getPort( ); String capitalizedSentence = sent ence.toUpperCase(); //Change sentence to Capital lett er sendData = capitalizedSentence.ge tBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, send Data.length, IPAddress, port); serverSocket.send(sendPacket); //Send Capitalized data back to c lient } } }

UDPClient.java //Client Side: import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Ex ception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(S ystem.in)); DatagramSocket clientSocket = new DatagramSoc ket(); //Client Socket is created InetAddress IPAddress = InetAddress.getByName ("localhost");

Page 46: MCC Workshop Booklet

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 DatagramPacke t(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPa cket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receiveP acket.getData()); System.out.println("FROM SERVER:" + modifiedS entence); 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.

Page 47: MCC Workshop Booklet

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);

Page 48: MCC Workshop Booklet

34

System.out.println("Message from Client: " +s.t rim()); } } 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,I netAddress.getLocalHost(),1600); ds1.send(dp1); } } catch(Exception e) {

Page 49: MCC Workshop Booklet

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(); } }

Page 50: MCC Workshop Booklet

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.t rim()); } } 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,I netAddress.getLocalHost(),1400); ds2.send(dp1); } }

Page 51: MCC Workshop Booklet

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.t rim()); } } catch(Exception e) { e.printStackTrace(); } } }; }; }

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

Page 52: MCC Workshop Booklet

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,I netAddress.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 {

Page 53: MCC Workshop Booklet

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.t rim()); } } catch(Exception e) { e.printStackTrace(); } } }; }

Output:

Page 54: MCC Workshop Booklet

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:

Page 55: MCC Workshop Booklet

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

Page 56: MCC Workshop Booklet

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

Page 57: MCC Workshop Booklet

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.getRemoteS ocketAddress()); DataInputStream in = new DataInputStream(server .getInputStream()); System.out.println(in.readUTF()); DataOutputStream out = new DataOutputStream(ser ver.getOutputStream()); out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye! "); server.close(); }catch(SocketTimeoutException s) {

Page 58: MCC Workshop Booklet

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.getRemoteSock etAddress()); OutputStream outToServer = client.getOutputStrea m(); DataOutputStream out = new DataOutputStream(outT oServer); out.writeUTF("Hello from " + client.getLocalSock etAddress()); InputStream inFromServer = client.getInputStream (); DataInputStream in = new DataInputStream(inFromS erver); System.out.println("Server says " + in.readUTF() ); client.close(); }catch(IOException e) { e.printStackTrace(); } } }

Output:

Page 59: MCC Workshop Booklet

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 InputStreamRead er(s1.getInputStream()); br=new BufferedReader(i); start(); System.out.println("Server"); ServerInner ci = new ServerInner(); } catch(Exception e) { e.printStackTrace(); } }

Page 60: MCC Workshop Booklet

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(Sy stem.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(); } } } }

Page 61: MCC Workshop Booklet

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(Sys tem.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 InputStre amReader(s.getInputStream());

Page 62: MCC Workshop Booklet

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:

Page 63: MCC Workshop Booklet

49

Page 64: MCC Workshop Booklet

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 client’s 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 E xception { ServerSocket soc=new ServerSocket(8400); while(true) try { Socket client=soc.accept(); BufferedReader br=new BufferedReader(ne w InputStreamReader(client .getInputStream())); PrintWriter out = new PrintWriter(clien t.getOutputStream()); String l = null; String t1 = br.readLine();

Page 65: MCC Workshop Booklet

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.indexO f("?")); } catch(Exception e) { filename = t2.substring(0,t2.indexO f(" ")); } BufferedReader br2 = new BufferedReader(new File Reader(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.

Page 66: MCC Workshop Booklet

52

Page 67: MCC Workshop Booklet

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 ([email protected] 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 Messa gingException { String sender_email = "[email protected]", sender_password = "aaaaaaaa", sender_host = "smtp.gmail.com", sender_port = "465", reciever_id = "[email protected]",

Page 68: MCC Workshop Booklet

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.SSLSocke tFactory"); props.put("mail.smtp.socketFactory.fallb","false "); SecurityManager security = System.getSecurityMan ager(); try { Authenticator auth = new SMTPAuthenticator(); Session session = Session.getInstance(props, au th); //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.Authenti cator { String sender_email = "[email protected]", sender_password = "aaaaaaaaaaa", sender_host = "smtp.gmail.com", sender_port = "465", reciever_id = "[email protected]", subject_to_be_given = "Greeting...", message_mi = "Hello Athu!"; public PasswordAuthentication getPasswordAuthentic ation() { return new PasswordAuthentication(sender_email, sender_password); } }

Page 69: MCC Workshop Booklet

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(prop s, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthenticatio n() { return new PasswordAuthentication("gir [email protected]","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 al l the best!"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }

Page 70: MCC Workshop Booklet

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 = "[email protected]"; 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 getPasswordAuth entication() { return new PasswordAuthentication(username, pas sword); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("girish.tere @gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected] om")); message.setSubject("Testing Subject"); message.setText("Dear Athu, congratulations!\n K eep up the good work!");

Page 71: MCC Workshop Booklet

57

Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }

Page 72: MCC Workshop Booklet

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 UnicastRemoteOb ject 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 a s argument String s; s="Hello, "+a; return s; } public static void main(String[] arguments) { try

Page 73: MCC Workshop Booklet

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 re mote 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 m achine and call1 is the name with which the Server O bject 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)

Page 74: MCC Workshop Booklet

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:

Page 75: MCC Workshop Booklet

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 UnicastRemoteObj ect 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);

Page 76: MCC Workshop Booklet

62

/* The name call1 is a bind name given to the re mote 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:

Page 77: MCC Workshop Booklet

63

All the best!

Page 78: MCC Workshop Booklet

TYBSC

Computer Science

USCS502 & USCS602

Paper 2

Advanced Java

Page 79: MCC Workshop Booklet

17‐Jul‐2013

1

SCS 02USCS502Advanced JAVA - I

Unit IIntroduction to JFC and SwinggFeatures of the Java Foundation ClassesSwing API ComponentsJComponent ClassWindows, Dialog Boxes, and Panels:, g ,(Container, JDialog, JFrame, JWindow,

JDesktopPane, JInternalFrame, JOptionPane, JPanel)

Page 80: MCC Workshop Booklet

17‐Jul‐2013

2

Unit ILabels, Buttons, Check Boxes:

(JLabel, JButton, JToggleButton, JCheckBox, JRadioButton, ButtonGroup)

Pane, JScrollPane, DesktopPane(RootPane, GlassPane, LayeredPane, JTabbedPane JSplitPane) JScrollPaneJTabbedPane, JSplitPane), JScrollPane

Scrollbars(JScrollBar)

Unit ILists and Combo Boxes(JList, JComboBox)

Text-Entry Components(JTextField, JPasswordField, JTextArea,

JEditorPane, JTextPane)

References:1. JAVA Tutorial (Preferable)2. JPAT

Page 81: MCC Workshop Booklet

17‐Jul‐2013

3

U nit IIMenus, Toolbars, Implementing Action p ginterface(JMenuBar, JMenuItem, JMenu,

JPopupMenu, JCheckboxMeuItem, JRadioButtonMenuItem, JToolBar, AbstractAction

Colors and File Choosers(JColorChooser, JFileChooser)

Tables and Trees(JTable, JTree)

Unit IIPrinting with 2D API and Java Print gService API.

References1. JAVA Tutorial (Preferable)2. JPAT

Page 82: MCC Workshop Booklet

17‐Jul‐2013

4

Unit IIThreads and Multithreading - The gLifecycle 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 IISchedules Tasks using JVMg(using thread priority)

Thread-safe code, Synchronizing threads,Communication between threads.

References:1. JPAT

Page 83: MCC Workshop Booklet

17‐Jul‐2013

5

Unit IIIJDBC IntroductionJDBC Architecture

References:1. JAVA Tutorial

JDBC DriversReferences1. JPAT/Core JAVA-Volume II

Unit IIIThe Connectivity ModelyThe java.sql packageNavigating the ResultSet object’s contents, Manipulating records of a ResultSet object through User Interface The JDBC Exception classesDatabase Connectivity

Page 84: MCC Workshop Booklet

17‐Jul‐2013

6

Unit IData Manipulation (using Prepared p ( g pStatements, Joins, Transactions, Stored Procedures)Data navigation

References1. JAVA Tutorial (Preferable)2. Ivan Bayross, Web Enabled Commercial

Applications Development Using Java 2, BPB Publications, Revised Edition, 2006

Unit IVWorking with URLg(What is URL, Creating URL, Parsing URL,

Reading from URL using openStream())Reference: JAVA Tutorial/J2CR

Connecting to a Server, Implementing Servers Serving multiple ClientsServers, Serving multiple Clients, Sending E-Mail, Socket ProgrammingReference: Core JAVA Volume - II

Page 85: MCC Workshop Booklet

17‐Jul‐2013

7

Unit IVInet AddressesReference: J2CRURL Connections, Posting Form Data, Accessing Network interface parameters, Cookies, Overview of Understanding the S k Di P lSockets Direct Protocol.

Reference :1. JAVA Tutorial

Unit IVIntroduction to distributed object systemDistributed Object TechnologiesRMI for distributed computingRMI ArchitectureRMI Registry ServiceCreating RMI applicationCreating RMI applicationSteps involved in running the RMI application

Reference:1 . Ivan Bayross

Page 86: MCC Workshop Booklet

17‐Jul‐2013

8

Unit IVParameter Passing in Remote MethodsgUsing RMI with Applets

Reference:1. JAVA Tutorial

SCS602USCS602Advanced JAVA-II

Page 87: MCC Workshop Booklet

17‐Jul‐2013

9

Unit IWhat Is a Servlet? The Example Servlets,pServlet Life Cycle, Sharing Information, Initializing a Servlet, Writing Service Methods,Filtering Requests and Responses,Invoking Other Web Resources,Accessing the Web Context,

Unit IMaintaining Client State,gFinalizing a Servlet.

Reference:The Java EE 6Tutorial (Preferable)( )Head First Servlets and JSP

Page 88: MCC Workshop Booklet

17‐Jul‐2013

10

Unit IIWhat Is a JSP Page?, The Example JSP g pPages,The Life Cycle of a JSP Page,Creating Static Content, Creating Dynamic Content, Unified Expression Language

Reference:The Java EE 6Tutorial (Preferable)Head First Servlets and JSP

Unit IIJavaBeans Components, JavaBeans pConcepts,Using NetBeans GUI BuilderWriting a Simple Bean, Properties: Simple Properties

Reference:1 . JAVA Tutorial

Page 89: MCC Workshop Booklet

17‐Jul‐2013

11

Unit IIUsing Custom tags, Reusing content in JSP g g gPagesTransferring Control to Another Web Component, Including an Applet.

Reference:The Java EE 6Tutorial (Preferable)Head First Servlets and JSP

Unit - IIIIntroduction to EJB, Benefits of EJB, Types ypof EJB,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,

Page 90: MCC Workshop Booklet

17‐Jul‐2013

12

Unit IIIThe Life Cycle of a Stateful Session Bean,yThe Life Cycle of a Stateless Session Bean,The Life Cycle of a Message-Driven Bean

Reference:1. The Java EE 6 Tutorial

Unit - IVDefining Client Access with Interfaces: gRemote Access, Local Access,Local Interfaces and Container-Managed Relationships, Deciding on Remote or Local Access,W b S i Cli M h d PWeb Service Clients, Method Parameters and Access.

Page 91: MCC Workshop Booklet

17‐Jul‐2013

13

Unit IVBuilding Web Services with JAX-WS: gSetting the Port, Creating a Simple Web Service and Client with JAX-WS.

Reference:1. JAVA EE 6 Tutorial

Page 92: MCC Workshop Booklet

17-Jul-2013

1

USCSP05 + USCSP07

Paper 2 – Sample Practical List

Advance Java Practicals

SEM V - Topic List

1. Using Basic Swing Controls2 Using JScrollPane JTabbedPane JDesktopPane2. Using JScrollPane, JTabbedPane, JDesktopPane3. Using Common Dialog Boxes4. Using JTable and JTree5. Creating Table in database6. Inserting data in tables & Displaying data7. Using ResultSetMetaData8 U i P d S8. Using Prepared Statements

Page 93: MCC Workshop Booklet

17-Jul-2013

2

1. Using Basic Swing ControlsWrite 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 Icecreamflavours 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.

Page 94: MCC Workshop Booklet

17-Jul-2013

3

2. Using JScrollPane, JTabbedPane, JDesktopPane

Create an application, which is a subclass of the JFrame class whichwill have a text box button image and a scroll pane The user willwill have a text box, button, image and a scroll pane. The user willinput the image path in the text field. On click of the button the imageshould 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 JTextAreaDialog 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.

Page 95: MCC Workshop Booklet

17-Jul-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 emptable will have EmpNo EmpName Salary and Locationtable will have EmpNo, EmpName, Salary and Location.

Write a JDBC program that will create a Student table. The emptable will have StudentRollNo, StudentName, MarksSSC and MarksHSC.

Page 96: MCC Workshop Booklet

17-Jul-2013

5

6. Inserting data in tables & Displaying data

Write a JDBC program that will insert 5 records in the Emptable and display all the recordstable 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.

Page 97: MCC Workshop Booklet

17-Jul-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, DeptNameand Location.

SEM VI - Topic List

1. Simple Server-Side Programming using Servlets

2 Ad S Sid P i i S l2. 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

Page 98: MCC Workshop Booklet

17-Jul-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 field’s 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.

Page 99: MCC Workshop Booklet

17-Jul-2013

8

3. Simple Server-side programming using JSP

Write JSP files that accept a number from the HTML form andDi l h th it’ dd Displays whether it s even or odd It’s 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 , Jpage 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.

Page 100: MCC Workshop Booklet

17-Jul-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 gparameter, getPrice & getFeatures don’t 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.

Page 101: MCC Workshop Booklet

17-Jul-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- 1st

function getCutoff accepts coursename as parameter and returns last year’s cutoff for that course as floating point number, 2nd

function – getFees accepts coursename as parameter and returns this year’s 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 – 1st

function called getBreakingNews which accepts date as string parameter and returns special news of that day, 2nd function accepts sunsign name as string parameter and returns predictions as string. Design a client to test the above web service.

Page 102: MCC Workshop Booklet

TYBSC

Computer Science

USCS503 & USCS603

Paper 3

Operating Systems &

Linux

Page 103: MCC Workshop Booklet

17-Jul-2013

1

TYBSc Comp Sci Syllabus Workshop@MCC College17th July 2013

Operating Systems(Sem V) and

Linux OS(Sem VI)

Operating System – Sem V

Page 104: MCC Workshop Booklet

17-Jul-2013

2

Operating Systems TheoryOperating System Principles – VII Edition  ‐

Silberschatz, Galvin and Gagne(Wiley India Edition)

• Chapter 1  ‐ Introduction to OS P 3 35Page 3 – 35

• Chapter 2 : System StructuresPage 39‐65

• Chapter 3 : Process ConceptPage 79 – 99

• Chapter 4 : Multithreaded Programming  Page 123 – 127

• Chapter 5 : Process Scheduling Page 149 – 165,Page 177‐178

Operating Systems TheoryOperating System Principles – VII Edition  ‐

Silberschatz, Galvin and Gagne(Wiley India Edition)

• Chapter 6 : Synchronization  p yPage187‐213

• Chapter 7 : Deadlocks Page 237‐259

• Chapter 8 : Memory Mgmt StrategiesChapter 8 : Memory Mgmt Strategies Page 265‐ 295

• Chapter 9: Virtual Memory mgmtPage 303 – 333

Page 105: MCC Workshop Booklet

17-Jul-2013

3

Operating Systems TheoryOperating System Principles – VII Edition  ‐

Silberschatz, Galvin and Gagne(Wiley India Edition)

• Chapter 10 : File System Page 359 – 376

• Chapter 13: I/O Systems Page 477‐489

• Chapter 12 : Secondary Storage Structure p y gPage 435‐443

• Chapter 18 – OS Security Page 623‐639

OS Practical

Page 106: MCC Workshop Booklet

17-Jul-2013

4

General Instructions

• Should be done in Java

• Should be done using threads as necessary

• Can change the order of OS theory topics to complement OS Practical

For example ‐ 1,2,3,6,7,8,4,5For example  1,2,3,6,7,8,4,5

• Can teach Java threads in OS Practical

• Avoid lengthy practical in exam

1. Demonstrate round‐robin scheduling using threads• Create a thread

• Job can be to count numbers from 1 to n where n represents number of instr

• Accept n, time quantum, process id from user

• Actual Round‐Robin algorithm processes the jobs in FCFS manner But when you are usingjobs in FCFS manner.  But when you are using Java threads, they may not be in FCFS manner since you cannot control order of execution of threads.  

Page 107: MCC Workshop Booklet

17-Jul-2013

5

1. Demonstrate priority scheduling using threads• Create a thread

• Job can be to count numbers from 1 to n where n represents number of instr

• Accept n, time quantum, process id, priority from user

• High priority job gets over first provided low• High priority job gets over first provided low‐priority jobs are not too small and if they start first

OutputEnter a user process starting number:500Enter a time quantum(in millis):100

Executing instr no 5 of process 503

Executing instr no 5 of process 501100Executing instr no 1 of process 502Executing instr no 1 of process 501Executing instr no 1 of process 503Executing instr no 2 of process 502Executing instr no 2 of process 503Executing instr no 2 of process 501Executing instr no 3 of process 501

Executing instr no 6 of process 501

Executing instr no 6 of process 503

Executing instr no 6 of process 502

Executing instr no 7 of process 503

Executing instr no 7 of process 502

Executing instr no 7 of process 501

Executing instr no 8 of process 501xecuting instr no 3 of process 50Executing instr no 3 of process 503Executing instr no 3 of process 502Executing instr no 4 of process 503Executing instr no 4 of process 502Executing instr no 4 of process 501Executing instr no 5 of process 502

Executing instr no 8 of process 501

Executing instr no 8 of process 503

Executing instr no 8 of process 502

Job 503 is over

Job 502 is over

Job 501 is over

Page 108: MCC Workshop Booklet

17-Jul-2013

6

2. For any scheduling algorithm, calculate turn‐around time• Use any 1 of the previous program

• Record time when the job starts

• Record time when the job ends

• Difference in Turn‐around time

• Add all turn‐around times & calculate avg

Output

Enter a user process starting number:500500Enter a time quantum(in millis):100Job 503 with 9 instructions has completed in 922 milliseconds

Job 502 with 15 instructions has completed in 1531 Job 50 with 5 instructions has completed in 53milliseconds

Job 501 with 25 instructions has completed in 2547 milliseconds

Average turn around time = 1666.6666

Page 109: MCC Workshop Booklet

17-Jul-2013

7

3. Demonstrate the concept of synchronized access to shared resource

• Shared resource can represent object of thi fil i tanything – file, room, printer

• Include 1 or more functions to use resource

• Create 2 or more user jobs to access this resource & call functions at the same time

• Test the above program with/without• Test the above program with/without synchronized keyword

Output(without synchronized)

Kamlakar Sir enters...P ji h M d tPrajisha Madam enters...Madhavi Madam enters...Kamlakar Sir starts lecture...Prajisha Madam starts lecture...Madhavi Madam starts lectureMadhavi Madam starts lecture...Kamlakar Sir exits...Prajisha Madam exits...Madhavi Madam exits...

Page 110: MCC Workshop Booklet

17-Jul-2013

8

Output(with synchronized)

Kamlakar Sir enters...K l k Si t t l tKamlakar Sir starts lecture...Kamlakar Sir exits...Prajisha Madam enters...Prajisha Madam starts lecture...Prajisha Madam exitsPrajisha Madam exits...Madhavi Madam enters...Madhavi Madam starts lecture...Madhavi Madam exits...

4. Demonstrate the use of inter‐process communication• Producer‐Consumer problem 

o From “Java Complete Reference”

o Dining‐ Philosopher problem

• May not get over in 1.5 hours

Page 111: MCC Workshop Booklet

17-Jul-2013

9

5. Demonstrate any 1 of deadlock‐avoidance algorithm

• Using Banker’s algorithm as given in text book

I l d f l i h• Includes safety algorithm

• Resource‐request algorithm

OutputApplying safety algorithm...Process  0 can be completed

b l dProcess  1 can be completedProcess  2 can be completedProcess  3 can be completedProcess  4 can be completedThe system is in safe state...

l i lApplying resource request algo...Process 2 has exceeded request for resource 3 hence is unsafe

the system is unsafe...

Page 112: MCC Workshop Booklet

17-Jul-2013

10

6. Demonstrate memory management using first/best/worst fit using arrays

• Create a big array representing Memory(RAM)

• Create job where each job with array representing size of job

• For showing execution of jobs, copy the job arrays to big array.

• Apply first fit/worst fit/best fit technique• Apply first fit/worst fit/best fit technique

• Add the jobs in vector in increasing/ decreasing order of size

OutputInitial memory layout...|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|Enter policy:1:First Fit2:Best Fit3:Worst Fit2Applying Best Fit Policy...copying 2 instructions at location 0|201|202|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|copying 6 instructions at location 2|201|202|901|902|903|904|905|906|0|0|0|0|0|0|0|0|0|0|0|0|copying 9 instructions at location 8|201|202|901|902|903|904|905|906|501|502|503|504|505|506|507|

508|509|0|0|0|

Page 113: MCC Workshop Booklet

17-Jul-2013

11

7. Demonstrate page replacement algorithm• Create a array of some block size as specified bby user

• Accept frame sequence from user

• Apply various techniques on the frame sequence and show the output

• Calculate number of page faults• Calculate number of page faults

OutputOptimal Page 

Replacement

Initial Memory layout...

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|

Loading page no.1:7

|7|‐1|‐1|

Loading page no.2:0

|7|0|‐1|

Loading page no.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|Loading page no.11:0

|2|0|3|

|2|0|1|Loading page no.17:1

|2|0|1|

Loading page no.18:7

|7|0|1|

Loading page no.19:0

|7|0|1||7|0|1|

Loading page no.4:2

|2|0|1|

Loading page no.5:0

|2|0|1|

Loading page no.12:3

|2|0|3|

Loading page no.13:2

|2|0|3|

Loading page no.14:1

|2|0|1|

|7|0|1|

Loading page no.20:1

|7|0|1|

Total Number of page faults:9

Page 114: MCC Workshop Booklet

17-Jul-2013

12

8. Demonstrate page replacement algorithm• Enter disk frame sequence

• Starting track number

• Additionally you can take algo. Specification

• Show starting track, new track positions & total cylinders traversed 

Output=======   SHORTEST SEEK‐TIME FIRST   ===========Traversing from:53to track : 65to track : 65to track : 67to track : 37to track : 14to track : 98to track : 122to track : 122to track : 124to track : 183Total cylinders traversed = 236

Page 115: MCC Workshop Booklet

17-Jul-2013

13

Linux

Linux Theory  ‐‐ #Unit 1

› Linux System: History, Design Principles,K l M d l P M tKernel Modules, Process Management,Scheduling, Memory Management, Filesystem, I/O (SGG: 20.1 to 20.8)

› Linux Basics: Looking into the Linux Kernel,GNU Utilities, Desktop environments. (RB:, p (Chapter‐1) , The Linux console (RB: Chapter‐2)The Unix/Linux architecture, Features ofUnix/Linux. . (SD: 2.1, 2.2)

Page 116: MCC Workshop Booklet

17-Jul-2013

14

#Unit 1

› Basic bash shell commands: Starting the shell, Sh ll t Fil t N i ti Fil dShell prompt, Filesystem Navigation, File and directory listing, File handling, Directory handling, Viewing file contents. (RB: Chapter‐3)  Directory structure, different types of shells, commands like ls, md, cd, rd, cat, cp, mv, rm etc

#Unit 1

› More bash shell commands:Monitoring programs Monitoring disk space Working withprograms, Monitoring disk space, Working with data files: Sorting, Searching, Compressing, Archiving.  (RB: Chapter‐4)  From the following commands  that are covered in chapter 4 like jobs, ps, du, sort, find, zip, unzip, zcat, tar etc  

› Filter Commands : more, head, tail, comm,diff, cmp, sort, tee, grep, egrep, fgrep, cut, tr,wc, split, paste…. (SD IV Edition: 229‐242)

Page 117: MCC Workshop Booklet

17-Jul-2013

15

#Unit 1› The Linux environment variable: Environment variables, setting environment variables, Removing environment variables, Default shell environment variables, setting the PATH environment variables, Locating system environment variables, Variable arrays, Using command aliases (RB: Chapter‐5) (SD 194 ‐command aliases. (RB: Chapter 5) (SD 194 201)

like PATH, HOME, PS1 etc, Commands like set, env, export, files like .profile, .bash_profile , .bash_login,  .bashrc,.bash_logout

# Unit 2

› Understanding Linux file permission: Linux it U i Li D di filsecurity, Using Linux groups, Decoding file 

permissions, Changing security settings, Sharing files. (RB: Chapter‐6) (SD 110‐117)

[Users & Groups,  chmod command, setting permissions using rwx &binary mask, user p g y ,representation such as uaga, user‐id and group‐id permission, creating links(soft/hard)]

Page 118: MCC Workshop Booklet

17-Jul-2013

16

#Unit 2

› Basic script building: Using multiple d C ti i t fil Di l icommands, Creating a script file, Displaying 

messages, Using variables, Redirecting Input and Output, Pipes, Performing math, Exiting the script. . (RB: Chapter‐8) 

[Using echo, declaring variables, using >, >>, < [ g , g , g , ,, |, expr and let statements, sh command etc]

#Unit 2

› Using structured commands: Working with th if th if th l d ti ifthe if‐then, if‐then‐else and nesting if statements, test command, Compound condition testing, advanced if then features, the case command. (RB: Chapter‐9)

Page 119: MCC Workshop Booklet

17-Jul-2013

17

# Unit 2

› More structured commands: for command, C‐t l f d hil d tilstyle for command, while command, until command, nesting loops, Looping on file data, controlling the loop, processing the o/p of a loop. (RB: Chapter‐10) 

#Unit 2

› Handling user input: Command line t S i l t i bl hiftparameters, Special parameter variables, shift 

command, working with options, Standardizing options, Getting user I/P.  (RB: Chapter‐11)  [Using $@, $*, $#, Using shift to change position of command line arguments etc]

Page 120: MCC Workshop Booklet

17-Jul-2013

18

#Unit 3

› Presenting data: Understanding I/O, R di ti O/ i i t R di ti I/ iRedirecting O/p in scripts, Redirecting I/p in scripts, Creating your own redirection, Listing open file descriptors, Suppressing command o/p, Using temporary files, Logging Messages.   (RB: Chapter‐12)  [Using ls  command, /dev/null, using /var/log/message file]

#Unit 3

• Script control: Handling signals, Running scripts in background mode Running scripts without ain background mode, Running scripts without a console, Job control, Job Scheduling Commands: nice, renice, at, batch, cron table, Running the script at boot. (RB: Chapter‐13) [commands like –fg, bg, jobs, crontab, at ] (SD : chapter 9)

• Editors : sed and awk (RB: Chapter‐16) (SD : 255‐265,382‐390)

Page 121: MCC Workshop Booklet

17-Jul-2013

19

#Unit 3

› TCP/IP networking: TCP/IP Basics, TCP/IP M d l R l i IP dd A li tiModel, Resolving IP addresses, Applications, telnet, ftp, Berkeley commands. (SD: Chapter‐17)  [commands like ifconfig, ping, traceroute, host, nslookup, netstat, wall, talk, etc]

# Unit 4

› Linux Firewall: Introduction to firewall, Di l i t t f fi ll T iDisplaying status of firewall, Turning an iptables Firewall on/off, Testing firewall, Configuring the firewall for Remote SSH Administration.(CS: 3.0, 3.7‐3.11) 

Page 122: MCC Workshop Booklet

17-Jul-2013

20

#Unit 4

› Essential System Administration: root: The t d i i t t ’ l i Thsystem administrator’s login, The 

administrator’s privileges, Startup & Shutdown. (SD: 15.1, 15.2, 15.5) 

Such as mounting devices, managing users/ groups, installing softwares, su commandg p , g ,

#Unit 4

› Advanced System Administration: Partitions & fil t / t /f t b f k S t t t& file systems, /etc/fstab, fsck, System startup and init, Shutdown & sync operation.  (SD: 25.2, 25.6.3, 25.7, 25.8, 25.9) 

[commands like fdisk, mount etc]

Page 123: MCC Workshop Booklet

17-Jul-2013

21

Linux Practical

• Basic Linux Commands such as file and directory manipulation, redirection and piping

• Basic Filter commands such asBasic Filter commands such as head,tail,more,cat,sort,cut,grep(with options –e,‐f),paste…

• Advanced Filter such as egrep, fgrep, tr,sed,awk

• File Operation Commands such as split tar find zip ln touch chmodsplit,tar,find,zip,ln,touch,chmod

• Basic Shell scripting such as – defining variables,reading user input, conditions,loops,string operations,arithmatic operartions

Linux Practical

• Advanced Shell Scripting such as –environment variables,shell features command line arguments file testfeatures,command line arguments, file test, backticks

• Process Management – ps, jobs, nice , fg, bg, at,sleep(for user management shell scripts)

• Linux System Administration – User yManagement, Mounting,Job control(crontab), chown, chgrp

Page 124: MCC Workshop Booklet

17-Jul-2013

22

•Thank you….•Any ?????

Page 125: MCC Workshop Booklet

OS PRACTICALS  

1. Demonstrate round‐robin / priority scheduling using threads.  Round‐Robin  import java.io.*;  class job implements Runnable {     int process_id, no_of_instr,time_quantum;     Thread t;     job(int pid, int instr, int tq)     {         process_id = pid;         no_of_instr = instr;         time_quantum = tq;         t = new Thread(this);         t.start();     }     public void run()     {         try         {             for(int i=1; i<=no_of_instr; i++)             {                 System.out.println("Executing instr no " + i + " of process " + process_id);                 Thread.sleep(time_quantum);             }             System.out.println("Job " + process_id + " is over");         }         catch(InterruptedException e)         {             System.out.println("The job has been interrupted...");         }     }                      } class os {         public static void main(String args[])      {         try         {             int process_id=100, time_quantum = 100;             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));             System.out.println("Enter a user process starting number:");             process_id = Integer.parseInt(br.readLine());             System.out.println("Enter a time quantum(in millis):");             time_quantum = Integer.parseInt(br.readLine()); 

Page 126: MCC Workshop Booklet

            job j1 = new job(++process_id, 10, time_quantum);             job j2 = new job(++process_id, 6, time_quantum);             job j3 = new job(++process_id, 8, time_quantum);         }         catch(Exception e)         {             System.out.println("Some process failed to complete...");             System.out.println("Plz contact system admin...");         }     } } Output Enter a user process starting number: 500 Enter a time quantum(in millis): 100 Executing instr no 1 of process 501 Executing instr no 1 of process 502 Executing instr no 1 of process 503 Executing instr no 2 of process 502 Executing instr no 2 of process 501 Executing instr no 2 of process 503 Executing instr no 3 of process 502 Executing instr no 3 of process 501 Executing instr no 3 of process 503 Executing instr no 4 of process 502 Executing instr no 4 of process 501 Executing instr no 4 of process 503 Executing instr no 5 of process 502 Executing instr no 5 of process 501 Executing instr no 5 of process 503 Executing instr no 6 of process 502 Executing instr no 6 of process 501 Executing instr no 6 of process 503 Job 502 is over Executing instr no 7 of process 501 Executing instr no 7 of process 503 Executing instr no 8 of process 501 Executing instr no 8 of process 503 Executing instr no 9 of process 501 Job 503 is over Executing instr no 10 of process 501 Job 501 is over  Priority   import java.io.*;  class job implements Runnable 

Page 127: MCC Workshop Booklet

{     int process_id, no_of_instr,priority_value, time_quantum;     Thread t;     job(int pid, int instr, int prio, int tq)     {         process_id = pid;         no_of_instr = instr;         time_quantum = tq;         priority_value = prio;         t = new Thread(this);         t.setPriority(priority_value);         t.start();      }     public void run()     {         try         {             for(int i=1; i<=no_of_instr; i++)             {                 System.out.println("Executing instr no " + i + " of process " + process_id);                 Thread.sleep(time_quantum);             }             System.out.println("Job " + process_id + " is over");         }         catch(InterruptedException e)         {             System.out.println("The job has been interrupted...");         }     }                      }  class os {         public static void main(String args[])      {         try         {             int process_id=100, time_quantum = 100;             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));             System.out.println("Enter a user process starting number:");             process_id = Integer.parseInt(br.readLine());             System.out.println("Enter a time quantum(in millis):");             time_quantum = Integer.parseInt(br.readLine());             job j1 = new job(++process_id, 8, 9, time_quantum);             job j2 = new job(++process_id, 8, 1, time_quantum);             job j3 = new job(++process_id, 8, 2, time_quantum);         }         catch(Exception e) 

Page 128: MCC Workshop Booklet

        {             System.out.println("Some process failed to complete...");             System.out.println("Plz contact system admin...");         }     } } Output  Enter a user process starting number: 500 Enter a time quantum(in millis): 100 Executing instr no 1 of process 502 Executing instr no 1 of process 501 Executing instr no 1 of process 503 Executing instr no 2 of process 502 Executing instr no 2 of process 503 Executing instr no 2 of process 501 Executing instr no 3 of process 501 Executing instr no 3 of process 503 Executing instr no 3 of process 502 Executing instr no 4 of process 503 Executing instr no 4 of process 502 Executing instr no 4 of process 501 Executing instr no 5 of process 502 Executing instr no 5 of process 503 Executing instr no 5 of process 501 Executing instr no 6 of process 501 Executing instr no 6 of process 503 Executing instr no 6 of process 502 Executing instr no 7 of process 503 Executing instr no 7 of process 502 Executing instr no 7 of process 501 Executing instr no 8 of process 501 Executing instr no 8 of process 503 Executing instr no 8 of process 502 Job 503 is over Job 502 is over Job 501 is over  2. For any scheduling algorithm, calculate turn‐around time.  import java.io.*; import java.util.*;  //class job represents os process //each job has some number of instructions //OS assigns process id and time quantum class job implements Runnable 

Page 129: MCC Workshop Booklet

{     int process_id, no_of_instr,time_quantum;     long millis;     Thread t;     job(int pid, int instr, int tq)     {         millis = System.currentTimeMillis();         process_id = pid;         no_of_instr = instr;         time_quantum = tq;         t = new Thread(this);                 t.start();     }     public void run()     {         try         {             for(int i=1; i<=no_of_instr; i++)             {                 //System.out.println("Executing instr no " + i + " of process " + 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 + " instructions has completed in " + millis + " milliseconds");         }         catch(InterruptedException e)         {             System.out.println("The job has been interrupted...");         }     }                      } class os {     static long millitime = 0;     static int process_id=100, time_quantum = 100;     public static void main(String args[])      {         try         {                        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));             System.out.println("Enter a user process starting number:");             process_id = Integer.parseInt(br.readLine());             System.out.println("Enter a time quantum(in millis):");             time_quantum = Integer.parseInt(br.readLine());             job j1 = new job(++process_id, 25, time_quantum);             job j2 = new job(++process_id, 15, time_quantum);             job j3 = new job(++process_id, 9, time_quantum); 

Page 130: MCC Workshop Booklet

            Thread mainthread = Thread.currentThread();             mainthread.sleep(3000);             System.out.println("Average turn around time = " + (millitime)/3.0f);         }         catch(Exception e)         {             System.out.println("Some process failed to complete...");             System.out.println("Plz contact system admin...");         }     } } Output Enter a user process starting number: 500 Enter a time quantum(in millis): 100 Job 503 with 9 instructions has completed in 922 milliseconds Job 502 with 15 instructions has completed in 1531 milliseconds Job 501 with 25 instructions has completed in 2547 milliseconds Average turn around time = 1666.6666   3. Demonstrate the concept of synchronized access to shared resource  class room {     public synchronized void takesLecture(String name) throws InterruptedException     {         System.out.println(name + " enters...");         Thread.sleep(250);         System.out.println(name + " starts lecture...");         Thread.sleep(500);         System.out.println(name + " exits...");         Thread.sleep(250);     } }  class lecturer implements Runnable {     String name;     room r;     Thread t;     lecturer(String n,room r)     {         name = n;          t = new Thread(this, n);         this.r = r;     }     public void start() 

Page 131: MCC Workshop Booklet

    {         t.start();     }     public void run()     {         try         {             r.takesLecture(name);         }         catch(InterruptedException e)         {             System.out.println(name + " operation interrupted...");         }     } }  class os {     public static void main(String args[])     {         room r = new room();         lecturer kamlakar = new lecturer("Kamlakar Sir",r);         lecturer madhavi = new lecturer("Madhavi Madam",r);         lecturer prajisha = new lecturer("Prajisha Madam",r);         kamlakar.start();         madhavi.start();         prajisha.start();     } } Output Kamlakar Sir enters... Kamlakar Sir starts lecture... Kamlakar Sir exits... Prajisha Madam enters... Prajisha Madam starts lecture... Prajisha Madam exits... Madhavi Madam enters... Madhavi Madam starts lecture... Madhavi Madam exits...  4. Demonstrate the use of inter‐process communication  Producer‐Consumer problem   From J2CR Dining Philosopher problem   to be solved   5. Demonstrate any 1 of deadlock‐avoidance algorithm  import java.io.*; 

Page 132: MCC Workshop Booklet

 class Banker {     int avail[];     int max[][] = { {3,2,2,1}, {8,12,0,0}, {2,1,0,0}, {4,3,0,0}, {2,0,3,1}};     int alloc[][] = { {1,1,1,0}, {2,1,0,0}, {1,0,0,0}, {2,1,0,0}, {1,0,0,0}};     int need[][];     int m,n;     Banker()     {         m = 4;         n = 5;         avail = new int[4];         avail[0] =  16; // Number of Registers         avail[1] =  50; // Number of Files         avail[2] =  5; // Number of Ports         avail[3] =  2; // Number of Printer           need = new int[5][4];          for(int i=0;i<5; i++)         for(int j=0;j<4; j++)         need[i][j] = max[i][j] ‐ alloc[i][j];             }     boolean isSafe()     {         int work[] = new int[m];         boolean finish[] = new boolean[n];         for(int i=0 ;i<m; i++)         work[i] = avail[i];          for(int i=0 ;i<n; i++)         finish[i] = false;          for(int i=0; i<n; i++)         {             if(finish[i]==false)             {                 boolean incomplete=false;                 for(int j=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])                     { 

Page 133: MCC Workshop Booklet

                        work[j] = work[j] ‐ need[i][j];                     }                 }                 if(!incomplete)                 {                     finish[i]=true;                                     }                 if(finish[i])                     System.out.println("Process  " + i + " can be completed");                 else                     System.out.println("Process  " + i + " can't be completed");             }         }         for(int i=0; i<n; i++)         {             if(!finish[i])             {                 return false;             }         }         return true;     }     void resourceRequest()     {         int request[][] = { {1,1,1,0}, {2,2,0,0}, {1,1,0,1}, {1,1,0,0}, {1,0,0,0}};         boolean safe=true;         for(int i=0; i<n; i++)         {             for(int j=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("Hey process " + i + "! resource " + j + " is not available now...try again later...");                         }                     }                     else                     {                         System.out.println("Process " + i + " has exceeded request for resource " + j + " hence is unsafe");                         safe = false; 

Page 134: MCC Workshop Booklet

                    }             }         }         if(safe)         {             System.out.println("the system is safe...");         }         else         {             System.out.println("the system is unsafe...");         }     } } class os {     public static void main(String args[]) throws Exception     {         Banker b = new Banker();         System.out.println("Applying safety algorithm...");         if(b.isSafe())         {             System.out.println("The system is in safe state...");         }         else         {             System.out.println("The system is not in safe state....");         }         System.out.println("Applying resource request algo...");         b.resourceRequest();     } } Ouput Applying safety algorithm... Process  0 can be completed Process  1 can be completed Process  2 can be completed Process  3 can be completed Process  4 can be completed The system is in safe state... Applying resource request algo... Process 2 has exceeded request for resource 3 hence is unsafe the system is unsafe...  6. Demonstrate memory management using first/best/worst fit  import java.util.*; import java.io.*;  class Job 

Page 135: MCC Workshop Booklet

{     int instr[];     int process_id, size;     Job(int pid, int n)     {         process_id = pid;         size = n;         instr = new int[size];         for(int i=0;i<size;i++)         {             instr[i] = process_id + i+1;         }     }     int getSize()     {         return size;     }     int [] getInstr()     {         return  instr;     }     int getProcessId()     {         return process_id;     } }   class MemMgmt {     int memory_array[];     Vector jobqueue;     MemMgmt(Vector v)     {         jobqueue = v;         memory_array = new int[20];         for(int i=0;i<20;i++)         {             memory_array[i] = 0;         }         System.out.println("Initial memory layout...");         printArray();     }     void addJob(Job newjob)     {         jobqueue.add(newjob);     }         void addSortedJob(Job newjob)     { 

Page 136: MCC Workshop Booklet

        if(jobqueue.size()==0)         {             jobqueue.add(newjob);             return;         }         for(int i=0; i<jobqueue.size(); i++)         {             Job j = (Job) jobqueue.elementAt(i);             if(j.getSize()>=newjob.getSize())             {                 jobqueue.insertElementAt(newjob,i);                 return;             }         }         jobqueue.add(newjob);     }     void printArray()     {         System.out.println();         System.out.print("|");         for(int i=0;i<20;i++)         {             System.out.print(memory_array[i]+"|");         }             }      void firstFit()     {         int mem_arr_index=0;         for(int i=0; i<jobqueue.size(); i++)         {             Job job = (Job) jobqueue.elementAt(i);             int instr_array[] = job.getInstr();             if(20‐mem_arr_index>=instr_array.length)             {                 System.out.print("\n\ncopying " + instr_array.length + " instructions at location " + mem_arr_index);                 for(int j=0;j<instr_array.length;j++)                 {                     memory_array[mem_arr_index] = instr_array[j];                     mem_arr_index++;                 }                 printArray();             }             else             {                 System.out.println("\nJob with process id " + job.getProcessId()+ " is too big!");             }         }       

Page 137: MCC Workshop Booklet

    }     void worstFit()     {         int mem_arr_index=0;         for(int i=jobqueue.size()‐1; i>=0; i‐‐)         {             Job job = (Job) jobqueue.elementAt(i);             int instr_array[] = job.getInstr();             if(20‐mem_arr_index>=instr_array.length)             {                 System.out.print("\n\ncopying " + instr_array.length + " instructions at location " + mem_arr_index);                 for(int j=0;j<instr_array.length;j++)                 {                     memory_array[mem_arr_index] = instr_array[j];                     mem_arr_index++;                 }                 printArray();             }             else             {                 System.out.println("\nJob with process id " + job.getProcessId()+ " is too big!");             }         }           } }  class os {     public static void main(String args[]) throws Exception     {         Vector v = new Vector();         MemMgmt m = new MemMgmt(v);          Job job1 = new Job(500, 9);         Job job2 = new Job(200, 2);         Job job3 = new Job(900, 6);          System.out.println("\n\nEnter policy:\n1:First Fit\n2:Best Fit\n3:Worst Fit");         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         int policy=Integer.parseInt(br.readLine());          if(policy==1)         {             System.out.println("\nApplying First Fit Policy...");             m.addJob(job1);             m.addJob(job2);             m.addJob(job3);             m.firstFit();             

Page 138: MCC Workshop Booklet

        }         else         if(policy==2)         {             System.out.println("\nApplying Best Fit Policy...");             m.addSortedJob(job1);             m.addSortedJob(job2);             m.addSortedJob(job3);             m.bestFit();                     }         else         if(policy==3)         {             System.out.println("\nApplying Worst Fit Policy...");             m.addSortedJob(job1);             m.addSortedJob(job2);             m.addSortedJob(job3);             m.worstFit();                     }     } } Output Initial memory layout...  |0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|  Enter policy: 1:First Fit 2:Best Fit 3:Worst Fit  Applying Best Fit Policy...  copying 2 instructions at location 0 |201|202|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|  copying 6 instructions at location 2 |201|202|901|902|903|904|905|906|0|0|0|0|0|0|0|0|0|0|0|0|  copying 9 instructions at location 8 |201|202|901|902|903|904|905|906|501|502|503|504|505|506|507|508|509|0|0|0|  7. Demonstrate page replacement algorithm  import java.io.*;  class MemMgmt {     String frame_sequence; 

Page 139: MCC Workshop Booklet

    int mem_block[];     MemMgmt(String fs,int n)     {         frame_sequence = fs;         mem_block = new int[n];         for(int i=0;i<n; i++)         mem_block[i]=‐1;     }     void dispMemBlock()     {         System.out.print("|");         for(int i=0;i<mem_block.length;i++)         {             System.out.print(mem_block[i]+"|");         }         System.out.println();     }     void fcfs()     {         System.out.println("=======   FCFS   ===========");         String strpages[] = frame_sequence.split(" ");         int pages[] = new int[strpages.length];         for(int i=0; i<strpages.length; i++)         pages[i] = Integer.parseInt(strpages[i]);         int mem_block_num=0, page_faults=0;         System.out.println("Initial Memory layout...");         dispMemBlock();         for(int i=0; i<pages.length; i++)         {             boolean present=false;             for(int j=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("Loading page no." + (i+1) + ":" + pages[i]);             dispMemBlock();         } 

Page 140: MCC Workshop Booklet

        System.out.println("Total Number of page faults:" + page_faults);     }      void oppr()     {         System.out.println("=======   Optimal Page Replacement   ===========");         String strpages[] = frame_sequence.split(" ");         int pages[] = new int[strpages.length];         int i=0;         for(i=0; i<strpages.length; i++)         pages[i] = Integer.parseInt(strpages[i]);         int mem_block_num=0,page_faults=0;         System.out.println("Initial Memory layout...");         dispMemBlock();         for(i=0; i<mem_block.length; i++)         {             boolean present=false;             for(int j=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("Loading page no." + (i+1) + ":" + pages[i]);             dispMemBlock();         }         for(; i<pages.length; i++)         {             boolean present=false;             for(int j=0;j<mem_block.length;j++)             {                 if(mem_block[j] == pages[i])                 {                     present=true;                     break;                 }             }             if(!present)             {                                    mem_block_num=‐1;                 int longest_page=‐1; 

Page 141: MCC Workshop Booklet

                for(int j=0;j<mem_block.length; j++)                 {                     int k=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("Loading page no." + (i+1) + ":" + pages[i]);             dispMemBlock();         }         System.out.println("Total Number of page faults:" + page_faults);     } } class os {     public static void main(String args[]) throws Exception     {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         System.out.println("Enter page frame sequence(separated by space):");         //String frame_sequence = br.readLine();         String frame_sequence = "7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1";         System.out.println("Enter page replacement algo:");         int i =  Integer.parseInt(br.readLine());         MemMgmt m = new MemMgmt(frame_sequence,3);         if(i==1)         m.fcfs();         else         if(i==2)         m.oppr();     } } Output 

Page 142: MCC Workshop Booklet

Enter page frame sequence(separated by space): Enter page replacement algo: =======   Optimal Page Replacement   =========== Initial Memory layout... |‐1|‐1|‐1| Loading page no.1:7 |7|‐1|‐1| Loading page no.2:0 |7|0|‐1| Loading page no.3:1 |7|0|1| Loading page no.4:2 |2|0|1| Loading page no.5:0 |2|0|1| Loading page no.6:3 |2|0|3| Loading page no.7:0 |2|0|3| Loading page no.8:4 |2|4|3| Loading page no.9:2 |2|4|3| Loading page no.10:3 |2|4|3| Loading page no.11:0 |2|0|3| Loading page no.12:3 |2|0|3| Loading page no.13:2 |2|0|3| Loading page no.14:1 |2|0|1| Loading page no.15:2 |2|0|1| Loading page no.16:0 |2|0|1| Loading page no.17:1 |2|0|1| Loading page no.18:7 |7|0|1| Loading page no.19:0 |7|0|1| Loading page no.20:1 |7|0|1| Total Number of page faults:9    

Page 143: MCC Workshop Booklet

   8. Demonstrate disk scheduling algorithm  import java.io.*;  class DevMgmt {     String disk_sequence;     DevMgmt(String fs)     {         disk_sequence = fs;     }     void sstf(int start_track)     {         System.out.println("=======   SHORTEST SEEK‐TIME FIRST   ===========");         String disknums[] = disk_sequence.split(" ");         int tracks[] = new int[disknums.length];         boolean tracks_bool[] = new boolean[disknums.length];         int min_dist=0,max_dist=0;         for(int i=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(int i=0; i<disknums.length; i++)         {             //System.out.println(tracks[i] + ":" + tracks_bool[i]);         }         //System.out.println(min_dist);          int total_cylinders=0,from_track=start_track,current_track_index=‐1;         System.out.println("Traversing from:" + from_track);         for(int i=0; i<tracks.length; i++)         {             //System.out.println("i="+i + ", from_track:" + from_track);             int to_track_index=0;             for(int t=0; t<tracks.length;t++)             {                 if((!tracks_bool[t]) && (Math.abs(from_track‐tracks[t])<min_dist) && (t!=current_track_index) )                 {                     to_track_index=t;                     min_dist = Math.abs(from_track‐tracks[t]);                     //System.out.println("* from track:" + from_track + ":" + tracks[t]);                 }             } 

Page 144: MCC Workshop Booklet

            System.out.println("to track : " + tracks[to_track_index] );// ":" + min_dist);             total_cylinders+= Math.abs(from_track‐tracks[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("Total cylinders traversed = " + total_cylinders);     }     void look(int start_track)     {         System.out.println("=======   LOOK   ===========");         String disknums[] = disk_sequence.split(" ");         int tracks[] = new int[disknums.length + 1];         int p=0;         for(p=0; p<disknums.length; p++)         {             tracks[p] = Integer.parseInt(disknums[p]);         }         tracks[p] = start_track;         for(int i=0; i<tracks.length; i++)         {             for(int j=0;j<tracks.length‐1; j++)             {                 if(tracks[j]>tracks[j+1])                 {                     int temp = tracks[j];                     tracks[j] = tracks[j+1];                     tracks[j+1] = temp;                 }             }         }         System.out.println("After sorting...");         int total_cylinders=0,from_track=start_track,to_track=0;         System.out.println("Traversing from:" + from_track);         int i=0;         for(i=0; i<tracks.length; i++)         {                                   if(tracks[i]==start_track)             break;         }         for(int x=i‐1; x>=0; x‐‐)         {             System.out.println("To track : " + tracks[x]);             to_track = tracks[x];             total_cylinders = total_cylinders + Math.abs(from_track‐to_track);             from_track = to_track;         }         for(int x=i+1; x<tracks.length; x++) 

Page 145: MCC Workshop Booklet

        {             System.out.println("To track : " + tracks[x]);             to_track = tracks[x];             total_cylinders = total_cylinders + Math.abs(from_track‐to_track);             from_track = to_track;         }                 System.out.println("Total cylinders traversed = " + total_cylinders);     }     }  class os {     public static void main(String args[]) throws Exception     {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));         System.out.println("Enter disk frame sequence(separated by space):");         //String frame_sequence = br.readLine();         String disk_sequence = "98 183 37 122 14 124 65 67";         System.out.println("Enter scan scheduling algo:");         int i =  Integer.parseInt(br.readLine());         System.out.println("Enter starting track number:");         int track =  53;//Integer.parseInt(br.readLine());                  DevMgmt m = new DevMgmt(disk_sequence);         if(i==1)         m.sstf(track);         else         if(i==2)         m.look(track);     } } Output Enter disk frame sequence(separated by space): Enter scan scheduling algo: Enter starting track number: =======   SHORTEST SEEK‐TIME FIRST   =========== Traversing from:53 to track : 65 to track : 67 to track : 37 to track : 14 to track : 98 to track : 122 to track : 124 to track : 183 Total cylinders traversed = 236  

Page 146: MCC Workshop Booklet

TYBSC

Computer Science

USCS504 & USCS604

Paper 4

Database Management

System & Software

Engineering

Page 147: MCC Workshop Booklet

17‐Jul‐2013

1

Paper IV

DBMS‐II & Software Engineering

SEMESTER‐ V

DBMS‐II

Page 148: MCC Workshop Booklet

17‐Jul‐2013

2

UNIT I• Decomposition: Functional dependency, Closure of aset of functional dependency, Lossless‐Joinset of functional dependency, Lossless Joindecomposition, Multi valued dependency and fourthnormal form, Join dependency, Fifth normal form.– Ref: [Ramakrishnam: 19.1‐19.3, 19.5, 19.8]

• Concurrency Control: Concept of a transaction, ACIDproperties Serial and serializable schedules Conflictproperties, Serial and serializable schedules, Conflictand View serializabilty, Precedence graphs and test forconflict seralizability.– Ref: [Ramakrishnam: 16.1‐16.3, 17.1]

UNIT II• Enforcing serializability by locks: Concept of locks, the

locking scheduler, Two phase Locking, upgrading and downdi l k C f d d l k C lgrading 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 basedrecovery, recovery related structures like transactionand dirty page table, Write‐ahead log protocol, checky p g , g p ,points, recovery from a system crash, Redo and Undophases.– Ref: [Ramakrishnam: 18.1‐18.6]

Page 149: MCC Workshop Booklet

17‐Jul‐2013

3

UNIT III• Fundamentals of PL/SQL: Defining variables and constants,

PL/SQL expressions and comparisons: Logical Operators,Boolean Expressions, CASE Expressions Handling, NullValues in Comparisons and Conditional Statements PL/SQLValues in Comparisons and Conditional Statements, PL/SQLDatatypes: Number Types, Character Types, Boolean Type,Datetime and Interval Types.– Ref: [Ivan Bayross: Chap 15]

• Overview of PL/SQL Control Structures: ConditionalControl: IF and CASE Statements, IF‐THEN Statement, IF‐THEN‐ELSE Statement IFTHEN‐ ELSIF Statement CASETHEN‐ELSE Statement, IFTHEN‐ ELSIF Statement, CASEStatement, Iterative Control: LOOP and EXIT Statements,WHILE‐LOOP, FOR‐LOOP, Sequential Control: GOTO andNULL Statements, Concept of nested tables.– Ref: [Ivan Bayross: Chap 15]

UNIT IV• Sequences: creating sequences, referencing, altering and dropping a

sequence.– Ref: [Ivan Bayross: Chap 11]

• Query evaluation: System Catalog, Evaluation of relational operatorslike selection projection join and set introduction to querylike selection, projection, join and set, introduction to queryoptimization.– Ref: [Ramakrishnam: 12.1‐12.4]

• Cursors: Concept of a cursor, types of cursors: implicit cursors;explicit cursor, Cursor for loops, Cursor variables, parameterizedcursors,– Ref: [Ivan Bayross: Chap 16]Ref: [Ivan Bayross: Chap 16]

• Transactions in SQL: Defining a transaction, Making ChangesPermanent with COMMIT, Undoing Changes with ROLLBACK, UndoingPartial Changes with SAVEPOINT and ROLLBACK, Defining read onlytransactions, explicit locks: transaction and system level, Choosing aLocking Strategy: ROW SHARE and ROW EXCLUSIVE Mode.– Ref: [Ivan Bayross: Chap 16,17]

Page 150: MCC Workshop Booklet

17‐Jul‐2013

4

References1) 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 – ABeginner’s Guide, Tata McGraw‐Hill.

Addi i l fAdditional Reference

1) Elsmasri and Navathe, “Fundamentals of Database Systems”, PearsonEducation.

2) Peter Rob and Coronel, “Database Systems, Design, Implementationand Management”, Thomson Learning

3) C.J.Date, Longman, “Introduction to database Systems”, PearsonEducation.

4) Jeffrey D. Ullman, Jennifer Widom, “A First Course in DatabaseSystems”, Pearson Education.

5) Martin Gruber, “Understanding SQL”,B.P.B. Publications.

6) George Koch and Kevin Loney ,ORACLE “The Complete Reference”, TataMcGraw Hill,New Delhi

7) P. S Deshpande Oracle SQL – PL/SQL Black Book

SQL – PL/SQL Practicals

Practical 1:Writing PL/SQL blocks with basic programming constructs by 

a. Sequential statement

b. unconstrained loop

c. If..then..else, if …elsif…else..end if

Practical 2:Writing PL/SQL blocks with basic programming constructs 

a. case…when 

b. using GO TO to jump out of loop

Page 151: MCC Workshop Booklet

17‐Jul‐2013

5

DBMS II Practical ProblemsPractical 3 : Procedures in PL/SQL

a. Create an empty procedure

b Create a stored procedure and call itb. Create a stored procedure and call it

c. Define procedure to insert data

d. a forward declaration of procedure

Practical 4 : Functions in PL/SQL

D fi d ll f tia. Define and call a function

b. Define and use functions in select/print stmt

c. Recursive function

d. call function and store return to a variable

DBMS II Practical ProblemsPractical 5: cursors with

a. Cursor Attributes for Implicit and Explicit 

b.  Types : Implicit and Explicit

c. Cursor For Loop

d. declare, open, fetch values and close cursor

Practical 6: Cursors with

a. Subqueries

b. Joins

c. Clauses like group by with having ,order by with where

Page 152: MCC Workshop Booklet

17‐Jul‐2013

6

DBMS II Practical ProblemsPractical 7 : Execution of Sequence Command

Using all options including cycle/no cycle and nextval and currval 

Practical 8: Study of Transactions and locks

a.  Commit, Rollback

b. Savepoint

Sample List of Practical on Group 11.Create a table student_list(rollno,name,marks)and generate the sequence on rollno & display

2 Q i it llb k d2.Queries on commit, rollback commands. Sequences

3. Write a PL/SQL block to update the price of the book by its title, if price > 300  then update it by 10%,else update its price by 5%.Raise an exception if book title not availableexception if book title not available. 

4. Write a pl/sql block to call a cursor in a procedure. This procedure is called from the pl/sql block and result is displayed.

Page 153: MCC Workshop Booklet

17‐Jul‐2013

7

Questions???

SEMESTER‐ VI

Software Engineering

Page 154: MCC Workshop Booklet

17‐Jul‐2013

8

What is in TY???• In SY, we covered phases of SDLC, SSAD & OOAD Approach

• In TY(Sem VI) we will be covering ProjectIn TY(Sem VI), we will be covering Project Management,  Changing trends in Software Engineering & Testing

• Testing should be covered in such a way that for the projects it will be useful (for ex. Test cases etc) As STLC starts along with SDLC

• Students should be told to search for projects from the month of August

UNIT I• Revision of Project Management Process[Jalote‐2.4.1],  Role of Project Manager, Project M t K l d A [S t i Ch 3Management Knowledge Areas [Satzinger‐Chap3 (Pg99‐100,104)] 

• Managing Changes in requirements[Jalote‐2.4.4] 

• Role of software Metrics  [Jalote‐1.3.2, Pressman‐23.1.5] 

• Project Scheduling : Building WBS, Use of Gantt and PERT /CPMChart

Page 155: MCC Workshop Booklet

17‐Jul‐2013

9

UNIT II• Configuration Management Process & Functionality & 

Mechanism[Jalote‐2.4.3]

Process Management, CMM & its levels[Jalote‐2.4.5]

• Risk Management & activities [Jalote‐5 6 1‐5 6 3]Risk Management & activities [Jalote 5.6.1 5.6.3]  

• Management of OO software Projects ‐ Object oriented metrics, Use‐Case Estimation [Pressman‐23.3.3(CK Metric Suite),25.2.5,26.6.7‐26.6.8,27.5.3]    [Some part is related to testing*]

• Selecting development tools, Introduction to CASE[Satzinger ‐Chap2(Pg85 86 Pg 341)]Chap2(Pg85‐86, Pg 341)] 

• Unified Process, Its phases & disciplines, 

Agile Development – Principles & Practices, Extreme programming‐ Core values & Practices 

[Satzinger ‐Chap16(Pg692‐705)]

UNIT III• Software Testing: Introduction to Quality Assurance, Six Sigma 

[Pressman‐14.4.4, 16.2, 16.5.2] 

• Testing Fundamentals, Common Terms (like Error, Fault, Failure, Bug, Crash) Objectives of testing, Challenges in Testing Principles of Testing [Mustafa‐1 2 1 2 1 1 2 3 1 2 4Testing, Principles of Testing [Mustafa 1.2, 1.2.1, 1.2.3,1.2.4, 1.5], 

• Static Testing – Introduction & Principles 

[ Mustafa‐3.1,3.2] 

• Types of Testing – Levels of testing such as Unit testing, System testing, Validation Testing, Acceptance testing, 

• Types of testing such as Black box, White Box, Functional, Performance, Regression, Acceptance, Volume, Stress, Alpha, Beta testing [Mustafa‐1.4] 

• Planning Software Testing – Test Plan, Test Plan Specification, Test Case Execution and Analysis, Defect logging and tracking 

[ Jalote‐10.4.2‐10.4.5]

Page 156: MCC Workshop Booklet

17‐Jul‐2013

10

UNIT IV

• Black Box Testing : Introduction, Equivalence partitioning, Boundary‐value analysis, Robustness testing, Cause EffectBoundary value analysis, Robustness testing, Cause Effect Graph, [Mustafa‐4.1‐4.5, Jalote‐10.2.3] 

• White Box Testing :Statement Coverage, Branch/Decision Coverage, Condition Coverage, Graph Matrix, Cyclomatic complexity, Mutation Testing 

[Mustafa‐5.1‐5.6]   

• Object Oriented Testing & Web site testing Object Oriented• Object Oriented Testing & Web site testing – Object Oriented Testing Strategies(*), Testing methods, [Pressman‐19.3, 19.4.3, 19.4.5, Mustafa‐11.2] Overview of web site testing[Pressman ‐20.1.1]

References• 1. System Analysis & Design – Satzinger, Jackson,Burd,Cengage Learning, 

India Ed. • 2. Software Engineering‐ A Practitioner’s Approach, 7th Edition, McGraw 

Hill Int. • 3. Integrated Approach to Software Engineering  ‐ Pankaj Jalote (Narosa), 

3rd Edition• 4. Design Patterns – Elements of Reusable Object‐Oriented Software, 

Pearson By – Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, • 5. Software Testing – Concepts & Practices, Narosa, 

• Additional Reference1) Design Patterns – Elements of Reusable Object‐Oriented Software, Pearson By –

hErichGamma, Richard Helm, Ralph Johnson, John Vlissides,2) Software Engineering: Waman Jawadekar, TMH3) Software Engineering : Sommerville, Pearson Education

Page 157: MCC Workshop Booklet

17‐Jul‐2013

11

Additional References for projects

• UML For Java Programmers – Robert Martin

• Designing Flexible Object Oriented Systems with UML – Charles Richter

• Building Web Applications with UML – Jim Connalen

• ASPNET 3 5 Application Architecture &• ASP.NET 3.5  Application Architecture & Design – Vivek Thakur

Project Discussion…

• ?????

Page 158: MCC Workshop Booklet

17‐Jul‐2013

12

Questions???

Thank You !!