0% found this document useful (0 votes)
24 views

Java REST Web Services

The document discusses various technologies related to web services including SOAP, REST, XML, JSON, JAX-WS, JAXB and REST APIs. It provides details on topics like service oriented architecture, XML schema, namespaces, JSON serialization and deserialization, JAX-WS annotations, JAXB and generating stubs from XML schema.

Uploaded by

Acmin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Java REST Web Services

The document discusses various technologies related to web services including SOAP, REST, XML, JSON, JAX-WS, JAXB and REST APIs. It provides details on topics like service oriented architecture, XML schema, namespaces, JSON serialization and deserialization, JAX-WS annotations, JAXB and generating stubs from XML schema.

Uploaded by

Acmin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

29 October 2020 12:09 PM

Incase of Any Maven Issues,


1. Delete .m2 folder from user repository
2. Right click on project in IDE
3. Run As -> Maven Clean
4. Run As -> Maven Install (pulls latest dependencies
Central repository)
5. Maven Update

Web Services
• Interoperability - Apps developed in different programming languages can communicate with each
other irrespective of their platforms
• Loosely Coupled - Two or more apps can be connected in loosely coupled fashion
• Extensibility - Clients can extend apps through web services with their own logic
• Mashups - Mashup apps are consumer of more than one webservices

SOAP -> XML -> HTTP Post Method (JAX-WS - Standard)


RESTful -> Multiple Formats -> HTTP Methods (JAX-RS - Standard)

Service oriented Architecture (SOA) - Architectural Principles to design and implement software
applications that have several interfaces and can use services in a loosely coupled manner. The SOA
standard is maintained by open bodies like W3C and OASIS.

Roles -
1. Consumer
2. Provider

Service Contract (Date Format -> XML) -


1. Soap - WSDL File
2. REST - WADL File

SOA Advantages:
1. Platform Independent
2. Focussed developer roles
3. Loosely coupled
4. Reusability
5. Cost Reduction
6. Scalability
7. Availability on multiple servers

XML -> Used for configuration + Exchanging Data + Save/Manipulate Data (Apache CXF - Spring
Configuration)
XSD -> XML Schema, used for defining contracts for XML for various parties
Namespaces -> Allow us to uniquely qualify a XML element allowing us to use multiple elements with
the same name

XML (Extensible Markup Language)


XML Schema - Grammar of Blueprint
1. Elements
Advantages:
2. Attributes
1. Custom Markup / tags
3. Namespaces
2. Holds data and metadata
4. Order
3. Validation Rules
5. Number of Occurrences
4. Well Formed
6. Restrictions

Namespaces
Schema:
targetNamespace: http://www.amazon.com/order

Use Prefix instead like:


xmlns:amz="http://www.amazon.com/order"

Similarly, in XML Document:


<order xmlns:amz="http://www.amazon.com/order">
<amz:lineitem/>
<amz:shippingaddress/>

To Add Prefix use:


elementFormDefault="qualified" in the schema tag of the XSD

<sequence> -> All elements defined within this tag should appear in the same order
<element> -> Defines an element in the tag such as name, dob, gender etc.
<simpleType> -> Consists of various features such as restrictions
<restriction> -> Add validations using a base="<datatype>". Consists of various other types of tags inside it
<choice> -> Only one element should occur
<all> -> All of the elements should appear, sequence does not matter
<attribute> -> Defines once for entire XML

JSON -> Javascript Object Notation


It is a syntax for storing and exchanging data between 2 software apps or between back end and front
end
Example:
Var customerOrder= {
"customerName" : "Bharath",
"Phone" : 911,
"items" : ["laptop","watch"]
};
console.log(customerOrder.customerName);

REST API Page 1


"customerName" : "Bharath",
"Phone" : 911,
"items" : ["laptop","watch"]
};
console.log(customerOrder.customerName);

Serialization - Converting Java objects into JSON


Eg : var jsonString = JSON.stringify(customerOrder);

Deserialization - Converting JSON string into java object


Eg : var abc = JSON.parse(jsonString);

JAX-WS

Annotations:
• @javax.jws.WebService - Marks as endpoint which can handle incoming requests
• @javax.jws.WebMethod - Each method on endpoint will be marked with this
• @javax.xml.ws.WebFault - Custom Exceptions or errors
• @javax.jws.soap.SOAPBinding - by default document/literal
• @javax.xml.ws.RequestWrapper - wrap or map the incoming soap message to our Java objects in
a custom manner
• @javax.xml.ws.ResponseWrapper - customize response

JAXB - Java Architecture for XML Binding


Provides an easy way to map Java classes and xml schema hiding the complexity
Allows us to convert this xml and xml API into Java classes and objects

Tools :
• XJC - XML Schema compiler which generates Java classes from given xml
• SCHEMAGEN - Generate XML schema from Java classes
• Runtime API - Marshalling and unmarshalling + Annotations

Generate Stubs from XML Schema


1. Create the project
2. Create the schemas
3. Use the JAXB Plugin
4. Generate the stubs and use them

REST - Representational State Transfer STATELESSNESS


