<<

CS6501/ CS6501 programming

M.I.E.T. ENGINEERING COLLEGE (Approved by AICTE and Affiliated to Anna University Chennai) TRICHY – PUDUKKOTTAI ROAD, TIRUCHIRAPPALLI – 620 007

DEPARTMENT OF COMPUTER SCIENCE AND

ENGINEERING

COURSE MATERIAL

CS6501 - INTERNET PROGRAMMING

III YEAR - V SEMESTER

M.I.E.T./CSE/III/Internet Programming

CS6501/ CS6501 internet programming

M.I.E.T. ENGINEERING COLLEGE (Approved by AICTE and Affiliated to Anna University Chennai) TRICHY – PUDUKKOTTAI ROAD, TIRUCHIRAPPALLI – 620 007 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING SYLLABUS (THEORY) Sub. Code : CS6501 Branch / Year / Sem : CSE/III/V Sub.Name : INTERNET PROGRAMMING Staff Name : P.RAMESH

SYLLABUS CS6501 INTERNET PROGRAMMING L T P 3 1 0 4 UNIT I JAVA PROGRAMMING 9 An overview of Java – Data Types – Variables and Arrays – Operators – Control Statements – Classes – Objects – Methods – Inheritance - Packages – Abstract classes – Interfaces and Inner classes – Exception handling - Introduction to Threads – Multithreading – String handling – Streams and I/O – Applets. UNIT II BASICS, HTML 5, CSS 3, WEB 2.0 8 Web 2.0: Basics-RIA Rich Internet Applications - Collaborations tools - Understanding websites and web servers: Understanding Internet – Difference between websites and - Internet technologies Overview –Understanding the difference between internet and intranet; HTML and CSS: HTML 5.0 , XHTML, CSS 3

UNIT II I CLIENT SIDE AND SERVER SIDE PROGRAMMING 11 Java Script: An introduction to JavaScript–JavaScript DOM Model-Date and Objects,- Regular Expressions- Exception Handling-Validation-Built-in objects-Event Handling- DHTML with JavaScript. Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST actions- Session Handling- Understanding Cookies- Installing and Configuring Web Server;- CONNECTIVITY: JDBC perspectives, JDBC program example - JSP: Understanding Java Server Pages-JSP Standard Tag Library(JSTL)- Creating HTML forms by embedding JSP code. UNIT IV PHP and XML 8 An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in functions- Connecting to Database – Using Cookies-Regular Expressions; XML: Basic XML- Document Type Definition- XML Schema DOM and Presenting XML, XML Parsers and Validation, XSL and XSLT Transformation, News Feed (RSS and ).

M.I.E.T./CSE/III/Internet Programming

CS6501/ CS6501 internet programming

UNIT V INTRODUCTION TO and WEB SERVICES 9 AJAX: Ajax Client Server Architecture-XML Http Request Object-Call Back Methods; Web Services: Introduction- Java web services Basics – Creating, Publishing ,Testing and Describing a Web services (WSDL)- Consuming a , Database Driven web service from an application – SOAP TOTAL (L:45+T:15): 60 PERIODS TEXT BOOKS: 1. Deitel and Deitel and Nieto, ―Internet and - How to Program‖, Prentice Hall, 5th Edition, 2011. 2. Herbert Schildt, ―Java-The Complete Reference‖, Eighth Edition, Mc Graw Hill Professional, 2011. REFERENCES: 1. Stephen Wynkoop and John Burke ―Running a Perfect ‖, QUE, 2nd Edition,1999. 2. Chris Bates, Web Programming – Building Intranet Applications, 3rd Edition, Wiley Publications, 2009. 3. Jeffrey C and Jackson, ―Web Technologies A Computer Science Perspective‖, Pearson Education, 2011.

M.I.E.T./CSE/III/Internet Programming

CS6501/ CS6501 internet programming

M.I.E.T. ENGINEERING COLLEGE (Approved by AICTE and Affiliated to Anna University Chennai) TRICHY – PUDUKKOTTAI ROAD, TIRUCHIRAPPALLI – 620 007

Sub. Code : CS6501 Branch/Year/Sem : CSE/III/V

Sub Name : Internet programming Staff Name :P.Ramesh

COURSE OBJECTIVE

Students will be able to: 1. Learn Java Programming. 2. Understand different Internet Technologies 3. Design and implement with validation using JavaScript objects and by applying different event handling mechanisms. 4. Learn server side programs using Servlets and JSP. 5. Be exposed to java specific web services architecture

COURSE OUTCOMES

On completion of course the students will be able to: 1. .Demonstrate how the real time logics are applied to basic java programs. 2. Understand, analyze and apply the role languages like HTML, CSS and protocols in the workings of web and web applications. 3. Create and communicate between client and server using Java and create a good, effective and dynamic website. 4. Understand about network and security programming using Java and know about the application of dynamic page functionality in web pages using Servlets, and JSP. 5. Design and implement simple web page in PHP, and to present data in XML format 6. Make clear a web services and client presentation using AJAX.

Prepared by Verified By

STAFF NAME HOD

P.RAMESH

Approved by

PRINCIPAL

M.I.E.T./CSE/III/Internet Programming

CS6501/ CS6501 internet programming

UNIT I JAVA PROGRAMMING 1.1 AN OVERVIEW OF JAVA Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:

1.1.1 C++ Vs Java Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class. Class - A class can be defined as a template/blue print that describes the behaviors/states that object of its type support. Objects in Java: Let us now look deep into what are objects. If we consider the real- world we can find many objects around us, Cars, Dogs, Humans, etc. All these objects have a state and behavior. If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging, running If you compare the software object with a real world object, they have very similar characteristics. Software objects also have a state and behavior. A software object's state is stored in fields and behavior is shown via methods. So in software development, methods operate on the internal state of an object and the object-to- object communication is done via methods.

Classes in Java: A class is a blue print from which individual objects are created. A sample of a class isgiven below public class Dog{ String breed; int age; String color; void barking(){ } void hungry(){ } void sleeping(){ } }

M.I.E.T./CSE/III/Internet Programming Subject code/Name: CS6501 internet programming

1.2 Data Types and Variables

Type Capacity Range Default value

byte 1B ( 8 bits) -27 to 27 - 1 0

short 2B (16 bits) -215 to 215 – 1 0

int 4B (32 bits) -231 to 231 – 1 0

long 8B (64 bits) -263 to 263 – 1 0.0L

float 32 bits IEEE 754 floating point 0.0f

double 64 bits IEEE 754 floating point 0.0D

boolea n 1 bit True / False False

‗\u0000‘ to char 16 bits ‗\uffff‘ NA

A class can contain any of the following variable types. Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.

Instance variables: Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. Class variables: Class variables are variables declared with in a class, outside any method, with the static keyword. A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(), hungry() and sleeping() are methods. Below mentioned are some of the important topics that need to be discussed when looking into classes of the Java Language. 1.3 Array

Normally, array is a collection of similar type of elements that have contiguous memory location.

Java array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array. M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Array in java is index based, first element of the array is stored at 0 index.

Advantage of Java Array

 Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.  Random access: We can get any data located at any index position.

Disadvantage of Java Array

 Size Limit: We can store only fixed size of elements in the array. It doesn't grow its sizeat runtime. To solve this problem, collection framework is used in java.

