You are on page 1of 69

UNIT-II : Web services

Agenda
• What is a web service?
• Basic concept behind web service.
• Why we use it?
• How web services work?
• Client-Server model
• Types of web services
What a web service is?
Web services are all over: S/W Developer, tester,
etc.
• Service available over the web
• Enables communication between applications
over the web
• Provides a standard protocol/format for
communication.
Why we use web service?
• Platform independent communication
• Using web service two different applications
(implementations) can talk to each other and
exchange data/information.
i.e one application written in C++ over
windows platform and it uses MySQL DB.
another application written in java over
linux platform and it uses oracle DB.
• Question is- who is creating this web service?
• Service provider: is an entity that
develops/implements the application(web
service) and makes it available over the
web(internet)
• The service consumer needs to know about
the service like functionalities of it, request
and response parameters etc.
• To describe the functionalities of web services,
we use WSDL which is XML based interface.
WSDL
• Web Services Description Languages
-- Written in XML.
– Describe functionality of a web service
– Specify how to access the service (binding protocol,
message format, etc.)
The Main Structure of WSDL
<definition namespace = “http/… “>
<type> data types </type>
<message> … </message>
<port> a set of operations </port>
<binding> communication protocols </binding>
<service> a list of binding and ports </service>
<definition>
Why WSDL is XML based?
• It is machine readable.
• XML (Extensible Markup Language) as the
intermediate language for exchanging data
between heterogeneous applications (such as a
web application designed in Java, another in .Net
and another in PHP).
• Global weather wsdl

• We can use some tools and programming


languages to pass this document and generate the
request and response structure.
How consumer will get this document?
• If consumer and provider already know each
other: they can use URL directly.
• If does not know each other: how will get?
Sol: web service provider publishes this
WS(through WSDL) on an online directory
from where consumer can query and search
the WS.
• This online Registry/ directory is called as
UDDI
What is UDDI?
• UDDI is a platform-independent framework for
describing services, discovering businesses, and
integrating business services by using the Internet.

• UDDI stands for Universal Description, Discovery


and Integration .

• UDDI is a directory for storing &finding web services

• UDDI is a directory of web service interfaces


described by WSDL.
How can UDDI be Used?
• If the industry published an UDDI standard for
flight rate checking and reservation, airlines could
register their services into an UDDI directory.

• Travel agencies could then search the UDDI directory


to find the airline's reservation interface.

• When the interface is found, the travel agency can


communicate with the service immediately because it
uses a well-defined reservation interface. (by WSDL)
Components of web services
• WSDL
• UDDI
The consumer needs to know:
• What are the services available?
• What are the request and response parameters?
• How to call the web service?
i.e the structure of web services.
Architecture of SOA

Key components of SOA


• Services
• Service Description
• Advertising and Discovery
• Specification of associated data model
• Service contracts
Types of web services
• Web services are implemented in two types.
1. SOAP(Simple Object Access Protocol)
Medium: HTTP (POST) / [SMTP,TCP,UDP]
Format: XML
2. REST(REpresentational State Transfer)
Medium: HTTP (POST,GET,PUT,DELETE etc.)
Format: XML/JSON/TEXT
The Problem
Interoperability between Internet applications
• different operating systems,
• different firewalls,
• different methods of making remote procedure calls,
• In order to interoperate across the Internet both
the client and server need to understand each
others:
• security types and trusts,
• service deployment schemas, and
• implementation details.
Remote objects can give a program with lots of power
over the Internet, but most firewalls block non-HTTP
requests.
The Goal
• The goal is a world where you can access
objects and services on remote (or local)
servers in a platform-independent manner.
• The Solution: SOAP
SOAP bridges the gap between competing
object RPC (Remote Procedure Calls)
technologies and provides a light-weight
messaging format that works with
any operating system,
any programming language
SOAP web services
• SOAP is known as the Simple Object Access
Protocol.
• SOAP is an XML-based protocol for accessing
web services over HTTP. It has some
specification which could be used across all
applications.
• so that applications built on various
programming languages could talk quickly to
each other.
• Every programming language can understand
the XML markup language. Hence, XML was
used as the underlying medium for data
exchange.
• But there are no standard specifications on use
of XML across all programming languages for
data exchange. That is where SOAP comes in.
• SOAP was designed to work with XML over
HTTP and have some sort of specification
which could be used across all applications.
SOAP Skeleton
<?xml version="1.0"?>
<soap:Envelope (root element-defines XML doc as SOAP msg)
xmlns:soap=http://www.w3.org/2001/12/soap-envelope
soap:encodingStyle="http://www.w3.org/2001/12/soap-
encoding">
<soap:Header>
... contains application specific information (like
authentication, payment, etc)
</soap:Header>
<soap:Body>
...
<soap:Fault>
...
</soap:Fault>
</soap:Body>
</soap:Envelope>
3 Main Components
• The SOAP envelope construct defines an overall
framework for expressing
what is in a message;
who should deal with it, and
whether it is optional or mandatory.
• The SOAP encoding rules defines a serialization
mechanism that can be used to exchange instances of
application-defined data types.
• The SOAP RPC representation defines a convention
that can be used to represent remote procedure calls
and responses.
SOAP Skeleton:Simple Example
MESSAGE RESPONSE

