Basic java part_ii

Post on 31-Oct-2014

894 views 3 download

Tags:

description

 

Transcript of Basic java part_ii

© 2004 VeriSign, Inc.

Java Beans

MaruthaIT Architect, ISL, BPTSE

amarutha@in.ibm.com

2

Java Beans+ Component architecture, a reusable software component written in Java programming language.

+ Components (JavaBeans) are reusable software programs that you can develop and assemble easily to create sophisticated applications.

+ Used for using & building components in Java.

+ Doesn’t alter the existing Java language.

3

Features of Java Bean

Independent Reusability Secure Bean Bridge Interface Etc.

4

Basic Bean Concepts Properties Introspection Customization Events Persistence Methods

5

Java Beans : Properties

• Simple Properties

• Indexed Properties

• Bound Properties

• Constrained Properties

6

Java Beans : Introspection

• Introspection allows a builder tool to analyze how Beans work. They adhere to specific rules called design patterns for naming Bean features.

7

Java Beans : Customization

• Customization allows a user to alter the appearance and behavior of a Bean.

• Beans support customization by using property editors.

8

Java Beans : Events

+ Events are used by Beans to communicate with other Beans.

+ Beans fire events.

+ The Bean receiving event is called a listener Bean.

9

Java Beans : Persistence

+ Beans use Java object serialization, to save and restore state that may have changed as a result of customization.

10

Java Beans : Methods

+ Identical to Java classes.

© 2004 VeriSign, Inc.

Applet

12

Introduction

+ Java Application vs Java Applets+ Running Java Applet

+ Using Browser+ Using Appletviewe

+ Java includes classes.

13

Applet Class

+ All applets are subclass of the Applet class.+ Applet Class is present in the ‘java.applet’ package. + Applet must import java.applet and java.awt.+ Applets contain a single default class.

14

Creating, Running and executing an Applet

import java.applet.Applet;import java.awt.Graphics; public class FirstApplet extends Applet {

public void paint(Graphics g){

g.drawString(“Welcome to the World of Applets!!”, 10, 50);}

}

15

Viewing In Applet

+ Write a HTML file, and view it in browser

+ Include a commented applet tag in the java program and view it in appletviewer.

16

Activities In An Applet

Creation

Initialization

Starting

Stop

Destroy

17

Paint() Method

+ Paint is how an applet displays something on the screen. This can be anything from a text, a line, background color or an image.

+ public void paint(Graphics g)

{

g.drawString( String message, int x, int y);

}

18

Repaint() Method

+ Whenever your applet needs to update the information displayed in its window, it simply calls repaint().

+ The repaint() method is defined by the AWT.

+ It causes the AWT run-time system to execute a call to your applet’s update() method, which, in its default implementation, calls paint()

19

HTML Applet Tag

<APPLET[CODEBASE = codebaseURL]CODE = appletFile[ALT = alternateText][NAME = appletInstanceName]WIDTH = pixels HEIGHT = pixels[ALIGN = alignment][VSPACE = pixels][HSPACE = pixels]>[< PARAM NAME = attributeName VALUE = AtrributeValue>]..</APPLET>

20

Passing Parameters to Applets

+ The Applet tag in HTML allows you to pass parameters to your applet. To retrieve a parameter, use the getParameter() method.

21

Important Methods

+ getDocumentBase( )+ Returns the path of the document file as url.

+ getCodeBase( )+ Returns the path of .class file as url

22

Applet Context

+ Methods Of Applet Context+ Void showDocument(URL url)

+ Void showDocument(URL url String where) + AudioClip getAudioClip(URL url)

+ AudioClp getAudioClip(URL url, String name) + Image getImage(URL url)

+ Image getImage(URL url, String name)

23

Applet Context (Contd…)

+ Enumeration getApplets().

+  Applet getapplet(String name)

24

Security Restrictions applied on Applets

+ Cannot read or write files on the user system.+ Cannot communicate with an Internet site but only with the one that

served the web page including the applet. + Cannot run any programs on the reader’s system. + Cannot load any programs stored on the user’s system.

25

File Name Filters

+ FilenameFilter+ public boolean accept(File dir, String name)

+ Sample Program

26

+ RandomAccessFile Class+ This class provides the capability to perform I/O to specific locations

within a file. + The name randomaccess is due to the fact that data can be read or

written to random locations within a file instead of a continuous stream of information.

+ An argument ‘r’ or ‘rw’ is passed to the RandomAccessFile indicating read-only and read-write file access.

© 2004 VeriSign, Inc.

Java Thread

28

Thread

+ Benefits + User and Kernel Threads+ Multithreading Models+ Solaris 2 Threads+ Java Threads

