Top Banner
ABSTRACT A Digital watermark is a digital signal or pattern inserted into a digital image. Since this signal or pattern is present in each unaltered copy of the original image, the digital watermark may also serve as digital signature for the copies. Digital watermarking is also to be contrasted with public key encryption, which also transforms original files into another form. Unlike encryption, digital watermarking leaves the original digital data basically intact and recognizable. Digital watermarks are designed to be persistence in viewing, printing or subsequent retransmission or discrimination. Thus, watermarking does not prevent copying but it deters illegal copying by providing a means for establishing the original ownership of a redistributed copy. Watermarking data for copyright protection is an accepted technique adopted for digital information. This subject has been quite exhaustively researched and several techniques have been established for protecting copyright for still images, audio and video files.
177
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: watermarking_newDoc

ABSTRACT A Digital watermark is a digital signal or pattern inserted into a digital

image. Since this signal or pattern is present in each unaltered copy of the original

image, the digital watermark may also serve as digital signature for the copies.

Digital watermarking is also to be contrasted with public key encryption,

which also transforms original files into another form. Unlike encryption, digital

watermarking leaves the original digital data basically intact and recognizable. Digital

watermarks are designed to be persistence in viewing, printing or subsequent

retransmission or discrimination. Thus, watermarking does not prevent copying but it

deters illegal copying by providing a means for establishing the original ownership of

a redistributed copy.

Watermarking data for copyright protection is an accepted technique

adopted for digital information. This subject has been quite exhaustively researched

and several techniques have been established for protecting copyright for still images,

audio and video files.

The main aim of this project is to propose a possible new technique for

watermarking on images.

Digital Watermarking is a robust and efficient digital image water marking algorithm

using the Fast Hadamard Transform is proposed for the copyright protection of digital

images. This algorithm can embed or hide an entire image or pattern as a watermark

such as a company’s logo or trademark into the original image. The performance of

the proposed algorithm is evaluated using the Stirmark, which consists of 90 different

types of image attacks. Results show that the proposed algorithm is very robust and

can survive most of the stirmark attacks.

Page 2: watermarking_newDoc

Organizational Profile

Page 3: watermarking_newDoc

INTRODUCTION

Overview of The Project

PRESENT SYSTEM: - Digital Watermark is an invisible mark inserted into the digital

multimedia data so that it can be detected in the later stage of evidence of rightful

ownership. A great deal of research efforts has been focused on digital watermark in

recent years. The techniques proposed so far can be divided into two main groups of

according to the embedding domain of the container image.

1) Spatial Domain Approach:

One group is SPATIAL domain approach .The earliest watermarking

techniques are mainly this kind and the simplest example is to embed the watermark

into least significant bits(LSB) of the image pixels. However, this technique has

relatively low information hiding capacity and can be easily erased by lossy image

compression.

2) Frequency Domain Approach:

The other group is FREQUENCY domain approach. This can

embed more information bits and is relatively robust to attacks. They embedded a

Guassian distributed sequence into the perceptually most significant frequency

components of the container image. Another technique embedded an image

watermark into selectively modified middle frequency of discrete cosine

transform coefficients. One more algorithm embedded watermark using Fourier

transformations that is invariant to image manipulations or attacks due to rotation

scaling and translation. Still several methods used to hide the data to the

frequency domain such as HVS, JND.

The major problem with many of these watermarking schemas is

that they are not very robust against different types of image manipulations or

attacks such as ones found in Stirmark. Moreover, some of these techniques are

quite complicated to implement in real-time.

Page 4: watermarking_newDoc

PROPOSED SYSTEM: -

Due to above mentioned failures a new technique has been proposed

so that to cover and maintain the drawbacks prevailed in the previous system and

hence a technique called Fast Hadamard Transformation proposed. This algorithm

is often referred as robust one because of its following properties and attributes

that meets the requirements.

Fast Hadamard Transform (FHT) is a watermarking approach

proposed in a conference paper developed by Datamark Technologies Pvt Ltd,

Singapore. In this paper we propose a fast Hadamard transform based

watermarking approach that embeds a gray scale image as a watermark. The

watermark gray scale image is decomposed into Hadamard coefficients for

embedding.

To increase the invisibility of he water mark a visual model based on

the original image charecterstics, such as edges and textures are incorporated to

determine the watermarking strength factor. This factor is used to scale the

watermark coefficients in a similar range to the coefficients from Hadamard

coefficients of the sub blocks of the container image.

The FHT embedding algorithm was found to provide a robust and

efficient approach to perform digital watermarking of digital image data for

copyright protection and proof of rightful ownership. The simplicity of FHT

offers a significant advantage in shorter processing time and ease of hardware

implementation than most orthogonal transform techniques such as DCT and

DWT.

The Hadamard transform has more useful middle and high frequency

bands than several high gain transforms, such as DCT.When compared with the

DCT, it found to be more robust against various attacks .It also offers a significant

advantage in term of a shorter processing time and the ease of hardware

implementation than many common transformation techniques.

Page 5: watermarking_newDoc

Requirement Specifications: -

HARDWARE REQUIREMENTS: -

The selection of hardware is very important in the existence and proper

working of any software. In the selection of hardware, the size and the capacity

requirements are also important.

The Digital Watermarking Algorithm (FHT) can efficiently run on System

With minimum requirements, of at least 128 MB RAM and Hard disk drive having

20 GB that can be driven by a processor of 600 MHz. suits the information system

operation

Processor -------- PIII, 600MHz

RAM Capacity -------- 128MB or above

Hard Disk -------- 20GB or above

SOFTWARE REQUIREMENTS

One of the most difficult tasks is that, the selection of the software, once

system requirement is known is determining whether a particular software package

fits the requirements. This section first summarizes the application requirement

question and then suggests more detailed comparisons.

Operating System -------- Windows 2000 or later

Software -------- Java

0000000000

Page 6: watermarking_newDoc

DESIGN PRINCIPLES & EXPLANATION: -

With the advent of the Internet, the online purchasing and distribution of

digital images can now be performed relatively easily.However, there exists one

major problem associated with the distribution of any digital images is the important

issue of copyright protection and the proof of rightful ownership.Over the past few

years, the technology of digital watermarking has gained prominence and emerged as

a leading candidate that could solve the fundamental problems of legal ownership and

content authentications for digital multimedia data(e.g. audio,image,and video).

A digital watermark is a sequence of information, containing the

owner’s copyright information for the protected multimedia data so that it can be

detected in the later stage for evidence of rightful ownership. A great deal of

research efforts has been focused on digital image watermarking in recent years.

The techniques proposed so far can be divided into two main groups according to

the embedding domain of the container image.

One group is the spatial domain approach. The earliest watermarking

techniques are mainly this kind and the simplest example is to embed the

watermark into least significant bits(LSBs) of the image pixels[2].However,this

technique has relatively low information hiding capacity and can be easily erased

by lossy image compression. The other is the frequency domain approach. This

approach can be embed more information bits and is relatively robust to attacks.

Cox et al,[3] used the spread spectrum communication for digital multimedia

watermarking. They embedded a Gaussian distributed sequence into the

perceptually most significant frequency components of container image.

Hsu and Wu embedded an image watermark into selectively modified

middle frequency of discrete cosine transform (DCT) coefficients of container

image[4]. Joseph et al developed a digital image watermarking using the Fourier

Mellin transform that is invariant to image manipulations or attacks due to

Page 7: watermarking_newDoc

rotation ,scaling and translation[5].Several other methods used discrete wavelet

transform (DWT) to hide the data to the frequency domain[6-8],Wie et al applied

JND(just-noticeable distortion)feature of HVS(human visual system)in wavelet

transform domain and hid 236 information bits into the ‘lenna’image[6].The major

problem with many of these watermarking schemes is that they are not very robust

against different types of image manipulations or attacks such as the ones found in

Stirmark.Moreover,some of these techniques are quite complicated to implement in

real-time.

In this algorithm ,we propose a fast Hadamard transform(FHT) based

watermarking approach that embeds a grayscale image as a water mark.The

watermark grayscale image is decomposed into Hadamard coefficients for

embedding. To increase the invisibility of the watermark, a visual model based on

the original image characteristics,such as edges and textures are incorporated to

determine the watermarking strength factor.This factor is used to scale the

watermark coefficients to similar range to the coefficients from the Hadamard

coefficients of the sub-blocks of the container image.The FHT embedding

algorithm was found to provide a robust and efficient approach to perform digital

watermarking of digital image data for copyright protection and proof of rightful

ownership.The simplicity of FHT offers a advantage in shorter processing time

and ease of hardware implementation than most orthogonal transform techniques

such as DCT and DWT.

2 . 2D-Hadamard transform of signal

The 2D-Hadamard transformation has been used extensively in image processing

and image compression [9,10]. In this section,we give a brief overview of the

Hadamard tranform representation of image data,which is used in the watermarking

embedding and extraction process.The reason of choosing FHT domain is given

below.

Let [U] represents the original image and[V] the transformed image ,the 2D-Hadamard transform is given by

Page 8: watermarking_newDoc

[V]= Hn [U] Hn

N

1.1 Digital Watermarking

Watermarking is not a new technique. It is descendent of a technique known as

steganography which had been in existence for at least a few hundred years.

Steganography is a technique for concealed communication. In contrast to

cryptography where the content of a communicated message is secret, in

steganography the very existence of the message that is communicated is a secret and

its presence is known only by parties involved in the communication. Steganography

is technique where a secret message is hidden within another unrelated message and

then communicated to the other party. Some of the techniques of steganography like

use of invisible ink, word spacing patterns in printed documents, coding messages in

music compositions, etc., have been used by military intelligence since the times of

ancient Greek civilization

Watermarking can be considered as a special technique of steganography where one

message is embedded in another and the two messages are related to each other in

some way. The most common examples of watermarking are the presence of specific

patterns in currency notes which are visible only when the note is held to light and

logos in the background of printed text documents. The watermarking techniques

prevent forgery and unauthorized replication of physical objects.

Digital watermarking is similar to watermarking physical objects except that the

watermarking technique is used for digital content instead of physical objects. In

digital watermarking a low-energy signal is imperceptibly embedded in another

signal. The low-energy signal is called watermark and it depicts some metadata, like

security or rights information about the main signal. The main signal in which the

watermark is embedded is referred to as cover signal since it covers the watermark.

Page 9: watermarking_newDoc

The cover signal is generally a still image, audio clip, video sequence or a text

document in digital format.

The digital watermarking system essentially consists of a watermark embedder and a

watermark detector (see Figure 1). The watermark embedder inserts a watermark onto

the cover signal and the watermark detector detects the presence of watermark signal.

Note that an entity called watermark key is used during the process of embedding and

detecting watermarks. The watermark key has a one-to-one correspondence with

watermark signal (i.e., a unique watermark key exists for every watermark signal).

The watermark key is private and known to only authorized parties and it ensures that

only authorized parties can detect the watermark. Further, note that the

communication channel can be noisy and hostile (i.e.,prone to security attacks) and

hence the digital watermarking techniques should be resilient to both noise and

security attacks.

1.2 Features of Digital Watermarking

As mentioned earlier, digital watermarking techniques are useful for embedding

metadata in multimedia content. There are alternate mechanisms like using the header

of a digital file to store meta-information. However, for inserting visible marks in

images & video and for adding information about audio at the beginning or end of the

audio clip etc. the digital watermarking technique is appealing, since it provides

Page 10: watermarking_newDoc

following main features and does not require out-of-band data as in other

mechanisms.

• Imperceptibility:

The embedded watermarks are imperceptible both perceptually as well as statistically

and do not alter the aesthetics of the content that is watermarked. The watermarks do

not create visible artifacts in still images, alter the bit rate of video or introduce

audible frequencies in audio signals.

• Robustness:

Depending on the application, the digital watermarking technique can support

different levels of robustness against changes made to the watermarked content. If

digital watermarking is used for ownership identification, then the watermark has to

be robust against any modifications. The watermarks should not get degraded or

destroyed as a result of unintentional or malicious signal and geometric distortions

like analog-to digital conversion, digital-to-analog conversion, cropping, resampling,

rotation, dithering, quantization, scaling and compression of the content. On the other

hand, if digital watermarking is used for content authentication, the watermarks

should be fragile, i.e., the watermarks should get destroyed whenever the content is

modified so that any modification to content can be detected.

• Inseparability:

After the digital content is embedded with watermark, separating the content from

the watermark to retrieve the original content is not possible.

• Security:

The digital watermarking techniques prevent unauthorized users from detecting and

modifying the watermark embedded in the cover signal. Watermark keys ensure that

only authorized users are able to detect/modify the watermark.

Page 11: watermarking_newDoc

Requirements of watermarks

To be effective in the protection of the ownership of intellectual property, the

invisibly watermarked document should satisfy several criteria:

1. the watermark must be difficult or impossible to remove, at least without

visibly degrading the original image,

2. the watermark must survive image modifications that are common to typical

image-processing applications (e.g., scaling, color requantization, dithering,

cropping, and image compression),

3. an invisible watermark should be imperceptible so as not to affect the

experience of viewing the image, and

4. for some invisible watermarking applications, watermarks should be readily

detectable by the proper authorities, even if imperceptible to the average

observer. Such decodability without requiring the original, un-watermarked

image would be necessary for efficient recovery of property and subsequent

prosecution.

1.3 Applications of Digital Watermarking

Digital watermarking techniques have wide ranging applications. Some of the

applications are enlisted below.

• Copyright Protection:

Digital watermarks can be used to identify and protect copyright ownership. Digital

content can be embedded with watermarks depicting metadata identifying the

copyright owners.

• Copy Protection:

Digital content can be watermarked to indicate that the content cannot be illegally

replicated. Devices capable of replication can then detect such watermarks and

prevent unauthorized replication of the content.

Page 12: watermarking_newDoc

• Tracking:

Digital watermarks can be used to track the usage of digital content. Each copy of

digital content can be uniquely watermarked with metadata specifying the authorized

users of the content. Such watermarks can be used to detect illegal replication of

content by identifying the users who replicated the content illegally. The

watermarking technique used for tracking is called as fingerprinting.

Tamper Proofing:

Digital watermarks, which are fragile in nature, can be used for tamper proofing.

Digital content can be embedded with fragile watermarks that get destroyed whenever

any sort of modification is made to the content. Such watermarks can be used to

authenticate the content.

• Broadcast Monitoring:

Digital watermarks can be used to monitor broadcasted content like television and

broadcast radio signals. Advertising companies can use systems that can detect the

broadcast of advertisements for billing purposes by identifying the watermarks

broadcast along with the content.

• Concealed Communication:

Since watermarking is a special technique of steganography, it can be used for

concealed communication also.

1.4 Classification of Digital Watermarking Techniques: -

Digital Watermarking techniques can be classified in a number of ways

depending on different parameters. Various types of watermarking techniques are

enlisted below. Each of the different types mentioned below have different

applications.

1. Robust & Fragile Watermarking

2. Visible & Transparent Watermarking

Page 13: watermarking_newDoc

3. Public & Private Watermarking

4. Asymmetric & Symmetric Watermarking

5. Steganographic & Non-Steganographic Watermarking.

• Robust & Fragile Watermarking :

Robust watermarking is a technique in which modification to the watermarked

content will not affect the watermark. As opposed to this, fragile watermarking is a

technique in which watermark gets destroyed when watermarked content is modified

or tampered with.

• Visible & Transparent Watermarking:

Visible watermarks are ones which are embedded in visual content in such a way that

they are visible when the content is viewed. Transparent watermarks are

imperceptible and they cannot be detected by just viewing the digital content.

• Public & Private Watermarking:

In public watermarking, users of the content are authorized to detect the watermark

while in private watermarking the users are not authorized to detect the watermark.

• Asymmetric & Symmetric Watermarking:

Asymmetric watermarking (also called asymmetric key watermarking) is a technique

where different keys are used for embedding and detecting the watermark. In

symmetric watermarking (or symmetric key watermarking) the same keys are used

for embedding and detecting watermarks.

• Steganographic & Non-Steganographic watermarking:

Steganographic watermarking is the technique where content users are unaware of the

presence of a watermark. In non-steganographic watermarking, the users are aware of

the presence of a watermark.

Page 14: watermarking_newDoc

Steganographic watermarking is used in fingerprinting applications while non

steganographic watermarking techniques can be used to deter piracy

2.2 Digital watermarking

A Digital watermark is a sequence of information, containing the owner’s copy right

information for protected digital content. It is an invisible mark inserted into the

digital data so that it can be detected in the later stage for evidence of rightful

ownership. Although water marking does not prevent data being stolen (illegal

copying), but allows establishing the original ownership. Several techniques have

been proposed and tested , for water marking digital data and several commercial