<?xml version="1.0"?> <?xml version="1.0"?>


<soap:Envelope <soap:Envelope
xmlns:soap=http://www.w3.org/2001/12/s xmlns:soap=http://www.w3.org/2001/12/
oap-envelope soap-envelope
soap:encodingStyle="http://www.w3.org/2 soap:encodingStyle="http://www.w3.org/
001/12/soap-encoding"> 2001/12/soap-encoding">
<soap:Header> <soap:Header>
<n:movie>Star <n:movie>Star
Wars</n:movie> Wars</n:movie>
</soap:Header> </soap:Header>

<soap:Body> <soap:Body>
<p:day>Wednesday</p:day> <p:day>Wednesday</p:day>
<p:times>7 p.m-12 <p:times>12 a.m.</p:times>
a.m.</p:times> </soap:Body>
</soap:Body>
</soap:Envelope> </soap:Envelope>
• Give me an example of real web service?
• What kind of security is needed for web
services?
• What tools are used to test a web service?
• Differentiate between a SOA and a Web service?
• Is there any special application required to
access web service?
• Can you name few free and commercial
implementations for web services?
• Can you tell few benefits of web services?
• What are the steps performed by the client to
access a web service?
REST Web Services
• (REpresentational State Transfer)
• It is a certain approach to creating Web Services.
• REST is a design pattern.
• REST is an architectural style not a protocol.
• describe an architecture style of networked
systems.

REST based web services


• Online shopping
• Search services
Why is it called Representational State Transfer ?

• A web page is a representation of a resource.


Resources are just concepts
• URIs tell a client that there's a concept some where.
Clients can then request a specific representation of
the concept.
• “State” means application/session state
• Maintained as part of the content transferred from
client to server back to client
• Transfer of state: Connectors (client, server, tunnel)
are unrelated to sessions.
http://weather.example.com/oaxaca
Client Resource
OaxacaWeather.html
Rest – An architectural Style
Elements
• Components – Proxy , gateway etc
• Connectors – client , server etc
• Data – resource , representation etc
REST
• Ignores component implementation details.
• Focus on roles of components, their
interactions and their interpretation of data
elements.
• URI-Uniform Resource
Identifier (or URL)
• Resource

• Web Page (HTML Page)

• Resources are identified by uniform resource


identifiers (URIs)
• Resources are manipulated through their
representations
• Multiple representations are accepted or sent
• Hypertext is the engine of application state
Example:
Airline Reservation Service
• Suppose that an airline wants to create a
telephone reservation system for customers to
call in and make flight reservations.
• The airline wants to ensure that its premier
members get immediate service, its frequent
flyer members get expedited service and all
others get regular service.
• There are two main approaches to implementing
the reservation service.
Approach 1
"Press 1 for Premier, Press 2 for…"
The airline provides a single telephone number.
Upon entry into the system a customer encounters an
automated message, "Press 1 if you are a premier member,
press 2 if you are a frequent flyer, press 3 for all others."

Premier
Customer
Representative
Premier Members
F.F.
Answering
Airline Reservations Customer
Machine Representative
Frequent Flyer Members

Regular
Customer
Representative
Regular Members
Approach 2
Telephone Numbers are Cheap! Use Them!
The airline provides several telephone numbers - one
number for premier members, a different number for
frequent flyers, and still another for regular customers.
Premier
1-800-Premier Customer
Representative
Premier Members