Example: class Testarray{ public static void main(String args[]){ int a[]=new int[5];//declaration and instantiation a[0]=10;//initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50; //printing array for(int i=0;i

} Output: 10 20 70 40 50

1.4 OPERATORS AND CONTROL STATEMENTS M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups −

 Arithmetic Operators  Relational Operators  Bitwise Operators  Logical Operators  Assignment Operators  Misc Operators

The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators −

Assume integer variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

Adds values on either side of the + (Addition) A + B will give 30 operator.

Subtracts right-hand operand from left- - (Subtraction) A - B will give -10 hand operand.

Multiplies values on either side of the * (Multiplication) A * B will give 200 operator.

Divides left-hand operand by right-hand / (Division) B / A will give 2 operand.

Divides left-hand operand by right-hand % (Modulus) B % A will give 0 operand and returns remainder.

++ (Increment) Increases the value of operand by 1. B++ gives 21

-- (Decrement) Decreases the value of operand by 1. B-- gives 19

The Relational Operators

There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Checks if the values of two operands are equal or == (equal to) (A == B) is not true. not, if yes then condition becomes true.

Checks if the values of two operands are equal or != (not equal to) not, if values are not equal then condition (A != B) is true. becomes true.

Checks if the value of left operand is greater than > (greater than) the value of right operand, if yes then condition (A > B) is not true. becomes true.

Checks if the value of left operand is less than the < (less than) value of right operand, if yes then condition (A < B) is true. becomes true.

Checks if the value of left operand is greater than >= (greater than or equal or equal to the value of right operand, if yes then (A >= B) is not true. to) condition becomes true.

Checks if the value of left operand is less than or <= (less than or equal equal to the value of right operand, if yes then (A <= B) is true. to) condition becomes true.

The Bitwise Operators

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows − a = 0011 1100 b = 0000 1101

------a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators −

Assume integer variable A holds 60 and variable B holds 13 then −

Show Examples

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Operator Description Example

Binary AND Operator copies a bit to the result (A & B) will give 12 which is & (bitwise and) if it exists in both operands. 0000 1100

Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is | (bitwise or) either operand. 0011 1101

Binary XOR Operator copies the bit if it is set (A ^ B) will give 49 which is ^ (bitwise XOR) in one operand but not both. 0011 0001

(~A ) will give -61 which is Binary Ones Complement Operator is unary 1100 0011 in 2's complement ~ (bitwise compliment) and has the effect of 'flipping' bits. due to a signed binary number.

Binary Left Shift Operator. The left operands A << 2 will give 240 which is << (left shift) value is moved left by the number of bits 1111 0000 specified by the right operand.

Binary Right Shift Operator. The left operands A >> 2 will give 15 which is >> (right shift) value is moved right by the number of bits 1111 specified by the right operand.

Shift right zero fill operator. The left operands value is moved right by the number of bits A >>>2 will give 15 which is >>> (zero fill right shift) specified by the right operand and shifted 0000 1111 values are filled up with zeros.

The Logical Operators

The following table lists the logical operators −

Assume Boolean variables A holds true and variable B holds false, then −

Show Examples

Operator Description Example

Called Logical AND operator. If both the operands are && (logical and) (A && B) is false non-zero, then the condition becomes true.

Called Logical OR Operator. If any of the two || (logical or) operands are non-zero, then the condition becomes (A || B) is true true.

Called Logical NOT Operator. Use to reverses the ! (logical not) logical state of its operand. If a condition is true then !(A && B) is true Logical NOT operator will make false.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

The Assignment Operators

Following are the assignment operators supported by Java language −

Show Examples

Operator Description Example

Simple assignment operator. Assigns values from C = A + B will assign value of A + B into = right side operands to left side operand. C

Add AND assignment operator. It adds right += operand to the left operand and assign the result to C += A is equivalent to C = C + A left operand.

Subtract AND assignment operator. It subtracts -= right operand from the left operand and assign the C -= A is equivalent to C = C – A result to left operand.

Multiply AND assignment operator. It multiplies *= right operand with the left operand and assign the C *= A is equivalent to C = C * A result to left operand.

Divide AND assignment operator. It divides left operand with the right operand and assign the result /= to left operand. C /= A is equivalent to C = C / A

Modulus AND assignment operator. It takes %= modulus using two operands and assign the result to C %= A is equivalent to C = C % A left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Miscellaneous Operators

There are few other operators supported by Java Language.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Conditional Operator ( ? : )

Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as − variable x = (expression) ? value if true : value if false

Following is an example −

Example public class Test {

public static void main(String args[]) { int a, b; a = 10; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30; System.out.println( "Value of b is : " + b ); } }

This will produce the following result −

Output

Value of b is : 30 Value of b is : 20 instanceof Operator

This operator is used only for object reference variables. The operator checks whether the object is of a particular type (class type or interface type). instanceof operator is written as −

( Object reference variable ) instanceof (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is an example −

Example public class Test {

public static void main(String args[]) {

String name = "James";

// following will return true since name is type of String M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

boolean result = name instanceof String; System.out.println( result ); } }

This will produce the following result −

Output true

This operator will still return true, if the object being compared is the assignment compatible with the type on the right. Following is one more example −

Example class Vehicle {} public class Car extends Vehicle {

public static void main(String args[]) {

Vehicle a = new Car(); boolean result = a instanceof Car; System.out.println( result ); } }

This will produce the following result −

Output true

Precedence of Java Operators

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −

For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix >() [] . (dot operator) Left toright

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Unary >++ - - ! ~ Right to left

Multiplicative >* / Left to right

Additive >+ - Left to right

Shift >>> >>> << Left to right

Relational >> >= < <= Left to right

Equality >== != Left to right

Bitwise AND >& Left to right

Bitwise XOR >^ Left to right

Bitwise OR >| Left to right

Logical AND >&& Left to right

Logical OR >|| Left to right

Conditional ?: Right to left

Assignment >= += -= *= /= %= >>= <<= &= ^= |= Right to left

CONTROL STATEMENTS There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop. Java has very flexible three looping mechanisms. You can use one of the following three loops: while Loop do...while Loop for Loop

As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop: A while loop is a control structure that allows you to repeat a task a certain number of times. Syntax: The syntax of a while loop is: while(Boolean_expression) {

//Statements }

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true. Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example: public class Test {

public static void main(String args[]) { int x = 10; while( x < 20 ) { System.out.print("value of x : " + x ); x++;

System.out.print("\n"); } } } This would produce the following result: value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 The do...while Loop: A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax: The syntax of a do...while loop is: do { //Statements }while(Boolean_expression); Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

If the Boolean expression is true, the of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

Example: public class Test { public static void main(String args[]){ int x = 10;

do{ System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 20 ) }

} This would produce the following result: value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19

The for Loop: A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. A for loop is useful when you know how many times a task is to be repeated.

Syntax: The syntax of a for loop is: for(initialization; Boolean_expression; update) { //Statements } Here is the flow of control in a for loop: The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates. Example: public class Test { public static void main(String args[]) { for(int x = 10; x < 20; x = x+1) { System.out.print("value of x : " + x ); System.out.print("\n"); } } } This would produce the following result: value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19

Enhanced for loop in Java: As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

Syntax: The syntax of enhanced for loop is: for(declaration : expression) {

//Statements } Declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element. Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.

Example: public class Test { M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

public static void main(String args[]){ int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){ System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] names ={"James", "Larry", "Tom", "Lacy"}; for( String name : names ) { System.out.print( name ); System.out.print(",");

} } }

This would produce the following result: 10,20,30,40,50, James,Larry,Tom,Lacy, The break Keyword: The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement. The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.

Syntax: The syntax of a break is a single statement inside any loop: break; Example: public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { if( x == 30 ) { break;

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

} System.out.print( x ); System.out.print("\n");

} } This would produce the following result: 10

20 The continue Keyword: The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.

In a for loop, the continue keyword causes flow of control to immediately jump to the update statement. In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression. Syntax: The syntax of a continue is a single statement inside any loop: continue; Example: public class Test {

public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { if( x == 30 ) { continue; } System.out.print( x ); System.out.print("\n");

} } } This would produce the following result: M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

10 20 40 50

1.5 CLASSES – OBJECTS – METHODS The object-oriented extension of Objective CAML is integrated with the functional and imperative kernels of the language, as well as with its type system. Indeed, this last point is unique to the language. Thus we have an object-oriented, statically typed language, with type inference. This extension allows definition of classes and instances, class inheritance (including multiple inheritance), parameterized classes, and abstract classes. Class interfaces are generated from their definition, but may be made more precise through a signature, similarly to what is done for modules.

Object-Oriented Terminology We summarize below the main object-oriented programming terms. class: a class describes the contents of the objects that belong to it: it describes an aggregate of data fields (called instance variables), and defines the operations (called methods). object: an object is an element (or instance) of a class; objects have the behaviors of their class. The object is the actual component of programs, while the class specifies how instances are created and how they behave. method: a method is an action which an object is able to perform. sending a message sending a message to an object means asking the object to execute or invoke one of its methods.

Class Declaration The simplest syntax for defining a class is as follows. We shall develop this definition throughout this chapter.

Syntax

class name p1 ...pn =

object

:

instance variables

:

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

methods

:

end

p1, ..., pn are the parameters for the constructor of the class; they are omitted if the class has no parameters.

An instance variable is declared as follows:

Syntax val name = expr or val mutable name = expr

When a data field is declared mutable, its value may be modified. Otherwise, the value is always the one that was computed when expr was evaluated during object creation.

Methods are declared as follows:

Syntax

method name p1 ...pn = expr

Other clauses than val and method can be used in a class declaration: we shall introduce them as needed. Our first class example. We start with the unavoidable class point:

 the data fields x and y contain the coordinates of the point,  two methods provide access to the data fields (get_x and get_y),  two displacement methods (moveto: absolute displacement) and (rmoveto: relative displacement),  one method presents the data as a string (to_string),  one method computes the distance to the point from the origin (distance).

# class point (x_init,y_init) = object val mutable x = x_init val mutable y = y_init method get_x = x method get_y = y method moveto (a,b) = x <- a ; y <- b M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

method rmoveto (dx,dy) = x <- x + dx ; y <- y + dy method to_string () = "( " ^ (string_of_int x) ^ ", " ^ (string_of_int y) ^")" method distance () = sqrt (float(x*x + y*y)) end ;;

Note that some methods do not need parameters; this is the case for get_x and get_y. We usually access instance variables with parameterless methods.

After we declare the class point, the system prints the following text: class point : int * int -> object val mutable x : int val mutable y : int method distance : unit -> float method get_x : int method get_y : int method moveto : int * int -> unit method rmoveto : int * int -> unit method to_string : unit -> string end

This text contains two pieces of information. First, the type for objects of the class; this type will be abbreviated as point. The type of an object is the list of names and types of methods in its class. In our example, point is an abbreviation for:

< distance : unit -> unit; get_x : int; get_y : int; moveto : int * int -> unit; rmoveto : int * int -> unit; to_string : unit -> unit >

Next, we have a constructor for instances of class point, whose type is int*int -> oint. The constructor allows us to construct point objects (we´ll just say ``points'' to be brief) from the initial values provided as arguments. In this case, we construct a point from a pair of integers (meaning the initial position). The constructor point is used with the keyword new. It is possible to define class types:

# type simple_point = < get_x : int; get_y : int; to_string : unit -> unit > ;; type simple_point = < get_x : int; get_y : int; to_string : unit -> unit >

1.6 INHERITANCE Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order. When we talk about inheritance, the most commonly used keyword would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

IS-A Relationship: IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance. public class Animal{ } public class Mammal extends Animal{ } public class Reptile extends Animal{

} public class Dog extends Mammal{ } Now, based on the above example, In Object Oriented terms, the following are true: Animal is the superclass of Mammal class. Animal is the superclass of Reptile class. Mammal and Reptile are subclasses of Animal class. Dog is the subclass of both Mammal and Animal classes. if we consider the IS-A relationship, we can say: Mammal IS-A Animal Reptile IS-A Animal Dog IS-A Mammal Hence : Dog IS-A Animal as well With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass. We can assure that Mammal is actually an Animal with the use of the instance operator.

Example: public class Dog extends Mammal{ public static void main(String args[]){ Animal a = new Animal(); Mammal m = new Mammal(); Dog = new Dog();

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal); } } This would produce the following result: true true true Since we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship. The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended by the classes.

Example: public interface Animal {} public class Mammal implements Animal{ } public class Dog extends Mammal{ }

The instanceof Keyword: Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal interface Animal{} class Mammal implements Animal{} public class Dog extends Mammal{ public static void main(String args[]){ Mammal m = new Mammal(); Dog d = new Dog(); System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal); } } This would produce the following result:

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming true true true

HAS-A relationship: These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs. Lets us look into an example: public class Vehicle{} public class Speed{} public class Van extends Vehicle{ private Speed sp; }In Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.

A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot extend more than one class. Therefore following is illegal: public class extends Animal, Mammal{} However, a class can implement one or more interfaces. This has made Java get rid of the impossibility of multiple inheritance. 1.7 PACKAGES and ABSTRACT CLASSES Java Package: In simple, it is a way of categorizing the classes and interfaces. When developing applications in Java, hundreds of classes and interfaces will be written, therefore categorizing these classes is a must as well as makes life much easier.

Import statements: In Java if a fully qualified name, which includes the package and the class name, is given then the compiler can easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler to find that particular class. For example, the following line would ask compiler to load all the classes available in directory java_installation/java/io : import java.io.*; For our case study, we will be creating two classes. They are Employee and EmployeeTest. First open notepad and add the following code. Remember this is the Employee class and the class is a public class. Now, save this source file with the name Employee.java.

The Employee class has four instance variables name, age, designation and salary. The class has one explicitly defined constructor, which takes a parameter.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming import java.io.*; public class Employee{ String name; int age; String designation; double salary; // This is the constructor of the class Employee public Employee(String name){ this.name = name; } // Assign the age of the Employee to the variable age. public void empAge(int empAge){ age = empAge; } /* Assign the designation to the variable designation.*/ public void empDesignation(String empDesig){ designation = empDesig; } /* Assign the salary to the variable salary.*/ public void empSalary(double empSalary){ salary = empSalary; } /* Print the Employee details */ public void printEmployee(){

System.out.println("Name:"+ name ); System.out.println("Age:" + age ); System.out.println("Designation:" + designation ); System.out.println("Salary:" + salary); }

Given below is the EmployeeTest class, which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable.

Save the following code in EmployeeTest.java file import java.io.*; public class EmployeeTest{

public static void main(String args[]){

/* Create two objects using constructor */

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Employee empOne = new Employee("James Smith"); Employee empTwo = new Employee("Mary Anne");

// Invoking methods for each object created empOne.empAge(26); empOne.empDesignation("Senior Software Engineer"); empOne.empSalary(1000);

empOne.printEmployee();

empTwo.empAge(21); empTwo.empDesignation("Software Engineer"); empTwo.empSalary(500); empTwo.printEmployee(); } } Now, compile both the classes and then run EmployeeTest to see the result as follows:

C :> javac Employee.java C :> vi EmployeeTest.java C :> javac EmployeeTest.java C :> java EmployeeTest Name:James Smith Age:26

Designation:Senior Software Engineer Salary:1000.0 Name:Mary Anne Age:21 Designation:Software Engineer Salary:500.0

Abstraction Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class.

If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclass. This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own.

Abstract Class: Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration somewhere before the class keyword.

/* File name : Employee.java */ public abstract class Employee {

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming private String name; private String address; private int number; public Employee(String name, String address, int number) { System.out.println("Constructing an Employee"); this.name = name; this.address = address; this.number = number; } public double computePay()

{

System.out.println("Inside Employee computePay"); return 0.0; } public void mailCheck() { System.out.println("Mailing a check to " + this.name + " " + this.address); } public String toString() { return name + " " + address + " " + number; } public String getName() {

return name; } public String getAddress() {

return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber()

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

{ return number; } }

Notice that nothing is different in this Employee class. The class is now abstract, but it still has three fields, seven methods, and one constructor. Now if you would try as follows: /* File name : AbstractDemo.java */ public class AbstractDemo { public static void main(String [] args) /* Following is not allowed and would raise error */

Employee e = new Employee("George W.", "Houston, TX", 43);

System.out.println("\n Call mailCheck using Employee reference--"); e.mailCheck();

} } When you would compile above class then you would get the following error:

Employee.java:46: Employee is abstract; cannot be instantiated Employee e = new Employee("George W.", "Houston, TX", 43)

1.8 INTERFACES AND INNER CLASSES

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

An interface is similar to a class in the following ways:

An interface can contain any number of methods.

An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.

The of an interface appears in a .class file. M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to declare an interface:

Example:

Let us look at an example that depicts encapsulation:

/* File name : NameOfInterface.java */ import java.lang.*;

//Any number of import statements public interface NameOfInterface

{ //Any number of final, static fields

//Any number of abstract method declarations\ }

Interfaces have the following properties: An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface. Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. Methods in an interface are implicitly public.

Example:

/* File name : Animal.java */ interface Animal {

public void eat(); public void travel();

}

Implementing Interfaces:

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.

A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

/* File name : MammalInt.java */ public class MammalInt implements Animal{ public void eat(){ System.out.println("Mammal eats");

}

public void travel(){ System.out.println("Mammal travels");

}

public int noOfLegs(){ return 0;

}

public static void main(String args[]){ MammalInt m = new MammalInt(); m.eat(); m.travel(); }

}

This would produce the following result:

Mammal eats

Mammal travels

When overriding methods defined in interfaces there are several rules to be followed:

Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method.

The signature of the interface method and the same return type or subtype should be maintained when overriding the methods.

An implementation class itself can be abstract and if so interface methods need not be implemented.

When implementation interfaces there are several rules:

A class can implement more than one interface at a time.

A class can extend only one class, but implement many interfaces.

An interface can extend another interface, similarly to the way that a class can extend another class.

Extending Interfaces: M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

An interface can extend another interface, similarly to the way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.

The following Sports interface is extended by Hockey and Football interfaces. //Filename: Sports.java public interface Sports { public void setHomeTeam(String name); public void setVisitingTeam(String name); }

//Filename: Football.java public interface Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter);

} //Filename: Hockey.jav public interface Hockey extends Sports { public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); } The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports. Extending Multiple Interfaces: A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface. The extends keyword is used once, and the parent interfaces are declared in a comma-separated list. For example, if the Hockey interface extended both Sports and Event, it would be declared as: public interface Hockey extends Sports, Event Tagging Interfaces: The most common use of extending interfaces occurs when the parent interface does not contain any methods. For example, the MouseListener interface in the java.awt.event package extended java.util.EventListener, which is defined as: package java.util; M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming public interface EventListener {} An interface with no methods in it is referred to as a tagging interface. There are two basic design purposes of tagging interfaces: Creates a common parent: As with the EventListener interface, which is extended by dozens of other interfaces in the Java API, you can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends EventListener, the JVM knows that this particular interface is going to be used in an event delegation scenario. 1.9 EXCEPTION HANDLING Exception

An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following: A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by error, and others by physical resources that have failed in some manner. Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following: try

{ //Protected code }catch(ExceptionName e1) {

//Catch block }

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. Example: The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.

// File Name : ExcepTest.java import java.io.*; public class ExcepTest{

public static void main(String args[]){ try{ M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e);

} System.out.println("Out of the block"); } }