software are also available . All these techniques are based on one basic principle that

the watermarking software introduces small errors into the object being watermarked.

These intentional errors are the marks that constitute the total watermarking. However

these marks (errors) are chosen so as to have an insignificant impact on the usefulness

of the data and further a malicious user cannot precisely locate these marks.

Therefore an important aspect of these techniques is that the malicious user cannot

destroy the watermarks without considerably degrading the quality of the data and

thus rendering it almost useless. A great deal of research efforts has been focused on

digital image watermarking in recent years. The techniques proposed so far can be

divided into two main groups according to the embedding domain of container image.

Spatial domain approach

Frequency domain approach

2.2.1 Spatial domain approach

There is a vast majority of image watermarking approaches. One method of data

hiding exploits the least significant bit (LSB) plane, with direct replacement between

cover image’s LSB and message (watermark) bits by adopting different logical or

arithmetic combinations. However, because information is hidden in LSB, it is fragile

to any data processing, which results in loss of information from these LSB bits.

Page 15: watermarking_newDoc

The earliest watermarking techniques are mainly this kind and simplest example is to

embed the watermark into least significant bits (LSBs) of the image pixels. However,

this technique has relatively low information hiding capacity and can be easily erased

by lossy image compression.

The watermarks that are constructed using spatial domain approach are called spatial

watermarks. And they are embedded directly into an image's pixel data. Spectral (or

transform-based) watermarks are incorporated into an image's transform coefficients

(DCT, Wavelet).

Image-adaptive watermarks are usually transform-based, and very robust. They

locally adapt the strength of the watermark to the image content through perceptual

models for human vision. These models originally developed for image compression.

The image-adaptive watermarks are based on the robustness of the basic spread-

spectrum technique

The work in image-adaptive watermarking shows that using visual models in the

embedding scheme can produce an even more robust watermark than the standard

spread-spectrum technique. Specifically, visual models allow the user to raise or

lower the amplitude of the watermark according to the image content (hence the

name, image-adaptive). These visual models provide thresholds for how much a

given transform coefficient can change, before such changes are noticeable under

standard viewing conditions. Below Figure shows the procedure for image-adaptive

watermarking

Page 16: watermarking_newDoc

Figure 2.1 Image adaptive watermarking

2.2.2 Frequency domain approach

This approach can embed more information bits and is relatively robust to attacks.

DCT and wavelet transforms are examples of Frequency Domain Approach. The

Discrete Cosine Transform (DCT) helps separate the image into parts (or spectral

sub-bands) of differing importance (with respect to the image's visual quality). The

DCT is similar to the discrete Fourier transform: it transforms a signal or image from

the spatial domain to the frequency domain.

2.2.3 Non-Blind Digital watermarking

It is also called as Private Watermarking. In this scheme the original cover signal is

required during the detection process. For example the integer value 10 could be

added to the integer value of the blue channel on every pixel to represent a ‘1’ and

perhaps 5 added for a ‘0’ value. Watermark extraction would be a simple matter of

subtracting the original image’s blue channel from the watermarked image’s blue

channel, and then it produces the watermark. The main issue is the requirement of the

original image at the detection/decoding stage.

Page 17: watermarking_newDoc

2.2.4 Blind Digital watermarking

It is also called as Public Watermarking. In this scheme, the cover signal (the original

signal) is not needed during the detection process to detect the mark. Solely the key,

which is typically used to generate some random sequence used during the

embedding process, is required. This scheme can be used easily in mass-market

electronic equipment or software.

2.2.5 Symmetric Digital watermarking

The key for embedding and detection of the watermark are identical. The detector

must know the required private key for extracting the watermark from the digital data.

Figure 2.2 General Symmetric Watermarking Schemes

The above Fig. depicts a general blind symmetric watermarking scheme. The term

blind”

indicates that the host signal (Original data) is not known at the watermark detector.

The watermark information is embedded into the host signal dependent on a private

key. With the same private key the watermark is detected from watermarked data.

Embed Attack Detection

Private Key Private Key

Page 18: watermarking_newDoc

2.2.6 Asymmetric Digital watermarking

One particular problem, even with state-of-the-art watermarking schemes, is that they

are Symmetric. This means that the keys necessary for watermark embedding and

detection are identical. Thus, the watermark detector knows all critical parameter of

the watermarking scheme that also allows efficient removal of the embedded

watermark.

Figure 2.3 General Asymmetric Watermarking Schemes

The above Fig. depicts a general asymmetric watermarking scheme. With aid of a

private

and a public key, the watermark is embedded into the host signal(Original data) . The

significant difference to the symmetric scheme is that all entities, embedding, attack

and detection, have access to the public key necessary for watermark detection.

Obviously, an attacker can try to use the knowledge of the public key to destroy the

embedded watermark information. Here, public key and private key is used to embed

the watermark. Public key is used to detect and attack the watermark. So, without

knowledge of private key it is not possible to completely eliminate the embedded

watermark.

2.2.7 Fragile watermarking

A fragile mark is designed to detect slight changes to the watermarked image with

high probability.

A fragile watermark is a mark that is readily altered or destroyed when the host image

is modified through a linear or nonlinear transformation. Fragile marks are not suited

for enforcing copyright ownership of digital images; an attacker would attempt to

Embed Attack Detection

Data

Watermark Seq

Page 19: watermarking_newDoc

destroy the embedded mark and fragile marks are, by definition, easily destroyed. The

sensitivity of fragile marks to modification leads to their use in image authentication.

That is, it may be of interest for parties to verify that an image has not been edited,

damaged, or altered since it was marked.

Features of Fragile Marking Systems

Detect tampering.

Perceptual Transparency.

Detection should not require the original image.

Detector should be able to locate and characterize alterations made to a

marked image.

2.4.2 Malicious Attacks

Mallory may know that the data he has stolen contains a watermark, but he may try to

erase the watermark or try other means for claiming false ownership. The

watermarking system should protect Alice from various forms of Mallory’s malicious

attacks:

Bit Attacks :

The simplest malicious attack attempts to destroy the watermark by updating some

bits. Clearly, if Mallory can change all the bits, he can easily destroy the watermark.

However, he has also made his data completely useless. The effectiveness of an

attack should therefore consider the relationship between the numbers of bits that

Mallory and Alice change, since each change can be considered an error. Having

more errors clearly makes the data less useful.

A randomization attack assigns random values to some number of bit positions. A

zero out attack sets values of some number of bit positions to zero.

A bit flipping attack inverts the values of some number of bit positions. Note that

benign updates can also be modeled as a randomization attack.

Page 20: watermarking_newDoc

Rounding Attack Mallory may try to lose the marks contained in a numeric attribute

by rounding all the values of the attribute. This attack is not any better than the bit

attacks discussed above. Mallory has to correctly guess how many bit positions are

involved in the watermarking. If he underestimates it, his attack may not succeed. If

he overestimates it, he has degraded the quality of his data more than necessary. Even

if his guess is correct, his data will not be competitive against Alice’s data because his

data values are less precise.

A related attack will be one in which the numeric values are uniformly translated. For

example, Mallory may translate using units of measurement (e.g., imperial units to

metric units). Alice simply needs to convert the values back to the original system in

order to recover the marks. In general, Mallory can apply arbitrary translations to

numeric values. In this case, Mallory would also need to inform potential users of the

conversion used which could also be applied by Alice before detecting her

watermark. The unnecessary conversion would also raise suspicion among users.

Subset Attack Mallory may take a subset of the tuples or attributes of a watermarked

relation and hope that the watermark is lost.

Mix and Match Attack Mallory may create his relation by taking disjoint tuples from

multiple relations containing similar information.

Additive Attack Mallory may simply add his watermark to Alice’s watermarked

relation and claim ownership.

Invertibility Attack Mallory may launch an invertibility attack [7] to claim ownership

if he can successfully discover a fictitious watermark. Mallory’s claimed watermark

is in fact a random occurrence.

Horizontal Data Partitioning

Mallory can randomly select and use a subset of the original data set that might still

provide value for its intended purpose.

Page 21: watermarking_newDoc

Subset Addition

Mallory adds a set of tuples to the original data. This addition is not to significantly

alter the useful (from Mallory’s perspective) properties of the initial set versus the

resulting set.

Subset Alteration

Altering a subset of the items in the original data set such that there is still value

associated with the resulting set. In the categorical data framework, subset alteration

is intuitively quite expensive from a data-value preservation perspective. One has also

to take into account semantic consistency issues that become immediately visible

because of the discrete nature of the data.

Watermarking a Sample Image

Watermarking an image involves two steps to provide the original authentication and

the steps are

a) Embedding a watermark

b) Extracting a watermark

a) Embedding a watermark: -

Digital watermarking Using Fast Hadamard Transform

A great deal of research efforts has been focused on digital image

watermarking in the recent years. FHT (Fast Hadamard Transform) [15] is one of the

blind and symmetric digital watermarking technique.

Page 22: watermarking_newDoc

FHT is a robust and efficient digital image watermarking algorithm for copy right

protection of digital images. This algorithm can embed or hide entire image or pattern

as a watermark such as company’s logo or trademark directly into the original image.

Fast Hadamard transform (FHT) based watermarking approach that embeds grayscale

image as a watermark. The watermark grayscale image as a watermark. The

watermark grayscale image is decomposed into Hadamard coefficients for

embedding. To increase the invisibility of the watermark, a visual model based on the

original image characteristics, such as edges and textures are incorporated to

determine the watermarking strength factor.

This factor is used to scale the watermark coefficients to a similar range to the

coefficients from the Hadamard coefficients of the sub-blocks of the container image.

The FHT embedding algorithm was found to provide a robust and efficient approach

to perform digital watermarking of digital image data for copyright protection and

proof of rightful ownership. The simplicity of FHT offers a significant advantage in

shorter processing time and ease of hardware implementation than most orthogonal

transform techniques such as DCT and DWT.

3.1 2D-Hadamard transform of signal

The 2D-Hadamard transform has been used extensively in image processing

and image compression.

Let [U] represents the original image and [V] the transformed image, the 2D-

Hadamard transform is given by

[V]= Hn [U] Hn

N

Where Hn represents and NxN Hadamard matrix, N=2n, n=1, 2, 3….with

element values either +1 or -1.

Page 23: watermarking_newDoc

The advantages of Hadamard transform are that the elements of the transform

matrix Hn are simple: they are binary, real numbers and the rows or columns of H n are

orthogonal. Hence the Hadamard transform matrix has the following property:

Hn=Hn*=HT=H-1

Since Hn has N orthogonal rows HnHn=NI (I is identity matrix) and HnHn=NHnHn-1,

thus

H-1=Hn/N

The inverse 2D-fast Hadamard transform (IHFT) is given as

[U]=Hn-1[V]Hn*=Hn[V]Hn/N

The Hadamard matrix of the order n is generated in terms of Hadamard matrix of

order n-1 using Kronecker product , as

Hn = Hn-1 H1

Or

In our algorithm, the processing is performed based on 8x8 sub-blocks of the

whole image, the third order Hadamard transform matrix H3 is used.

Page 24: watermarking_newDoc

For a H3 matix,the no of transitions for row1 to row 8 is 0,7,3,4,1,6,2 and 5.The

number of sign changes is referred to as sequency .The concept of sequency is

analogous to frequency for the Fourier Transform. Zero sign transitions correspond to

a DC component. While a large number of sign transitions correspond to high

frequency components. For a Hadamard matrix H3, the elements are not arranged in

an increasing sequency, such that the transitions are 0,1,2,3,4,5,6 and 7.

3.2 Watermark Insertion process

Copyright information in the form of a trademark or logo can be used as an

image watermark. In the watermarking embedding process, the watermark image, w

(x, y) is first transformed into FHT coefficients .We use a grey scale image of size

64x64 as a watermark for our testing. As such, a Hadamard transformation matrix H6

is used. After transformation, 64x64 Hadamrd transform coefficients are obtained.

The DC component is stored in the key file and AC components are then selected for

embedding.

The original image, f(x,y) is also decomposed into a set of non-overlapped blocks of

hxh,denoted by fk(x’,y’),k=0,1,……..K-1,where the subscript k denotes the index of

blocks and K denotes total number of blocks. In our experiment, a test image of size

256x256and sub-block size of 8x8 is used.The algorithm pseudo-randomly selects the

sub-blocks for watermark insertion using an m-sequence random number generator.

Page 25: watermarking_newDoc

The seed of this m-sequence and initial state are also stored in the key file. After that,

a FHT is performed on each selected sub-blocks of original image. Since the sub-

block size is 8x8 a Hadamard transform of matrix size H3 is used. For each 8x8 sub-

block, 64 Hadamard transform coefficients are obtained.

Let the watermark FHT coefficients denote by m i.The AC components of FHT

coefficients of the original image sub-blocks, before and after inserting watermark

are denoted by xi and xi* respectively. Where i Є (0, n], with n the number of

watermarked co-efficients.The embedding formula is

Xi*=Bmi

3.3 Watermark Detection

The original coefficient Xi is replaced by Xi*.After the watermark

insertion, a new 8x8 matrix of FHT coefficients is obtained. The IFHT is then applied

to the 8x8 matrix using equation(3) to obtain the luminance value matrix of the

watermarked image sub-block,fk’(x’,y’).After performing the watermark insertion for

all the relevant sub-blocks of the original image, the watermarked image,f’(x’,y’) is

obtained. At the same time, a key file is also generated, which is needed for the

decoding process. The image-in-image watermark embedding process is shown in

below figure.

Original Image watermark watermarked image

Figure 3.1 Watermark embedding process

b) Extracting Watermark: -

+LOGOImage Image

Page 26: watermarking_newDoc

The Watermark is extracted by using the embedding position and the

watermark strength factor B. Let the received watermarked image denoted by

f’’(x,y).The information of watermark embedded sub-blocks’ position is extracted

from the seed of m-sequence and initial state number stored in the key file. By

transforming all the relevant sub-blocks ,fk’’(x’,y’),into the FHT domain, we obtain

all the Hadamard transform coefficients embedded with the watermark. For example,

in each of the sub-block FHT coefficients, the watermark bits are inserted into the

bottom right sixteen middle and high frequency components. Let these components

denote by xi*’,the retrieved watermark FHT coefficients denote by mi

’,where i Є

(0,n],and the number of the watermarked co-efficient n=16.The watermark extraction

formula is given as:

mi’= xi

* / B

The watermark FHT coefficients are extracted from all the sub-blocks of

original image. Along with the DC component stored in the key file, the AC

coefficients are rearranged into a 64x64 FHT coefficients matrix. The extracted

watermark image, w’(x, y), is obtained by IFHT of the 64x64 Hadamard coefficients

matrix using equation (3).

3.4 Watermark Strength Factor

The determination of the watermark strength factor is based on the original

image textures and edges characteristic. The classification of different areas is based

on the Hadamard transformed space energy analysis and canny edge detection

algorithm. The first visual mask model is determined by the Hadamard transformed

space image energy distribution. The analysis is performed on the FHT coefficients of

sub-blocks for watermarking. For coarse texture and outstanding edge areas, most of

the signal energy is concentrated in the AC components of the Hadamard transform

for smooth areas, the energy is mainly concentrated in the low AC and DC

components.

Page 27: watermarking_newDoc

We use a squared sum of AC components to generate this visual mask,

mask1 (j, k) to distinguish the smooth and coarse texture areas.

The canny edge algorithm was selected because of its ability in detecting

weak edges by using two different thresholds. it is applied to each selected sub-blocks

of the original image used for watermarking. Counting the number of edge points in

each sub-block, we obtain another visual mask, mask2 (j, k).This mask is used to

determine the coarse texture or outstanding edge in the image block. Large values in

this mask indicate that the corresponding block is highly textured. Smaller values

indicate that the block contains outstanding edges .The two mask values are

multiplied and scaled to a specific range. The water mark strength factor B is

obtained as follows:

B=b*mask1 (j, k)*mask2 (j, k)

Where b is scaling factor, j and k indicate the positions of the sub-blocks.

3.5 Advantages

FHT watermarking algorithm does not require the original information at the

watermark identification stage. This is blind or public digital watermarking.

Shorter processing time and the easy of hardware implementation than many

common transform techniques.

Page 28: watermarking_newDoc

FEASIBILITY ANALYSIS

Feasibility study is an important phase in the software development process.

It enables the developer to have an assessment of the product being developed. It

refers to the feasibility study of the product in terms of out comes of the product,

operational use and technical support required for implementing it.

Feasibility study should be performed on the basis of various criteria and

parameters. The various feasibility studies are:

Economic Feasibility

Operational Feasibility

Technical Feasibility

Economic Feasibility

It refers to the benefits or outcomes we are deriving from the product as