F.F.
1-800-Frequent Customer
Representative
Frequent Flyer Members
Regular
1-800-Reservation Customer
Representative
Regular Members
Discussion
• In Approach 1 the answering machine introduces
an extra delay, which is particularly annoying to
premier members. (Doesn't everyone hate those
answering systems)
• With Approach 2 there is no intermediate step.
Premier members get instant pickup from a
customer service representative. Others may
have to wait for an operator.
Web-Based Reservation Service
• Suppose now the airline (kings-air.com) wants to
provide a Web reservation service for customers to
make flight reservations through the Web.
• Just as with the telephone service, the airline wants to
ensure that its premier members get immediate
service, its frequent flyer members get expedited
service, all others get regular service.
• There are two main approaches to implementing the
Web reservation service. The approaches are
analogous to the telephone service...
Approach 1
One-Stop Shopping
The airline provides a single URL. The Web service is
responsible for examining incoming client requests to
determine their priority and process them accordingly.

client
Premier
Premier Members Customer

Web Determine F.F.


client Reservation Priority Customer
Frequent Flyer Members Service
Regular
Customer

client
Regular Members
Approach 1 Disadvantages
• There is currently no industry accepted practice (rules) for
expressing priorities, so rules would need to be made. The
clients must learn the rule, and the Web service application
must be written to understand the rule.
• This approach is based upon the incorrect assumption that a
URL is "expensive" and that their use must be rationed.
• The Web service is a central point of failure. It is a bottleneck.
Load balancing is a challenge.
• It violates Tim Berners-Lee Web Design, Axiom 0 (see next
slide).
Web Design, Axiom 0
(Tim Berners-Lee, director of W3C)

• Axiom 0: all resources on the Web must be


uniquely identified with a URI.

URL1
resource1

URL2
resource2

URL3
resource3
Approach 2:
URLs are Cheap! Use Them!
The airline provides several URLs - one URL for premier
members, a different URL for frequent flyers, and still
another for regular customers.
Premier
http://www.kings-air/reservations/premier Member
client Reservation
Premier Members Service

Frequent
http://www.kings-air/reservations/frequent-flyer Flyer
client Reservation
Frequent Flyer Members Service

Regular
http://www.kings-air/reservations/regular Member
client Reservation
Service
Regular Members
Approach 2 Advantages
• The different URLs are discoverable by search engines and
UDDI registries.
• It's easy to understand what each service does simply by
examining the URL, i.e., it exploits the Principle of Least
Surprise.
• There is no need to introduce rules. Priorities are elevated to
the level of a URL. "What you see is what you get."
• It's easy to implement high priority - simply assign a fast
machine at the premier member URL.
• There is no bottleneck. There is no central point of failure.
• Consistent with Axiom 0.
Recap
• We have looked at a reservation service.
• We have seen a telephone-based version and
a Web-based version of the reservation
service.
• With each version we have seen two main
approaches to implementing the service.
• Which approach is the REST design pattern
and which isn't? See the following slides.
This Ain't the
REST Design Pattern

Premier
Customer
Representative
Premier Members
F.F.
Answering
Airline Reservation Customer
Machine Representative
Frequent Flyer Members

Regular
Customer
Representative
Regular Members
This is the
REST Design Pattern
Premier
1-800-Premier Customer
Representative
Premier Members

F.F.
1-800-Frequent Customer
Representative
Frequent Flyer Members
Regular
1-800-Reservation Customer
Representative
Regular Members
This ain't the
REST Design Pattern

client
Premier
Premier Members Customer

Reservation Determine F.F.


client Web Priority Customer
Frequent Flyer Members Service
Regular
Customer

client
Regular Members
This is the
REST Design Pattern
Premier
http://www.kings-air/reservations/premier Member
client Reservation
Premier Members Service

Frequent
http://www.kings-air/reservations/frequent-flyer Flyer
client Reservation
Frequent Flyer Members Service