This would produce the following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block Multiple catch Blocks: A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following: try { //Protected code }catch(ExceptionType1 e1) {

//Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block } The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.

Example: Here is code segment showing how to use multiple try/catch statements. Try { file = new FileInputStream(fileName); x = (byte) file.read();

}catch(IOException i) M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

{ i.printStackTrace(); return - 1;

}catch(FileNotFoundException f) //Not valid! {

f.printStackTrace(); return - 1;

}

1.10 INTRODUCTION TO THREADS 1.10.1 Life Cycle of a Thread: A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread. New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Thread Priorities: Every Java thread has a priority that helps the determine the order in which threads are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependentant. Create Thread by Implementing Runnable Interface: If your class is intended to be executed as a thread then you can achieve this by implementing Runnable interface. You will need to follow three basic steps:

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Step 1: As a first step you need to implement a run() method provided by Runnable interface. This method provides entry point for the thread and you will put you complete business logic inside this method. Following is simple syntax of run() method: public void run( )

Step 2: At second step you will instantiate a Thread object using the following constructor: Thread(Runnable threadObj, String threadName); Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread.

Step 3 Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method. Following is simple syntax of start() method: void start( );

Example: Here is an example that creates a new thread and starts it running: class RunnableDemo implements Runnable { private Thread t; private String threadName; RunnableDemo( String name){ threadName = name; System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadName + ", " + i);

// Let the thread sleep for a while. Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrupted.");

} System.out.println("Thread " + threadName + " exiting."); M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

}