compared to the total cost we are spending for developing the product. If the benefits

are more or less the same as the older system, then it is not feasible to develop the

product.

Operational Feasibility

It refers to the feasibility of the product to be operational. Some products may

work very well at design and implementation but may fail in the real time

environment. It includes the study of additional human resource required and their

technical expertise.

Technical Feasibility

It refers to whether the software that is available in the market fully supports

the present application. It studies the pros and cons of using particular software for

the development and its feasibility. It also studies the additional training needed to be

given to the people to make the application work.

Page 29: watermarking_newDoc

7. SOFTWARE REQUIREMENT SPECIFICATION

What is SRS?

Software Requirement Specification (SRS) is the starting point of the software

developing activity. As system grew more complex it became evident that the goal of

the entire system cannot be easily comprehended. Hence the need for the requirement

phase arose. The software project is initiated by the client needs. The SRS is the

means of translating the ideas of the minds of clients (the input) into a formal

document (the output of the requirement phase.)

The SRS phase consists of two basic activities:

1) Problem/Requirement Analysis:

The process is order and more nebulous of the two, deals with understand the

problem, the goal and constraints.

2) Requirement Specification:

Here, the focus is on specifying what has been found giving analysis such as

representation, specification languages and tools, and checking the specifications are

addressed during this activity.

The Requirement phase terminates with the production of the validate SRS document.

Producing the SRS document is the basic goal of this phase.

Role of Srs:

The purpose of the Software Requirement Specification is to reduce the

communication gap between the clients and the developers. Software Requirement

Specification is the medium though which the client and user needs are accurately

specified. It forms the basis of software development. A good SRS should satisfy all

the parties involved in the system.

Page 30: watermarking_newDoc

PURPOSE:

The purpose of this document is to describe all external requirements for the

JDBC Editor. It also describes the interfaces for the system.

SCOPE:

This document is the only one that describes the requirements of the system. It

is meant for the use by the developers, and will also by the basis for validating the

final delivered system. Any changes made to the requirements in the future will have

to go through a formal change approval process. The developer is responsible for

asking for clarifications, where necessary, and will not make any alterations without

the permission of the client.

Page 31: watermarking_newDoc

DIAGRAMS

CLASS DIAGRAMS :-

1) FHTDigitalWatermarking.java

2) ImageBuilt.java

Page 32: watermarking_newDoc
Page 33: watermarking_newDoc

OBJECT DIAGRAMS:-

:FHTDigitalWatermarking

fname : String

ib:ImageBuild

img : Imageimg2 : Image

Page 34: watermarking_newDoc

USECASE DIAGRAMS:-

WatermarkInsertion

randomNumberGeneration

performFHTOnWatermark

performFHTOnOriginal

Original

InsertWatermark

PerformIFhtOnOriginal

check

loading

performFHTOnOriginal

PerformIFHTOnWatermark

paint

WatermarkExtraction

Close

Page 35: watermarking_newDoc

SEQUENCE DIAGRAMS:-

Insertion Sequence Diagram:-:FHTDigitalWaterma...

ib:ImageBuilt

wm:int[256] k:int[100] opixels:int[65536]

flag:boolean

iwm:int[10] out:FileOutputS...

displayrseq:int[100]

keyfile.datcount

show()actionPerformed()

performFHTOnWatermark()

performFHTOnOriginal()

randomGeneration()

check()

false

k++ true

insertWaterMark() 0 < wm[i] < -99999 count<10 iwm[count]

0>wm[i]>-99999 & count>10

writeInt(0)

writeInt(wm[i])

i<256

opixel[]+iwm[j]%100-opixel[]-iwm[j]%100

iwm[j]!=0

j<10j>10

performIFHTOnOriginal()

loading()

k<100

Page 36: watermarking_newDoc

2)Extraction Sequence Diagram:-

Page 37: watermarking_newDoc

wm2:int[256]

ib:ImageBuilt

rev:int opixels:int[65536]

i6:int int:i2 rseq:int[100]

i:int in:FileInputSt...

displaycount2:intcount1:int keyfile.dat

performFHTOnOriginal()

readInt()wm2[i]wm2[i]=0

opixels[i2]

i6=(i6+opixels[i2])*100count1++ count2++

i6=0

rseq[count2]

count1>2i6=i6%100

rev=0

rev=rev*100+i6

i6=i6/100i6!=0

i6=0rev =rev *-1

wm2[i]=revi++

count1< 3i > 256

i > 256performIFHTOnWatermark( )

paint( )

TECHNOLOGIES

One of the most difficult tasks is that, the selection of the software, once

system requirement is known is determining whether a particular software package

fits the requirements. After initial selection further security is needed to determine the

desirability of particular software compared with other candidates. This section first

Page 38: watermarking_newDoc

summarizes the application requirement question and then suggests more detailed

comparisons.

Java,

AWT,

SWINGS.

JAVA

Java technology is both a programming language and a platform.

The Java Programming Language

The Java programming language is a high-level language that can be

characterized by all of the following buzzwords:

Simple Architecture neutral

Object oriented Portable

Distributed High performance

Interpreted Multithreaded

Robust Dynamic

Secure

With most programming languages, you either compile or interpret a

program so that you can run it on your computer. The Java

programming language is unusual in that a program is both compiled

and interpreted. With the compiler, first you translate a program into

an intermediate language called Java bytecodes —the platform-

independent codes interpreted by the interpreter on the Java platform.

The interpreter parses and runs each Java bytecode instruction on the

computer. Compilation happens just once; interpretation occurs each

time the program is executed.

Page 39: watermarking_newDoc

You can think of Java bytecodes as the machine code instructions for

the Java Virtual Machine (Java VM). Every Java interpreter, whether

it's a development tool or a Web browser that can run applets, is an

implementation of the Java VM.

Java bytecodes help make "write once, run anywhere" possible. You

can compile your program into bytecodes on any platform that has a

Java compiler. The bytecodes can then be run on any implementation

of the Java VM. That means that as long as a computer has a Java VM,

the same program written in the Java programming language can run

on Windows 2000, a Solaris workstation, or on an iMac.

The Java Platform

A platform is the hardware or software environment in which a

program runs. We've already mentioned some of the most popular

platforms like Windows 2000, Linux, Solaris, and MacOS. Most

platforms can be described as a combination of the operating system

and hardware. The Java platform differs from most other platforms in

that it's a software-only platform that runs on top of other hardware-

based platforms.

The Java platform has two components:

The Java Virtual Machine (Java VM)

The Java Application Programming Interface (Java API)

You've already been introduced to the Java VM. It's the base for the

Java platform and is ported onto various hardware-based platforms.

The Java API is a large collection of ready-made software components

that provide many useful capabilities, such as graphical user interface

Page 40: watermarking_newDoc

(GUI) widgets. The Java API is grouped into libraries of related

classes and interfaces; these libraries are known as packages.

Native code is code that after you compile it, the compiled code runs

on a specific hardware platform. As a platform-independent

environment, the Java platform can be a bit slower than native code.

However, smart compilers, well-tuned interpreters, and just-in-time

bytecode compilers can bring performance close to that of native code

without threatening portability.

Creation of Java:

Java was conceived by James Gosling, Patrick Naughton, Chris Warth,

EdFrank and Mike Sheridan at SUN Micro systems Incorporation in 1991. It took 18

months to develop the first working version. This language was initially called

"OAK", but was renamed "JAVA" in 1995. Before the initial implementation of Oak

in 1992 and the public announcement of Java in 1995, many more contributed to the

design and evolution of the language.

Java is developed in year 1990 by “Sun micro system” to develop special soft

wear that is used to manipulate censurer electronic drivers. In year 1992 “Green

project team” win micro system, demonstrated the application of their new language

to control list of home application (or) appliances to handle device with any they

touch screen. In year 1993 www(world wide web) appeared on the internet and

transformed the text – based internet in to graphical –rich environment. The green

project team come up with the idea of developing web applets, using the new

language. In year 1994 the “green project team” developed a web browser called “Hot

Java” demonstrated the power of the new language. In year 1996, java established it

self-not only as a leader for Internet programming, but also as general purpose, object

– oriented programming language.

Page 41: watermarking_newDoc

JAVA FEATURES

The invents of java wanted to design language which could offeg solution to

the problems encovntcged in modern programming “win micro systems” officially

describes java with the following categories

Completed & integrated

Platform– independent and portable.

Object – oriented

Robust and secure.

Distributed.

Timelier, simple and smell.

Multithreaded and interactive.

High performance.

Dynamic &Extensible.

Completed and Integrated:

Usually a computer language is either completed (&) interrogated.

Java combines both these approaches, this making java two-stage system. Java

compiler translates source code in to know by to code instruction. Java interpreter

generates machine code that can be directly executed by the machine that is running

the java program.

Platform – independent & portable :-

Java programs can be easily moved from one computer system to another,

anywhere and any time. Changes and upgrades in operating systems, processor and

system resources will not trice any changes in java programs. We can download a

java Internet &execute it locally. Java ensures portalrility in two ways. First, java

compiler generates byte code instruction that can be implemented on any machine –

independent.

Page 42: watermarking_newDoc

Object-Oriented:

Java is a true object – language, every thing in java is an Object. 411 program

code and data resides within object and classes. The object model in java is simple

and easy to extend.

Robust and secure:

Java is a robust language. It provides many safeguards to ensure reliable code.

It has strict compiled time and run time checking for data types. It is designed as a

garbage collected language relieving the programmers virtually all memory

management problems. java also in cooperates in concept of expectation handling

which captures series errors and eliminates any risk of crashing the system. Security

becomes an important issue for language that is use for programming on internet.

Threat of viruses and abuse of resources every where. Java systems not only verify all

memory access but also ensure that viruses are communicated with an applet. The

absence of pointers in java ensures that programs cannot gain access to memory

locations with out proper authorization.

Distributed:

Java is designed as a distributed language for creating applications on

networks. It has the ability to shear both data and programs. Java application can open

and access remote object on internet as easily as they can do in a local system. This

enables multiple programmers at multiple remote locations to collaborate and work

together on a single project.

Simple, small and familiar :

Java is a small and simple language. Many features of C & C++ that are either

redundant or sources of unreliable code or not part of java. For example, java dose

not use pointers, preprocessor header files, goto statement and many others. It also

Page 43: watermarking_newDoc

eliminates operator overloading and multiple inheritance. For more detailed

comparison of java with C & C++, refer to section 2,3.

Familiarity is another striking feature of java. To make the language look

familiar to the existing programmers, it was modeled on C & C++ languages. Java

uses many construets of C &C++ and therefore, java code “looks like a C++” code. In

fact, Java is a simplified version of C++.

Multithreaded and Interactive :

Multithreaded means handling multiple tasks simultaneously. Java supports

multithreaded programs. The means that we need not wait for the application to finish

one task before beginning another. For example, we can listen to an audio clip while

scrolling a page and at the same time download an applet from a distant computer.

This feature greatly improves the interactive performance of graphical applications.

The java runtime comes with tools that support multiprocess synchronization and

construct smoothly running interactive systems.

Java Overview:

Java is a powerful but lean object oriented programming language. It

has generated a lot of excitement because it makes it possible to program for internet

by creating applets, programs that can be embedded in web page.

The context of an applet is limited only by one's imagination. For

example, an applet can be animation with sound, an interactive game or a ticker tape

with constantly updated stock prices. Applets can be serious application like work

processor or spreadsheet.

But Java is more than a programming language for writing applets. It

is being used more and more for writing standalone applications as well. It is

becoming so popular that many people believe it will become standard language for

both general purpose and Internet programming. There are many buzzwords

Page 44: watermarking_newDoc

associated with Java, but because of its spectacular growth in popularity, a new

buzzword has appeared ubiquitous. Indeed, all indications are that it will soon be

every where.

Java builds on the strength of C++. It has taken the best features of C+

+ and discarded the more problematic and error prone parts. To this lean core, it has

added garbage collection (automatic memory management), multithreading (the

capacity for on program to do more than one thing at a time), security capabilities.

The result is simple, elegant, powerful and easy to use.

Java is actually a platform consisting of three components:

1. Java programming Language.

2. Java Library of Classes and Interfaces.

3. Java Virtual Machine.

The following sections will say more about their components:

Java is Portable:

One of the biggest advantages Java offers is that it is portable. An application

written in Java will run on all the major platforms. Any computer with a Java based

browser can earn the applications or applets written in the Java Programming

Language. A programmer no longer has to write one program to run on a Macintosh,

another program to run on a windows machine, still another to run on a UNIX

machine, and so on. In other words, with Java, developer writes their programs only

once. The virtual machine is what gives Java is cross platform capabilities. Rather

than being compiled into machine language, which is different for each operating

systems and computer architecture, Java code is compiled into byte codes.

With other languages, the program can understand. The problem is

that other computers with different machine instruction set cannot understand that

language. Java code, on the other hand it is compiled into byte codes rather than a

machine language. These byte codes go to the Java virtual machine, which executes

Page 45: watermarking_newDoc

them directly or translate them into the language that is understood by the machine

running it.

In summary, these means that with the JDBC API extending Java, a

programmer writing Java code can access all the major relational databases on any

plat form that supports the Java virtual machine.

Java Is Object Oriented:

The Java programming language is object orients, which makes

program design focus on what you are dealing with rather than on how you are going

to do something. This makes it more useful for programming in sophisticated

projects because one can break the things down into understandable components. A

big benefit is that these components. A big benefit is that these components can then

be reused.

Object oriented languages use the paradigm of classes. In simplest

term, a class includes both the data and the functions to operate on the data. You can

create an instance of a class, also called an object, which will have all the data

members and functionality of its calls. Because of this, you can think of a class as

being like template, with each object being a specific instance of a particular type of

class. The class paradigm allows one to encapsulate data so that specific data values

are function implementation cannot be seen by those using the data. Encapsulation

makes it possible to make the changes in code without breaking other programs that

use that code. If for example the implementation of a function is changed, the change

is invisible to the another programmer who invokes that function, and it does not

affect his/her program, except hopefully to improve it.

Java includes inheritance, or the ability to derive new classes from

existing classes. The derived class, also called a subclass, inherits all the data and the

functions of the existing class referred to as the parent class. A subclass can add new

data members to those inherited from the parent class. As far as methods are

Page 46: watermarking_newDoc

concerned, the subclass can reuse the inherited methods, as it is, change them, and/or

add its own new methods.

Java Makes It Easy To Write Correct Code:

In addition to being portable and object oriented, Java facilitates writing

correct code. Programmers spend less time writing Java code and a lot less time

debugging it. In fact, developers have reported slashing development time by as

much as two thirds. The following is a list of some of Java's features that make it

easier to write correct code.

Garbage Collection:

Automatically takes care of allocating and reallocating memory, a

huge potential source of errors. If an object is no longer being used (has no

references to it), then it is automatically removed from memory, or "Garbage

Collected" programmers don't have to keep track of memory. Dynamic binding is

possible and often very useful, but static binding with strict type checking is used

when possible.

Simplicity:

Makes Java easier to learn and use correctly. Java keep it simple by

having just one way to do something instead of having just one way to do something

instead of having several alternatives, as in some languages. Java also stays lean by

not including multiple inheritance, which eliminate the errors and ambiguity that arise

when you create a subclass that inherits from two or more classes.

To replace capabilities, multiple inheritance provides, Java lets you add

functionality to a class throws the use of interfaces.

Page 47: watermarking_newDoc

Java Includes a Library of Classes and Interfaces:

The Java platform includes an extensive class library so that

programmers can use already existing class as it is, create subclasses to modify

exiting classes, or implement interfaces to augment the capabilities of classes. Both