• Performs CRUD operations - Statelessness
• HTTP provides interface to perform CRUD operations via POST, GET, PUT and DELETE method doesn’t mean
not having a
Example: state at all but
CREATE exchanging
1. Create a patient by using POST method from browser/restful web consumer representationa
2. Send URI like this /patients l state between
3. The RESTful provider will send a HTTP status OK once data is created in database with unique id applications.
4. Later we can read the data by using GET /patients/unique_id The provider
will send the
UPDATE state back to
1. Use PUT method and pass patient information as XML the consumer
2. Send URI like PUT /patients and vice versa.
3. Provider will update information and send status code OK State can be
maintained at
DELETE the client side
1. Use DELETE method and pass patient information as XML rather than
2. Send URI like DELETE /patients/unique_id maintaining on
3. The RESTful provider will send a HTTP status OK once data is delete in database with unique id the server side.

Advantages When to use REST?


1. Single Interface 1. Well defined contract
GET Add exists
2. Multiple data formats
POST Update 3. Bandwidth and memory
a.
PUT Delete 4. Stateless
5. Caching
DELETE Read\
6. Existing Logic can be
2. Easy to access exposed easily
http://www.hostpital.com/patients
/patients/{id}
/prescriptions -> Change URI
/prescriptions/{id}

3. Deliver interoperability and Multiple Data Formats


4. Statelessness
5. Scalability
a. Can be done easily using a load balancer
b. We can cache our since HTTP is stateless, no matter how many times we
perform all the single interface operations (CRUD), the state of application
will not be affected. Improves performance

JAXRS Annotations

Import javax.ws.rs.*;

@Path("/users/{username}") -> Map URIs


@Consumes("text/plain") -> Type of things this can consume
@Produces({"application/json","application/xml"})

Map Parameters to Java objects:


• @PathParam
• @QueryParam
• @FormParam
• @Service - Very imp as spring will consider the class marked with this as the service class
Exception Mappers:

REST API Page 2


Map Parameters to Java objects:
• @PathParam
• @QueryParam
• @FormParam
• @Service - Very imp as spring will consider the class marked with this as the service class
Exception Mappers:
• @Provider

JSON Support @Consumes -


Consumes this type
Add Jackson Dependencies - 3rd part library of data
1. jackson-jaxrs - serialize java objects into JSON @Produces -
2. Jackson-xc - deserialize JSON into java objects Produces this type
3. Change configuration of data as a result
4. Use @Consumes / @Produces datatype

HTTP Status Codes

1. Success : 200 to 399


2. Failure : 400 (error codes) to 599 (redirect codes)

Types of Errors :
1. Standard Errors - Common across all types of platforms and applications
2. Application Error - Specific errors related to specific service or app

Web Application Exceptions


WebApplicationException(Response.Status.NOT_FOUND)

BadRequestException 400
NotAuthorizedException 401
ForbiddenException 403
InternalServerException 500
ServiceUnavailableException 503

JAX-RS Client API

1. Client Builder - Allows to create an instance of the client


2. Client - Communication channel from restful client to the restful resources running on the server.
3. WebTarget - Using client we will create a web target. It points to a unique restful resource that is
available on the server
4. Invoker.Builder - Used to invoke methods like GET,POST, PUT etc.
5. Entity - Represents the data that we exchange and also the data type

JAX-RS Injection

1. @PathParam("id") int id -> /Patient/123 - Pulls info from incomimg REST request URI
and injects it into the java method parameters
2. @QueryParam - can be used along with paging technique to read values from client
3. @FormParam - same but use application/x-www-form-urlencoded in @Consumes to read data
4. @HeaderParam - Reads single header from the HTTP request that comes in
5. @Context - Injects all the HTTPS headers into the object
6. @CookieParam - Sends and reads cookies from HTTP headers

Synchronous Request

• Client sends request to service provider


• Service provider sends status code 200 or 400
• Client has to wait until response is received

Asynchronous Request
• Client sends request to service provider
• Service provider spawns multiple threads to process request
• While threads are processing, the provider sends 202 status code to client indicating that request
has been accepted
• Once the threads are done processing the data, the provider sends 200 status code to client

Provider/Server
Asynchronous -> JAX-RS
Client API

Polling Callback

Async Method
1. ASyncResponse - Tells apache CXF that this method should be asynchronous as soon as it looks at
this parameter
2. Even though Async methods return a value using response.resume(true), we still place the return
type as void
3. @Suspended - Tells the framework that right now the request will be suspended but the response
will come back soon

Client Side
1. AsyncInvoket - Can be used to do polling
2. InvocationCallback - We can write our own callback and wait for the response to come back
3. Future<datatype> -> Java concurrency API represents something that comes in future so it will pull
service
Exceptions:
1. e.getCause() - Exception wrapped inside this (exception handling at client side)

REST API Page 3


End User -
Resource
Spring Security Owner
JavaWorld.com
Publish Endpoint (application.properties) - Client
1. Cxf.jaxrs.classes-scan = true Resource
2. Cxf.jaxrs.classes-scan-packages=package.name,package.name2 Server,
3. Server.servlet.context-path=/springsecurity Authorizaition
4. Spring.security.user.name=customer Server - Google
5. Spring.security.user.password=customer