public void start ()

{ System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); }

}

} public class TestThread {

public static void main(String args[]) {

RunnableDemo R1 = new RunnableDemo( "Thread-1");

R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2"); R2.start();

} }

This would produce the following result: Creating Thread-1

Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3

Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2

Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

1.11 MULTITHREADING

Create Thread by Extending Thread Class: The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class. Step 1 You will need to override run( ) method available in Thread class. This method provides entry point for the thread and you will put you complete business logic inside this method. Following is simple syntax of run() method: public void run( ) Step 2 Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method. Following is simple syntax of start() method: void start( ); Here is the preceding program rewritten to extend Thread: class ThreadDemo extends Thread { private Thread t; private String threadName; ThreadDemo( String name){ threadName = name; System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { for(int i = 4; i > 0; i--) System.out.println("Thread: " + threadName + ", " + i); // Let the thread sleep for a while. Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrupted."); } System.out.println("Thread " + threadName + " exiting."); }

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

public void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread {

public static void main(String args[]) {

ThreadDemo T1 = new ThreadDemo( "Thread-1");

T1.start();

ThreadDemo T2 = new ThreadDemo( "Thread-2"); T2.start();

} }

This would produce the following result:

Creating Thread-1

Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4

Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread:Thread-1,2

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

1.12 STRING HANDLING String Handling in Java The basic aim of String Handling concept is storing the string data in the main memory (RAM), manipulating the data of the String, retrieving the part of the String etc. String Handling provides a lot of concepts that can be performed on a string such as concatenation of string, comparison of string, find sub string etc.

Character It is an identifier enclosed within single quotes (' '). Example: 'A', '$', 'p'

String: String is a sequence of characters enclosed within double quotes (" ") is known as String. Example: "Java Programming".

In java programming to store the character data we have a fundamental datatype called char. Similarly to store the string data and to perform various operation on String data, we have three predefined classes they are:

 String  StringBuffer  StringBuilder

How to create String object? There are two ways to create String object: 1. By string literal 2. By new keyword

1) String Literal Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:

1. String s1="Welcome"; 2. String s2="Welcome";//will not create new instance

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

In the above example only one object will be created. Firstly JVM will not find any string object with the value "Welcome" in string constant pool, so it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create new object but will return the reference to the same instance.

2) By new keyword

1. String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).

Java String Example

1. public class StringExample{ 2. public static void main(String args[]){ 3. String s1="java";//creating string by java string literal 4. char ch[]={'s','t','r','i','n','g','s'}; 5. String s2=new String(ch);//converting char array to string 6. String s3=new String("example");//creating java string by new keyword 7. System.out.println(s1); 8. System.out.println(s2); 9. System.out.println(s3); 10. }}

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

OUTPUT: java strings example

1.13 STREAMS AND I/O IO Stream The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters, etc.

A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers very basic functionality related to streams and I/O. We would see most commonly used example one by one:

Byte Streams Java byte streams are used to perform input and output of 8 -bit bytes. Though there are many classes related to byte streams but the most frequently used classes are , FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file: import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null;

try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally {

if (in != null) { in.close(); }

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

if (out != null) { out.close();

}

} }} now let's have a file input.txt with the following content:

This is test for copy file.

As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the following:

$javac CopyFile.java

$java CopyFile

Character Streams

Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are , FileReader and FileWriter.. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