classes and interfaces contain data members (fields and functions (methods), but there

are major differences. In a class, fields may be either variable or constant, and

methods are fully implemented. In an interface, fields must be constants, and

methods are fully implemented. In an interface, fields must be constants, and

methods are just prototypes with no implementations. The prototypes give the

method signature (the return type, the function name, and the number of parameters

with the type for each parameter), but the programmer must supply implementations.

To use an interface, and then implements all the methods in that interface as

part of the class. These methods are implemented in a way that is appropriate for the

class in which the methods are being used. Interfaces let one add functionality to a

class and give a great deal of flexibility in doing it. In other words interfaces provide

most of the advantages of multiple inheritance without its disadvantages.

A package is a collection of related Java classes and interfaces. The

following list, though not complete, gives example of some Java packages and what

they cover.

Java.lang---- The basic classes. This package is so basic that it automatically

is included in any Java program. It includes classes dealing with numeric, strings,

objects, runtime, security, and threads.

Java.io---- Classes that manage reading data from input streams and writing

data to the output streams.

Page 48: watermarking_newDoc

Java.util---- Miscellaneous utility classes, including generic data structures, bit

sets, time, date, the string manipulation, random number generation, system

properties, notification and enumeration of data structures.

Java.net---- Classes that manage user interface components such as windows,

dialog boxes, buttons, checkboxes, lists, menus, scrollbars, and text fields, the

"AWT" stands for Abstract Window Toolkit.

Java.awt.image---- Classes for managing image data, including color models,

dropping color flittering, setting pixels values, and grabbing snapshots.

Java.applet---- The Applet class, which provides the ability to write applets,

this package also, includes several interfaces that connect an applet to its documents

and to its document and to recourses for playing audio.

Java.sql---- The JDBC API, classes and interfaces that access databases and

send SQL Statements. The first three packages listed, Java.lang, Java.io and Java.util

form the Foundation, they are basic classes and interfaces for general purposes

programming, Java development kit version 1.2 added some new packages, with

JDBC being one of them. Other new packages include such thing as Remote Method

Invocation, Security and Java Beans the new API for creating resizable components.

In Java, packages server as the foundation for building other packages,

As discussed in the following section.

Java Is Extensible:

A big plus for Java is the fact it can be extended. It was purposely

written to be lean with the emphasis on doing what it does very well; instead of trying

Page 49: watermarking_newDoc

to do everything from the beginning, it was return so that extending it is very easy.

Programmers can modify existing classes for write their own new classes or they can

write a whole new package. The JDBC API, the Java.sql package, is one example of

a foundation upon which extensions are being built. Other extensions are being

added or worked on in area such as multimedia, Internet Commerce, conferencing,

and telephony. In addition to extensions there are also main tools being developed to

make existing capabilities easier to use. For example, there is already a tool that

greatly simplifies creating and laying out Graphical User Interfaces such as menus,

Dialog boxes and buttons.

Java Is Secure:

It is important that a programmer not be able to write subversive code

for Applications or applets. This is especially true with the Internet being used more

extensively for services such as electronic commerce and electronic distribution of

software and multimedia content. The Java platform builds in security in four ways.

The way memory is allocated and laid out

In Java an object’s location in memory is not determined until The runtime, as

opposed to C and C++, where the compiler maker memory layout decisions. As the

result, a programmer can not look at a class definition and figure out how it might be

laid out in memory. Also since, Java has no pointers, a programmer can not forge

pointers to memory.

The way incoming code is checked. The Java virtual machine doesn’t

trust any incoming code and subjects it to what is called byte code verification. The

Byte code Verifies, part of the virtual machine, checks that

A: The format of incoming code is correct

B: Incoming code doesn’t forge pointers

C: It doesn’t violate access restrictions

D: It accesses objects as what they are.

Page 50: watermarking_newDoc

The way classes are loaded. The Java byte code loader, another part of the

virtual machine, whether classes loaded during program execution are local or from

across a Network. Imported classes cannot substitute for built in classes, and built in

classes cannot accidentally reference classes bring in over a network.

The way access is restricted for untested code: The Java security

manager allows user to restrict untested Java applets so that they cannot access the

local network, files and other resources.

Java Performs Well:

Java performance is better than one might expect. Java’s many

advantages such as having built in security and being interpreted as will as compiled,

do have a cost Attached to them. However, various optimizations have been built in,

and the byte code Interpreter can run very fast the cost it doesn’t have to do may

checking. As a result, Java has done quite respectably in performance tests. Its

performance numbers for interpreted Byte codes are usually more than adequate to

run interactive graphical end user applications.

For situations that require unusually high performance, byte codes can

be translated on the fly, generating the final machine code for the particular CPU on

which the application is running at run time. High levels interpreted scripting

language generally offer great portability and fast prototyping but poor performance.

Low level compiled language like C and C++ offer great performance but

require large amounts of time for writing and debugging Code because of problems

with areas such as memory management, pointers and multiple inheritance. Java

offers good performance, with the advantages of high level Languages but without

the disadvantages of C and C++. In the world of design trade-off, you can think of

Java as providing a very attractive middle ground.

Page 51: watermarking_newDoc

Java Is Robust:

The multi platform environment of WEB places extraordinary

demands on a program, because it must execute reliably in a variety of systems. Thus

the ability to create robust programs was given a high priority in the design of Java.

To gain reliability, Java restricts you in a few key areas to force you to find mistakes

early in program developments. At the same time, Java frees you from having to

worry about many of the most common cause of programming errors. Because Java

is strictly typed language, it checks your code at compile time.

However, it also checks your code at run time. In fact, many hard to track

down bugs that often turn up in hard to reproduce runtime situations are simply

impossible to create in Java. Knowing that what you have written will behave in a

predictable way under diverse conditions is a key feature of Java to understand how

Java robust, consider two main reasons for program failure: Memory management

mistakes and mishandled exceptional conditions (run time errors).

Memory management can be difficult, tedious task in traditional programming

environments. For example in C/C++ the programmer must manually allocate and

free all dynamic memory. This sometimes leads to problems. For example some

programmers some times forget the free memory that has been previously allocated.

Or worse, they may free some memory that another part of their code is still using.

Java virtually eliminates these problems by managing memory allocations

and reallocations. Java helps in this area by providing object oriented exception

handling. In a well-written Java program a program should manage all run time

errors.

Java Scales Well:

Java platform is designed to scale well, from portable consumer

electronic devices to powerful desktop and server machines. The virtual machine

takes a small footprint and Java accommodates the need for low storage and for low

Page 52: watermarking_newDoc

bandwidth transmission over the Internet. In addition the Java operating system

offers a standalone Java platform that eliminates host operating system overhead

while still supporting the full Java platform API. This makes Java ideal for low cost

network computers whose sole purpose is to access the Internet.

Java Is Multi Threaded:

Multithreading is simply the ability of a program to do more than one

thing at a time. For example an application could be faxing a document at the same

time it is printing another document. Or a program could process new inventory

figures while it maintains a feed for current prices. Multithreading is particularly

important in multimedia; a multimedia program might often be running a movie,

running an audio track and displaying text all at the same time.

Java Is Important To the Internet:

The Internet helped catapult Java to the forefront of programming and

Java in turn has a profound effect on the Internet. The reason is simple: Java expands

the universe of objects that can move about freely in cyberspace. In a network, there

are two broad categories of objects transmitted between the server and your personal

Computer. Passive information and dynamic, active programs. For example, when

you read your e-mail, you are viewing passive data. Even when you download a

program, the program’s code is still only passive data until you execute it.

However, there is a second type of object that can be transmitted to your

computer. A dynamic, self-executing program. Such a program would be an active

agent on the client computer, yet the server would initiate it. As desirable as

dynamic, networked programs are, they also present serious problems in the areas of

security and portability. Prior to Java cyberspace was effectively closed to half the

entities that now live there. Java addressed these concerns and doing so, has opened

the door to an exiting a new form of program.

Page 53: watermarking_newDoc

Exception Handling:

An exception is an abnormal condition that arises in a code sequence

at run time. In other words, an exception is a run-time error.

Exception-Handling Fundamentals:

A Java exception is an object that describes an exceptional (that is,

error) condition that has occurred in a piece of code. When an exceptional condition

arises, an object representing that exception is created and thrown in the method that

caused the error.

Exceptions can be generated by the Java run-time system, or they can be

manually generated by your code. Exceptions thrown by Java relate to fundamental

errors that violate the rules of the Java language or the constraints of the Java

execution environment. Manually generated exceptions are typically used to report

some error condition to the caller of a method.

Java exception handling is managed via five keywords: try, catch, throw,

throws and finally.

Program statements that you want to monitor for exceptions are contained

within a try block. If an exception occurs within, the try block, it is thrown. Your

code can catch this exception (using catch) and handle it in some rational manner.

System-generated exceptions are automatically thrown by the Java run-time system.

To manually throw an exception, use the keyboard throw. Any exception that is

thrown out of a method must be specified as such by a throws clause. Any code that

absolutely must be executed before a method returns is put in a finally block.

Exception Types:

Page 54: watermarking_newDoc

All exception types are subclasses of the built-in class Throwable. Throwable

is at the top of the exception class hierarchy. Throwable are two subclasses that

partition exceptions into two distinct branches. One branch is headed by Exception.

There is an important subclass of Exception, called Run-time Exception. The

other branch is topped by Error, which defines exceptions that are not expected to be

caught under normal circumstances by your program.

Throw:

It is possible for your program to throw an exception explicitly, using the

throw statement. The general form of throw is shown here.

Throw Throwable Instance.

Throwable Instance must be an object of type Throwable or a subclass of Throwable.

There are two ways you can obtain a Throwable object: using a parameter into a

catch, or creating one with the new operator.

The flow of execution stops immediately after the throw statement, any subsequent

statements are not executed.

Throws:

A Throws clause lists the types of exceptions that a method might throw. This

is necessary for all exceptions, except those of type Error of Runtime Exception, or

any of their subclasses.

Other exceptions that a method can throw must be declared in the

throws clause, if they are not, a compile-time error will result.

This is the general form of a method declaration that includes a throws

clause.

Page 55: watermarking_newDoc

Type method-name (parameter-list) throws exception-list

{

//body of method

------------------

------------------

}

Finally:

The finally block will execute whether or not an exception is thrown. If an

exception is thrown, the finally block will execute even if no catch statement matches

the exception. Any time a method is about to return to the caller from inside a

try/catch block, via an uncaught exception or an explicit return statement, the finally

clause is also executed just before the method returns.

The finally clause is optional. However, each try statement requires at least

one catch or a finally clause.

Java’s Built Exceptions:

Exception Meaning

Arithmetic Exception Arithmetic error, such as divide-by-zero.

Array Index Out of bounds Exception Array index is out-of-bounds.

Array Store Exception Assignment to an array element of an Incompatible

type.

Class Cast Exception Invalid cast.

Illegal Argument Exception Illegal argument used to invoke a method.

Index Out of Bounds Exceptions Some type of index is out-of-bounds.

Page 56: watermarking_newDoc

Negative Array size Exception Array created with a negative size.

Null Pointer Exception Invalid use of a null reference.

Number format Exception Invalid conversion of a string a numeric format.

Security Exception Attempt violate security.

String Index Out Of Bound Attempt to index outside the bounds of a string.

Class not Found Exception Class not found.

Illegal Access Exception Access to a class is denied.

Instantiation Exception Attempt to create an object of an abstract Class

or interface.

No Such Field Exception A requested field does not exist.

No Such Method Exception A requested method does not exist.

Creating Your Own Exception Sub Classes:

Although Java’s built-in exceptions handle most common errors, you

will probably want to create your own exception types to handle situations specific to

your applications. This is quite easy to do: just define a subclass of Exception (which

is of course, a subclass of Throwable).

The Exception class does not define any methods of its own.

Using Exception:

Page 57: watermarking_newDoc

Exception handling provides a powerful mechanism for controlling

complex program’s that have many dynamic run-time characteristics. It is important

to think of try, throw, and catch as clean ways to handle errors and unusual boundary

conditions in your program’s logic.

An introduction to Java that will help Java newbies to become Java developers:

High-level overview of Java

Java is a general-purpose, object-oriented language that looks a lot like C and C++.

Its design, however, was built on those of its predecessors, making it easier, safer, and

more productive than C++. While Java started out as a niche language for developing

applets or small programs that run in Web browsers, it has evolved to arguably

become the most important programming language for developing ecommerce and

other Web-driven applications. Its area of use is growing daily and includes dynamic

Web-content generation with servlet technology, the building of business components

with Enterprise JavaBeans, the creation of cross-platform user interfaces with Swing,

and much more. Portable, distributed, multitier, object-oriented programs driven by

the Web are the order of the day, and there is no language better than Java for writing

these programs.

The Java Virtual Machine

Let's take a look at a central component of the Java architecture, the Java Virtual

Machine (JVM). The JVM is what gives Java its cross-platform functionality and

many of its security and safety capabilities. The JVM is basically an abstract

computer implemented in software. I'll focus mainly on its instruction set, which is

called bytecode. Bytecode is an intermediate language between Java source and the

target computer you want to run on. The following figure demonstrates how it works

at a very high level.

From Java source to bytecode to host machine code

* Programs are written in Java and stored in .java files (for example, MyClass.java)

Page 58: watermarking_newDoc

* The .java files are compiled by the Java compiler into bytecode and stored in .class

files (for example, MyClass.class)

* The JVM loads the bytecode (the .class files), performs some checks on it, and then

converts it to the machine code of the target platform that executes it

This is where Java gets its platform independence. The bytecode format is the same

on all platforms because it runs in the same abstract machine -- the JVM. As long as

there is a JVM on any given platform, you can run Java on it. There's an old saying in

computer programming, "You can solve any problem with another level of

indirection." The JVM and bytecode together is another level of indirection.

That's about it on the JVM for now. If you want to know more, check out Sun's JVM

specification in the Resources section below.

Setting up Java on your system

The first thing you need is the Java 2 Software Development Kit or SDK (formerly

known as the Java Development Kit, or JDK). This is a set of software and software

tools supplied by Sun that includes all of the basic components needed to build Java

programs. If you don't have this, you'll need to download the Java 2 SDK from Sun

(see Resources below). Here's a brief description of what you need to do to install

version 1.2.x for the Windows platform:

* For Windows, the download will be a self-extracting archive, and the file name

follows the form: jdk<version>-win.exe. For example, for version 1.2.2, the file is

named jdk1_2_2-win.exe.

* Execute the program to install the Java 2 SDK.

* You can execute it by typing its name at a command prompt.

* You can double-click it from Explorer.

* On Windows, the default installation directory is C:\JDK1.2.x

* You must set up your environment correctly

* Your path must be set to include the bin subdirectory

Page 59: watermarking_newDoc

* For example, if you installed the Java 2 SDK in C:\JDK1.2.x, you must

include C:\JDK1.2.x\bin in your path

* If you are using Windows 95/98, you can do this in autoexec.bat

* If you are using Windows NT, go to Control Panel, System, Environment

* You can set environment variables in the dialog box there

* There are other parts of the environment that are important, especially the

CLASSPATH environment variable. I'll discuss this in future columns.

* It's also important to download the javadoc HTML documentation for the core API

classes. This is a separate download, in zip format, and the filename is in the form of

jdk<version>-doc.zip (for example, jdk1_2_2-doc.zip).

* The javadoc HTML documentation should be unzipped into the Java 2 SDK

installation directory

* Note that the zip file has a directory structure within it, so that unzipping it into C:\

will place all of the files at the root directory C:\JDK1.2.x\docs, which is a good place

for them.

The following tools will be used to create and run our first program:

* javac: the Java compiler that converts Java source to bytecode

* java: the Java Virtual Machine

How to write a Java program

OK, it's time to write our first Java program. A Java program looks like this:

public class MyProgram {

public static void main(String[] args) {

System.out.println(

"Eureka, I can put Java on my resume.");

}

}

Page 60: watermarking_newDoc

A Java program is a class with a main method in it. The main method is a special

method that is the starting point for every Java application. It has to be declared

exactly as above, and it has to appear within a class, as the above example also

shows. System.out.println is the magic incantation you use to get things sent to the

console.

This code example is for a standalone, nongraphical Java program that prints the

string Eureka, I can put Java on my resume. to the console. Your salary can double

now, so if you want, you can stop here. Those that want to learn more can keep going.

Type the above program into a file named MyProgram.java. It's a good idea to put it

in its own directory just to keep things organized. Use your favorite text editor for

this, or check out the Resources section for some of my favorites. Once you've done

that, go to a command line that is open to the location your file is in.

Type in the following code to compile the file. (This generates the .class

file from the .java file):

javac MyProgram.java

Once it compiles without errors, do a directory listing to see that you've generated a

MyProgram.class file. (Hey -- that's the bytecode.)

Now type the following to run the program:

java MyProgram

This executes the JVM, and makes it run the bytecode in the MyProgram.class file.

You should see the following output on your screen:

Eureka, I can put Java on my resume.

Congratulations! You've generated your first Java program.

There are a couple of things you should notice. The Java compiler (javac) requires

that you include the .java extension for the files you're compiling. It's just a program,

and that's what it expects you to give it. The JVM (java) does not expect you to

Page 61: watermarking_newDoc

include the .class extension. Try typing java MyProgram.class, and you'll get an error

message because it will look for a file called MyProgram.class.class. Note also that

things are set up in such a way that you have to do everything from one directory.

Object-oriented programming (OOP)

Object-oriented programming is the key organizational factor in using Java well.

Simply put, this means that you organize your program around objects. What's an

object? It's a representation of some concept or thing. This is a powerful model

because it reflects the way we think about the world, and the way we conceptualize it

using language.

Here are the key characteristics that define an object:

* Behavior: What an object can do, or what can be done to it

* Properties: Data or information associated with an object (often called state)

* Type: The kind (or class) of thing an object is

* Identity: The unique existence of every object, independent of its characteristics

You might see object described elsewhere using different terminology, but don't

worry too much about that. Grasping the concepts is the important thing.

Let's further explore the notion of type. We're almost always dealing with many

different objects, and the natural inclination is to classify or label them in some way.

A type is the way to classify objects, and it's also the blueprint that defines the

behavior and properties for objects of a certain type.

Here are some real-world examples of different types from different areas:

* Concrete: Person, car, alarm clock, planet, star

* Conceptual: Number, democracy

* Events: General protection fault, earthquake

Page 62: watermarking_newDoc

Every object has a type associated with it, and possibly more than one type. Creating

types and classifying your objects is one of the arts of OOP, and there is no single

"correct" way to do this.

Let's examine the alarm clock type. We'll take a crack at determining its behavior and

properties.

* Alarm clock properties: Current time, alarm time

* Alarm clock behavior: Ring, snooze, turn alarm on or off

* Alarm clock property-related behavior: Get and set current time; get and set alarm

time

We've made a bit of a distinction here between general behavior, and behavior that is

just related to getting and setting properties. We'll talk more about this later when we

delve into the best way to actually program a type.

How do we use this type? Easy. We buy an alarm clock and bring it home. We set the

current time and the alarm time. When it rings, we hit the snooze button (repeat five

to six times), and we finally turn the alarm off and get out of bed.

The system depicted in this example is the core of OOP. We have types that represent

the different kinds of things in our system, (the alarm clock type), and we have

objects that are instances or examples of the types (we bought a particular alarm

clock). Objects interact through their behaviors, sometimes resulting in changes in

their properties, and ultimately (hopefully) do useful work. C'mon, you already knew

this, otherwise you wouldn't be able to use your alarm clock, and you'd never get to

work on time. Rewrite your resume -- you're an object-oriented programmer.

OOP and Java

Page 63: watermarking_newDoc

We've been talking abstractly until now about OOP. Let's shift back and see how

OOP is done in Java. A class is used to define a new type in Java, and classes are

central to the language. Everything happens within classes. All executable code exists

in classes (generally in methods), and all data appears within a class (in variables

within a class, and in variables in methods).

Classes are defined in a class definition. Here's a (simple and incomplete) definition

for an AlarmClock class.

public class AlarmClock {

}

* The class keyword introduces the class

* AlarmClock is the name of the class

* { starts the class body

* The data and methods are declared within the class body

* } ends the class definition

* We'll look at what public means shortly

It's time to create your first class, albeit one that doesn't do much yet. It will soon,

though. Create a file called AlarmClock.java, and put in the code for the class

definition above. Compile it using javac.

javac AlarmClock.java

Note that when a class definition starts with the keyword public, Java requires you to

put the class definition (the Java source) into a file that starts with the name of the

class. Hence, we name our file AlarmClock.java because the class name is

AlarmClock.

What can we do with this? Have we actually created an AlarmClock? Nope.

Remember that a class (that defines a type in Java) is a blueprint for an object, but it's

not the actual object. A class definition is like a cookie cutter, but it's not a cookie.

Page 64: watermarking_newDoc

You create cookies by cutting some dough with the cookie cutter. Similarly, we have

to cut some objects from memory to create them. You create or instantiate objects in

Java with an operator called new followed by the name of the class for which you

want to create an instance. The syntax looks like this:

new AlarmClock();

This creates an alarm clock off the heap. There's still a problem here, however.

Unlike cookies we can just pick up and put on a cookie sheet (and then pick up and

eat), objects float around in a computer's memory, and we need to have a way to get

to them. Java uses special variables called object references to refer to objects. You

can initialize a reference to refer to a given object, and then use the reference to

interact with that object. Here's what this looks like:

AlarmClock aClock = new AlarmClock();

The first AlarmClock declares the type of the variable; aClock is the name of the

variable; and new AlarmClock() creates a new alarm clock that is then used to

initialize aClock.

Just for fun, let's add a little behavior to our alarm clock. You add behavior in

methods. We'll add the snooze method, which will just print a message to the console

as our first program did. Methods go inside classes, and here's what one looks like:

public void snooze() {

System.out.println("ZZZZZ");

}

When we put it in our AlarmClock class, we get the following:

public class AlarmClock {

public void snooze() {

System.out.println("ZZZZZ");

Page 65: watermarking_newDoc

}

}

Does AlarmClock.java contain a program? No, it doesn't, because there is no main

method in class AlarmClock. Remember that a Java program is just a class with a

main method in it.

Let's create another program called AlarmClockTest. This just means we'll create a

class AlarmClockTest with a main method in it. We'll create an instance of

AlarmClock in this program.

public class AlarmClockTest {

public static void main(String[] args) {

AlarmClock aClock = new AlarmClock();

}

}

Last, but not least, we want to do work with this alarm clock. The way you tell an

object to do something is by calling, or, invoking, one of its methods. You generally

do this through the variable that refers to it, and you use the dot operator for this. All

we can do is snooze with this clock, but hey, that's everybody's favorite action with an

alarm clock anyway. Here's what the code looks like:

public class AlarmClockTest {

public static void main(String[] args) {

AlarmClock aClock = new AlarmClock();

aClock.snooze();

}

}

Ready? Create AlarmClockTest.java, and type in the code above. Compile it (javac

AlarmClockTest.java) as well as AlarmClock.java. You're ready to run your new

Page 66: watermarking_newDoc

program. The main method is in AlarmClockTest class, so this is how you run the

program:

java AlarmClockTest

JFC(swings):

In 1995, Java technology shook the World Wide Web with a network-centric, object-

oriented language that provided client side processing for otherwise static pages.

Many Web developers used Java technology to animate sites and loved it. Java

platform's graphical user interface library, the Abstract Window Toolkit (AWT),

fulfilled a key role in the creation of dynamic Web pages.

Early adopters of Java technology have recognized its significant productivity

advantages. Java programming language is an excellent implementation of object-

oriented technology which makes it easier to learn. Java language enables any

application to be portable to any Java technology-enabled platform without the

additional cost of development or maintenance -- no extra effort is expended to create

the port. This is a huge advantage for developers and system architects that use the

Java development platform.

Java technology has evolved quickly and now transcends the browser, its initial

runtime environment. Today, businesses worldwide are standardizing on Java as their

primary development and deployment platform. The Java Virtual Machine* (JVM) is

rapidly being incorporated into operating systems and hardware devices to provide a

common meta-platform for applications.

The Java Development Kit (JDK) software release 1.1 introduces the first installation

of the most significant cross-platform graphical user interface technology since the

advent of windowing systems: the Java Foundation Classes (JFC).

Java Foundation Classes extends the original AWT by adding a comprehensive set of

graphical user interface class libraries that is completely portable and delivered as

part of the Java platform. In addition, JFC will also include many of the key features

Page 67: watermarking_newDoc

found in Netscape's Internet Foundation Classes. Since the JFC is core to the Java

platform, it eliminates the need to download special classes at runtime and is

compatible with all AWT-based applications.JFC's continually evolving new features

include a rich suite of high-level components and services that are fully and uniquely

cross-platform compatible, and offer significant performance improvements. With the

JFC, developers can create and deploy large scale, mission-critical intranet , Internet

and Crossware applications. And because Java is an open, standard technology, a

broad complement of third party tools and components are available to enhance

application development.

The JFC raises the bar for GUI functionality in the Java language and delivers a rich

API with a growing set of components and services to develop commercial-grade

applications.

The Java Foundation Classes includes many new, easy-to-use and sophisticated

features that are designed together to offer the following key advantages over other

frameworks:

* JFC is core to the Java platform and reduces the need for bundled classes.

* All new JFC components are JavaBeansTM architecture-based.

* No framework lock-in. Developers can easily bring in other third party components

to enhance their JFC applications.

* Components are cross-platform.

* Enhanced services promote development of feature rich applications.

* JFC subclasses are fully customizable and fully extendible.

History of Java Foundation Classes

The Abstract Window Toolkit (AWT) provided developers with a rudimentary library

for building applications and applets. Applets are Java applications that are executed

from inside a browser instead of being launched and run from the native operating

system. Designed for simple, web-centric tasks, developers encountered limitations

with the AWT when attempting to create modern, sophisticated client applications.

Page 68: watermarking_newDoc

Although the AWT was limited in scope, it did offer two important features for all

applets and applications:

* 100% portability from a single set of source code

* Assumed a native look and feel on the deployment platforms

The AWT delivered on the promise of a standards-based platform that adapted to the

user desktop. It also provided a good starting point for graphical Java development

with room for improvements, some evolutionary and some revolutionary.

The Challenge of a Portable GUI Library

The technical issues surrounding cross-platform compatibility have plagued software

developers for years. Many vendors have attempted to solve this seemingly simple

problem by making applications independent of their windowing systems. Most

implementations involved "lowest common denominator" approaches and used

proprietary libraries. None offered an open solution. With the AWT, Java solved this

portable GUI environment problem in the most elegant and simple way possible.

There are many different approaches to implementing a portable GUI class library or

environment. A common approach is to layer an API or class library on top of the

native toolkit. Alternatively, other portable GUI environments contain a single toolkit

and then emulate the native look and feel on each platform. The first approach has the

desired look and feel, but applications often do not work consistently across

platforms. The later approach enables applications to work consistently but their

emulation never fully captures the correct look and feel on all platforms.

The AWT uses the layered toolkit model where each Java component creates a native

component. The JDK refers to this as the "peer" model. Each Java component class

"wraps" the peer or native implementation. This can increase complexity because

many native components maintain their own state. More challenges arise at the toolkit

level. Each native toolkit has a completely different event model and contains a

distinct set of native components.

Page 69: watermarking_newDoc

For users, differences in native appearance can have a radical and negative effect on

the look and behavior of an application. Problems can arise when applications

designed and developed for one platform are deployed on a different windowing

system. Components such as the scrollbar can exhibit inconsistent behavior across

platforms. Changes to minimum sizes, shading and colors, and fonts can result in

unusable user interfaces for applications that are otherwise healthy. Since cross

platform capabilities are one of the compelling reasons for developing with Java, the

cross platform capabilities of the GUI had to be improved.

AWT 1.0 -- Write Once, Run Anywhere

AWT 1.0 had several strengths and weaknesses. It's biggest strength was that with it,

an application/applet could be written once and run anywhere-a single set of source

code, 100% portability. No other toolkit or language has been able to match AWT's

breadth of deployment platforms while supporting native look and feel.

Many seasoned GUI developers have complained that the AWT's peer model was too

restrictive in rendering and event handling, and that because of this, it was difficult to

extend or override different aspects of the component. It was also prone to problems

if the idiosyncrasies of a platform were not implemented properly. Generally

speaking, the peer model was viewed as unacceptable if Java was to truly act as a

metaplatform that would guarantee cross platform support.

Nevertheless, the peer model played an important role in the acceptance of the AWT.

It enabled Java's AWT to be brought to market quickly and provided true native look

and feel. In fact, browsers are moving users toward a more universal look and feel on

all platforms and soon, users will expect this uniformity. However, in 1995 the

market was much more dogmatic about the appearance of applications and would

have almost certainly rejected the AWT if it had not provided native look and feel.

In retrospect, AWT 1.0 was a good initial step that enabled applet development. It

provided the initial foundation upon which further releases of the AWT could build

and eventually improved. The API was simple and clean, and enabled developers to

come up to speed quickly. The AWT shielded developers from each platform's

Page 70: watermarking_newDoc

idiosyncrasies and yet was 100% portable with a native look and feel. Finally, the

AWT enabled the early Java adopters to deliver applets and applications on any Java

enabled platform with one set of source code and no "porting".

Internet Foundation Classes

To address the needs of developers who wanted to create commercial applications

that behave and appear identical across all platforms, Netscape created the Internet

Foundation Classes (IFC). While IFC was a robust framework which delivered many

important functionalities to the development community, Java developers demanded a

single industry standard solution.

As a result, Sun, Netscape, and IBM joined force to create Java Foundation Classes

which provides a single GUI component and services solution. Java Foundation

Classes builds on top of the existing AWT by integrating the best of new Sun

technologies and Netscape's Internet Foundation Classes.

JFC -- A Comprehensive Set of Classes and Services

With JDK software version 1.1, the web-centric AWT GUI toolkit becomes part of a

comprehensive set of GUI classes and services called The Java Foundation Classes.

The Java Foundation Classes, a superset of the AWT, provides a robust infrastructure

for creating commercial quality intranet and Internet applets and applications. The

JFC is the result of developer and end user feedback and provides a significant

advance in the development of client applications written in the Java programming

language.

The JFC released in JDK 1.1 provides a wide range of new features that enable Java

developers to be more productive while delivering applications that are fully

integrated into the desktop environment. The JFC contains a powerful, mature

delegation event model, printing, clipboard support, a lightweight UI framework and

is 100% JavaBeans compliant. The new capabilities of JFC make Java a platform that

Page 71: watermarking_newDoc

will support the most sophisticated enterprise applications. Development of

commercial applications using Java is now both possible and attractive.

Java and the AWT freed developers from being tied to a specific or proprietary

platform for GUI application development and deployment. Today, the JFC provides

the core set of classes and services enabling applications to scale from the desktop to

the enterprise and across multiple platforms. Java developers will find the additions

and improvements to the toolkit greatly enhance their ability to deliver 100% Java

applications quickly and provide reliability and cross-platform consistency.

The release of JFC with JDK 1.1 is only a starting point. JFC will be extended to

encompass an even wider range of components and services which will support the

development of even richer Java applications. The JFC strategic roadmap intends to

build on this solid foundation with new functionality that will continue to deliver a

new generation of applications to a new era of computing.

Current JFC Features

GUI developers expect baseline functionality to create professional quality

applications. The AWT, while best suited for applet development, provided little

integration into the desktop environment and even less functionality for creating large

scale applications. JFC, introduced in JDK 1.1, delivers a more robust framework for

GUI development. It also delivers the baseline components and frameworks that

developers expect from the Java platform.

With JFC, Sun placed a great emphasis on quality, fixing many of the platform

inconsistencies which existed in the AWT. While it is recognized that the peer model

of the AWT was limited in its scope, it was necessary to correct existing problems

and to help customers deploy existing applications reliably. In particular, the Win32

native implementation was 100% re-written in order to provide a more robust base for

the JFC going forward. Although newly introduced, JFC is based on a mature,

consistent, and widely known set of classes and services.

Current features of the Java Foundation Classes are:

Page 72: watermarking_newDoc

* JavaBeans Architecture Compliant

* Lightweight UI Framework

* Delegation Event Model

* Printing

* Data Transfer/Clipboard

* Desktop Colors Integration

* Graphics & Image Enhancements

* Mouseless Operation

* Popup Menu

* ScrollPane Container

JavaBeans has played an important role in the JFC. The JavaBeans specification

defines a standard component architecture for visual and non-visual components. All

JFC components in JDK release 1.1 are JavaBeans architecture compliant, which

means they have a consistent API and a standard event handling mechanism. This

standard property and event model lends itself well to component reuse and

interoperability. JavaBeans also ensures easy integration of standard components and

frameworks with RAD tools and GUI builders.

As described earlier, the peer model has certain limitations. While native look and

feel is still important, a universal look and feel is also becoming increasingly more

desirable. The Lightweight UI Framework enables components to be peerless, or

lightweight, and completely written in Java. This new framework will enable

component developers to create and deliver a wide range of third party components

that will work consistently across platforms while remaining completely portable.

The lightweight UI also enables Java developers to easily create stunning user

interfaces.

The new event model is especially well suited to visual development environments

and development of distributed and multicast applications. The new delegation event

model in the JFC extends the previous single method implementation of the AWT.

Page 73: watermarking_newDoc

Before large conditional statements were required to determine an event's type or

origin. Now, events are class specific and can be "sent to" or "delegated" directly to

the object that can handle the request. This provides a large degree of flexibility when

handling the many different types of events generated by a GUI application.

Operating system vendors are currently integrating Java's Virtual Machine directly

into the OS which will shift deployment from webcentric browsers to applications,

provide a common metaplatform from IBM MVS to Microsoft Windows, and provide

a more consistent, flexible, and reliable operating environment than a browser. Once

this is accomplished and applications based on release 1.1 are in operation, users will

no longer have to view the future of the desktop windowing environment through a

single vendor's eyes. Innovation will expand as the time-to-market for application

decreases.

In summary, JavaBeans, lightweight components, and the delegation event model

provide a stronger infrastructure which enables larger and more complex applications

to be built more easily and in less time. The remaining features such as popup menus,

desktop colors, mouseless operation, and printing all allow Java applications to be

seamlessly integrated into the native windowing environment. Collectively, these

additions to the core Java GUI toolkit are designed to result in feature-rich, high-

performance applications.

100% Pure Java Certified -- Ensuring Portability

It is important that both applications and applets should be written completely in the

Java programming language to preserve cross-platform capability. Today, as

customers mix and match different desktop systems developers cannot assume a

single deployment platform. It's also important that Java applications and applets do

not rely on any proprietary technologies. Some operating system vendors attempt to

"capture" their developers by providing proprietary technologies as a part of the Java

development tools, thus limiting the deployment of created Java applications or

applets to a single platform. Developing exclusively using the native toolkit, or

Page 74: watermarking_newDoc

"100% Pure Java" frees the developer from these concerns and lets them take

advantage of the full benefits of the Java platform. Of course, the native toolkit must

support all the capabilities that developers require and take full advantage of whatever

native environment they are on.

"100% Pure Java" means the application is written completely in Java and does not

rely on any external class libraries or native code. Third party technologies can be

used but their technology must be part of the application or applet download in order

for the software to be "100% Pure Java." This works well for third party components

that are typically small in size with few classes. It becomes a problem with large third

party frameworks.

Although there is a growing third party market for additions to the Java platform, an

obvious need arose in the Java development community. Initially, AWT was intended

to support only a limited set of GUI components. It was expected that the market

would provide the higher-level components. The Java development community has

overwhelmingly asked for the additional components to be delivered as part of the

JDK. Why? So applications can more easily be "100% Pure Java." Java developers do

not want to deliver these additional components along with their applets and

applications. With JFC, much of this additional functionality has been incorporated

into the Java platform, thus improving overall performance and appeal of Java

applications and applets.

Java Technology -- A Commitment To Open Standards

Recently, other companies have announced or delivered specifications and class

libraries to the Java development community. Although their apparent enthusiasm for

the Java platform is certainly understandable, such offerings can cause confusion in

the marketplace. Sun has endeavored to cultivate relationships with other technology

providers in order to provide an open standard for all Java developers. This

collaboration is evident in many of the specifications now available for review. JFC

represents the demands of Java stakeholders and is a high quality development

environment that makes high performance, network-centric applications a reality.

Page 75: watermarking_newDoc

It is important to remember that all specifications from Sun have been made available

to the larger Java development community for comment and do not reflect the views

or position of a single vendor. Once these specifications have been implemented the

technology will become part of the JDK and will exist on every Java platform. This is

why it is important for Java applications and applets remain "100% Pure Java."

JFC -- Expanding On A Solid Foundation

The JFC represents a significant introduction of new functionality to the Java

development environment. The release of these classes with JDK 1.1 marks the

beginning of major enhancements that will continue to improve the completeness and

functionality of Java GUI applications.

Additions to the Java Foundation Classes will soon incorporate several features that

further enhance a developer's ability to deliver scalable, commercial-grade

applications. These new features will be made available to developers as they are

completed over the next few months and then rolled into the next release of the JDK.

New features will include:

* Drag and Drop

* New High-Level Components

* Pluggable Look and Feel

* Java 2D API

* Accessibility Features for the Physically Challenged

* Additional new features continually being added

Drag and Drop

The Drag and Drop specification is available in the JDK 1.1 documentation and will

soon be released as an update to the JFC. Drag and Drop (D&D) functionality as part

of the core JFC class library means it will be available on all Java platforms in a

consistent and supported fashion. It will significantly improve application

interoperability by enabling D&D between Java applications and non-Java

applications.

Page 76: watermarking_newDoc

The generic, platform-independent implementation of D&D will enable objects to be

dragged and dropped from one application to another. This update will support D&D

between two Java applications, but more importantly, it will support D&D between a

Java application and a native application. This means a user running the application

on UNIX will be able to D&D to a Motif application and then run the same code on

Microsoft-Windows and D&D to native application running there. D&D support

makes it much easier to introduce Java applications to the enterprise.

New Java Foundation Classes Components

Working closely with Netscape and IBM, Sun will soon release an expanded set of

components written in 100% Pure Java that will enable applications to be more fully

integrated into the native environments. These new high-level components will be

available on all platforms as part of the standard Java platform, thereby eliminating

the need to download extra classes. In addition, new JFC components will carry two

important attributes: all components will be both lightweight and peerless, thus

facilitating a customizable look and feel without relying on native windowing

systems or adding system overhead, and improving the deployment of applications

will be simplified.

This comprehensive set of new high-level components will allow developers to create

sophisticated professional-quality applets and applications using core JDK 1.1

functionality. The following components will be included with JFC:

* Tree View

* List View

* Table View

* Toolbar

* Pane Splitter

* Tabbed Folder

* List

* Multi-column

Page 77: watermarking_newDoc

* Supports Images

* Progress Bar

* Slider

* Styled Text

* Support import/export of HTML and Rich Text Format

* Font Chooser

* Color Chooser

* File Chooser

* Custom Cursors

* Tool Tips

* Generic Button and MenuItem

* Support Images, Check marks

* StatusBar

* SpinBox

* ComboBox

* Drop down ComboBox

* Drop down ListBox

* Composable Button

* Multimedia Controls

* MovieSlider

* AudioController

* MovieController

* Properties

* AudioGauge

* MidiPanel

Pluggable Look and Feel

Native look and feel was once the mantra of cross-platform developers. Since all

applications on a platform had a common look, all new applications were assumed to

require that user interface. Or so it seemed until World Wide Web came along. Now,

users are familiar with and excited by the rich and unique user interfaces delivered

Page 78: watermarking_newDoc

through browsers. The rigor with which user interfaces were designed in the past has

been replaced with the requirement for effective and reliable clients.

Pluggable look and feel will increase the reliability and consistency of applications

and applets deployed across platforms. The "pluggable" look and feel will provide an

easy yet powerful mechanism for individualizing an application's visual personality

without having to subclass the entire component set. This will increase user

acceptance of network computer (NC) replacement of PCs as users will select an

operating environment they are comfortable with.

To further enhance a user's visual experience, an entire application's GUI will be able

to switch from one look and feel to a different one at runtime. This feature will give

users the ability to switch without restarting the application. This is significant since

users will want to work in a GUI that is familiar to them, even if they are using a

network computer.

2D Graphics API

The existing graphic capabilities of Java will be extended with new classes. New

graphical capabilities will promote the development of visually rich applications. The

Java 2D API extends the JFC's strengths by enabling developers to incorporate high-

quality graphics into their applications and applets. The Java 2D API will extend the

java.awt and java.awt.image core class libraries. By extending the existing classes,

the Java 2D API maintains compatibility for existing programs and allows programs

to seamlessly integrate the features provided by JFC. This is one of many

evolutionary additions to the Java platform which ensures that existing code co-exists

and benefits from these new enhancements.

The Java 2D API provides a subclass of the AWT Graphics class, Graphics2D, with

additional features for specifying fancy paint styles, defining complex shapes, and

controlling the rendering process. The Java 2D API treats paths, text, and images

uniformly; they can all be rotated, scaled, skewed, and composited using the new

Graphics2D class.

The Java 2D API will:

Page 79: watermarking_newDoc

* Enable the path to be specified to define complex shapes.

* Enable text to be drawn, transformed, used as a clipping path, and composited just

like any other graphic element.

* Provide text layout facilities that handle most common cases, including text strings

with mixed fonts, mixed languages, and bidirectional text.

* Provide a full range of features for handling images with several new classes

including: BufferedImage, Tile, Channel, ComponentColorModel and ColorSpace.

* Enable the control of how graphics primitives are rendered by specifying a set of

attributes that allows characteristics such as the stroke width, join types, and color

and texture fills.

This means better performing, more sophisticated visual applications for scientific,

engineering, and business users.

Accessibility Features for the Physically Challenged

JFC introduces new capabilities to the Java platform that deliver benefits to end users.

Many physically challenged users are prevented from using applications because

developers did not integrate with the necessary accessibility functionality. The JFC

Accessibility API enables Java applications to scale to encompass the physically

challenged users. Two of the most important features are Screen Readers and Screen

Magnifiers.

The Screen Reader creates an off screen representation of the GUI components

enabling the information to be provided via a text to speech and/or a Braille terminal.

The user can then interact with the GUI through the alternate computer input and

output device.

The Screen Magnifier enables the user to adjust the magnification of the screen from

1 to 16 times the normal size. Event tracking and screen content knowledge enable

the user to more easily navigate the interface. Font smoothing and text highlighting

act in concert to create a clearer picture which renders the content more easily read

and understood.

Page 80: watermarking_newDoc

Accessibility features will be easily integrated into existing Java applications and will

ensure an even broader audience for information in a networked age.

JFC Features Delivered in JDK 1.1

An In depth Look

JFC provides significant new capabilities for Java developers. With the JDK 1.1

release, JFC embraces the new JavaBeans component model, introduces a new high-

performance UI framework, improves event handling, enables printing support,

supports keyboard navigation, and introduces popup menu and scroll pane

components. JFC delivers a wish list of features that make Java the most compelling

development platform available.

JavaBeans Architecture Compliant

JavaBeans is an architecture and platform neutral API for creating and using dynamic

Java components. JavaBeans enhances the Java platform by allowing richer, more

dynamic interaction. JavaBeans allow developers to define independent components

that can be used and re-used in a variety of combinations to compose new

applications. JavaBeans will be supported inside browsers and in standalone

applications.

JavaBeans components can be GUI widgets, non-visual functions and services,

applets and or scale applications. Each of these components can be built by different

developers at separate times. JavaBeans components do not need to be part of the

same application build. Instead, they communicate dynamically.

By delivering JFC as JavaBeans, developers will be able to create Java applications

and applets that interoperate with legacy applications, can be created with visual

development environments, and can be distributed easily across the network.

Lightweight UI Framework

Page 81: watermarking_newDoc

In AWT release 1.0, peer-based components (Button, Label, etc.) could not be easily

extended or have their look and feel overridden. Many developers created their own

components by deriving new ones from java.awt.Canvas and specialized containers

were derived from java.awt.Panel. The problem with this approach was that each

Canvas or Panel derived component was "heavy-weight", meaning it required a native

window which is rendered opaquely. Opaque windows can cause problems for those

wanting to layer components on top of each other, since they completely cover the

components behind them. Additional overhead occurs when developers create their

own classes-the applet or application must download additional classes to perform

what should be a standard task. JFC solves these problems by introducing a

lightweight framework that radically improves the performance and appearance of

Java applications.

Lightweight components are completely transparent because they do not require a

native window. This means that they can be written entirely in Java and do not carry

with them any overhead from the native windowing system. Lightweight components

also provide a consistent look and feel across all platforms. It also allows for a new

class of GUI components such as tool tips without significant overhead.

It is remarkably easy to take advantage of this new framework in existing applications

and applets. To convert existing Canvas and Panel based components into

Lightweight components, a developer needs only to change the superclass from

Canvas to Component and from Panel to Container. When the paint() method is

called, all rendering will be performed within the parent's Graphic context and

transparent areas can be left unrendered thus enabling the background to show

through.

Advantages of the new lightweight UI framework are:

* improved runtime performance for GUI applications

* improved "time to load" for applets with fewer classes to download

* easy conversion of existing AWT components to JFC lightweight components

Page 82: watermarking_newDoc

Delegation Event Model

The event model in AWT 1.0 was quite simple. All events were passed up the

inheritance hierarchy forcing objects to catch and process events by subclassing and

overriding either the handleEvent() or action() methods. Complex if-then-else

conditional logic was required in the top level object to determine which object

triggered an event. This was not scalable and was ill-suited to high-performance

distributed applications.

With JFC, the callback-style delegation event model is elegant yet powerful. Events

are identified by their class instead of their ID and are either propagated or delegated

from an event "Source" to and event "Listener." Only objects interested in a particular

event need deal with the event and no super-event handler is required. This is also a

better way of passing events to distributed objects.

The new event hierarchy is defined by the package java.awt.event. Each derived class

from java.util.EventObject is now unique because of the data it holds. There are no

longer public data fields, all event data is accessed through a standard set/get

JavaBeans compliant interface. However, some derived Event classes still contain an

ID to help objects distinguish between events within a specific group of events.

The real power behind the new model is the enabling of an object to delegate or "fire"

an event to a specific listener or set of listeners. When a source object wishes to

delegate a specific event type, it must first define a set of methods that enable the

listener object(s) to register with the source. These methods take the form of

set<EventType>Listener for single-cast and/or add<EventType>Listener for multi-

cast delegation.

Any object desiring to be a "Listener" of a specific event type must implement the

<EventType>Listener interface for that event type. The "Listener" interface is

typically defined by only a few methods, which makes it easy to implement the

interface. For example, a new Lightweight component may wish to send an

Page 83: watermarking_newDoc

"ActionEvent" when the user clicks on the component. The creator of the component

would define an event registration method call addActionListener() which enables

any object implementing the ActionListener interface to register as a consumer of

ActionEvents.

Additionally, a new language feature called "Inner Classes" has been added in JDK

1.1 which makes creating listener objects much more convenient. With Inner Classes,

you can create a listener class on the fly within the body of another class.

The following example uses Inner classes to hook the action of pushing a button to

closing a Frame:

public class MyFrame extends Frame {

public MyFrame(String title) {

super(title);

Button button = new Button("Close");

ActionListener action = new ActionListener() {

public actionPerformed(ActionEvent e) { close(); }

};

button.addActionListener(action);

add("Center", button);

pack();

}

public void close() {

hide();

}

}

Printing

Until now Java applications have not been able to send text or graphics to a printer.

Native code could be used to print text but then the application/ applet was no longer

Page 84: watermarking_newDoc

portable, which did not solve the problem of printing graphics. This limitation has

made it difficult for Java applications to be truly integrated into the native

environment. JFC eliminates these barriers by introducing printer support that can be

easily integrated into existing applications and makes the Java platform ready for a

wide range of commercial software applications.

JFC has made it simple to add printing to any Java application or applet. To send

content or graphics to the printer, a call is made to a Frame object's paint() method

with a new type of Graphics context. This special context is derived from the

Graphics class and implements the java.awt.PrintGraphics interface. It is obtained

from the newly implemented PrintJob class.

The PrintJob class encapsulates all the printing functionality. A call method call to

getPrintJob in the java.awt.Toolkit package displays a platform specific dialog,

allowing the user to enter typical printing information such as, print name, number of

pages, etc.

The returned PrintJob object contains the Graphics context which can be used to call

a component's paint() method. This sends all the rendering information to the printer.

The underlying JFC implementation takes care of translating those calls to the

appropriate print device. Sometimes it is necessary to print the entire GUI hierarchy;

this can be accomplished with a call to printAll().

The following code is an example of a method that handles a print request:

public void actionPerformed(ActionEvent e) {

String cmd = e.getActionCommand();

if (cmd.equals("print")) {

PrintJob pjob = getToolkit().getPrintJob(this,

"Printing Test", null);

if (pjob != null) {

Graphics pg = pjob.getGraphics();

Page 85: watermarking_newDoc

if (pg != null) {

canvas.printAll(pg);

pg.dispose(); // flush page

}

pjob.end();

}

}

}

Data Transfer/Clipboard

JDK release 1.1 now has full clipboard support. It enables dynamic data types to be

created, registered, and transferred from both within and across process space

boundaries. This means that any object can be transferred within an application and

also to other applications. It also supports data transfer between Java and non-Java

applications by enabling access to the "system clipboard." Java applications can now

be easily rolled out to end users with a high degree of interoperability with existing

applications. This increases the overall acceptance of the Java platform.

The new API is centered around the "transferable" objects. A transferable object must

be able to provide a list of formats, called "data flavors". It must also be able to return

the data (in the form of an Object reference) when requested in a particular flavor.

The data transfer architecture introduced in 1.1 is a key enabling technology for the

upcoming drag and drop functionality.

Desktop Colors

An important aspect of an application's integration into the desktop environment is its

ability to adhere to the system color scheme, such as those offered by Windows95 or

CDE. Although some applications achieve a unique look or personality through a

distinct set of colors, most applications change their colors when a user selects a new

Page 86: watermarking_newDoc

desktop scheme. Developers will need to implement a new class in their applications,

but Java applications will now be further indistinguishable from native applications.

In previous releases of the AWT this was not possible. JFC in JDK release 1.1

introduced a new class java.awt.SystemColor to handle the dynamic changes in

desktop color scheme. The SystemColor class is derived from java.awt.Color and

defines "symbolic" colors for backgrounds highlights, shadows, etc. The following

code demonstrates how a lightweight component can use the symbolic colors to

render itself:

// draw highlight left and top

g.setColor(SystemColor.controlLtHighlight);

g.drawLine(0, 0, 0, mySize.height);

g.drawLine(0, 0, mySize.width, 0);

// drawbackground

g.setColor(SystemColor.control);

g.fillRect(1,1, mySize.width-2, mySize.height-2);

// draw shadow bottom and right

g.setColor(SystemColor.controlDkShadow);

g.drawLine(0, mySize.height-1, mySize.width-1, mySize.height-1);

g.drawLine(mySize.width-1, 0, mySize.width-1, mySize.height-1);

Graphics & Image Enhancements

The JFC enhances the graphical capabilities available for creating truly high-

performance financial, business, and engineering vertical applications.

While certain problems did exist with graphics handling in AWT, these have been

corrected with the JFC. For example, in AWT 1.0 the graphics clipping area could

only be set to an ever decreasing area. Developers found themselves creating a

temporary graphics object, setting a clipping area, calling the drawing methods and

then disposing of the object. The JFC adds a new class "Shape" and several new

clipping methods, most important of which is setClip. It allows developers to set the

Page 87: watermarking_newDoc

clipping area to any size and does not maintain a relationship to the previously set

clipping area.

The AWT 1.0 did not offer an easy way to render a subset of an image or a

mechanism for flipping the image horizontally or vertically, a typical requirement

when working with labels. JFC corrects this with addition of two new drawImage

methods. Each drawImage method requires a source and destination rectangle

definition and uses the pixels from the original unscaled image to draw into the

Graphics object. The following line of code demonstrates the scaling the 100x100

pixel area down to a 50x50 area:

g.drawImage(myImage, 10, 10, 110, 110, 0, 0, 50, 50, this);

Creating images on the fly is much more flexible and offers better performance than

retrieving images from files. In release 1.0 an image could be created from an array of

pixels. The pixels were converted into a screen representation and as long as the

image was drawn at the same scale it ignored any changes to the original array.

Several new methods have been added to the MemoryImageSource class giving the

developer a finer grain of control and easier animation capability.

The final area improved in the JFC with respect to image handling came directly from

the request of developers input. Several enhancements were made to the PixelGrabber

class. This class now enables developers to get the original ColorModel for the

image, retrieve the size of the buffer needed for the image, and start and stop grab

operations before the image is loaded.

Mouseless Operation

Two important aspects of a GUI are second nature to most users: keyboard navigation

and accelerators on menus. For data entry applications, keyboard traversal is a

requirement. It is common to use the "tab" key to move from component to

component in a standard user interface, and the "control" keys to perform accelerated

actions or short cuts, like <control> C to copy text. JFC based applications now take

advantage of keyboard traversal transparently.

Page 88: watermarking_newDoc

Components can now be "tabbable", they can request and transfer focus, and can be

notified when they gain or lose focus. To better support menu short cuts a new class,

java.awt.MenuShortcut has been added. Additional methods and constructors have

been added to the MenuItem and MenuBar classes to handle the new class. The short

cut keys apply to the "command" key on the Macintosh and the <control> keys on

UNIX(r) and Microsoft Windows platforms.

The benefits of mouseless operation are:

* Ideally suited for data entry and operational applications typical of terminal-based

applications

* Ensures higher user acceptance of Java applications

* Supports power user navigation

Popup Menu

Popup menus (also known as "context menus") are now a very common UI element

in modern GUIs (Windows 95, CDE, etc.). The JFC introduces a new component that

makes it easy to enable the creation and display of popup menus.

Popup menus are created by simply allocating a new PopupMenu object and adding

MenuItem objects to it, much like you would create a MenuBar menu. When the

popup event is fired (right-button click on MS Windows, middle-button click on

UNIX) a single method is called to assign the popup menu to a component and

display it. This enables a single popup menu to be used by many different

components. Here is a simple one item popup menu:

// Create and add the popup

popup = new PopupMenu("Edit");

mi = new MenuItem("Cut");

mi.addActionListener(this);

popup.add(mi);

add(popup); // add popup menu to applet

enableEvents(AWTEvent.MOUSE_EVENT_MASK);

Page 89: watermarking_newDoc

// The activation code

public void processMouseEvent(MouseEvent e) {

if (e.isPopupTrigger()) {

popup.show(e.getComponent(), e.getX(), e.getY());

}

super.processMouseEvent(e);

}

Popup Menus will enable:

* user control of object attributes at runtime

* easier application navigation

* better end user acceptance of applications

ScrollPane Container

In the AWT 1.0, the task of implementing all scrolling behavior is left to the

developer. Only a basic Scrollbar class is provided which must be managed by the

application, meaning the application must catch the scrollbar events and then take the

appropriate action to update the contents being scrolled. This made applications slow

and unreliable across platforms. This was a problem for virtually any scrolling

function.

Not only is this a general burden to developers who are accustomed to better support

for this in toolkits, but it is also a serious performance problem, since there is a round

trip (native-> java-> native) for each individual scroll event that occurs, and the

application must respond to the event and move its contents using slower Java

draw/move operations. This is particularly noticeable during the event-intensive

scroll-drag operations. The result was slow applications prone to flickering and

unreliable actions.

To resolve this problem, a ScrollPane class has been added to the JFC. ScrollPane

provides a container that implements automatic scrolling for a single component child

Page 90: watermarking_newDoc

and supports three modes for its scrollbars: "when needed", "always", and "never".

The introduction of the ScrollPane container greatly simplifies the task of displaying

information in a fixed area.

The Java Foundation Classes delivered with JDK 1.1 casts Java GUI development in

a new light. The JFC is a complete GUI toolkit that dramatically extends the original

AWT with a comprehensive set of classes

and services.

The JFC is a scalable, robust and open technology that enables developers to create

and deploy commercial-grade intranet and Internet applications. Even as components

and services grow, JFC promotes ease of use and facilitates rapid application

development. JFC is delivered as core Java technology, which means it is available

on all Java platforms. This results in faster application downloads, more reliable

applications, and simplified application deployment.

The JFC will continue to expand with plans in-process to include a rich complement

of high-level components that will enhance the user's visual experience and improve

productivity. New application services are slated for JFC that will further integrate

Java applications into the desktop environment.

* Drag and Drop

* New High-Level Components

* Pluggable Look and Feel

* The Java 2D API

* Accessibility Features for the Physically Challenged

The Java Foundation Classes empowers developers on all platforms, and brings the

future of portable GUI development here today, realizing Java technology's promise,

"Write Once, Run Anywhere."

Page 91: watermarking_newDoc

Overview of Java Foundation Classes (JFC) Features

Abstract Window Toolkit (AWT) - APIs that enable programs to integrate into the

native desktop window system, including APIs for Drag and Drop.

Java 2D - APIs to enable advanced 2D graphics, imaging, text and printing.

Swing GUI Components - APIs that extend the AWT to provide a rich, extensible

GUI component library with a pluggable look and feel.

Accessibility - APIs and assistive technologies are for ensuring an application is

accessible to users with disabilities and meets government requirements for

accessibility.

Internationalization - All JFC technologies include support for creating applications

that can interact with users around the world using the user's own language and

cultural conventions. This includes the Input Method Framework API.

These five technologies are designed to be used together to enable you to build fully

functional GUI client applications that run and integrate on any client machine that

supports the J2SE platform, including Microsoft Windows, Solaris, Linux, and Mac

OSX.

Focus management with JFC's Swing components :

ocus is the mechanism that determines which of the components in a window will

receive keyboard input events. A focus manager looks for special keystrokes that

change the focus (usually the Tab and Shift-Tab keys), and then decides which

component will next get the focus. Often, you'll want to control how the focus moves

between components, especially if you're designing a complex form or dialog for

users to enter information.

Java has had a focus manager for AWT components since version 1.0 of the Java

Development Kit (JDK), and developers have howled about its inadequacies ever

Page 92: watermarking_newDoc

since. Well, it's time to stop howling. The focus management services provided with

the Java Foundation Classes (JFC) should satisfy all of your needs for controlling

focus changes.

A bit of history

The only way to manage focus changes with JDK 1.0 is through a few methods in the

Component class. JDK 1.0 allows components to set the focus to themselves with

requestFocus and to change the focus to the next component with nextFocus. Other

than getting notification of focus changes with gotFocus and lostFocus, that's pretty

much all you can do.

JDK 1.1 deprecates nextFocus and replaces it with transferFocus, which provides

exactly the same functionality as nextFocus. Likewise, 1.1 deprecates gotFocus and

lostFocus and replaces them with the addFocusListener method to support focus

change notification using the 1.1 event model.

Neither JDK 1.0 nor 1.1 provide any means for applications to override the behavior

of the focus manager, or to change the algorithm used to determine focus traversal.

What's new with Swing's focus management

Swing provides some powerful new ways to manage focus changes at the component

level. Here's what you can do with focus management at that level:

* Set the focus to a given component

* Transfer the focus to the next component in the focus-change order

* Determine if a component has the focus

* Disable a component from responding to focus requests

* Allow the component that currently has the focus to manage the next focus change

And if this isn't enough to meet your focus control needs, Swing allows you to create

and use your own custom focus manager.

Page 93: watermarking_newDoc

Let's take a quick look at the relationship between the AWT and Swing focus

managers. The following figure shows how JFC incorporates both the AWT and

Swing focus managers.

AWT and Swing focus manager relationship

Explicitly setting the focus

There are two JComponent methods that allow you to explicitly set the focus to a

given component: requestFocus and grabFocus. If you've worked with AWT

components, you're probably familiar with the requestFocus method. Swing overrides

this Component method with an implementation that allows you to call the new

setRequestFocusEnabled method. This method can enable or disable the component

from getting the focus via requestFocus.

However, you can't use setRequestFocusEnabled to prevent a component from getting

the focus via the focus manager. That's because the focus manager uses a new Swing

method, grabFocus, to give components the focus. grabFocus works just like

requestFocus, except that you can't disable it. The Swing docs say that only focus

managers should use grabFocus.

Let's take a look at a bit of sample code written for components. This code will cause

a component to get the focus whenever the component is under the mouse:

// add a listener for mouse enter

addMouseListener(new MouseAdapter() {

public void mouseEntered(MouseEvent event) {

// Request the focus (if don't already have it)

if(!hasFocus()) { requestFocus(); }

}

});

Page 94: watermarking_newDoc

This fragment adds a mouse listener, which is implemented in an anonymous inner

class based on the MouseAdapter adapter class. The mouse adapter's mouseEntered

method is called whenever the mouse passes over the component. The

implementation for mouseEntered calls hasFocus to see if the component already has

the focus, and if it doesn't, calls requestFocus to give the component the focus. A

slightly more fail-safe way to set the focus would be:

if(!hasFocus()) {

// ensure requestFocus is enabled

if(!isRequestFocusEnabled()) { setRequestFocusEnabled(true); }

requestFocus();

}

And if you're writing a focus manager, you can use grabFocus:

if(!hasFocus()) { grabFocus(); }

Transferring the focus

Like AWT 1.1, Swing provides the means for a component to transfer the focus to the

next component with the transferFocus method.

public void transferFocus();

This method can be useful for implementing components that automatically advance

the focus when the user has completed whatever task or purpose is served by the

component (like choosing from a group of radio buttons or items in a list).

transferFocus is not really useful for explicitly setting the focus -- you would have to

know which component has the focus just before the component that you actually

want to set the focus to.

Detecting focus changes

Page 95: watermarking_newDoc

Swing doesn't bring any changes to the operation of AWT 1.1's focus listener

implementation. I'll give a brief description of focus listeners for those readers that

aren't familiar with them; if you know this stuff you may want to skip on to the next

section. Focus listeners provide a means of notifying applications when components

gain or lose the focus. The adapter class for focus events, FocusAdapter, has two

methods: focusGained and focusLost. The addFocusListener and

removeFocusListener methods add and remove focus listeners for components.

Standard event-listener stuff -- nothing fancy here. Let's glance at a piece of code.

The following code fragment adds a focus listener that changes the background color

when a component gets the focus.

// private instance variables

private boolean bFocusIndicated = false;

private Color originalColor;

.

.

.

// add a listener for focus events

addFocusListener(new FocusAdapter() {

public void focusGained(FocusEvent e) {

if(!bFocusIndicated) {

// set background to a darker color to indicate focus

originalColor = getBackground();

setBackground(originalColor.darker());

bFocusIndicated = true;

}

}

public void focusLost(FocusEvent e) {

// restore original background color

setBackground(originalColor);

Page 96: watermarking_newDoc

bFocusIndicated = false;

}

});

You can't always count on getting focusGained and focusLost events in matched

pairs, hence the need for the bFocusIndicated variable to keep up with whether we've

indicated focus on a component.

Managing focus at the component level

Up until this point, most of what I've covered is probably familiar to you if you have

much experience with AWT 1.1 components. Now we'll start getting into Swing's

new and improved features. Swing provides a mechanism for component-managed

focus traversal. This can be a powerful alternative to writing your own focus manager

and is a better solution for developing components that have their own particular

behavior when it comes to gaining and losing the focus. For example, say you want to

develop a text field component that won't surrender the focus until the user enters

valid data. If you've tried to implement such a component in AWT 1.1 by using the

focusLost notification to validate the data and then set the focus back to the text field,

you've probably experienced some frustration. One obvious solution to this problem

-- calling requestFocus while processing the focusLost event -- doesn't always have a

predictable outcome. With Swing components, you can override the

isManagingFocus method to return true and get Tab and Shift-Tab keystrokes sent to

the component's key listener. This allows the component to manage focus traversal

when the component has the focus. The following code implements a text field that

doesn't allow the focus to traverse to the next component until valid data is entered:

class MyTextField extends JTextField {

boolean validDataEntered = false;

// Constructors

public MyTextField () {

super();

Page 97: watermarking_newDoc

init();

}

public MyTextField (String text) {

super(text);

init();

}

// Private initialization routine to be run at construct time

private void init() {

// add a key event listener that will consume tab keys until valid data entered in field

addKeyListener(new KeyAdapter() {

public void keyPressed(KeyEvent event) {

// look for tab keys

if(event.getKeyCode() == KeyEvent.VK_TAB

|| event.getKeyChar() == '\t') {

// if no valid data entered in field, consume event

// so that it won't be passed on to focus manager

if(!validDataEntered) {

event.consume();

}

}

else {

// assume any key other than tab is valid data

validDataEntered = true;

}

}

});

}

Page 98: watermarking_newDoc

// Override to inform focus manager that component is managing focus changes

public boolean isManagingFocus() { return true; }

}

In this example, any keystrokes other than Tab keystrokes are considered to be valid

data. If no valid data has been entered, the text field's key listener consumes Tab

keystrokes, preventing them from reaching the focus manager. Of course, if you were

implementing this technique in a real application, you would want to present a

message to the user and inform them as to why they are being prevented from tabbing

away from the text field. One limitation to managing focus traversal at the component

level is that you can't control focus changes initiated by mouse actions. In fact, you

can't even do this by writing your own custom focus manager. To control focus

changes initiated by mouse actions, you'll have to modify the low-level mouse

handling for all of your components.

Mixing AWT and Swing components

The Swing focus manager effectively sits on top of the AWT focus manager. It can

only manage focus for Swing components, so if you're mixing AWT and Swing

components, you should disable the Swing focus manager with the following line of

code.

FocusManager.disableSwingFocusManager();

The AWT focus manager will then manage focus for all of your components.

Unfortunately, you can't disable the focus manager on a per-window or per-container

basis -- when you disable it, it's disabled for your entire application.

Writing a custom focus manager

Swing provides the ability for applications to install and use their own custom focus

manager. If you can't get the focus traversal behavior you want by using requestFocus

and transferFocus, or by managing focus at the component level, you might want to

consider writing a custom focus manager. Although Swing does provide a complete,

Page 99: watermarking_newDoc

clean structure for supporting custom focus managers, writing a robust focus manager

that works well with any arbitrary component hierarchy is no trivial task. Overriding

the behavior of the default focus manager (represented by the DefaultFocusManager

class) may look like a promising and cheap way to create a custom focus manager. I

don't recommend this approach. In my opinion, the default focus manager isn't really

designed to be extended. For example, you might think you can just override the

compareTabOrder method and implement any tabbing algorithm you like. That would

be nice, but it doesn't quite work that way -- the default focus manager makes certain

assumptions about the tabbing order before it even calls compareTabOrder. If you try

to customize the default focus manager, I guarantee you will spend a lot of time in the

sources trying to understand exactly how everything works.

The structure of a focus manager

Let's take a look at the structure of a Swing focus manager. Focus managers are based

on the abstract FocusManager class. This class contains four static class methods for

applications to use to install and manage focus managers.

* getCurrentManager

* setCurrentManager

* disableSwingFocusManager

* isFocusManagerEnabled

The remaining three methods in the class are abstract methods that focus managers

must implement:

* processKeyEvent

* focusNextComponent

* focusPreviousComponent

That's right -- there are only three methods you must implement to create a custom

focus manager. Two of the methods, focusNextComponent and

focusPreviousComponent, simply advance the focus to the next or previous

component. The other method, processKeyEvent, is a low-level handler for key

events. This method looks for focus-change keystrokes (normally Tab and Shift-Tab)

Page 100: watermarking_newDoc

and then calls focusNextComponent or focusPreviousComponent to change the focus.

The static class methods getCurrentManager, setCurrentManager,

disableSwingFocusManager and isFocusManagerEnabled give you access to the

current focus manager and allow you to disable the Swing focus management services

as well as install your own focus manager. The abstract methods processKeyEvent,

focusNextComponent, and focusPreviousComponent are methods you must override

and implement if you are writing a focus manager.

Example of a custom focus manager

Let's take a look at an example of a custom focus manager. This example application,

called "CustomFocusManagerExample," implements a focus manager that allows you

to specify the tab order of components, regardless of their screen position or the order

in which they were added to their container. The custom focus manager used in this

example determines focus changes by querying the currently-focused component for

the next or previous component to get the focus. Components managed by this focus

manager must implement methods for setting and getting the next and previous focus

recipients. There are four parts to this example:

* A custom focus manager, represented by the CustomFocusManager class.

* An interface class that components managed by this custom focus manager must

implement. The interface class is represented by the CustomFocusManagerSupport

class.

* A component that implements methods required by the custom focus manager. This

component is represented by the MyTextField class, an extension of JTextField.

* The application shell to illustrate use of the custom focus manager. The application

shell consists of the CustomFocusManagerExample and AppPanel classes. It's

designed to be run as an applet or as a standalone application.

The application creates six text fields identified by a number from one to six. Instead

of adding the text fields to their container in numerical order, it adds them in a

somewhat arbitrary order: one, six, three, five, two, four. The application then sets the

Page 101: watermarking_newDoc

tab order such that focus traverses the text fields in numerical order: one, two, three,

four,

five, six. Here's a screen shot of the application when it's run as a standalone

application.

Screen shot of CustomFocusManagerExample application

Now let's get into the implementation. We'll start with the interface that components

must implement to be managed by our custom focus manager.

interface CustomFocusManagerSupport {

public void setNextFocus(JComponent component);

public void setPreviousFocus(JComponent component);

public JComponent getNextFocus();

public JComponent getPreviousFocus();

}

The interface is pretty simple -- just a few methods to set and get focus-traversal

information. The MyTextField class implements this interface by adding two private

instance data members to store the next and previous components to get the focus.

class MyTextField extends JTextField implements CustomFocusManagerSupport {

private JComponent nextFocus = null;

private JComponent previousFocus = null;

// Constructors

...

// Implementation of CustomFocusManagerSupport interface

public void setNextFocus(JComponent component) { nextFocus = component; }

public void setPreviousFocus(JComponent component) { previousFocus =

component; }

Page 102: watermarking_newDoc

public JComponent getPreviousFocus() { return (previousFocus); }

public JComponent getNextFocus() { return (nextFocus); }

}

Now let's look at the code for the custom focus manager. This example focus

manager is implemented in a class named CustomFocusManager, an extension of the

FocusManager class. Two of the abstract methods that focus managers must

implement are focusNextComponent and focusPreviousComponent. Here's how we

implement these methods in the CustomFocusManager class.

public void focusNextComponent(Component component) {

if(component instanceof CustomFocusManagerSupport) {

CustomFocusManagerSupport focusedComponent = (CustomFocusManagerSupport)

component;

if (focusedComponent.getNextFocus() != null) {

focusedComponent.getNextFocus().grabFocus();

}

}

}

public void focusPreviousComponent(Component component) {

if(component instanceof CustomFocusManagerSupport) {

CustomFocusManagerSupport focusedComponent = (CustomFocusManagerSupport)

component;

if (focusedComponent.getPreviousFocus() != null) {

focusedComponent.getPreviousFocus().grabFocus();

}

}

}

Nothing fancy here either -- we just check to see if the given component implements

the CustomFocusManagerSupport interface and call getPreviousFocus or

Page 103: watermarking_newDoc

getNextFocus to get the component that should next get the focus. We then set the

focus to that component by calling its grabFocus method. Before I show you how the

focus manager processes keystrokes, let's stop for a moment and think about the

focusNextComponent and focusPreviousComponent methods. Remember, these are

abstract methods that all focus managers must implement. Does it seem odd that these

methods have a parameter specifying a component? When you tell the focus manager

to advance the focus, you must give it the component that should have the focus

before the component you want to advance it to. I know this seems convoluted, but it

makes sense when you understand that the focus manager doesn't keep track of which

component currently has the focus. Focus management is a cooperative effort

between components and the focus manager. The final part of the custom focus

manager code is the implementation of the processKeyEvent method. This is the part

of the focus manager that actually handles the special keystrokes that change the

focus.

public void processKeyEvent(Component component, KeyEvent event) {

if(component instanceof CustomFocusManagerSupport) {

// look for tab key

if(event.getKeyCode() == KeyEvent.VK_TAB || event.getKeyChar() == '\t') {

if(event.getID() == KeyEvent.KEY_PRESSED){

// is shift pressed?

if ((event.getModifiers() & ActionEvent.SHIFT_MASK) ==

ActionEvent.SHIFT_MASK) {

focusPreviousComponent(component);

}

else {

focusNextComponent(component);

}

}

Page 104: watermarking_newDoc

// consume all tab key events

event.consume();

}

}

}

The processKeyEvent method looks for Tab and Shift-Tab keystrokes and then calls

focusNextComponent and focusPreviousComponent to change the focus. It only

handles focus for components that implement the CustomFocusManagerSupport

interface. Note that focus changes occur only on the KEY_PRESSED event --

processKeyEvent consumes corresponding KEY_RELEASED and KEY_TYPED

events by calling the KeyEvent.consume method. The remaining piece of the puzzle

is how the application installs a custom focus manager. This is accomplished by

creating an instance of the custom focus manager and setting it as the current focus

manager by calling the FocusManager class method setCurrentManager.

FocusManager fm = new CustomFocusManager();

FocusManager.setCurrentManager(fm);

Firstly, all components in Swing are 100% pure Java

(referred to as lightweight). This means that the windows should look the same

whatever

platform they are on and should be easier to maintain (for Sun). As all graphical

components

are “lightweight”, their appearance is controlled purely by the Java code (without the

need for

platform dependent peers – as in JDK 1.0 and 1.1). In swing, a separate user interface

“view”

component performs the actual rendering of the component on the screen. This allows

Page 105: watermarking_newDoc

different views to be plugged in. This in turn allows the idea of different “looks and

feels”. This

means that it should be possible for a Unix developer to select the Win95/NT look

and feel

and see what the interface would look like on that platform. It also means that it is

easier to

deploy the same software on different platforms, but with interfaces that match the

interface

manager on that particular platform. This separation of view form the actual

component is

based on a modified version of the Model-View-Controller architecture (described

later).

Swing also provides a greatly increased set of facilities for graphical user interfaces,

including

trees, icons on buttons, dockable menus bars, menus with icons, borders and

improved

support for fonts and colours.

So does this mean that the AWT (The Abstract Window Kit) of version 1.0 and 1.1 of

Java is

being thrown out of the window? Not exactly, the AWT will still be available and

systems can

be constructed using both the AWT and Swing (although there are some limitations).

However, as the AWT knows nothing about different “look and feels” and mixes both

Page 106: watermarking_newDoc

lightweight (pure Java) and heavy weight (native) components, any AWT windows

may not be

consistent with the Swing windows. From the point of view of the developer, it makes

little

sense to continue to use the AWT when all of the AWT’s facilities (and more) are

replicated in

Swing. Indeed, much of what an AWT developer already knows will go a long way to

helping

them to get started with Swing as will be shown by this article.

So that’s Swing, but what is its relationship to the JFC and the JDK? Essentially,

Swing is a

core component of the JFC along with Java2D, Accessibility and Drag and Drop. It is

the

largest element of the JFC (as it stands now) and will therefore be taken by many to

equate to

the JFC. Indeed one insider has said that it is “spelt JFC but pronounced Swing”.

However, as

can be seem from the above list, this is not the case. As this column is about Swing

we will

not digress into Java2D, the Accessibility API or Drag and Drop, except to say that

each is a

significant development with Java2D being a major improvement over the basic

facilities in

previous version of the JDK.

Page 107: watermarking_newDoc

So where does that leave the JDK 1.2? In many ways JDK 1.2 is the JFC plus various

enhancements which consolidate JDK 1.1. For example, JDK 1.2 includes numerous

collection classes for data structures that greatly improve on the basic set of facilities

provided

with JDK 1.0 and 1.1. Equally, the performance enhancements provided will be of

welcome,

however it is the Swing set of components that will grab the attention.

SCREENS :-

1) Executing the application

Page 108: watermarking_newDoc

2) Screen 2