OAUTH - Data access without shaing usernames and passwords with every
application

• Federated Authentication - The process of one application using


another application to authenticate a user, such as when an app
takes google login or something to check if the customer is actually a
user of google or not
• Delegated Authorization - When an application or site access a
particular part of user's asset such as only google drive to store
some documents after its processing

Attachments using REST

Client POST ------------> REST App (data will be sent in form of a stream)
Client GET <------------- REST App (data can be downloaded in the same way)

Frameworks like Apache CXF converts the file into a Java Object called Attachment
(java.util.File)

Method and URI Design


Upload
POST /fileService/upload
Download
GET /fileService/download

MySQL Workbench -> same as Oracle SQL Developer

Download
Install
Configure

Using Repository:
1. Create Respository.java
2. Mention it in Implementation class which implements Service class
3. Use @Autowired to inject repository at runtime
4. Repository.save(object) -> Data gets saved in DB

Annotations
1. @OneToMany - gives one to many relationship in database
Eg :
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER,mappedBy="patient")

• Cascade = If there is any change in the first class, it should reflect in the second class
table also
• FetchType.EAGER = Immediate fetching of data from first to second
• FetchType.LAZY = Reverse of EAGER
• MappedBy = Parent data entity class

2. @JoinColumn(name="foreign_key_between_2_table_column",nullable=false)
3. @PathParam is a parameter annotation which allows you to map variable URI path
fragments into your method call

Rest API Steps


1. Create a spring starter project in STS
2. Add dependency in pom.xml
○ Jackson JAXRS dependency - To use JSON
○ Spring boot JPA Dependency - For persistence
○ MySql Connector - To Communicate with DB (JDBC Jar)
3. Create Model Objects (Entity Class)
○ Patient.java
▪ Will have List of ClinicalData (One to Many) -> One patient can have
Multiple clinical data
○ ClinicalData.java
▪ Many To One relationship with the Patient class
4. Create Spring Repository (basic interfaces) -> Helps in CRUD operation against DB
5. Create Restful Endpoints
○ PatientService.java -> All patient related operations happen here
▪ Create Patient
▪ Getting single patient
▪ Getting data of all the patients
▪ Analyze Data of Patient (BMI Logic) and add calculated data to DB
○ ClinicalDataService.java -> Store clinical data of patients such as BP, heart rate etc.
○ ClinicalDataReq.java -> Endpoint to hit URL and fetch clinical data from DB
6. Mark with annotations such as @Consumes, @Produces, @Path,
@CrossOriginResourceSharing (access endpoint with angular, react etc.)
7. Application.properties configuration
○ Class Scan
○ Class Scan packages
○ Context Path
○ Datasource URL
○ Datasource username
○ Datasource password

React

REST API Page 4


○ Datasource URL
○ Datasource username
○ Datasource password

React
1. React automatically handles state management
2. Provides virtual DOM and after changes are made, converts minimal required changes to
actual DOM to keep in sync. This process is called as Reconciliation.
3. Provides great API to create reusable UI widgets
4. Combine small API components to create a complex component
5. Views will be defined in Javascript
6. Can use HTML like elements within the Javascript code (JSX Syntax -> Javascript Extensions)
7. Stands for View in MVC

• Yarn - Used to install certain node modules, works better than NPM
• Run in terminal to Install React CLI :
npm I create-react-app

Steps to Create Front End (ORANGE ones are components, each separate JS) :
1. Display Patients
2. Add Patients
3. Collect Clinicals
4. Analyze Data
5. Chart Generator
6. Routing
7. Backend Calls

CLI Commands in Terminal to Start a project:


1. npx create-react-app appname
2. dir (to check if the app is created)
3. cd appname/
4. npm install --save react-router-dom (used to navigate from one page to another)
5. npm install --save axios (used for backend AJAX calls/restful API calls)

Index.js
1. <App> component is main component consisting of rest of the components
2. Wrap the App component with <BrowserRouter>
3. Import {BrowserRouter} from 'reach-router-dom'
4. Go to App.js

App.js
1. Delete everything inside <div> </div>
2. Use <Switch>
3. Import {Route,Switch} from 'react-router-dom'
4. <Route exact path="/" component={Home}/> -> Root component
5. Similarly configurer other components with URI such as:
<Route exact path="/patientDetails/:patientId" component={CollectClinicals}/>

Home.js
1. componentWillMount() -> Life cycle method to get patient information from
backend
2. Import axios from 'axios'
3. Use axios.get('URI') to fetch data
4. Use other functions such as then() to set the data into a local state
5. Design front end within the <div> tags by defining a table
6. Wrap <tr> header inside tags <thead>
7. Use <tbody>
8. Use a RowCreator to create rows
9. Create RowCreator class extending React.Component
10. Create local variable = this.props.___________ -> item name mentioned in tbody
11. Return row consisting of various data
12. Create links for Add Data, Analyze by giving URI
13. Create link under main table for Register Patient by giving URI
.
.
.
.
.
.
.
.
.
.
.

REST API Page 5

You might also like