Regular
http://www.kings-air/reservations/regular Member
client Reservation
Service
Regular Members
Characteristics of a REST based network
• Client-Server: a pull-based interaction style(Client
request data from servers as and when needed).
• Stateless: each request from client to server must
contain all the information necessary to understand
the request, and cannot take advantage of any stored
context on the server.
• Uniform interface: all resources are accessed with a
generic interface (e.g., HTTP GET, POST, PUT,
DELETE).
• Named resources - the system is comprised of
resources which are named using a URL.
• Interconnected resource representations - the
representations of the resources are interconnected
using URLs, thereby enabling a client to progress
from one state to another.
Advantages of RESTful Web
Services
• Fast: RESTful Web Services are fast because there is
no strict specification like SOAP. It consumes less
bandwidth and resource.
• Language and Platform independent: RESTful web
services can be written in any programming language
and executed in any platform.
• Can use SOAP: RESTful web services can use SOAP
web services as the implementation.
• Permits different data format: RESTful web service
permits different data format such as Plain Text,
HTML, XML and JSON.
SOAP vs REST Web Services
No. SOAP REST
1) SOAP is a protocol. REST is an architectural style.
2) SOAP stands for Simple Object Access REST stands for REpresentational State
Protocol. Transfer.
3) SOAP can't use REST because it is a protocol. REST can use SOAP web services because it
is a concept and can use any protocol like
HTTP, SOAP.
4) SOAP uses services interfaces to expose the REST uses URI to expose business logic.
business logic.
5) JAX-WS is the java API for SOAP web JAX-RS is the java API for RESTful web
services. services.
6) SOAP defines standards to be strictly followed. REST does not define too much standards like
SOAP.
7) SOAP requires more bandwidth and resource REST requires less bandwidth and resource
than REST. than SOAP.
8) SOAP defines its own security. RESTful web services inherits security
measures from the underlying transport.
9) SOAP permits XML data format only. REST permits different data format such as
Plain text, HTML, XML, JSON etc.
10) SOAP is less preferred than REST. REST more preferred than SOAP.
JDBC
• Java Database Connectivity (JDBC)
• JDBC provides Java applications with
access to most database systems via SQL
• JDBC Architecture
Java Application

JDBC API

JDBC DriverManager

JDBC Driver JDBC Driver


JDBC API
With JDBC, the application programmer uses the JDBC API

A set of classes and interfaces written in the Java


 a standard API for database developers &
 makes possible to write database
applications using an Java API.
The JDBC API
Includes two packages:
 java.sql package
 javax.sql package (adds server-side
capabilities)
The java.sql Package
JDBC Classes

DriverManager
Manages JDBC Drivers
Used to Obtain a connection to a Database

• Types
Defines constants which identify SQL types

Date
Used to Map between java.util.Date and the SQL DATE type

• Time
Used to Map between java.util.Date and the SQL TIME type

TimeStamp
Used to Map between java.util.Date and the SQL TIMESTAMP
type
JDBC Interfaces

Driver
All JDBC Drivers must implement the Driver interface. Used to
obtain a connection to a specific database type

• Connection
Represents a connection to a specific database
Used for creating statements
Used for managing database transactions
Used for accessing stored procedures
Used for creating callable statements

Statement
Used for executing SQL statements against the database
JDBC Interfaces
ResultSet
Represents the result of an SQL statement
Provides methods for navigating through the resulting data

• PreparedStatement
Similar to a stored procedure
An SQL statement (which can contain parameters) is compiled and
stored in the database

CallableStatement
Used for executing stored procedures

DatabaseMetaData
Provides access to a database's system catalogue

ResultSetMetaData
Provides information about the data contained within a ResultSet
javax.sql package
What Does the JDBC API Do?
 Establish a connection with a data source
 Send queries and update statements to the data source
 Process the results
Connection con = DriverManager.getConnection(
"jdbc:myDriver:wombat", "myLogin", "myPassword");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery ("SELECT a, b, c FROM
Table1");
while (rs. next()) {
int x = rs.getInt ("a")
String s = rs.getString ("b");
float f = rs.getFloat ("c");
}
Why not Use ODBC from Java?
 Before the development of the JDBC API
The most widely used programming interface Microsoft's ODBC (Open
DataBase Connectivity) API
 To access relational databases
 ODBC is not appropriate for direct use from the Java programming
language
Uses C interface.
Occurs a number of drawbacks in the security, implementation,
robustness, automatic portability
 during the calls from Java to native C code
QUESTION:
What are other important differences between JDBC API and ODBC API?

 Once ODBC (as native code) is called, Java programming language can't guarantee
that a security violation won't occur (untrusted).
JDBC Drivers

There are 4 types of JDBC Drivers


Type 1 - JDBC-ODBC Bridge
Type 2 - JDBC-Native Bridge
Type 3 - JDBC-Net Bridge
Type 4 - Direct JDBC Driver

Type 1 only runs on platforms where ODBC is available


ODBC must be configured separately

Type 2 Drivers map between a proprietary Database API and the


JDBC API

Type 3 Drivers are used with middleware products

Type 4 Drivers are written in Java