Page 109: watermarking_newDoc

2) Screen 3

Page 110: watermarking_newDoc

4) Screen 4

Page 111: watermarking_newDoc

Testing: -

Page 112: watermarking_newDoc

Software testing is a critical element of software quality assurance and

represents the ultimate reviews of specification, design and coding. Testing

represents interesting anomaly for the software. During earlier definition and

development phases, it was attempted to build software from an abstract concept to

tangible implementation.

The testing phase involves the testing of the developed system using various test

data. Preparation of the test data plays a vital role in the system testing. After

preparing the test data the system under study was tested using those test data. While

testing the system, errors were found and corrected by using the following testing

steps and corrections are also noted for future use. Thus, a series of testing is

performed for the proposed system, before the system was ready for the

implementation.

Testing is the process of detecting errors.Testing performs a very critical role for

quality assurance and for ensuring the reliability of software.The results of testing are

used later on during maintainence also

The aim of testing is often to demonstrate that a program works by showing that it has

no errors.The basic purpose of testing phase is to detect the errors that may be present

in the program.Hence one should not start testing with the intent of showing that a

program works,but the intent should be to show that a program

Doesn’t work.

.

Testing Objectives:

Page 113: watermarking_newDoc

The main objective of testing is to uncover a host of errors, systematically and

