Share
Explore

CSD 4464 s5 Day Plans a1

Day 01: September 6
Welcome to Class
Review quiz and programming activity of basic Java Skills
Write a Calculator Program:
Accept input parameters for 2 numbers and an operator
output the answer.
Use at least 2 OBJECTS, connected with shared field compostion and method calls.

Lab: Introduction to Java Web Services
Study the Course Outline
Evaluation Timetable

megaphone

Write Java programs with JAX, Java Web Services,

SOAP : Simple Object Access Protocol

http: Hyper Text Transfer Protocol
Using SOAP enable conveying entire OBJECTS between end points, more than just text.

WSDL: WEB Services Description Language

Spring : A framework for implementing SOAP/WSDL Solutions


Do not fall into the mistaken belief that WS must be java-java.
You can build connectors for both sides of the communication path, that both speak WSDL and communicate via WSDL Grammer.

Java API for XML Web Services (JAX-WS)
Understanding the JAX-WS framework
Creating and deploying web services using JAX-WS annotations
RESTful Web Services with JAX-RS [Representational State Transfer]
RESTful architecture principles
Implementing RESTful APIs using JAX-RS annotations
SOAP Web Services
SOAP protocol and message structure
Developing SOAP-based web services in Java
Web Services Description Language (WSDL)
Understanding WSDL structure and elements
Generating and interpreting WSDL documents
Spring Framework Basics
Dependency Injection and Inversion of Control
Spring application context and bean lifecycle
Spring MVC
Model-View-Controller architecture in Spring
Building web applications with Spring MVC
Spring Boot
Rapid application development with Spring Boot
Auto-configuration and embedded servers
Web Service Security
Implementing authentication and authorization
Securing web services using Spring Security
Working with XML and JSON
Parsing and generating XML/JSON in Java
Data binding with JAXB and Jackson
Testing Web Services
Unit testing with JUnit and Mockito
Integration testing of web services
This outline covers the key areas for developing Java-based web services using JAX-WS, JAX-RS, SOAP, WSDL, and the Spring framework.
It provides a structured approach to learning these technologies for building robust and scalable web services.

Here's an introductory lecture on web services, including their history and some sample code:
Title: Introduction to Web Services
I. What are Web Services?
Web services are software systems designed to support interoperable machine-to-machine interaction over a network.
They allow different applications from different sources to communicate with each other without the need to write custom code.
Web services use standardized protocols and data formats, making them platform and language-independent.
Key characteristics of web services: 1. XML-based 2. Loosely coupled 3. Coarse-grained 4. Ability to be synchronous: for eg. HTTP; or asynchronous : eg Email. 5. Supports remote procedure calls: RPC / a way of doing RMI. 6. Supports document exchange.


II. History of Web Services

1. Late 1990s: The concept of web services emerges as businesses seek ways to integrate different software systems.
2. 1999: SOAP (Simple Object Access Protocol) is introduced by Microsoft.
3. 2000: UDDI (Universal Description, Discovery, and Integration) is developed by Ariba, IBM, and Microsoft.
4. 2001: W3C publishes the first public draft of WSDL (Web Services Description Language).
5. Early 2000s: SOAP-based web services gain popularity, often referred to as "Big Web Services."
6. 2000-2002: XML-RPC, a precursor to SOAP, is widely used for its simplicity.
7. 2004: REST (Representational State Transfer) architectural style gains traction as an alternative to SOAP.
8. 2006-present: RESTful web services become increasingly popular due to their simplicity and scalability.
9. 2008-present: Microservices architecture emerges, often implemented using RESTful web services.
III. Types of Web Services
ok

The earliest days of RMI was CORBA

Let's discuss CORBA and Remote Method Invocation (RMI) in the context of JAX-WS (Java API for XML Web Services).
CORBA (Common Object Request Broker Architecture)
CORBA is an older standard for creating distributed object systems. It was developed in the early 1990s by the Object Management Group (OMG).

Key features of CORBA: Common OBJECT Request Broker Access
Language-independent: CORBA objects can be written in different programming languages and still communicate with each other.
Platform-independent: CORBA applications can run on different operating systems and hardware.
Uses Interface Definition Language (IDL) to define interfaces between objects.
Supports synchronous and asynchronous communication.
CORBA was widely used in the 1990s and early 2000s but has since declined in popularity due to its complexity and the rise of simpler technologies like web services.
Remote Method Invocation (RMI)
RMI is a Java-specific technology that allows an object to invoke a method on an object running in another Java Virtual Machine (JVM).
Key features of RMI:
Java-centric: Both client and server must be written in Java.
Supports distributed garbage collection.
Uses Java interfaces to define remote objects.
Allows passing of serializable Java objects between JVMs over the TCP IP connection, as parameters and return values.

