Showing posts with label Webservice. Show all posts
Showing posts with label Webservice. Show all posts

Wednesday, June 14, 2023

MS - Springboot + Hibernate + Rest web service chapter 1

 Create a simple REST web service using springboot.

Use spring initializer   https://start.spring.io/

Dependencies

Web, JPA, database ( Mysql Connctor ) 

for your wish you can use, lombok, actuator, devtools

Webservice will include simple CRUD operation alias with REST POST,GET, PUT, GET

Tech Stack

Java 8, Maven, Springboot 3.10 , 


Sample code as below

POM file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo.micro</groupId>
<artifactId>student</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>student</name>
<description>Student Service</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


Application properties

server.port=8203
spring.datasource.url=jdbc:mysql://localhost:3306/student_mgt
spring.datasource.username=root
spring.datasource.password=root

# for Spring Boot 2
# spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
# for Spring Boot 3
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=false
spring.jpa.generate-ddl=true
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl



Code base Structure

com.demo.micro.student

controller --> will include REST API

model --> model classes

repository --> repo file, db connection

service --> service classes

MainApllication --> StudentApplication with @SpringBootApplication


Controller

package com.demo.micro.student.controller;

import com.demo.micro.student.model.Student;
import com.demo.micro.student.service.StudentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/students")
public class StudentController {

@Autowired
StudentServiceImpl studentService;

@GetMapping("")
public ResponseEntity<List<Student>> list() {
return new ResponseEntity<List<Student>>(studentService.list(), HttpStatus.OK);
}

@PostMapping("")
public ResponseEntity<Student> resgiterStudent(@RequestBody Student student) {
try {
Student st = studentService.createStudent(student);
return new ResponseEntity<>(st, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

@PutMapping("")
public ResponseEntity<Student> updateStudent(@RequestBody Student student) {
return new ResponseEntity<>(studentService.createStudent(student), HttpStatus.OK);
}

@PutMapping("/{id}")
public ResponseEntity<Student> updateStudent(@PathVariable("id") int id, @RequestBody Student student) {
Optional<Student> st = studentService.findById(id);
if (st.isPresent()) {
// set details for student
return new ResponseEntity<>(studentService.createStudent(student), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}

/**
* Don't do this. We normally makes a soft delete -
* 1. update flag/property as deleted. But flag is redundant field
* 2. use date/time option. nullable date time or default old time.
*
* @param student
* @return
*/
@DeleteMapping("")
public ResponseEntity<Student> deleteStudent(@RequestBody Student student) {
studentService.deleteStudent(student);
return new ResponseEntity<>(null, HttpStatus.ACCEPTED);
}
}


Model

package com.demo.micro.student.model;

import jakarta.persistence.*;
import lombok.Data;

/**
* Student details.
*/
@Entity
@Table(name = "student")
@Data
public class Student {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "student_id")
private int studentId;

/**
* First name of the student.
*/
@Column(name = "first_name")
private String firstName;

/**
* Last name of the student.
*/
@Column(name = "last_name")
private String lastName;


}

Repository

package com.demo.micro.student.repository;

import com.demo.micro.student.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository<Student,Integer> {
}


Service classes - Interface and Impl

package com.demo.micro.student.service;

import com.demo.micro.student.model.Student;

import java.util.List;
import java.util.Optional;

/**
*
*/
public interface StudentService {

/**
* Returns a list of {@link Student}s.
* @return list of {@link Student}
*/
List<Student> list();
Student createStudent(Student student);

Optional<Student> findById(int studentId);

void deleteStudent(Student student);
}


package com.demo.micro.student.service;

import com.demo.micro.student.model.Student;
import com.demo.micro.student.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class StudentServiceImpl implements StudentService {

@Autowired
StudentRepository studentRepository;

/**
* List all the {@link Student}
*
* @return
*/
@Override
public List<Student> list() {
return studentRepository.findAll();
}

/**
* Create a new record of {@link Student}.
*
* @param student
* @return
*/
@Override
public Student createStudent(Student student) {
return studentRepository.save(student);
}

@Override
public Optional<Student> findById(int studentId) {
return studentRepository.findById(studentId);
}

public void deleteStudent(Student student) {
studentRepository.delete(student);
}

}


Important : Note that we put @Srvivie at Impl class, not Interface


Main class

package com.demo.micro.student;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class StudentApplication {

public static void main(String[] args) {
SpringApplication.run(StudentApplication.class, args);
}

}






Thursday, January 4, 2018

Useful Chrome Browser features

1. check the disk cache write, read etc

chrome://net-internals/#timeline

once you type chrome:// , you will get popups for so many extenstions

Thursday, November 3, 2016

Steps of building the Rest webservice

I have made a blog on creating a rest application. Just thought giving some steps to follow and check the application building process.

this is based on the link
http://cgenit.blogspot.com/2015/06/creating-webservice.html

1.       Create application “Rest” using maven plugin in eclipse.
2.       Deployed to tomcat and http://localhost:8080/Rest/ loading the home page
4.       Apache CXF , spring , Jaxon, JAXB
5.       Added all the maven dependencies
6.       Build the project  mvn clean package , and redeploy in tomcat server and check home page http://localhost:8080/Rest/  loading fine
7.       Change the web.xml , Initially no entries except for
8.       You cannot just add changes to web.xml and test. It won’t work as web.xml refers beans and etc.
9.       Change web.xml
a.       Added classed
b.      Build and deploy   - not working
c.       My added “java” folder was not inside “Rest\src\main”
d.      I copied ”java” folder
e.      It was not working, cause I have named bean.xml where it should have been beans.xml – which is referred by the web.xml
f.        Make sure names are spelled correctly. Working fine


Simple Angular Application to Call A Rest Webservice

Here I make an simple angular application to call a rest web service call

1. create sample rest web service. get an employee with id

http://cgenit.blogspot.com/2015/06/creating-webservice.html

2. let's create a simple web application calling this rest service

we call this rest service with

http://localhost:8080/Rest/rest/employeeservices/getemployeedetail?employeeId=1

3. We use the same "index.jsp" for this application
4. we create "hello.js" to put the angular based scripts
5. These script is called inside the "index.jsp"


the two files should be inside "webapp" folder . For this application path would be "Rest\src\main\webapp"

 6. build the project with maven and deploy the Rest.war file inside the tomcat and access the application using the url http://localhost:8080/Rest/

you will simply get an output as below.



Rest Application code structure


Below are the code snipets


hello.js
===========================================================


angular.module('demo', []).controller(
'Hello',
function($scope, $http) {
$http.get('http://localhost:8080/Rest/rest/employeeservices/getemployeedetail?employeeId=1').then(
function(response) {
$scope.employee = response.data;
});
});



=========================================================


index.jsp

============================================================


<!doctype html>
<html ng-app="demo">
<head>
<title>Hello AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
    <script src="hello.js"></script>
</head>

<body>
<div ng-controller="Hello">
<p>The ID is  = {{employee.employeeId}}</p>
<p>First name = {{employee.firstName}}</p>
<p>Last name  = {{employee.lastName}}</p>
<p>Date of join = {{employee.dateOfJoining}}</p>
<p>Department = {{employee.department}}</p>
<p>Email{{employee.email}}</p>
</div>
</body>
</html
============================================================

Thursday, June 25, 2015

Creating WebService

Let's create a web service.
We will use maven as build tool and it will makes our life easy.
I will be using STS , Spring Tool Suite.

First we create a maven  web project using STS.
It will have below structure.
Web Project structure



you can build war file using maven tool.
Go to folder where "pom.xml" file exists. and open a command window
execute the maven command

===============
mvn clean package
==============

above command will build the war file.
eg: Here my folder path is "C:\eclipseWorkSpace\2015-01-19_SpringSecurity\Rest>"  where "pom.xml" file reside and remember this the basic web project create with maven using STS. you can create a web project using maven commands directly also. So when i execute the command "mvn clean package " in the command line I have to change the directory to the above mention folder where "pom.xml" resides.
you will see the war file will be created inside target directory. "C:\eclipseWorkSpace\2015-01-19_SpringSecurity\Rest\target"

Web project structure after building war file - Rest.war created

Now get the war file and deploy in the tomcat.
to deploy copy "Rest.war" and paste it inside "webapps" folder inside tomcat.

To refresh your knowledge in tomcat, we can get the tomcat from site and unzip and go to "bin" folder
Here in my case it is "C:\Softwares\Apache\Apache Tomcat\Apache Tomcat 8.0.3\apache-tomcat-8.0.3\bin" and open commad window. set the path to bin directory. execute the command "catalina.bat run"

===================================
C:\Softwares\Apache\Apache Tomcat\Apache Tomcat 8.0.3\apache-tomcat-8.0.3\bin>catalina.bat run
===================================

you will see the starting of the tomcat and trace will shown in the same command window.
If you need you can also run "startup " also, but it will have a seperate window open and run tomcat.

Now you application is deployed in tomcat and to test open browser and type "http://localhost:8080/Rest/" and you will see the default message or default page created with the app showing "Hello World!" in the browser.

Steps we did so far
========
1. create a maven web project using STS
2. build the project using maven - command line "mvn clean package"
3. deploy the web project "war file" in the  tomcat and view in the browser.

Above are the simple steps to create a default web project , pakage war file , deploy and test whether create project really works.

Below are the inside of the files created in the web project. Initially we do not have lots of files only basic files and folder structure will be as shown above and i won't try to explain it again.

Web.xml
======================================================================
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
</web-app>
======================================================================

index.jsp
======================================================================
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
======================================================================

pom.properties
======================================================================
#Generated by Maven
#Fri Jun 26 10:41:37 IST 2015
version=0.0.1-SNAPSHOT
groupId=com.webservice.rest
artifactId=Rest

======================================================================

pom.xml
======================================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.webservice.rest</groupId>
  <artifactId>Rest</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Rest Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>Rest</finalName>
  </build>
</project>
======================================================================

Now let's go to create the web service application.
Here we use Apache CXF , spring , Jaxon, JAXB

First I will add all coding 

REST Web Service
---------------------
All dependencies

Pom.xml
======================================================================
<modelVersion>4.0.0</modelVersion>
<groupId>com.webservice.rest</groupId>
<artifactId>Rest</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT&lt;/version>
<name>Rest Maven Webapp</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope&gt;
</dependency>

<!-- Spring Dependencies -->
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-core&lt;/artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-context</artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-web&lt;/artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-beans</artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>

<!-- XML dependency -->
<dependency>
<groupId>javax.xml.bind&lt;/groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>

<!-- Apache CXF Dependencies -->
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId&gt;
<version>2.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>2.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>2.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId&gt;
<version>2.7.13</version>
</dependency>
<!-- Jackson The JSON Producer dependency -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>
</dependencies>
<build>
<finalName>Rest</finalName>
</build>
</project>

======================================================================

web.xml
======================================================================
<?xml version="1.0" encoding="UTF-8"?>
id="WebApp_ID" version="3.0">


<display-name>Archetype Created Web Application</display-name&gt;

<welcome-file-list>
<welcome-file>index.jsp&lt;/welcome-file>
</welcome-file-list>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans.xml</param-value>
</context-param>

<servlet>
<servlet-name>CXFServlet</servlet-name&gt;
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class&gt;
</servlet>

<servlet-mapping>
<servlet-name>CXFServlet</servlet-name&gt;
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

</web-app>

======================================================================

Employee.java    -->model class
======================================================================
package com.rest.cxfrestservice.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employee")
public class Employee {
private String firstName;
private String lastName;
private String employeeId;
private String email;
private String dateOfJoining;
private String department;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmployeeId() {
return employeeId;
}

public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getDateOfJoining() {
return dateOfJoining;
}

public void setDateOfJoining(String dateOfJoining) {
this.dateOfJoining = dateOfJoining;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}

}

======================================================================

EmployeeDao .java --> dao class
======================================================================
package com.rest.cxfrestservice.dao;

import com.rest.cxfrestservice.model.Employee;

public class EmployeeDao {
public Employee getEmployeeDetails(String employeeId) {
Employee emp = new Employee();
emp.setDateOfJoining("01-02-2001");
emp.setDepartment("Sales");
emp.setEmail("test@example.com");
emp.setEmployeeId("675436");
emp.setFirstName("John");
emp.setLastName("Smith");
return emp;
}
}

======================================================================

CxfRestService .java  -->  Interface for Employee Service.
======================================================================
package com.rest.cxfrestservice.service;

import javax.jws.WebService;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * Interface for Employee Service.
 * 
 * @author APRASAD
 * 
 */

@Path("/")
@WebService(name="employeeService" , targetNamespace="http://localhost/cxf-rest/example")
public interface CxfRestService {

@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/getemployeedetail")
public Response getEmployeeDetails(
@QueryParam("employeeId") String employeeId);
}

======================================================================

CxfRestServiceImpl .java --> implementation of for Employee Service.
======================================================================
package com.rest.cxfrestservice.service;

import javax.ws.rs.core.Response;

import org.springframework.beans.factory.annotation.Autowired;

import com.rest.cxfrestservice.dao.EmployeeDao;

public class CxfRestServiceImpl implements CxfRestService {

@Autowired
private EmployeeDao employeeDao;

public Response getEmployeeDetails(String employeeId) {
if (employeeId == null) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
return Response.ok(employeeDao.getEmployeeDetails(employeeId)).build();
}
}

======================================================================

bean.xml
======================================================================

<import resource="classpath:META-INF/cxf/cxf.xml" />
<context:component-scan base-package="com.rest.*" />

<jaxrs:server id="employeeService" address="/employeeservices"&gt;
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
<jaxrs:serviceBeans>
<ref bean="cxfServiceImpl" />
</jaxrs:serviceBeans>
<jaxrs:extensionMappings&gt;
<entry key="xml" value="application/xml" />
<entry key="json" value="application/json" />
</jaxrs:extensionMappings&gt;
</jaxrs:server>

<bean id="cxfServiceImpl" class="com.rest.cxfrestservice.service.CxfRestServiceImpl" />
<bean id="employeeDao" class="com.rest.cxfrestservice.dao.EmployeeDao" />
</beans>
======================================================================


access above depolyed jar with


you will get out as

======================================================================
<employee>
<dateOfJoining>01-02-2001</dateOfJoining>
<department>Sales</department>
<employeeId>675436</employeeId>
<firstName>John</firstName>
<lastName>Smith</lastName>
</employee>
======================================================================



======================================================================

<grammars/>
<resource path="/">
<resource path="getemployeedetail">
<method name="GET">
<request>
<param name="employeeId" style="query" type="xs:string"/>
</request>
<response>
<representation mediaType="application/xml"/&gt;
<representation mediaType="application/json"/&gt;
</response>
</method>
</resource>
</resource>
</resources>
</application>
======================================================================

Tuesday, April 7, 2015

Creating SOAP client

1. create simple maven project.
You can create directly if you use STS(Spring Tool Suite), Eclipse, you have maven plugin , or directly create using maven tool.

2. Now you need to create subs for the client. To access the webservice.
We will use the web service which was taken from the mkyong.
http://www.mkyong.com/webservices/jax-ws/jax-ws-java-web-application-integration-example/

This has some issues, missing jaxws-rt.jar etc. I have explained what you should do in
http://cgenit.blogspot.com/2015/04/error-deploying-soap-application.html

best thing is to add jaxws-rt.jar as maven dependency. you can get the maven dependency by simply doing a google search for maven dependency.

let's get back  into building client stubs

3. Now you need apache cxf libraries to build the stubs. These libs will give you access for specific set of commands where you can use for various purposes.
You can donload this from apache cxf site.
http://cxf.apache.org/docs/tools.html
here i will be using wsdl2java , where this will help me to build the stubs.
I have downloaded whole set. you can unzip where ever you need.
I have unzip it to the "C:\Softwares\Apache" folder
so my location for wsdl2java will looks like "C:\Softwares\Apache\apache-cxf-3.0.4\bin"
this will have lots of

Next use of the command "wsdl2java"

4. set path to "wsdl2java"  tool
take command prompt.
you get the command prompt from the programs menu in windows or simply get the run (windows + R) , then type "cmd" and press enter.

type "wsdl2java" in the command prompt.
It will give the message
=================================================================
'wsdl2java' is not recognized as an internal or external command,
operable program or batch file.
=================================================================

you need to set the path to the commands.

below is the commad

===================================================================
>set path=C:\Softwares\Apache\apache-cxf-3.0.4\bin
===================================================================

bin folder is the directory, where you have all the apache tools including "wsdl2java"

Now if you run the same command, you will get the output like as below.
this is same as setting path to java bin

note : i am executing the command from respective to the directory i have created
"C:\waste\webservices\client\WebClientTest>" and it will prompt straight away for missing argument list.

I have create "WebClientTest" directory to include the created stubs from "wsdl2java"


===================================================================

C:\waste\webservices\client\WebClientTest>wsdl2java
Missing argument: wsdlurl

Usage : wsdl2java -fe|-frontend -db|-databinding -wv -p <[wsdl-namespace =]package-name>
* -sn -b * -reserveClass * -catalog -d -compile -classd
ir -impl -server -client -clientjar -all -autoNameResolution -allowElementReferences|-aer<=true>
 -defaultValues<=class-name-for-DefaultValueProvider> -ant -nexclude * -exsh <(true, false)> -noType
s -dns -dex <(true, false)> -validate<[=all|basic|none]> -keep -wsdlLocation -xjc* -as
yncMethods<[=method1,method2,...]>* -bareMethods<[=method1,method2,...]>* -mimeMethods<[=method1,method2,...]>* -noAddressBinding -faultSeri
alVersionUID -encoding -exceptionSuper -mark-generated -h|-?|-help -version|-v -verbose
|-V -quiet|-q|-Q -wsdlList


WSDLToJava Error: org.apache.cxf.tools.common.toolspec.parser.BadUsageException: Missing argument: wsdlurl



C:\waste\webservices\client\WebClientTest>

===================================================================



5. create stubs

run the command "wsdl2java -client http://localhost:8080/webservices/hello?wsdl"

wsdl2java   - is the tool from apache cxf
-clent -  choice given by apache tool wsdl2java to create client stubs
http://localhost:8080/webservices/hello?wsdl  - is the location for wsdl, here i have used locally developed and deployed service in the tomcat, you can give any location to the wsdl file

Note: I have not given the output directory for client stubs. stubs will be created in the directory where you are running the command.
In my case it will be "C:\waste\webservices\client\WebClientTest"

So my command and output will be
Note: empty command return after execution of the command.
This will create structure for stubs inside "C:\waste\webservices\client\WebClientTest" directory.

===================================================================
C:\waste\webservices\client\WebClientTest>wsdl2java -client http://localhost:8080/webservices/hello?wsdl

C:\waste\webservices\client\WebClientTest>

===================================================================



6. Copy paste the created directory sructure to the src folder inside your maven project.
Normally it has "src\main\java" folder structure.
I have created the maven project with "WebClientTest" , so the structure would be "C:\eclipseWorkSpace\2015-01-19_SpringSecurity\WebClientTest\src\main\java"

copy the stubs to "C:\eclipseWorkSpace\2015-01-19_SpringSecurity\WebClientTest\src\main\java"

Note : stubs will have below folder structure
"C:\waste\webservices\client\WebClientTest\com\mkyong\ws"

where "C:\waste\webservices\client\WebClientTest\"  is the created folder for include stubs file by running "wsdl2java" command
It will create stubs inside folder / or package structure "com\mkyong\ws" , this is the webservice code structure we have deployed in the tomcat.

structure would be as below , where you will have 7 java files.
==============================================================

C:\waste\webservices\client\WebClientTest\com\mkyong\ws>dir
 Volume in drive C is Windows
 Volume Serial Number is 76A1-C302

 Directory of C:\waste\webservices\client\WebClientTest\com\mkyong\ws

04/07/2015  03:33 PM              .
04/07/2015  03:33 PM              ..
04/07/2015  03:33 PM             1,398 GetHelloWorld.java
04/07/2015  03:33 PM             1,532 GetHelloWorldResponse.java
04/07/2015  03:33 PM             1,219 HelloWorld.java
04/07/2015  03:33 PM             3,417 HelloWorldService.java
04/07/2015  03:33 PM             1,934 HelloWorld_HelloWorldPort_Client.java
04/07/2015  03:33 PM             2,488 ObjectFactory.java
04/07/2015  03:33 PM                99 package-info.java
               7 File(s)         12,087 bytes
               2 Dir(s)  386,769,772,544 bytes free

===================================================================

7. Write main class / client  to test the created client and web service.

create "ClientHello.java" class under package "com.webservices.client".
We write the main method inside here.

* first we create service object. Stubs will have a class with name "service". In this case it is "HelloWorldService" , this is an extension of "Service" provided by "javax.xml.ws" inside the "rt.jar"

                // create service
HelloWorldService helloWorldService =  new HelloWorldService();

* Then we create the port object
                // create soap object from service which is port. 
HelloWorld helloWorld = helloWorldService.getHelloWorldPort();

* once we create the port, we access the web service methods via the port. This time we have only one.
               // through the port we call the methods.
String output = helloWorld.getHelloWorld("John");

* you ill see the out put as
                     Hello World JAX-WS John

Below is the main method

ClientHello.java
=-==================================================================
package com.webservices.client;

import com.mkyong.ws.HelloWorld;
import com.mkyong.ws.HelloWorldService;

public class ClientHello {
public static void main(String[] args) {

// create service
HelloWorldService helloWorldService =  new HelloWorldService();
// create soap object from service which is port.
HelloWorld helloWorld = helloWorldService.getHelloWorldPort();

// through the port we call the methods.
String output = helloWorld.getHelloWorld("John");

System.out.println(output);
}
}

=-==================================================================



8. wsdl2java generates test client itself to test the generated stubs and webservice.
In this case you have seen java class with the name "HelloWorld_HelloWorldPort_Client.java"
This has the main method which has been design to test the webservice

code will looks like below

HelloWorld_HelloWorldPort_Client.java
=-==================================================================

package com.mkyong.ws;

/**
 * Please modify this class to meet your needs
 * This class is not complete
 */

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;

/**
 * This class was generated by Apache CXF 3.0.4
 * 2015-04-07T15:33:01.951+05:30
 * Generated source version: 3.0.4
 *
 */
public final class HelloWorld_HelloWorldPort_Client {

    private static final QName SERVICE_NAME = new QName("http://ws.mkyong.com/", "HelloWorldService");

    private HelloWorld_HelloWorldPort_Client() {
    }

    public static void main(String args[]) throws java.lang.Exception {
        URL wsdlURL = HelloWorldService.WSDL_LOCATION;
        if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
            File wsdlFile = new File(args[0]);
            try {
                if (wsdlFile.exists()) {
                    wsdlURL = wsdlFile.toURI().toURL();
                } else {
                    wsdlURL = new URL(args[0]);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
     
        HelloWorldService ss = new HelloWorldService(wsdlURL, SERVICE_NAME);
        HelloWorld port = ss.getHelloWorldPort();
       
        {
        System.out.println("Invoking getHelloWorld...");
        java.lang.String _getHelloWorld_arg0 = "";
        java.lang.String _getHelloWorld__return = port.getHelloWorld(_getHelloWorld_arg0);
        System.out.println("getHelloWorld.result=" + _getHelloWorld__return);


        }

        System.exit(0);
    }

}

=-==================================================================


output will be as below
=-==================================================================

Invoking getHelloWorld...
getHelloWorld.result=Hello World JAX-WS
=-==================================================================


Note : we have invoked the "getHelloWorld" method with empty string. Default values has been set to empty string in the creation time from the "wsdl2java"

so if you assign a value to "_getHelloWorld_arg0" it will have output with the given value.
let's assign "John"

the new code and value would be as below.


HelloWorld_HelloWorldPort_Client.java
=-==================================================================


package com.mkyong.ws;

/**
 * Please modify this class to meet your needs
 * This class is not complete
 */

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;

/**
 * This class was generated by Apache CXF 3.0.4
 * 2015-04-07T15:33:01.951+05:30
 * Generated source version: 3.0.4
 *
 */
public final class HelloWorld_HelloWorldPort_Client {

    private static final QName SERVICE_NAME = new QName("http://ws.mkyong.com/", "HelloWorldService");

    private HelloWorld_HelloWorldPort_Client() {
    }

    public static void main(String args[]) throws java.lang.Exception {
        URL wsdlURL = HelloWorldService.WSDL_LOCATION;
        if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
            File wsdlFile = new File(args[0]);
            try {
                if (wsdlFile.exists()) {
                    wsdlURL = wsdlFile.toURI().toURL();
                } else {
                    wsdlURL = new URL(args[0]);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
     
        HelloWorldService ss = new HelloWorldService(wsdlURL, SERVICE_NAME);
        HelloWorld port = ss.getHelloWorldPort();
       
        {
        System.out.println("Invoking getHelloWorld...");
        java.lang.String _getHelloWorld_arg0 = "John";
        java.lang.String _getHelloWorld__return = port.getHelloWorld(_getHelloWorld_arg0);
        System.out.println("getHelloWorld.result=" + _getHelloWorld__return);


        }

        System.exit(0);
    }

}

=-==================================================================

output will be as below
=-==================================================================

Invoking getHelloWorld...
getHelloWorld.result=Hello World JAX-WS John

=-==================================================================