with minimum effort and time. Stating formally, we can say,

Testing is a process of executing a program with the intent of finding an error.

A successful test is one that uncovers an as yet undiscovered error.

A good test case is one that has a high probability of finding error, if it exists.

The tests are inadequate to detect possibly present errors.

The software more or less confirms to the quality and reliable standards.

Levels of testing

In order to uncover the errors present in different phases we have the concept of

levels of testing.The basic levels of testing are

Client Needs Acceptance Testing

Requirements System Testing

Design Integration Testing

Code Unit Testing

Unit testing:

Unit testing focuses verification effort on the smallest unit of software i.e. the

module. Using the detailed design and the process specifications testing is done to

Page 114: watermarking_newDoc

uncover errors within the boundary of the module. All modules must be successful in

the unit test before the start of the integration testing begins.

In this project ’Digital Water Marking on Multimedia Files’ the techniques FHT and

DCT

Are tested using Unit testing.

Unit testing focuses verification effort on the similar unit of software design the form.

This is known as form testing. Using the unit test plans, prepared in design phase of

the system development as a guide, important control paths are tested to uncover error

with in the boundary of the module. In this testing step, each module is found to be

working satisfactorily, as regard to the expected output from the module.

Each module has been tested by giving different sets of inputs,when developing the

module as well as finishing the development so that each module works without any