29

30

31

32

33

MultiThread Models

+ Many-to-One

Many User-Level Threads Mapped to Single Kernel Thread.

Used on Systems That Do Not Support Kernel Threads.

34

35

36

37

38

39

40

Java Thread

+ Java Threads May be Created by:+ – Extending Thread class+ – Implementing the Runnable interface

41

Extending Thread Class

class Worker1 extends Thread

{

public void run() {

System.out.println(“I am a Worker Thread”);

}

}

42

Creating the Thread

public class First

{

public static void main(String args[]) {

Worker runner = new Worker1();

runner.start();

System.out.println(“I am the main thread”);

}

}

43

Runnable Interface

public interface Runnable

{

public abstract void run();

}

44

Implementing Runnable

class Worker2 implements Runnable

{

public void run() {

System.out.println(“I am a Worker Thread”);

}

}

45

Creating the Threadpublic class Second

{

public static void main(String args[]) {

Runnable runner = new Worker2();

Thread thrd = new Thread(runner);

thrd.start();

System.out.println(“I am the main thread”);

}

}

46

Java Thread Management

+ suspend() – suspends execution of the currently running thread.+ • sleep() – puts the currently running thread to sleep for a+ specified amount of time.+ • resume() – resumes execution of a suspended thread.+ • stop() – stops execution of a thread.

47

48

Life Cycle of a Thread

new Threadnew Thread

runnablerunnable

blockedblocked

deaddead

start( )

stop( )

sleep( )

suspend( )

resume( )

notify( )

wait( )

49

What is Multithreading?

+ A thread is a smallest unit of executable code that performs a particular task.

+ Java supports multithreading. + An application can contain multiple threads. + Each thread is specified a particular task which is executed

concurrently with the other threads. + The capability of working with multiple thread is called

Multithreading.

50

What is Multithreading? (Contd…)

+ Multithreading allows you to write efficient programs that makes the maximum use of CPU, by keeping the idle time to a minimum.

+ It is a specialized form of multitasking.+ Multitasking is running multiple programs simultaneously, with each

program having at least one thread in it. + These programs are executed by a single processor.

51

Thread Scheduling and Setting the Priorities (Contd…)

+ It is the programmer, or the Java Virtual Machine or the operating system that makes sure that the CPU is shared between the threads.

+ This is called scheduling of threads.+ Every thread in Java has its own priority. + This priority is in the range:

+ Thread.MIN_PRIORITY &+ Thread.MAX_PRIORITY

52

Thread Scheduling and Setting the Priorities (Contd…)

+ By default, a thread has a priority of Thread.NORM_PRIORITY, a constant of 5.

+ Every new thread that is created, inherits the priority of the thread that creates it.

+ The priority of the thread can be adjusted with the method called setPriority( ).

+ This takes an integer as an argument. + This value has to be within the range of 1 to 10, else, the method throws

an exception called as IllegalArgumentException.

53

Daemon Threads

+ A Java program is terminated only after all threads die. + There are two types of threads in a Java program:

+ User threads+ Daemon threads

+ The threads that are created by the Java Virtual Machine on your behalf are called daemon threads.

+ Java provides garbage collector thread that reclaims dynamically allocated memory.

54

Daemon Threads (Contd…)

+ This thread runs as a low priority thread + The garbage collection is marked as a daemon thread.+ Thread class has two methods that deal with daemon threads.

+ public void setDaemon(boolean on)+ public boolean isDaemon( )

55

Thread Synchronization

+ It may so happen that more than one thread wants to access the same variable at the same time

+ One thread tries to read the data while the other tries to change the data. + What we need to do is, allow one thread to finish its task completely

(changing the value) and then allow the next thread to read the data. + This can be attained with the help of synchronized( ) method. + This method tells the system to put a lock around a particular method.

56

InterThread Communication

+ Necessary to avoid polling + Methods

+ wait()+ notify()+ notifyAll()

© 2004 VeriSign, Inc.

JDBC

58

JDBC

+ Overview of JDBC and its design goals+ Key API classes+ Some examples

59

What is JDBC?

+ JDBC is a Java™ API for executing SQL+ statements+ It’s deliberately a “low level” API+ But it’s intended as a base for higher level APIs+ And for application builder tools+ It’s influenced by existing database APIs+ Notably the XOPEN SQL CLI+ And Microsoft’s ODBC

60

61

Types of JDBC technology drivers

+ JDBC-ODBC Bridge+ Native API Partly+ Net Protocol Fully+ Native Protocol Fully

62

JDBC-ODBC bridge

+ JDBC API access via one or more ODBC drivers+ ODBC native code and in many cases native database client code