RMI is simpler to use than CORBA for Java-to-Java communication but is limited to Java environments.

JAX-WS in Comparison
JAX-WS (Java API for XML Web Services) represents a more modern approach to distributed computing, addressing some limitations of CORBA and RMI while incorporating lessons learned from these technologies.
Language and Platform Independence:
Like CORBA, JAX-WS allows communication between different languages and platforms.
Unlike RMI, JAX-WS is not limited to Java-only environments.
Simplicity:
JAX-WS is generally simpler to use than CORBA, with less complex configuration.
It's more complex than RMI for Java-to-Java communication but offers greater interoperability.
Standards-Based:
JAX-WS uses widely adopted web standards (HTTP, XML, SOAP) instead of proprietary protocols.
This makes it easier to integrate with a wide range of systems and pass through firewalls.
Annotation-Driven Development:
JAX-WS uses Java annotations, simplifying the development process compared to CORBA's IDL or RMI's explicit remote interfaces.
Web Service Description Language (WSDL):
Similar to CORBA's IDL, WSDL provides a language-neutral way to describe web services.
However, WSDL is XML-based and more web-oriented than IDL.
Transport Flexibility:
While typically used over HTTP, JAX-WS can work with other protocols, offering some of the flexibility of CORBA.
Here's a simple comparison in code:
CORBA (IDL definition):
idl
Copy
module Calculator {
interface CalculatorService {
long add(in long a, in long b);
};
};
RMI:

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface CalculatorService extends Remote {
int add(int a, int b) throws RemoteException;
}
JAX-WS:
java
Copy
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;

@WebService
public interface CalculatorService {
@WebMethod
public int add(@WebParam(name = "a") int a, @WebParam(name = "b") int b);
}
In conclusion, while CORBA and RMI were groundbreaking in their time, JAX-WS represents a more modern, web-oriented approach to distributed computing.
It combines the language and platform independence of CORBA with simplicity closer to (though not quite as simple as) RMI, all while leveraging widely adopted web standards.
This makes JAX-WS a powerful tool for creating interoperable services in today's diverse and web-centric computing environments.

megaphone

History of CORBA

While CORBA was a significant early implementation of remote method invocation over TCP/IP networks, it wasn't the first. Let's explore the historical context:
1. Early Remote Procedure Call (RPC) Systems: - Sun RPC (1984): Developed by Sun Microsystems, this was one of the earliest widely-used RPC systems. It used TCP/IP and became the basis for NFS (Network File System). - DCE/RPC (1990): Developed by the Open Software Foundation, this was another early RPC system that worked over TCP/IP.
2. CORBA (Common Object Request Broker Architecture): - Initial release: 1991 - CORBA was developed by the Object Management Group (OMG) as a standard for object-oriented middleware. - It wasn't the first RPC system, but it was one of the first to focus on object-oriented programming and language-independent interoperability.
3. Other Early Distributed Object Systems: - Microsoft's DCOM (Distributed Component Object Model): Released in 1996 - Java RMI (Remote Method Invocation): First appeared in JDK 1.1 in 1997
The popularity of TCP/IP: - TCP/IP became the de facto standard for internet protocols in the early 1980s. - The growth of the internet in the late 1980s and early 1990s significantly increased the adoption and importance of TCP/IP.
CORBA's Significance: While not the first, CORBA was significant because: 1. It was designed to be language-independent and cross-platform from the start. 2. It introduced the concept of an Interface Definition Language (IDL) to describe interfaces between objects. 3. It was backed by a consortium of major tech companies, giving it widespread industry support.
In conclusion, CORBA wasn't the first implementation of remote method invocation over TCP/IP, but it was one of the most influential early systems. It built upon earlier RPC concepts and added object-oriented features and language independence, making it a landmark technology in the evolution of distributed computing.
The progression from early RPC systems to CORBA, and then to technologies like Java RMI, DCOM, and eventually web services (SOAP, REST), represents the ongoing evolution of distributed computing paradigms, each building on the lessons and limitations of its predecessors.