error.The inputs are validated when accepting from the user.

Integration Testing:

After the unit testing we have to perform integration testing. The goal here is to see if

modules can be integrated properly, the emphasis being on testing interfaces between

modules. This testing activity can be considered as testing the design and hence the

emphasis on testing module interactions.

In this project integrating all the modules forms the main system. When integrating

all the modules we have checked whether the integration effects working of any of

the services by giving different combinations of inputs with which the two services

run perfectly before Integration.

Page 115: watermarking_newDoc

Integration testing a systematic technique for constructing the program

structure while at the same time conducting tests to uncover errors associated with the

interface. All modules are combined in the testing step. Then the entire program is

tested as a whole.

Validation testing:

At the culmination of the integration testing, the software is completely

assembled as a package, interfacing errors have been uncovered and corrected and

final series of software validation testing begins.

SYSTEM TESTING

Here the entire software system is tested.The reference document for this process is

the requirements document, and the goal os to see if software meets its requirements.

Here entire project has been tested against requirements of project and it is checked

whether all requirements of project have been satisfied or not.

Output testing:

After performing validation testing, the next steps are output testing of the

proposed system, since no system could be useful if it does not produce the desired

output in the specified format. The output generated are displayed by the system

under consideration or tested by asking the user about the format required by them.

Here the output format is considered in two ways. One is on the screen and the other