In most cases, type 4 drivers are preferred
Using JDBC
To execute a statement against a database, the following flow is
observed
Load the driver (Only performed once)
Obtain a Connection to the database (Save for later use)
Obtain a Statement object from the Connection
Use the Statement object to execute SQL. Updates, inserts and
deletes return Boolean. Selects return a ResultSet
Navigate ResultSet, using data as required
Close ResultSet
Close Statement
• Do NOT close the connection
The same connection object can be used to create further
statements
A Connection may only have one active Statement at a time. Do
not forget to close the statement when it is no longer needed.
Close the connection when you no longer need to access the
database
Loading Drivers

When a JDBC Driver class is loaded, it must create an


instance of itself and register that instance with the
JDBC DriverManager

How does one load a "class" into the Virtual machine?


Use the static method Class.forName()

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connecting to a Database
Once a Driver is loaded, a connection can be made to the database
The connection is defined by URL
The URL has the following form:
jdbc:driver:databasename

• Examples:
jdbc:odbc:MyOdbcDatabase
jdbc:postgres:WebsiteDatabase
jdbc:oracle:CustomerInfo

A connection is obtained in the following manner:


Connection aConnection =
DriverManager.getConnection("jdbc:odbc:myDatabase");

• Overloaded versions of the getConnection method allow the


specification of a username and password for authentication with the
database.
Using a Connection

The Connection interface defines many methods for


managing and using a connection to the database

public Statement createStatement()


public PreparedStatement prepareStatement(String sql)
public void setAutoCommit(boolean)
public void commit()
public void rollback()
public void close()

• The most commonly used method is createStatement()


When an SQL statement is to be issued against the
database, a Statement object must be created through
the Connection
Using a Statement

The Statement interface defines two methods for executing


SQL against the database
public ResultSet executeQuery(String sql)
public int executeUpdate(String sql)

• executeQuery returns a ResultSet


• All rows and columns which match the query are contained
within the ResultSet
• The developer navigates through the ResultSet and uses
the data as required.

• executeUpdate returns the number of rows changed by the


update statement
This is used for insert statements, update statements and
Using a ResultSet
The ResultSet interface defines many navigation methods

public boolean first()


public boolean last()
public boolean next()
public boolean previous()

The ResultSet interface also defines data access methods

public int getInt(int columnNumber) -- Note: Columns are numbered


public int getInt(String columnName) -- from 1 (not 0)
public long getLong(int columnNumber)
public long getLong(String columnName)
public String getString(int columnNumber)
public String getString(String columnName)

There are MANY more methods. Check the API documentation for a
complete list
SQL Types/Java Types Mapping
SQL Type Java Type

CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC java.Math.BigDecimal
DECIMAL java.Math.BigDecimal
BIT boolean
TINYINT int
SMALLINT int
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE double
BINARY byte[]
VARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
Example Code:
Connection aConnection;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException x){
System.out.println("Cannot find driver class.
Check CLASSPATH");
return;
}
try{
aConnection =
DriverManager.getConnection("jdbc:odbc:MyDatabase
",
"Username", "Password");
}
catch(SQLException x){
System.out.println("Exception connecting to
database:" + x);
Example Code (continued):
try{
Statement aStmt = aConnection.createStatement();
StringBuffer sb = new StringBuffer("SELECT Employee_id,
Employee_Name");
sb.append(" FROM Employee WHERE EmployeeId>100");
ResultSet rs = aStmt.executeQuery(sb.toString());
while(rs.next()) {
int employeeId = rs.getInt(1);
String employeeName = rs.getString(2);
System.out.println("Id:" + employeeId + "\nName:" +
employeeName);
}
rs.close();
aStmt.close();
}
catch(SQLException x){
System.out.println("Exception while executing query:" + x);
}
Simple Example
Import java.sql;
class SimpleExample {
public static void main(String args[]) {
String url = “jdbc:odbc:mysource”;
try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection myConnection =

DriverManager.getConnection(url,”Bond”,”TopSecret”);
myConnection.close();
}
catch(java.lang.Exception) {
ex.printStackTrace();
}
}
}
Sending SQL statements
……
String query= “Select name,id,salary FROM employees ORDER By salary”;
Connection myConnection = DriverManager.getConnection(…..);
Statement myStatement = myConnection.createStatement();
ResultSet rs = myStatement.executeQuery(query);
While(rs.next){
String empName = rs.getString(1);
String empId = rs.getString(2);
String empSalary = rs.getString(3);
System.out.println(“Employee ” + empName + “ with id ” + empId
+ “ earns ” + empSalary);
}
myStatement.close();
myConnection.close();
…….

You might also like