1. SOAP (Simple Object Access Protocol) Web Services - Use XML for message format - Typically use HTTP for transport, but can use other protocols - More complex, but offer built-in error handling and security
2. RESTful (Representational State Transfer) Web Services - Use HTTP methods explicitly - Stateless operations - Typically use JSON for data format, but can use XML or others
IV. Key Technologies
1. XML (eXtensible Markup Language) 2. SOAP (Simple Object Access Protocol) 3. WSDL (Web Services Description Language) 4. UDDI (Universal Description, Discovery, and Integration) 5. JSON (JavaScript Object Notation) 6. HTTP (Hypertext Transfer Protocol)
V. Sample Code
Let's look at two examples: a simple SOAP web service and a RESTful web service using Java.
1. SOAP Web Service (using JAX-WS):
```java import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam;
@WebService(serviceName = "CalculatorService") public class CalculatorWS { @WebMethod(operationName = "add") public int add(@WebParam(name = "a") int a, @WebParam(name = "b") int b) { return a + b; } } ```
To publish this web service:
```java import javax.xml.ws.Endpoint;
public class CalculatorPublisher { public static void main(String[] args) { Endpoint.publish("http://localhost:8080/CalculatorService", new CalculatorWS()); System.out.println("Calculator Web Service is published!"); } } ```
2. RESTful Web Service (using JAX-RS with Jersey implementation):
First, add Jersey dependencies to your project. Then create the following classes:
```java import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType;
@Path("/calculator") public class CalculatorResource { @GET @Path("/add/{a}/{b}") @Produces(MediaType.TEXT_PLAIN) public String add(@PathParam("a") int a, @PathParam("b") int b) { return String.valueOf(a + b); } } ```
To run this RESTful service, you'll need to set up a Jersey servlet in your web.xml file or use a framework like Spring Boot.
VI. Conclusion
Web services have revolutionized how software systems communicate, enabling seamless integration between diverse applications. From the early days of SOAP to the current prevalence of RESTful services and microservices, web services continue to evolve to meet the changing needs of distributed systems.
As we move forward, trends like GraphQL, gRPC, and serverless architectures are shaping the future of web services, but the core principles of interoperability and standardization remain central to their design and implementation.



Let's expand on the Java API for XML Web Services (JAX-WS) stanza:

1. Java API for XML Web Services (JAX-WS)
a. Understanding the JAX-WS framework - JAX-WS is a Java API for creating web services, particularly SOAP web services - It simplifies web service development by using Java annotations - Key components: Service Endpoint Interface (SEI), Service Implementation Bean, and WSDL
b. Creating and deploying web services using JAX-WS annotations - Common annotations: @WebService, @WebMethod, @WebParam, @WebResult - Steps to create a web service: 1. Define the Service Endpoint Interface (SEI) 2. Implement the SEI 3. Publish the web service
Here's a sample code demonstrating a simple JAX-WS web service:
1. Define the Service Endpoint Interface (SEI):
```java import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam;
@WebService public interface CalculatorService { @WebMethod public int add(@WebParam(name = "a") int a, @WebParam(name = "b") int b); } ```
2. Implement the SEI:
```java import javax.jws.WebService;
@WebService(endpointInterface = "CalculatorService") public class CalculatorServiceImpl implements CalculatorService { @Override public int add(int a, int b) { return a + b; } } ```
3. Publish the web service:
```java import javax.xml.ws.Endpoint;
public class CalculatorPublisher { public static void main(String[] args) { Endpoint.publish("http://localhost:8080/calculatorservice", new CalculatorServiceImpl()); System.out.println("Calculator Service is published!"); } } ```
4. Generate a client to consume the web service:
```java import javax.xml.namespace.QName; import javax.xml.ws.Service; import java.net.URL;
public class CalculatorClient { public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:8080/calculatorservice?wsdl"); QName qname = new QName("http://impl.service.example.com/", "CalculatorServiceImplService"); Service service = Service.create(url, qname); CalculatorService calculator = service.getPort(CalculatorService.class); System.out.println("Sum: " + calculator.add(10, 20)); } } ```
This example demonstrates: - Using @WebService to define a web service interface and implementation - Using @WebMethod to expose a method as a web service operation - Using @WebParam to customize parameter names in the WSDL - Publishing a web service using the Endpoint class - Creating a client to consume the web service
Key points to remember: - JAX-WS handles the conversion between Java objects and XML (SOAP messages) - It automatically generates the WSDL file for the web service - JAX-WS supports both SOAP 1.1 and SOAP 1.2 - It can be used with Java SE 6 and later, or with Java EE 5 and later in a web container
By understanding these concepts and using the JAX-WS annotations, you can quickly develop and deploy web services in Java.