is on the printed form.

Page 116: watermarking_newDoc

ACCEPTANCE TESTING

Acceptance Test is performed with realistic data of the client to demonstrate that

the software is working satisfactorily. Testing here is focused on external

behavoiur of the system,the internal logic of program is not emphasized.

In this project ‘Digital Watermarking on Multimedia Files’ we have collected some

data and tested whether project is working correctly or not.

Test cases should be selected so that the largest number of attributes of an

equivalence class is exercised at once.The testing phase is an important part of

software development. It is the process of finding errors and missing operations and

also a complete verification to determine whether the objectives are met and the user

requirements are satisfied.

User acceptance of a system is the key factor for the success of any system.

The system under consideration was tested for user acceptance by constantly keeping

in touch with the perspective system users at the time of developing and making

changes whenever required. This is done with regard to the following points.

Input screen design

Output screen design

Online message to guide the user

Menu driven system

Page 117: watermarking_newDoc

White Box Testing

This is a unit testing method where a unit will be taken at a time and tested

thoroughly at a statement level to find the maximum possible errors.

I tested step wise every piece of code, taking care that every statement in the code

is executed at least once. The white box testing is also called Glass Box Testing.

I have generated a list of test cases ,sample data.which is used to check all possible

combinations of execution paths through the code at every module level.

Black Box Testing

This testing method considers a module as a single unit and checks the unit at

interface and communication with other modules rather getting into details at

statement level. Here the module will be treated as a block box that will take some

Input generate output. Output for a given set of input combinations are forwarded to

other module.

CONCLUSION

This paper has presented a robust hybrid watermarking technique for

Embedding characters or grayscale image watermark into a container image based on

the FHT.The embedding and extracting processes have been described in detail.In the

proposed method,the embedding scheme takes the spatial information into

consideration,and generates the watermark strength factor according to the visual

mask.This increases the invisibility of the watermark in the watermarked image.The

experimental results show that the proposed method is robust against approximately

70% of stirmark attacks.

Page 118: watermarking_newDoc

The Hadamard transform has more useful middle and high frequency

bands than several high gain transforms, such as DCT.When compared with the

DCT,it is found to be more robust against various attacks.It also refers significant

advantage in terms of shorter processing time and the ease of hardware

implementation than many common transform techniques.

Page 119: watermarking_newDoc

BIBLOGRAPHY

1.Miller, M.Cox, I,J., Bloom, J.,”Watermarking in the Real World: An Application

to DVD”, Proc. Wksp Multimedia and security at ACM Multimedia 98

,Bristol, U.K., Sept. 1998.

2.Van Schyndel, R.J., Trikel, A.Z., Osborne, A.F.,” A digital watermark,” Proc .

IEEE Int. Conf. Image Processing, vol . 2, 86-90, 1994.

3.Cox, I.J., Kilian, J., Leighton, F.T., Shamoon, T., “Secure spread spectrum

watermarking for multimedia,” IEEE Trans. Image Processing, vol. 6, 1673-

1687, Dec. 1997.

4.Hsu, C.T., Wu, J.L., “Hidden digital watermarks in images,” IEEE Trans. Image

Processing, vol.8, pp. 58-68, Jan. 1999.

5.Joseph, J.K., O’ Ruanaidh, Pun T., “Rotation, Scale and Translation Invarient .

Digital Image Watermarking”, Signal Processing, vol.66, No.3, 303-317, 1998.

6.Wei, Z.H., Qin, P., Fu, Y.Q.,”Perceptual digital watermark of image using

wavelet transform “, IEEE Trans. On Consumer Electronics, Vol. 44, No.4, 1267-

1272, Nov. 1998.

7.Dugad, R., Ratakonda, K., Ahuja, N, “A new wavelet – base for watermarking

image,” in Proc. Int . Conf. Image Processing, vol.45, 1097- 101, Aug. 1998.