must be loaded on each client machine+ (e.g) Microsoft ODBC-Drivers

63

native-API partly

+ JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS

+ this style of driver requires that some binary code be loaded on each client machine

+ Native Module of dependent form of H/W like .dll or .so.+ (e.g) OCI driver for local connection to Oracle

64

net-protocol fully

+ JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server

+ able to connect to many different databases+ (e.g) III party Driver using protocol depends on the vendor

65

native-protocol fully

+ JDBC technology calls into the network protocol used by DBMSs directly

+ a direct call from the client machine to the DBMS server+ It is independent from H/W because this driver is %100 java.+ (e.g) thin driver for local/global connection to Oracle

66

67

68

69

70

71

72

73

74

75

76

77

78

79

Seven Basic Steps in Using JDBC

+ Load the Driver+ Define the Connection URL+ Establish the Connection+ Create a Statement Object+ Execute a Query+ Process the result+ Close the Connection

80

+ Three types of statement objects are available+ Statement : executing Simple Query+ PreparedStatement : for executing pre-compiled SQL Statement + CallableStatement : for executing data base stored Procedure

81

82

83

84

85

JDBC Transaction

86

JDBC Transaction

87

Learnings from this Session

+ Tell me few responsibility of DriverManager+ What are the three different Statements?+ What is ResultsetMetaData?+ What is DatabaseMetaData?+ Write a Simple prg to create your own SQL> prompt and we can run

any SELECT query.

© 2004 VeriSign, Inc.

Networking in Java

89

Types Of Network Programming

Two general types are :+ Connection-oriented programming + Connectionless Programming

90

Connection-oriented Networking

The client and server have a communication link that is open and active from the time the application is executed until it is closed. Using Internet jargon, the Transmission control protocol os a connection oriented protocol. It is reliable connection - packets are guaranteed to arrive in the order they are sent.

                                                                                       

91

Connection-less Networking

The this type each instance that packets are sent, they are transmitted individually. No link to the receiver is maintained after the packets arrive. The Internet equivalent is the User Datagram Protocol (UDP). Connectionless communication is faster but not reliable. Datagrams are used to implement a connectionless protocol, such as UDP.                                                     

92

Common Port Numbers

Port Number Service

21 FTP

23 Telnet

25 SMTP

80 Http (Web)

110 POP

143 IMAP

443 HTTS (SSL)

93

94

95

URI, URL, URLConnection and HttpURLConnection

+ URI -Universal Resource Identifier -For parsing+ URL -Universal Resource Locator -For fetching+ URLConnection -Finer control of the transfer+ HttpURLConnection -Subclass specific to HTTP

96

URL

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

+ http://www.abc.com/

Protocol Identifier Resource Name

97

URL(contd…)

+ Contrustors Of URL are:+ URL(String urlspecifier)

+ Constructor that allows to break up the URL into its component parts are:

+ URL(String protocolName, String hostname, int port, String path)+ URL(String protocolName, String hostname, String path)

98

URL(contd…)

+ java.net.url consists of the following methods:+ openConnection( )

– This method establishes a connection and returns a stream.

+ getContent( )– This method makes a connection and reads addressed

contents.+ getFile( )

– This method returns the filename part of the URL.

99

URL(contd…)

+ getHost( )– This method returns only the host name part from the URL.

+ getPort( )– This method returns the port number part from the URL.

+ getProtocol( )– This method returns the name of the protocol of the URL.

100

URL(contd…)

+ URLConnection Class+ If we have an active HTTP connection to the web, the URLConnection

class encapsulates it. + It is an abstract class. + Its objects can be created from a single URL. + The URLConnection constructor is protected, hence to create a

URLConnection, we have to first open the connection using the openConnection( ) method.

101

URL(contd…)

+ This class supports several methods so as to modify the defaults, query and modify the current settings for a URLConnection object.

+ The methods are:

+ connect( )

– To open a communication link.

+ getDate( )

– To get the value of the date.

102

URL(contd…)

+ getExpiration( )

– To get the date of expiration of the URL.

+ getInputStream( )

– To get the InputStream that can be used to read the resource.

+ getLastModified( )

– To get the date last modified.

+ getURL( )

– To get the URL used to establish a connection.

103

Inside java.net

+ java.net package consists of the following classes:

+ Socket

+ InetAddress

+ ServerSocket

+ DatagramSocket

+ DatagramPacket

104

Inside java.net (Contd…)

+ InetAddress Class+ Eases finding of addresses of the Internet. + Summarizes Internet IP addresses.

+ The static getByName method returns an InetAddress object of a host.

+ getLocalHost method to get the address of your localhost.