minus
Simple Object Access Protocol and Web Services Description Language

Let's dive into how SOAP (Simple Object Access Protocol) and WSDL (Web Services Description Language) work, along with code examples.

SOAP (Simple Object Access Protocol):
SOAP is an XML-based protocol for exchanging structured data between systems, typically over HTTP. It defines a standard message format that consists of:
1. An Envelope (required) 2. A Header (optional) 3. A Body (required)
Here's a simple SOAP message example:
```xml <?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"> <soap:Header> <!-- Optional header information --> </soap:Header> <soap:Body> <m:GetStockPrice xmlns:m="http://www.example.org/stock"> <m:StockName>IBM</m:StockName> </m:GetStockPrice> </soap:Body> </soap:Envelope> ```
WSDL (Web Services Description Language): WSDL is an XML-based language used to describe web services. It defines:
1. The operations a web service offers 2. The format of the messages it accepts and returns 3. The protocols it supports 4. Where to find the service
Here's a simplified WSDL example:
```xml <?xml version="1.0"?> <definitions name="StockQuoteService" targetNamespace="http://example.com/stockquote.wsdl" xmlns:tns="http://example.com/stockquote.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/">
<types> <xsd:schema targetNamespace="http://example.com/stockquote.xsd"> <xsd:element name="TradePriceRequest"> <xsd:complexType> <xsd:all> <xsd:element name="tickerSymbol" type="xsd:string"/> </xsd:all> </xsd:complexType> </xsd:element> <xsd:element name="TradePrice"> <xsd:complexType> <xsd:all> <xsd:element name="price" type="xsd:float"/> </xsd:all> </xsd:complexType> </xsd:element> </xsd:schema> </types>
<message name="GetLastTradePriceInput"> <part name="body" element="tns:TradePriceRequest"/> </message> <message name="GetLastTradePriceOutput"> <part name="body" element="tns:TradePrice"/> </message>
<portType name="StockQuotePortType"> <operation name="GetLastTradePrice"> <input message="tns:GetLastTradePriceInput"/> <output message="tns:GetLastTradePriceOutput"/> </operation> </portType>
<binding name="StockQuoteSoapBinding" type="tns:StockQuotePortType"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="GetLastTradePrice"> <soap:operation soapAction="http://example.com/GetLastTradePrice"/> <input> <soap:body use="literal"/> </input> <output> <soap:body use="literal"/> </output> </operation> </binding>
<service name="StockQuoteService"> <port name="StockQuotePort" binding="tns:StockQuoteSoapBinding"> <soap:address location="http://example.com/stockquote"/> </port> </service>
</definitions> ```
Now, let's see how we can implement this using JAX-WS in Java:
1. Define the service interface:
```java import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam;
@WebService public interface StockQuoteService { @WebMethod public float getLastTradePrice(@WebParam(name = "tickerSymbol") String symbol); } ```
2. Implement the service:
```java import javax.jws.WebService;
@WebService(endpointInterface = "StockQuoteService") public class StockQuoteServiceImpl implements StockQuoteService { public float getLastTradePrice(String symbol) { // In a real implementation, this would fetch the actual stock price if ("IBM".equals(symbol)) { return 55.6f; } return 0; } } ```
3. Publish the web service:
```java import javax.xml.ws.Endpoint;
public class StockQuotePublisher { public static void main(String[] args) { Endpoint.publish("http://localhost:9999/ws/stock", new StockQuoteServiceImpl()); System.out.println("Stock Quote Service is published!"); } } ```
4. Create a client to consume the web service:
```java import javax.xml.namespace.QName; import javax.xml.ws.Service; import java.net.URL;
public class StockQuoteClient { public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:9999/ws/stock?wsdl"); QName qname = new QName("http://impl.service.example.com/", "StockQuoteServiceImplService"); Service service = Service.create(url, qname); StockQuoteService stockQuote = service.getPort(StockQuoteService.class); System.out.println("IBM stock price: " + stockQuote.getLastTradePrice("IBM")); } } ```
In this example:
1. JAX-WS uses the @WebService and @WebMethod annotations to generate the WSDL and SOAP binding automatically. 2. The SOAP messages are created and parsed by the JAX-WS runtime, abstracting these details from the developer. 3. The client uses the generated WSDL to create a proxy for the web service, allowing method calls as if they were local.
This demonstrates how SOAP and WSDL work together in a JAX-WS environment, providing a standard way to describe and interact with web services across different platforms and programming languages.
image.png