We can re-write above example which makes use of these two classes to copy an input file (having unicode characters) into an output file: import java.io.*; public class CopyFile {

public static void main(String args[]) throws IOException { FileReader in = null; FileWriter out = null;

try {

in = new FileReader("input.txt"); out = new FileWriter("output.txt");

int c;

while ((c = in.read()) != -1) { out.write(c); }

}finally { M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

if (in != null) { in.close(); }

if (out != null) { out.close(); }

} }

Now let's have a file input.txt with the following content: This is test for copy file. As a next step, compile above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put above code in CopyFile.java file and do the following: $javac CopyFile.java $java CopyFile Standard Streams All the programming languages provide support for standard I/O where user's program can take input from a keyboard and then produce output on the computer screen. If you are aware if C or C++ programming languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similar way Java provides following three standard streams Standard Input: This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System.in. Standard Output: This is used to output the data produced by the user's program and usually a computer screen is used to standard output stream and represented as System.out.

Standard Error: This is used to output the error data produced by the user's program and usually a computer screen is used to standard error stream and represented as System.err.

Following is a simple program which creates InputStreamReader to read standard input stream until the user types a "q": import java.io.*; public class ReadConsole {

public static void main(String args[]) throws IOException M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

{

InputStreamReader cin = null;

try {

cin = new InputStreamReader(System.in); System.out.println("Enter characters, 'q' to quit."); char c; do { c = (char) cin.read(); System.out.print(c);

} while(c != 'q'); }finally {

if (cin != null) { cin.close(); } } } }

Let's keep above code in ReadConsole.java file and try to compile and execute it as below. This program continues reading and outputting same character until we press 'q':

$javac ReadConsole.java $java ReadConsole

Enter characters, 'q' to quit. 1 1 e e q q

1.14 APPLETS

An applet is a Java program that runs in a . An applet can be a fully functional Java application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java application, including the following:

An applet is a Java class that extends the java.applet.Applet class.

A main() method is not invoked on an applet, and an applet class will not define main(). Applets are designed to be embedded within an HTML page.

.

Applets have strict security rules that are enforced by the Web browser. The security of an applet is often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various rules that must be followed. M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Life Cycle of an Applet: Four methods in the Applet class give you the framework on which you build any serious applet:

init: This method is intended for whatever initialization is needed for your applet. It is called after the param tags inside the applet tag have been processed. start: This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages. stop: This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet. destroy: This method is only called when the browser shuts down normally. Because applets are meant to live on an HTML page, you should not normally leave resources behind after a user leaves the page that contains the applet. paint: Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. The paint() method is actually inherited from the java.awt.

A "Hello, World" Applet:

The following is a simple applet named HelloWorldApplet.java: import java.applet. *; import java.awt.*; public class HelloWorldApplet extends Applet

{ public void paint (Graphics g) { g.drawString ("Hello World", 25, 50); }

}

These import statements bring the classes into the scope of our applet class:

java.applet.Applet.

java.awt.Graphics. without those import statements, the Java compiler would not recognize the classes Applet and Graphics, which the applet class refers to.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

The Applet CLASS:

Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods that a derived Applet class may call to obtain information and services from the browser context.

These include methods that do the following:

Get applet parameters

Get the network location of the HTML file that contains the applet Get the network location of the applet class directory Print a status message in the browser Fetch an image Fetch an audio clip

Play an audio clip Resize the applet

The Applet class provides default implementations of each of these methods. Those implementations may be overridden as necessary.

The "Hello, World" applet is complete as it stands. The only method overridden is the paint method.

Invoking an Applet:

An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser.

The tag is the basis for embedding an applet in an HTML file. Below is an example that invokes the "Hello, World" applet:

The Hello, World Applet


If your browser was Java-enabled, a "Hello, World" message would appear here.


M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

UNIT II

WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0 8

WEB 2.0: BASICS-RIA RICH INTERNET APPLICATIONS

2.1 WEB 2.0: BASICS

Web 2.0 (pronounced web two point oh) describes World Wide Web websites that emphasize user- generated content, usability (ease of use, even by non-experts), and interoperability (this means that a website can work well with other products, systems and devices) for end users. The term was popularized by Tim O'Reilly and Dale Dougherty at the O'Reilly Media Web 2.0 Conference in late 2004, though it was coined by Darcy DiNucci in 1999.[1][2][3][4] Web 2.0 does not refer to an update to any technical specification, but to changes in the way Web pages are designed and used.

A Web 2.0 website may allow users to interact and collaborate with each other in a social media dialogue as creators of user-generated content in a virtual community, in contrast to the first generation of Web 1.0-era websites where people were limited to the passive viewing of content. Examples of Web 2.0 include social networking sites and social media sites (e.g., Facebook), blogs, wikis, ("tagging" keywords on websites and ), video sharing sites (e.g., YouTube), hosted services, Web applications ("apps"), collaborative consumption platforms, and mashup applications.

Whether Web 2.0 is substantively different from prior Web technologies has been challenged by World Wide Web inventor Tim Berners-Lee, who describes the term as jargon.[5] His original vision of the Web was "a collaborative medium, a place where we [could] all meet and read and write".[6][7] On the other hand, the term Semantic Web (sometimes referred to as Web 3.0)[8] was coined by Berners-Lee to refer to a web of content where the meaning can be processed by machines

Advantages of Web 2.0:

 Available at any time, any place.  Variety of media.  Ease of usage.  Learners can actively be involved in knowledge building.  Can create dynamic learning communities.  Everybody is the author and the editor, every edit that has been made can be tracked.  User friendly.  Updates in wiki are immediate and it offers more sources for researchers.  Provides real-time discussion.

2.1.1 Web 2.0 features:

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

It allows users to collectively classify and find dynamic information that flows two ways between site owner and site user by means of evaluation, comments and reviews. Site users can add content for others to see. Web 2.0 sites provide to allow automated usage by an app or mashup like it provides location that can be processed by a simple browser tool.

The future:

The business forecasters are all claiming that Web 2.0 is an intermediate phase between the World Wide Web‘s existence and a more established phase they‘re calling Web 3.0.

The web as a whole can be designed more intelligently around serving a user‘s wants or needs. The developers and authors, singly or in collaboration, can use self-descriptions or similar techniques so that the information provided by the new context-aware program is relevant to the user.

Web 1.0 Web 2.0 Web 3.0 Content Speedy Ubiquitous destination sites and personal more timely information and more available at any time, anywhere, portals efficient tools to find information through any channel or device Search Collaborative Efficient critical mass of content drives actions of user a mass, police, and relevant and contextual information need for search engines prioritize content findable instantly Commerce Trust-worthy Individualized goes mainstrean; digital good user establish trust networks and filtered and shared by friends or rise home trust radars trust networks

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

2.1.2 Web 2.0 Technologies:

 The client-side (Web browser) technologies used in Web 2.0 development include Ajax and JavaScript frameworks. Ajax programming uses JavaScript and the to update selected regions of the page area without undergoing a full page reload.  To allow users to continue to interact with the page, communications such as data requests going to the server are separated from data coming back to the page (asynchronously). Otherwise, the user would have to routinely wait for the data to come back before they can do anything else on that page, just as a user has to wait for a page to complete the reload.  This also increases overall performance of the site, as the sending of requests can complete quicker independent of blocking and queueing required to send data back to the client. The data fetched by an Ajax request is typically formatted in XML or JSON (JavaScript Object Notation) format, two widely used structured data formats.  Since both of these formats are natively understood by JavaScript, a programmer can easily use them to transmit structured data in their . When this data is received via Ajax, the JavaScript program then uses the Document Object Model (DOM) to dynamically update the Web page based on the new data, allowing for a rapid and interactive user experience. In short, using these techniques, Web designers can make their pages function like desktop applications. For example, Google Docs uses this technique to create a Web-based word processor.  As a widely available plugin independent of W3C standards (the World Wide Web Consortium is the governing body of and protocols), is capable of doing many things that were not possible pre-HTML5. Of Flash's many capabilities, the most commonly used is its ability to integrate streaming multimedia into HTML pages.  With the introduction of HTML5 in 2010 and growing concerns with Flash's security, the role of Flash is decreasing. In addition to Flash and Ajax, JavaScript/Ajax frameworks have recently become a very popular means of creating Web 2.0 sites. At their core, these frameworks use the same technology as JavaScript, Ajax, and the DOM.  However, frameworks smooth over inconsistencies between Web browsers and extend the functionality available to developers. Many of them also come with customizable, prefabricated 'widgets' that accomplish such common tasks as picking a date from a calendar, displaying a data chart, or making a tabbed panel. On the server-side, Web 2.0 uses many of the same technologies as Web 1.0.  Languages such as , PHP, Python, Ruby, as well as Enterprise Java (J2EE) and .NET Framework, are used by developers to output data dynamically using information from files and . This allows websites and web services to share machine readable formats such as XML (Atom, RSS, etc.) and JSON.  When data is available in one of these formats, another website can use it to integrate a portion of that site's functionality.

2.1.3 Merits and Demerits:

Advantages of Web 2.0 are:

1. Web 2.0 provides large varieties of information just in one click. 2. Ability to search data and information appeared recently. 3. Web 2.0 is easy to handle. 4. Great varieties of entries is available on the internet. 5. Easy to search information in various languages. 6. Allows people to participate in discussion and forums to share their views and ideas, 7. Social media sites to share things happening around the world. 8. Web 2.0 allows people to complete and correct wrong information. M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

9. Easy and fast method to communicate with people via email and other services. 10. Ability to share files or documents with friends and family. 11. Easy and cheap method to promote your business online. 12. Opportunity to stay in touch with many people by web 2.0 13. Opportunity to know different people staying around the world. 14. Easy to share lots of information simply sitting at home. 15. Good quality of images and video can also be shared.

Disadvantages of Web 2.0 are:

1. Sometimes results shown are different from what is asked. 2. Sometimes Translation of results is not of good quality. 3. Sometimes It takes too long to get answer to what is asked. 4. Risk of getting wrong information. 5. Not able to contact people if you dont know the email address or website address. 6. Risk of Spamming , Fraud and Virus attack. 7. Sometimes Lack of privacy.

2.2 RIA (Rich Internet Application):-

 RIA (Rich Internet Application) is defined as a web application that is designed to give the same features and functions associated with desktop applications.  HTML is not having much capability and performance in web apps  Users need desktop type of interaction from web apps  RIA fulfils this need, user interactivity  It is the 3rd generation of web apps  It runs inside a web browser and does not need any special software installation (plug&play)

2.2.1 Features of RIA:-  Ability to work on web, presents complex info to users  Rich set of visual elements like image, video, graphics, etc  It works in real-time, helps business services  Users can know how to use complex apps  Reduce unnecessary page navigations  Responsiveness, interactivity  Ex: , Quick PHP, .NET framework, JavaFX

2.2.2 Framework of RIA:- GUI logic is moved from server to client

 Because GUI is executed in browser, CPU time needed to generate GUI is taken off from server, thereby making server free for more CPU cycles to run app logic  GUI state is kept in browser

 Because GUI is separated from app logic, it is easy to implement

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

 RIA communicate with servers by exchanging data, not the GUI code (HTML, CSS, JS)  Data exchange: XML via HTTP (or) JSON via HTTP

 If server side becomes completely free, then the app logic will become very clear to understand  App logic just need to focus on data in and data out

Technologies used in RIA:-  HTML5+CSS3, Java script, JS framework, jQuery, jQuery Mobile, AngularJS, SmartClient, GWT, JavaFX, Flex, MS Silverlight

2.2.3 Benefits of RIA:-  Increased productivity, new customers  Reduced operational costs  No installation required  Easy upgrade  Available through internet  Rich and more responsive UI  Client/server balance  Asynchronous communication  Efficiency in network

Limitations of RIA:-  Too fast in displaying contents  Maintain balance between HTML and RIA  GUI logic and app logic might be in different languages  Search engines are declining  Proprietary  Loss of integrity

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

 Complicated to develop apps, what to cache, what not to.  Breaks web page paradigm

2.3 COLLABORATIONS TOOLS Collaboration tools:-

 Collaboration tools allow a group of people work together virtually in real-time over the internet.

Features:-

Easy to use and set up. Clean interface

Secure Permissions control

Ability to upload documents File storage

Scalable Document locking

Examples:-

Tool Use

Google Docs Upload/modify/retrieve files anytime

Dropbox Store/share/sync files online

Blogger Blogging site of google

Wordpress Flexible, FOSS, easy blogging tool

PDFcatch e-books, PDF search engine

SlideShare PPT, PDF share/upload/download

Youtube Upload/download/view videos

Facebook Upload/download/view micro contents

Twitter Upload/doenload/view thoughts

Advantages of Collaboration tools:-

 Reduces distance between employees  Work in same room, together in same documents  No need to send documents back and forth between offices  Communication between employees is improved  Increases team work and transparency  Easy to keep track of projects  Easy to generate reports  Team members can be present anywhere  Online chatting M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

 IRC (Internet relay Chat)  Video conferencing  2.4 UNDERSTANDING WEBSITES AND WEB SERVERS

A website is a collection of related web pages, including multimedia content, typically identified with a common domain name, and published on at least one web server. A website may be accessible via a public Internet Protocol (IP) network, such as the Internet, or a private local area network (LAN), by referencing a uniform resource locator (URL) that identifies the site.

Websites have many functions and can be used in various fashions; a website can be a personal website, a commercial website for a company, a government website or a non-profit organization website. Websites are typically dedicated to a particular topic or purpose, ranging from entertainment and social networking to providing news and education. All publicly accessible websites collectively constitute the World Wide Web, while private websites, such as a company's website for its employees, are typically a part of an intranet.

Web pages, which are the building blocks of websites, are documents, typically composed in plain text interspersed with formatting instructions of Markup Language (HTML, XHTML). They may incorporate elements from other websites with suitable markup anchors. Web pages are accessed and transported with the Hypertext Transfer Protocol (HTTP), which may optionally employ encryption (HTTP Secure, HTTPS) to provide security and privacy for the user. The user's application, often a web browser, renders the page content according to its HTML markup instructions onto a display terminal.

Hyperlinking between web pages conveys to the reader the site structure and guides the navigation of the site, which often starts with a home page containing a directory of the site web content. Some websites require user registration or subscription to access content. Examples of subscription websites include many business sites, news websites, academic journal websites, gaming websites, file-sharing websites, message boards, web-based email, social networking websites, websites providing real-time stock market data, as well as sites providing various other services. As of 2016 end users can access websites on a range of devices, including desktop and laptop computers, tablet computers, smartphones and smart TVs.

Static website

A static website is one that has web pages stored on the server in the format that is sent to a client web browser. It is primarily coded in Hypertext Markup Language (HTML); Cascading Style Sheets (CSS) are used to control appearance beyond basic HTML. Images are commonly used to effect the desired appearance and as part of the main content. Audio or video might also be considered "static" content if it plays automatically or is generally non-interactive. This type of website usually displays the same information to all visitors. Similar to handing out a printed brochure to customers or clients, a static website will generally provide consistent, standard information for an extended period of time. Although the website owner may make updates periodically, it is a manual process to edit the text, photos and other content and may require basic website design skills and software. Simple forms or marketing examples of websites, such as classic website, a five-page website or a brochure website are often static websites, because they present pre-defined, static information to the user. This may include information about a company and its products and services through text, photos, animations, audio/video, and navigation menus.

Static websites can be edited using four broad categories of software:

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

 Text editors, such as Notepad or TextEdit, where content and HTML markup are manipulated directly within the editor program  WYSIWYG offline editors, such as Microsoft FrontPage and (previously Dreamweaver), with which the site is edited using a GUI and the final HTML markup is generated automatically by the editor software  WYSIWYG online editors which create media rich online presentation like web pages, widgets, intro, blogs, and other documents.  Template-based editors such as iWeb allow users to create and upload web pages to a web server without detailed HTML knowledge, as they pick a suitable template from a palette and add pictures and text to it in a desktop publishing fashion without direct manipulation of HTML code.

Static websites may still use (SSI) as an editing convenience, such as sharing a common menu bar across many pages. As the site's behaviour to the reader is still static, this is not considered a dynamic site.

Dynamic website

A dynamic website is one that changes or customizes itself frequently and automatically. Server-side dynamic pages are generated "on the fly" by computer code that produces the HTML (CSS are responsible for appearance and thus, are static files). There are a wide range of software systems, such as CGI, Java Servlets and Java Server Pages (JSP), and ColdFusion (CFML) that are available to generate dynamic web systems and dynamic sites. Various web application frameworks and web template systems are available for general-use programming languages like Perl, PHP, Python and Ruby to make it faster and easier to create complex dynamic websites.

A site can display the current state of a dialogue between users, monitor a changing situation, or provide information in some way personalized to the requirements of the individual user. For example, when the front page of a news site is requested, the code running on the web server might combine stored HTML fragments with news stories retrieved from a database or another website via RSS to produce a page that includes the latest information. Dynamic sites can be interactive by using HTML forms, storing and reading back browser cookies, or by creating a series of pages that reflect the previous history of clicks. Another example of dynamic content is when a retail website with a database of media products allows a user to input a search request, e.g. for the keyword Beatles. In response, the content of the web page will spontaneously change the way it looked before, and will then display a list of Beatles products like CDs, DVDs and books. Dynamic HTML uses JavaScript code to instruct the web browser how to interactively modify the page contents. One way to simulate a certain type of dynamic website while avoiding the performance loss of initiating the dynamic engine on a per-user or per-connection basis, is to periodically automatically regenerate a large series of static pages. web server

A web server is a computer system that processes requests via HTTP, the basic network protocol used to distribute information on the World Wide Web. The term can refer to the entire system, or specifically to the software that accepts and supervises the HTTP requests.[1]

OverviewThe primary function of a web server is to store, process and deliver web pages to clients. The communication between client and server takes place using the Hypertext Transfer Protocol (HTTP). Pages delivered are most frequently HTML documents, which may include images, style sheets and scripts in addition to text content.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Multiple web servers may be used for a high traffic website, here Dell servers are installed together being used for the Wikimedia Foundation

A user agent, commonly a web browser or web crawler, initiates communication by making a request for a specific resource using HTTP and the server responds with the content of that resource or an error message if unable to do so. The resource is typically a real file on the server's secondary storage, but this is not necessarily the case and depends on how the web server is implemented.

While the primary function is to serve content, a full implementation of HTTP also includes ways of receiving content from clients. This feature is used for submitting web forms, including uploading of files.

Many generic web servers also support server-side scripting using Active Server Pages (ASP), PHP, or other scripting languages. This means that the behaviour of the web server can be scripted in separate files, while the actual server software remains unchanged. Usually, this function is used to generate HTML documents dynamically ("on-the-fly") as opposed to returning static documents. The former is primarily used for retrieving or modifying information from databases. The latter is typically much faster and more easily cached but cannot deliver dynamic content.

Web servers are not only used for serving the World Wide Web. They can also be found embedded in devices such as printers, routers, webcams and serving only a local network. The web server may then be used as a part of a system for monitoring or administering the device in question. This usually means that no additional software has to be installed on the client computer, since only a web browser is required (which now is included with most operating systems).

Kernel-mode and user-mode web servers

A web server can be either incorporated into the OS kernel, or in user space (like other regular applications).

Web servers that run in user-mode have to ask the system for permission to use more memory or more CPU resources. Not only do these requests to the kernel take time, but they are not always satisfied because the system reserves resources for its own usage and has the responsibility to share hardware resources with all the other running applications. Executing in user mode can also mean useless buffer copies which are another handicap for user-mode web servers.

Load limits

A web server (program) has defined load limits, because it can handle only a limited number of concurrent client connections (usually between 2 and 80,000, by default between 500 and 1,000) per IP address (and TCP port) and it can serve only a certain maximum number of requests per second (RPS, also known as queries per second or QPS) depending on: M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

 its own settings,  the HTTP request type,  whether the content is static or dynamic,  whether the content is cached, and  the hardware and software limitations of the OS of the computer on which the web server runs.

When a web server is near to or over its limit, it becomes unresponsive.

2.5 UNDERSTANDING INTERNET

Understanding Internet Basics You can program for the Web, using your skills as a programmer, no matter what your level of experience with Internet technology. If you are new to the Internet or unfamiliar with its technology, Visual Basic allows you to quickly and easily produce functional applications. If you are more experienced with Internet technology, you can work at a more advanced level. From one perspective, Internet technology simply provides another area for your development efforts. When you deploy Internet applications on the Web, you may go about it differently — incorporating HTML pages with your Visual Basic code, providing security features, and so on — but you're still calling methods, setting properties, and handling events. In this way, all of your knowledge as a Visual Basic developer can be carried into the Internet . From another perspective, applying Internet technology enables you to extend your development skills in exciting new ways. For example, writing Visual Basic code that manipulates HTML pages allows you to decrease deployment costs, reduce client maintenance problems, and reach the broad audience of the Internet. Internet Clients and Servers A common way to think about Internet development is in terms of client/server relationships. In this case, the client is the browser, and the server is the Web server. Most interactions on the Internet or an intranet can be thought of in terms of requests and responses. The browser makes a request to the Web server (usually to display a page the user wants to see) and the Web server returns a response (usually an HTML page, an element, or an image) to the browser.  A network is defined as an interconnection of computing devices in order to transfer data between them

 An internet is defined as an interconnection of networks in order to transfer data between the networks across the globe

 It is a network connecting millions of computers across the globe.  Internet = Network of networks  It is a network of computers, open for all

 Unlimited number of users can participate in internet to retrieve data from unlimited number of information sources

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

 People and organizations connect into internet so that they can access its massive store of shared information

Essentials for an internet connection:-

Applicati Computer DSL on software: email Browser, , etc

Connection Modem ISP

Network Cable software: Wired/Wireless TCP/IP line

Evolution of internet:-

 It was originated in 1969 at ARPANET (Advanced research project Agency) of DoD (Department of Defense), USA

 It‘s prime purpose was to connect among various bodies of US government  Initially there were only four nodes (Hosts)  In 1972, ARPANET was spread across the globe with 23 nodes at different parts of the world

 Then all the other organizations in respective countries joined to this network in order to send and receive data among other countries

 Thereby internet has got populated with number of networks, thus became a tech giant

 Around 1990s, Tim Berners Lee and O-Reilly had developed WWW and other internet communication protocols

Terminologies used in internet:-  Host: A computer that is connected to internet

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

 Communication service: Protocols to send and receive data over the internet such as FTP, HTTP, WWW, VoIP, etc.

 ISP: Internet Service providers are decentralized and those who provide internet connectivity to its subscribers. Ex: BSNL

 Online: When a computer is connected to internet  : Allows an user to move from one page to another  Protocols: Set of rules for communication

 TCP/IP: to establish a virtual connection between source and destination. It guarantees data delivery, reliable, ordered packet delivery, etc

 Client/Server Model: TCP/IP uses this model where a client refers to any computing device that generates HTTP request and server refers to any computer that responds to the corresponding request

 IP address: It is the unique address assigned to a computing device that gets connected to the internet. It is also called as logical address or software address. It is mutable.

 DNS: Domain Name Servers are used to translate the website names given by the users into machine understandable IP addresses from a database.

 URL: Uniform Resource Locator (URL) is defined as an unique address for the file that has to be accessed over the internet. If we want to access a website, we enter its URL in the address bar of the web browser.

Syntax: protocol: //www.exampleDomain.com/path/filename Ex: ://www.vit.ac.in / home.aspx

 WWW: It is a standard in which all the websites are server on the internet via HTTP. It was invented by Tim Berner‘s Lee at Switzerland on 1990s. Later HTTP and HTML were invented, In 1994, WWW was invented at MIT (Massachusetts Institute of Technology) + DARPA Working:-  From a web browser, user sends HTTP request to a server  ISP finds the corresponding site from DNS and forwards it.  The request reaches the server after a long travel  Server responds to that request and the reply goes back  Any file transmitted in internet will not be sent as a whole  All the information will be chopped into chunks (data packets)  Packets have header and footer info, useful for ordering

2.6 DIFFERENCE BETWEEN WEBSITES AND WEB SERVER

WEBSITES WEB SERVER

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

A website is a set of linked documents The web server on the other side is a computer associated with a particular person, program, which delivers content, such as organization or topic that is held on a computer websites or web pages, for example, over the system and can be accessed as part of the world wide web from a web server to your world wide web. computer. (Not to be confused with: Web page, a document on the world wide web written in A website is a creation from HTML and displayed in a web browser.) webdesigners/webdevelopers, it's based on a theme, an idea. You can navigate in it by visiting one or a fews pages through , reading and watching texts, photos, videos players

The websites are composed by files, medias, ... The webdesigner is the person who creates these one are stocked on hardware connected websites. to the internet network, accessible by people in The webmaster is the person who maintains it the world. This hardwares and the websites but it often is the same person contained in it (the real word is "hosted") are managed by a computer, a server we call the "webserver". It can hosts a few websites

A web page is a simple document displayable A web server is a computer hosting one or by a browser. Such document is written in the more websites. "Hosting" means that all the HTML language (which we look into in more web pages and their supporting files are detail in other articles). available on that computer. The web server will send any web page from the website it is hosting to any user's browser, per user request.

2.7 INTERNET TECHNOLOGIES OVERVIEW

Internet

 Internet is a world-wide global system of interconnected computer networks.  Internet uses the standard Internet Protocol (TCP/IP).  Every computer in internet is identified by a unique IP address.  IP Address is a unique set of numbers (such as 110.22.33.114) which identifies a computer location.  A special computer DNS (Domain Name Server) is used to give name to the IP Address so that user can locate a computer by a name.  For example, a DNS server will resolve a name http://www.tutorialspoint.com to a particular IP address to uniquely identify the computer on which this website is hosted.  Internet is accessible to every user all over the world.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Internet Evoloution

The concept of Internet was originated in 1969 and has undergone several technological & Infrastructural changes as discussed below:

 The origin of Internet devised from the concept of Advanced Research Project Agency Network (ARPANET).  ARPANET was developed by United States Department of Defense.  Basic purpose of ARPANET was to provide communication among the various bodies of government.  Initially, there were only four nodes, formally called Hosts.  In 1972, the ARPANET spread over the globe with 23 nodes located at different countries and thus became known as Internet.  By the time, with invention of new technologies such as TCP/IP protocols, DNS, WWW, browsers, scripting languages etc.,Internet provided a medium to publish and access information over the web.

Internet Advantages

Internet covers almost every aspect of life, one can think of. Here, we will discuss some of the advantages of Internet:

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Internet Disadvantages

Extranet

Extranet refers to network within an organization, using internet to connect to the outsiders in controlled manner. It helps to connect businesses with their customers and suppliers and therefore allows working in a collaborative manner.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Extranet Issues

Apart for advantages there are also some issues associated with extranet. These issues are discussed below:

Hosting

Where the extranet pages will be held i.e. who will host the extranet pages. In this context there are two choices:

 Host it on your own server.  Host it with an Internet Service Provider (ISP) in the same way as web pages.

But hosting extranet pages on your own server requires high bandwidth internet connection which is very costly.

Extranet Benefits

Extranet proves to be a successful model for all kind of businesses whether small or big. Here are some of the advantages of extranet for employees, suppliers, business partners, and customers:

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Security

Additional firewall security is required if you host extranet pages on your own server which result in a complex security mechanism and increase work load.

Accessing Issues

Information can not be accessed without internet connection. However, information can be accessed in Intranet without internet connection.

Decreased Interaction

It decreases the face to face interaction in the business which results in lack of communication among customers, business partners and suppliers.

Extranet vs. Intranet

The following table shows differences between Extranet and Intranet:

Extranet Intranet

Internal network that can not be Internal network that can be accessed externally. accessed externally.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Extranet is extension of company's Intranet. Only limited users of a company.

For limited external communication between customers, Only for communication within a suppliers and business partners. company.

2.7.1 Basic Internet Protocol:

Transmission Control Protocol (TCP)

TCP is a connection oriented protocol and offers end-to-end packet delivery. It acts as back bone for connection.It exhibits the following key features:

 Transmission Control Protocol (TCP) corresponds to the Transport Layer of OSI Model.  TCP is a reliable and connection oriented protocol.  TCP offers: o Stream Data Transfer. o Reliability. o Efficient Flow Control o Full-duplex operation. o Multiplexing.  TCP offers connection oriented end-to-end packet delivery.  TCP ensures reliability by sequencing bytes with a forwarding acknowledgement number that indicates to the destination the next byte the source expect to receive.  It retransmits the bytes not acknowledged with in specified time period.

TCP Services

TCP offers following services to the processes at the application layer:

 Stream Delivery Service  Sending and Receiving Buffers  Bytes and Segments  Full Duplex Service  Connection Oriented Service  Reliable Service

Stream Deliver Service

TCP protocol is stream oriented because it allows the sending process to send data as stream of bytes and the receiving process to obtain data as stream of bytes.

Sending and Receiving Buffers

It may not be possible for sending and receiving process to produce and obtain data at same speed, therefore, TCP needs buffers for storage at sending and receiving ends.

Bytes and Segments

The Transmission Control Protocol (TCP), at transport layer groups the bytes into a packet. This packet is called segment. Before transmission of these packets, these segments are encapsulated into an IP datagram.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Full Duplex Service

Transmitting the data in duplex mode means flow of data in both the directions at the same time.

Connection Oriented Service

TCP offers connection oriented service in the following manner:

1. TCP of process-1 informs TCP of process – 2 and gets its approval. 2. TCP of process – 1 and TCP of process – 2 and exchange data in both the two directions. 3. After completing the data exchange, when buffers on both sides are empty, the two TCP‘s destroy their buffers.

Reliable Service

For sake of reliability, TCP uses acknowledgement mechanism.

Internet Protocol (IP)

Internet Protocol is connectionless and unreliable protocol. It ensures no guarantee of successfully transmission of data.

In order to make it reliable, it must be paired with reliable protocol such as TCP at the transport layer.

Internet protocol transmits the data in form of a datagram as shown in the following diagram:

Points to remember:

 The length of datagram is variable.  The Datagram is divided into two parts: header and data.  The length of header is 20 to 60 bytes.  The header contains information for routing and delivery of the packet.

User Datagram Protocol (UDP)

Like IP, UDP is connectionless and unreliable protocol. It doesn‘t require making a connection with the host to exchange data. Since UDP is unreliable protocol, there is no mechanism for ensuring that data sent is received.

UDP transmits the data in form of a datagram. The UDP datagram consists of five parts as shown in the following diagram:

Points to remember:

 UDP is used by the application that typically transmit small amount of data at one time.  UDP provides protocol port used i.e. UDP message contains both source and destination port number, that makes it possible for UDP software at the destination to deliver the message to correct application program.

File Transfer Protocol (FTP)

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

FTP is used to copy files from one host to another. FTP offers the mechanism for the same in following manner:

 FTP creates two processes such as Control Process and Data Transfer Process at both ends i.e. at client as well as at server.  FTP establishes two different connections: one is for data transfer and other is for control information.  Control connection is made between control processes while Data Connection is made between <="" b="">  FTP uses port 21 for the control connection and Port 20 for the data connection.

Trivial File Transfer Protocol (TFTP)

Trivial File Transfer Protocol is also used to transfer the files but it transfers the files without authentication. Unlike FTP, TFTP does not separate control and data information. Since there is no authentication exists, TFTP lacks in security features therefore it is not recommended to use TFTP.

Key points

 TFTP makes use of UDP for data transport. Each TFTP message is carried in separate UDP datagram.  The first two bytes of a TFTP message specify the type of message.  The TFTP session is initiated when a TFTP client sends a request to upload or download a file.  The request is sent from an ephemeral UDP port to the UDP port 69 of an TFTP server.

Difference between FTP and TFTP S.N. Parameter FTP TFTP

1 Operation Transferring Files Transferring Files

2 Authentication Yes No

3 Protocol TCP UDP

4 Ports 21 – Control, 20 – Data Port 3214, 69, 4012

5 Control and Data Separated Separated

6 Data Transfer Reliable Unreliable

Telnet

Telnet is a protocol used to log in to remote computer on the internet. There are a number of Telnet clients having user friendly . The following diagram shows a person is logged in to computer A, and from there, he remote logged into computer B.

Hyper Text Transfer Protocol (HTTP) M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

HTTP is a communication protocol. It defines mechanism for communication between browser and the web server. It is also called request and response protocol because the communication between browser and server takes place in request and response pairs.

HTTP Request

HTTP request comprises of lines which contains:

 Request line  Header Fields  Message body

Key Points

 The first line i.e. the Request line specifies the request method i.e. Get or Post.  The second line specifies the header which indicates the domain name of the server from where index.htm is retrieved.

HTTP Response

Like HTTP request, HTTP response also has certain structure. HTTP response contains:

 Status line  Headers  Message body

2.8 UNDERSTANDING THE DIFFERENCE BETWEEN INTERNET AND INTRANET

INTERNET: 1. Internet is wide network of computers and is open for all. 2. Internet itself contains a large number of intranets. 3. The number of users who use internet is Unlimited. 4. The Visitors traffic is unlimited. 5. Internet contains different source of information and is available for all.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

INTRANET: 1. Intranet is also a network of computers designed for a specific group of users. 2. Intranet can be accessed from Internet but with restrictions. 3. The number of users is limited. 4. The traffic allowed is also limited. 5. Intranet contains only specific group information.

2.9 HTML AND CSS

Hypertext Markup Language (HTML) is the standard markup language for creating web pages and web applications. With Cascading Style Sheets (CSS) and JavaScript it forms a triad of cornerstone technologies for the World Wide Web.[1] Web browsers receive HTML documents from a webserver or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.

HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects, such as interactive forms, may be embedded into the rendered page. It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. HTML elements are delineated by tags, written using angle . Tags such as and introduce content into the page directly. Others such as

...

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming surround and provide information about document text and may include other tags as sub-elements. Browsers do not display the HTML tags, but use them to interpret the content of the page.

HTML can embed programs written in a such as JavaScript which affect the behavior and content of web pages. Inclusion of CSS defines the look and layout of content. The World Wide Web Consortium (W3C), maintainer of both the HTML and the CSS standards, has encouraged the use of CSS over explicit presentational HTML since 1997.[2]

Markup

HTML markup consists of several key components, including those called tags (and their attributes), character-based data types, character references and entity references. HTML tags most commonly come in pairs like

and

, although some represent empty elements and so are unpaired, for example . The first tag in such a pair is the start tag, and the second is the end tag (they are also called opening tags and closing tags).

Another important component is the HTML document type declaration, which triggers standards mode rendering.

The following is an example of the classic Hello world program, a common test employed for comparing programming languages, scripting languages and markup languages. This example is made using 9 lines of code:

This is a title

Hello world!

(The text between and describes the web page, and the text between and is the visible page content. The markup text "This is a title" defines the browser page title.)

The Document Type Declaration is for HTML5. If a declaration is not included, various browsers will revert to "" for rendering.[60]

Elements Main article: HTML element

HTML documents imply a structure of nested HTML elements. These are indicated in the document by HTML tags, enclosed in angle brackets thus:

[61]

In the simple, general case, the extent of an element is indicated by a pair of tags: a "start tag"

and "end tag"

. The text content of the element, if any, is placed between these tags.

Tags may also enclose further tag markup between the start and end, including a mixture of tags and text. This indicates further (nested) elements, as children of the parent element. M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

The start tag may also include attributes within the tag. These indicate other information, such as identifiers for sections within the document, identifiers used to bind style information to the presentation of the document, and for some tags such as the used to embed images, the reference to the image resource.

Some elements, such as the line break
, do not permit any embedded content, either text or further tags. These require only a single empty tag (akin to a start tag) and do not use an end tag.

Many tags, particularly the closing end tag for the very commonly used paragraph element

, are optional. An HTML browser or other agent can infer the closure for the end of an element from the context and the structural rules defined by the HTML standard. These rules are complex and not widely understood by most HTML coders.

The general form of an HTML element is therefore: ''content''. Some HTML elements are defined as empty elements and take the form . Empty elements may enclose no content, for instance, the
tag or the inline tag. The name of an HTML element is the name used in the tags. Note that the end tag's name is preceded by a slash character, "/", and that in empty elements the end tag is neither required nor allowed. If attributes are not mentioned, default values are used in each case.

Element examples

Header of the HTML document: .... The title is included in the head, for example:

The Title

Headings: HTML headings are defined with the

to

tags:

Heading level 1

Heading level 2

Heading level 3

Heading level 4

Heading level 5
Heading level 6

Paragraphs:

Paragraph 1

Paragraph 2

Line breaks:
. The difference between
and

is that "br" breaks a line without altering the semantic structure of the page, whereas "p" sections the page into paragraphs. Note also that "br" is an empty element in that, although it may have attributes, it can take no content and it may not have an end tag.

This
is a paragraph
with
line breaks

This is a link in HTML. To create a link the tag is used. The href= attribute holds the URL address of the link. M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

A link to Wikipedia!

Comments:

Comments can help in the understanding of the markup and do not display in the webpage.

CSS:

Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language.[1] Although most often used to set the visual style of web pages and user interfaces written in HTML and XHTML, the language can be applied to any XML document, including plain XML, SVG and XUL, and is applicable to rendering in speech, or on other media. Along with HTML and JavaScript, CSS is a cornerstone technology used by most websites to create visually engaging webpages, user interfaces for web applications, and user interfaces for many mobile applications.[2]

CSS is designed primarily to enable the separation of presentation and content, including aspects such as the layout, colors, and fonts.[3] This separation can improve content accessibility, provide more flexibility and control in the specification of presentation characteristics, enable multiple HTML pages to share formatting by specifying the relevant CSS in a separate . file, and reduce complexity and repetition in the structural content.

Separation of formatting and content makes it possible to present the same markup page in different styles for different rendering methods, such as on-screen, in print, by voice (via speech-based browser or screen reader), and on Braille-based tactile devices. It can also display the web page differently depending on the screen size or viewing device. Readers can also specify a different style sheet, such as a CSS file stored on their own computer, to override the one the author specified.

Changes to the graphic design of a document (or hundreds of documents) can be applied quickly and easily, by editing a few lines in the CSS file they use, rather than by changing markup in the documents.

The CSS specification describes a priority scheme to determine which style rules apply if more than one rule matches against a particular element. In this so-called cascade, priorities (or weights) are calculated and assigned to rules, so that the results are predictable.

The CSS specifications are maintained by the World Wide Web Consortium (W3C). Internet media type (MIME type) text/css is registered for use with CSS by RFC 2318 (March 1998). The W3C operates a free CSS validation service for CSS documents

Syntax

CSS has a simple syntax and uses a number of English keywords to specify the names of various style properties.

A style sheet consists of a list of rules. Each rule or rule-set consists of one or more selectors, and a declaration block.

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

Selector

In CSS, selectors declare which part of the markup a style applies to by matching tags and attributes in the markup itself.

Selectors may apply to:

 all elements of a specific type, e.g. the second-level headers h2  elements specified by attribute, in particular: o id: an identifier unique within the document o class: an identifier that can annotate multiple elements in a document  elements depending on how they are placed relative to others in the document .

Classes and IDs are case-sensitive, start with letters, and can include alphanumeric characters and underscores. A class may apply to any number of instances of any elements. An ID may only be applied to a single element.

Pseudo-classes are used in CSS selectors to permit formatting based on information that is not contained in the document tree. One example of a widely used pseudo-class is :hover, which identifies content only when the user "points to" the visible element, usually by holding the mouse cursor over it. It is appended to a selector as in a:hover or #elementid:hover. A pseudo-class classifies document elements, such as :link or :visited, whereas a pseudo-element makes a selection that may consist of partial elements, such as ::first-line or ::first-letter.[5]

Selectors may be combined in many ways to achieve great specificity and flexibility.[6] Multiple selectors may be joined in a spaced list to specify elements by location, element type, id, class, or any combination thereof. The order of the selectors is important. For example, div .myClass {color: red;} applies to all elements of class myClass that are inside div elements, whereas .myClass div {color: red;} applies to all div elements that are in elements of class myClass.

The following table provides a summary of selector syntax indicating usage and the version of CSS that introduced it

Use

Before CSS, nearly all presentational attributes of HTML documents were contained within the HTML markup. All font colors, background styles, element alignments, borders and sizes had to be explicitly described, often repeatedly, within the HTML. CSS lets authors move much of that information to another file, the style sheet, resulting in considerably simpler HTML.

For example, headings (h1 elements), sub-headings (h2), sub-sub-headings (h3), etc., are defined structurally using HTML. In print and on the screen, choice of font, size, color and emphasis for these elements is presentational.

Before CSS, document authors who wanted to assign such typographic characteristics to, say, all h2 headings had to repeat HTML presentational markup for each occurrence of that heading type. This made documents more complex, larger, and more error-prone and difficult to maintain. CSS allows the separation of presentation from structure. CSS can define color, font, text alignment, size, borders, spacing, layout and many other typographic characteristics, and can do so independently for on-screen and printed views. CSS also defines non-visual styles, such as reading speed and emphasis for aural text readers. The W3C has now deprecated the use of all presentational HTML markup.[11]

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

For example, under pre-CSS HTML, a heading element defined with red text would be written as:

Chapter 1.

Using CSS, the same element can be coded using style properties instead of HTML presentational attributes:

Chapter 1.

An "external" CSS file, as described below, can be associated with an HTML document using the following syntax:

An internal CSS code can be typed in the head section of the code. The coding is started with the style tag. For example,

Example:

Consider this HTML fragment:

To demonstrate specificity

2.10 HTML 5.0

HTML5 is a markup language used for structuring and presenting content on the World Wide Web. It is the fifth and current version of the HTML standard.

It was published in October 2014 by the World Wide Web Consortium (W3C)[2][4] to improve the language with support for the latest multimedia, while keeping it both easily readable by humans and consistently understood by computers and devices such as web browsers, parsers, etc. HTML5 is intended to subsume not only HTML 4, but also XHTML 1 and DOM Level 2 HTML.

HTML5 includes detailed processing models to encourage more interoperable implementations; it extends, improves and rationalizes the markup available for documents, and introduces markup and application programming interfaces (APIs) for complex web applications.[6] For the same reasons,

M.I.E.T./CSE/III/Internet Programming

Subject code/Name: CS6501 internet programming

HTML5 is also a candidate for cross-platform mobile applications, because it includes features designed with low-powered devices in mind.

Many new syntactic features are included. To natively include and handle multimedia and graphical content, the new

,
,
,
,