Java REST Web Services
Java REST Web Services
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
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
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
Namespaces
Schema:
targetNamespace: http://www.amazon.com/order
<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
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
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
JAXRS Annotations
Import javax.ws.rs.*;
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
BadRequestException 400
NotAuthorizedException 401
ForbiddenException 403
InternalServerException 500
ServiceUnavailableException 503
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
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)
OAUTH - Data access without shaing usernames and passwords with every
application
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)
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
React
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
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
.
.
.
.
.
.
.
.
.
.
.