megaphone

Coding Exercise: The Calculator

Write a Calculator Program:
Write and document this to illustrate for student formally excellent coding :
high cohesion,
low coupling.
Next we will re-jig this program to work as a Java web services program with the server class in one jvm and the consumer class in another jvm.
Our Java program should Accept input parameters for 2 numbers and an operator output the answer.
Use at least 2 OBJECTS, connected with shared field compostion and method calls.

Lab: Introduction to Java Web Services
I'll create a well-documented Calculator program that demonstrates
High cohesion : 1 algorithm is housed in 1 class: 1 class, I job
Low coupling: Minimize the number of number of method calls in the application.
image.png
We'll structure it in a way that will make it easy to convert to a web service later.
package com.example.calculator;

import java.util.Scanner;

/**
* The main class that runs the calculator program.
*/
public class CalculatorApp {
public static void main(String[] args) {
Calculator calculator = new Calculator();
InputHandler inputHandler = new InputHandler();

while (true) {
double num1 = inputHandler.getNumber("Enter first number: ");
String operator = inputHandler.getOperator("Enter operator (+, -, *, /): ");
double num2 = inputHandler.getNumber("Enter second number: ");

try {
double result = calculator.calculate(num1, num2, operator);
System.out.printf("Result: %.2f%n", result);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}

if (!inputHandler.continueCalculation()) {
break;
}
}

inputHandler.close();
System.out.println("Thank you for using the calculator!");
}
}

/**
* Handles the calculation logic.
* This class demonstrates high cohesion by focusing solely on calculation operations.
*/
class Calculator {
/**
* Performs the calculation based on the provided numbers and operator.
*
* @param num1 The first number.
* @param num2 The second number.
* @param operator The arithmetic operator.
* @return The result of the calculation.
* @throws IllegalArgumentException If an invalid operator is provided or if division by zero is attempted.
*/
public double calculate(double num1, double num2, String operator) {
switch (operator) {
case "+":
return num1 + num2;
case "-":
return num1 - num2;
case "*":
return num1 * num2;
case "/":
if (num2 == 0) {
throw new IllegalArgumentException("Cannot divide by zero");
}
return num1 / num2;
default:
throw new IllegalArgumentException("Invalid operator");
}
}
}

/**
* Handles user input operations.
* This class demonstrates high cohesion by focusing solely on input handling.
*/
class InputHandler {
private Scanner scanner;

public InputHandler() {
this.scanner = new Scanner(System.in);
}

/**
* Gets a number input from the user.
*
* @param prompt The prompt to display to the user.
* @return The number entered by the user.
*/
public double getNumber(String prompt) {
System.out.print(prompt);
while (!scanner.hasNextDouble()) {
System.out.print("Invalid input. Please enter a number: ");
scanner.next();
}
return scanner.nextDouble();
}

/**
* Gets an operator input from the user.
*
* @param prompt The prompt to display to the user.
* @return The operator entered by the user.
*/
public String getOperator(String prompt) {
System.out.print(prompt);
String operator;
while (true) {
operator = scanner.next();
if (operator.matches("[+\\-*/]")) {
break;
}
System.out.print("Invalid operator. Please enter +, -, *, or /: ");
}
return operator;
}

/**
* Asks the user if they want to continue with another calculation.
*
* @return true if the user wants to continue, false otherwise.
*/
public boolean continueCalculation() {
System.out.print("Do you want to perform another calculation? (y/n): ");
return scanner.next().toLowerCase().startsWith("y");
}

/**
* Closes the scanner.
*/
public void close() {
scanner.close();
}
}
This program demonstrates:
High Cohesion:
The Calculator class is responsible only for performing calculations.
The InputHandler class is responsible only for handling user input.
The CalculatorApp class orchestrates the program flow.
Low Coupling:
The Calculator class doesn't depend on InputHandler or vice versa.
The CalculatorApp uses both classes but they don't depend on each other.
Separation of Concerns:
Input handling, calculation, and program flow are separated into different classes.
Error Handling:
The program handles invalid inputs and division by zero.
Reusability:
The Calculator and InputHandler classes can be easily reused in other contexts.
To convert this into a Java Web Service:
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.