105

Inside java.net (Contd…)

+ Socket Class+ Java programs connect to the network using a socket. + The socket class helps in establishing client connections. + It is this socket that helps establishing connections and developing

applications between the client and server.

106

Inside java.net (Contd…)

+ Socket class has eight constructors that create sockets. + They in turn connect to the destination host and port. + The port number of the machine to which the socket is connected is

obtained by the getPort( ) method. + The local port number is obtained using the getLocalPort( ) method.

107

Inside java.net (Contd…)

+ The local IP address is obtained using the getLocalAddress( ). + The input and output streams are accessed using the

getInputStream( ) and getOutputStream( ) methods. + The socket is closed using the close( ) method.+ The string representation of the object is written using the toString( )

method.

108

Inside java.net (Contd…)

+ The method to switch from the default Java socket implementation to a custom socket implementation is defined using the setSocketImplFactory( ) method.

109

Inside java.net (Contd…)

+ ServerSocket Class+ The TCP server socket is implemented using the ServerSocket class. + There are three constructors specifying the port to which the server socket is to

listen for incoming connection requests. + The address of the host to which the socket is connected is returned using

getInetAddress( ) method. + The local port on which the server socket listens for incoming connection is

returned using the getLocalPort( ) method. + The socket’s address and port number is returned as a string using the toString( )

method.

110

Inside java.net (Contd…)

+ DatagramSocket Class+ This class is used to implement the client and server sockets using the User

Datagram Protocol (UDP) protocol. + This class provides three constructors.

+ The default constructor creates a datagram socket. This is used by client applications. In this case no port number is specified.

+ The second constructor creates a datagram socket using a specified port. This is generally with the server applications.

+ The third constructor allows an Internet Address to be specified in addition to the port.

111

Inside java.net (Contd…)

+ The datagrams are sent and received using the send( ) and receive( ) methods respectively.

+ The local port and Internet address of the socket is returned using the getLocalPort( ) method and getLocalAddress( ) method respectively.

112

Inside java.net (Contd…)

+ DatagramPacket Class

+ This class encapsulates the datagrams that are sent and received using objects

of class DatagramSocket.

+ There are two different constructors, one for datagrams that are received from

the datagram socket and the other for creating datagrams that are sent over the

datagram socket.

113

Inside java.net (Contd…)

+ There are about eight access methods provided such as:+ getAddress( ) and getPort( ) for reading the destination IP address and port

of the datagram.

+ getLength( ) and getData( ) for getting the number of bytes of data in the datagram and reading the data into a byte array buffer.

+ setAddress( ), setPort( ), setLength( ) and setData( ) to allow the datagram’s IP address, port, length and data values to be set.

© 2004 VeriSign, Inc.

JNDI

115

Overview of the Architecture

+ The JNDI architecture consists of the JNDI API and the JNDI SPI. + The JNDI API allows Java applications to access a variety of

naming and directory services.+ The JNDI SPI is designed to be used by arbitrary service providers

including directory service providers.

116

JNDI Architecture

117

JNDI Architecture

118

Composite NameSpace

119

Lookup Process

120

Lookup Process

121

Mapping Directory To Schema

© 2004 VeriSign, Inc.

RMI

123

What is Distributed System?

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

RMI Registry

145

RMI Communication

146

147

148

149

150

151

152

153

154

UnicastRemoteObject

+ The server typically extends class+ java.rmi.server.UnicastRemoteObject+ The constructor of this class throws a RemoteException+ Therefore, so should the constructor of any specialization.

155

UnicastRemoteObject

+ Most arguments and results+ are converted to a sequence of bytes;+ the bytes are sent over the net+ therefore the class should implement the java.io.Serializable interface+ a clone of the argument/result is constructed on the other side.+ The effect is pass by object value, rather than by object reference.

156

157

158

159

160

161

162

163

RMI Issues

+ Concurrency -If there are multiple clients, the server may field multiple calls at the same time. So use synchronization as appropriate.

+ Argument passing - Arguments are usually passed by value, not reference.+ Proxy and Skeleton generation- Proxy and Skeleton classes are

automatically derrived from the server class+ Lookup - Objects are usually found via a registry

164

RMI Issues

+ The proxy and the server share an interface. This interface must extend java.rmi.remote.

+ Every method in the interface should be declared to throw java.rmi.RemoteException

+ RemoteExceptions are thrown when network problems are encountered,

+ or when server objects no longer exist.

165

Learning from this session

+ Tell me the Default port of RMI+ Remote+ UniCastRemoteObject+ RmiRegistry+ Stub & Skeleton

© 2004 VeriSign, Inc.

Thank You