2025-09 spring-32 http-client

This commit is contained in:
Vladimir Ivanov
2026-01-29 19:24:55 +03:00
parent 24a4d20487
commit 1e8923dbb1
28 changed files with 984 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.otus</groupId>
<artifactId>spring-32-http-client</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.2</version>
<relativePath/>
</parent>
<modules>
<module>rest-template</module>
<module>soap-client</module>
<module>soap-server</module>
</modules>
<properties>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<checkstyle-plugin.version>3.1.2</checkstyle-plugin.version>
<checkstyle.version>10.9.1</checkstyle.version>
<checkstyle.config.url>https://raw.githubusercontent.com/OtusTeam/Spring/master/checkstyle.xml
</checkstyle.config.url>
</properties>
</project>
@@ -0,0 +1,85 @@
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>rest-template</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>ru.otus</groupId>
<artifactId>spring-32-http-client</artifactId>
<version>1.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>
<!-- Cache-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Retry-->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2025.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,21 @@
package ru.otus.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.retry.annotation.EnableRetry;
import ru.otus.spring.config.ClientProperties;
@EnableCaching
@EnableRetry
@EnableFeignClients
@EnableConfigurationProperties(ClientProperties.class)
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
@@ -0,0 +1,15 @@
package ru.otus.spring.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("countries");
}
}
@@ -0,0 +1,12 @@
package ru.otus.spring.config;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
public class ClientConfiguration {
@Bean
public RequestInterceptor requestInterceptor(ClientProperties properties) {
return requestTemplate -> requestTemplate.query("access_key", properties.getKey());
}
}
@@ -0,0 +1,13 @@
package ru.otus.spring.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter
@Setter
@ConfigurationProperties(prefix = "client")
public class ClientProperties {
private String url;
private String key;
}
@@ -0,0 +1,19 @@
package ru.otus.spring.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@NoArgsConstructor
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class Country {
private String name;
// private String capital;
// private String region;
private String alpha3Code;
}
@@ -0,0 +1,12 @@
package ru.otus.spring.service;
import ru.otus.spring.dto.Country;
import java.util.List;
public interface CountryService {
Country findByCode(String id);
List<Country> getAll();
}
@@ -0,0 +1,25 @@
package ru.otus.spring.service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ru.otus.spring.config.ClientConfiguration;
import ru.otus.spring.dto.Country;
import java.util.List;
@FeignClient(value = "countrylayer", configuration = ClientConfiguration.class)
@Cacheable("countries")
@Retryable(retryFor = Exception.class, maxAttempts = 2, backoff = @Backoff(delay = 2000))
public interface FeignCountryService {
@RequestMapping(method = RequestMethod.GET, value = "/alpha/{code}", produces = "application/json")
Country findByCode(@PathVariable("code") String code);
@RequestMapping(method = RequestMethod.GET, value = "/all", produces = "application/json")
List<Country> getAll();
}
@@ -0,0 +1,29 @@
package ru.otus.spring.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;
import ru.otus.spring.dto.Country;
@Slf4j
@RequiredArgsConstructor
@Service
public class MainServiceImpl implements CommandLineRunner {
// private final TemplateCountryService countryService;
// private final WebCountryService countryService;
// private final RestCountryService countryService;
private final FeignCountryService countryService;
@Override
public void run(String... args) {
// List<Country> countries = countryService.getAll();
// log.info("Countries: {}", countries);
Country country = countryService.findByCode("col");
log.info("Find {}", country);
// country = countryService.findByCode("col");
// log.info("Find {}", country);
// country = countryService.findByCode("rus");
// log.info("Find {}", country);
}
}
@@ -0,0 +1,56 @@
package ru.otus.spring.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import ru.otus.spring.config.ClientProperties;
import ru.otus.spring.dto.Country;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class RestCountryService implements CountryService {
final ClientProperties properties;
final RestClient restClient;
public RestCountryService(ClientProperties properties) {
this.properties = properties;
this.restClient = RestClient.builder()
.requestFactory(new HttpComponentsClientHttpRequestFactory())
// .messageConverters(converters -> converters.add(new MyCustomMessageConverter()))
.baseUrl(properties.getUrl())
.defaultUriVariables(Map.of("key", properties.getKey()))
// .defaultHeader("Header", "")
// .requestInterceptor(myCustomInterceptor)
// .requestInitializer(myCustomInitializer)
.build();
}
@Override
public Country findByCode(String id) {
log.info("Rest client Request findByCode");
return restClient.get()
.uri(uriBuilder -> uriBuilder.path("/alpha/{id}")
.queryParam("access_key", properties.getKey())
.build(Map.of("id", id)))
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.body(Country.class);
}
@Override
public List<Country> getAll() {
log.info("Web client Request findByCode");
return restClient.get()
.uri("/all?access_key={key}")
.retrieve()
.body(new ParameterizedTypeReference<>() {
});
}
}
@@ -0,0 +1,48 @@
package ru.otus.spring.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import ru.otus.spring.config.ClientProperties;
import ru.otus.spring.dto.Country;
import java.net.URI;
import java.util.List;
@Slf4j
@RequiredArgsConstructor
@Service
public class TemplateCountryService implements CountryService {
final ClientProperties properties;
private final RestOperations rest = new RestTemplate();
@Override
public Country findByCode(String id) {
log.info("RestTemplate Request findByCode");
return rest.getForObject("http://api.countrylayer.com/v2/alpha/" + id + "?access_key=" + properties.getKey(),
Country.class);
}
@Override
public List<Country> getAll() {
log.info("RestTemplate Request getAll");
URI uri = UriComponentsBuilder.fromHttpUrl(properties.getUrl())
.path("/all")
.queryParam("access_key", properties.getKey())
.build().toUri();
RequestEntity<List<Country>> requestEntity = new RequestEntity<>(HttpMethod.GET,
uri);
// List<Country> countries = rest.getForObject(uri, List.class);
ResponseEntity<List<Country>> exchange = rest.exchange(requestEntity, new ParameterizedTypeReference<>() {
});
return exchange.getBody();
}
}
@@ -0,0 +1,66 @@
package ru.otus.spring.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import ru.otus.spring.config.ClientProperties;
import ru.otus.spring.dto.Country;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class WebCountryService implements CountryService {
final ClientProperties properties;
final WebClient webClient;
public WebCountryService(ClientProperties properties) {
this.properties = properties;
this.webClient = WebClient.builder()
.baseUrl(properties.getUrl())
.defaultUriVariables(Map.of("key", properties.getKey()))
.filter(errorHandler())
.build();
}
@Override
public Country findByCode(String id) {
log.info("Web client Request findByCode");
return webClient.get()
.uri("/alpha/{id}?access_key={key}", Map.of("id", id))
.retrieve()
.bodyToMono(Country.class)
.block();
}
@Override
public List<Country> getAll() {
log.info("Web client Request findByCode");
return webClient.get()
.uri("/all?access_key={key}")
.retrieve()
.bodyToMono(new ParameterizedTypeReference<List<Country>>() {
})
.block();
}
private static ExchangeFilterFunction errorHandler() {
return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
if (clientResponse.statusCode().is5xxServerError()) {
return clientResponse.bodyToMono(String.class)
.flatMap(errorBody -> Mono.error(new RuntimeException(errorBody)));
} else if (clientResponse.statusCode().is4xxClientError()) {
return clientResponse.bodyToMono(String.class)
.flatMap(errorBody -> Mono.error(new RuntimeException(errorBody)));
} else {
return Mono.just(clientResponse);
}
});
}
}
@@ -0,0 +1,19 @@
spring.main.web-application-type: none
spring:
cloud:
openfeign:
client:
config:
countrylayer:
url: http://api.countrylayer.com/v2
client:
url: http://api.countrylayer.com/v2
key: [ !!!Your key!!! ]
logging:
level:
org:
springframework:
web: debug
@@ -0,0 +1,67 @@
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>soap-client</artifactId>
<version>1.0</version>
<parent>
<groupId>ru.otus</groupId>
<artifactId>spring-32-http-client</artifactId>
<version>1.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</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>
<plugin>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
</execution>
</executions>
<configuration>
<packageName>hello.wsdl</packageName>
<wsdlUrls>
<wsdlUrl>src/main/resources/countries.wsdl</wsdlUrl>
<!-- <wsdlUrl>http://localhost:8080/ws/countries.wsdl</wsdlUrl>-->
</wsdlUrls>
<extension>true</extension>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,39 @@
package hello;
import hello.wsdl.Country;
import hello.wsdl.GetCountryResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@Slf4j
@SpringBootApplication
public class ClientApp {
public static void main(String[] args) {
SpringApplication.run(ClientApp.class, args);
}
@Bean
CommandLineRunner lookup(CountryClient quoteClient) {
return args -> {
String country = "Spain";
if (args.length > 0) {
country = args[0];
}
GetCountryResponse response = quoteClient.getCountry(country);
if (response.getCountry() != null) {
Country countryDetails = response.getCountry();
log.warn("GetCountry {} : Country[name={}, population={}, capital={}, currency={}]",
country, countryDetails.getName(), countryDetails.getPopulation(),
countryDetails.getCapital(), countryDetails.getCurrency());
} else {
log.warn("GetCountry {} : no country found in response", country);
}
};
}
}
@@ -0,0 +1,24 @@
package hello;
import hello.wsdl.GetCountryRequest;
import hello.wsdl.GetCountryResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
@Slf4j
public class CountryClient extends WebServiceGatewaySupport {
public GetCountryResponse getCountry(String country) {
GetCountryRequest request = new GetCountryRequest();
request.setName(country);
log.info("Requesting location for {}", country);
GetCountryResponse response = (GetCountryResponse) getWebServiceTemplate()
.marshalSendAndReceive("http://localhost:8080/ws", request);
return response;
}
}
@@ -0,0 +1,28 @@
package hello;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
@Configuration
public class CountryConfiguration {
@Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
// this package must match the package in the <generatePackage> specified in
// pom.xml
marshaller.setContextPath("hello.wsdl");
return marshaller;
}
@Bean
public CountryClient countryClient(Jaxb2Marshaller marshaller) {
CountryClient client = new CountryClient();
client.setDefaultUri("http://localhost:8080/ws");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
}
@@ -0,0 +1,6 @@
logging:
level:
hello: INFO
org:
springframework:
ws: DEBUG
@@ -0,0 +1,76 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://otus.ru/hello/web-service"
targetNamespace="http://otus.ru/hello/web-service">
<wsdl:types>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
targetNamespace="http://otus.ru/hello/web-service">
<xs:element name="getCountryRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="getCountryResponse">
<xs:complexType>
<xs:sequence>
<xs:element name="country" type="tns:country"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="country">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="population" type="xs:int"/>
<xs:element name="capital" type="xs:string"/>
<xs:element name="currency" type="tns:currency"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="currency">
<xs:restriction base="xs:string">
<xs:enumeration value="GBP"/>
<xs:enumeration value="EUR"/>
<xs:enumeration value="PLN"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
</wsdl:types>
<wsdl:message name="getCountryResponse">
<wsdl:part element="tns:getCountryResponse" name="getCountryResponse">
</wsdl:part>
</wsdl:message>
<wsdl:message name="getCountryRequest">
<wsdl:part element="tns:getCountryRequest" name="getCountryRequest">
</wsdl:part>
</wsdl:message>
<wsdl:portType name="CountriesPort">
<wsdl:operation name="getCountry">
<wsdl:input message="tns:getCountryRequest" name="getCountryRequest">
</wsdl:input>
<wsdl:output message="tns:getCountryResponse" name="getCountryResponse">
</wsdl:output>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="CountriesPortSoap11" type="tns:CountriesPort">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="getCountry">
<soap:operation soapAction=""/>
<wsdl:input name="getCountryRequest">
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output name="getCountryResponse">
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="CountriesPortService">
<wsdl:port binding="tns:CountriesPortSoap11" name="CountriesPortSoap11">
<soap:address location="http://localhost:8080/ws"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
@@ -0,0 +1,67 @@
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>soap-server</artifactId>
<version>1.0</version>
<parent>
<groupId>ru.otus</groupId>
<artifactId>spring-32-http-client</artifactId>
<version>1.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<sources>
<source>${project.basedir}/src/main/resources/countries.xsd</source>
</sources>
<packageName>ru.otus.hello.web_service</packageName>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,30 @@
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import ru.otus.hello.web_service.GetCountryRequest;
import ru.otus.hello.web_service.GetCountryResponse;
@Endpoint
public class CountryEndpoint {
private static final String NAMESPACE_URI = "http://otus.ru/hello/web-service";
private final CountryRepository countryRepository;
@Autowired
public CountryEndpoint(CountryRepository countryRepository) {
this.countryRepository = countryRepository;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCountryRequest")
@ResponsePayload
public GetCountryResponse getCountry(@RequestPayload GetCountryRequest request) {
GetCountryResponse response = new GetCountryResponse();
response.setCountry(countryRepository.findCountry(request.getName()));
return response;
}
}
@@ -0,0 +1,47 @@
package hello;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import ru.otus.hello.web_service.Country;
import ru.otus.hello.web_service.Currency;
import java.util.HashMap;
import java.util.Map;
@Component
public class CountryRepository {
private static final Map<String, Country> countries = new HashMap<>();
@PostConstruct
public void initData() {
Country spain = new Country();
spain.setName("Spain");
spain.setCapital("Madrid");
spain.setCurrency(Currency.EUR);
spain.setPopulation(46704314);
countries.put(spain.getName(), spain);
Country poland = new Country();
poland.setName("Poland");
poland.setCapital("Warsaw");
poland.setCurrency(Currency.PLN);
poland.setPopulation(38186860);
countries.put(poland.getName(), poland);
Country uk = new Country();
uk.setName("United Kingdom");
uk.setCapital("London");
uk.setCurrency(Currency.GBP);
uk.setPopulation(63705000);
countries.put(uk.getName(), uk);
}
public Country findCountry(String name) {
Assert.notNull(name, "The country's name must not be null");
return countries.get(name);
}
}
@@ -0,0 +1,12 @@
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ServerApp {
public static void main(String[] args) {
SpringApplication.run(ServerApp.class, args);
}
}
@@ -0,0 +1,40 @@
package hello;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurer;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
@EnableWs
@Configuration
public class WebServiceConfig implements WsConfigurer {
@Bean
public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean<>(servlet, "/ws/*");
}
@Bean(name = "countries")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("CountriesPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://otus.ru/hello/web-service");
wsdl11Definition.setSchema(countriesSchema);
return wsdl11Definition;
}
@Bean
public XsdSchema countriesSchema() {
return new SimpleXsdSchema(new ClassPathResource("countries.xsd"));
}
}
@@ -0,0 +1,3 @@
logging:
level:
root: debug
@@ -0,0 +1,36 @@
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://otus.ru/hello/web-service"
targetNamespace="http://otus.ru/hello/web-service" elementFormDefault="qualified">
<xs:element name="getCountryRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="getCountryResponse">
<xs:complexType>
<xs:sequence>
<xs:element name="country" type="tns:country"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="country">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="population" type="xs:int"/>
<xs:element name="capital" type="xs:string"/>
<xs:element name="currency" type="tns:currency"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="currency">
<xs:restriction base="xs:string">
<xs:enumeration value="GBP"/>
<xs:enumeration value="EUR"/>
<xs:enumeration value="PLN"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
@@ -0,0 +1,53 @@
/*
* Copyright 2014-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package hello;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.util.ClassUtils;
import org.springframework.ws.client.core.WebServiceTemplate;
import ru.otus.hello.web_service.GetCountryRequest;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ApplicationIntegrationTests {
private final Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
@LocalServerPort
private int port = 0;
@BeforeEach
public void init() throws Exception {
marshaller.setPackagesToScan(ClassUtils.getPackageName(GetCountryRequest.class));
marshaller.afterPropertiesSet();
}
@Test
public void testSendAndReceive() {
WebServiceTemplate ws = new WebServiceTemplate(marshaller);
GetCountryRequest request = new GetCountryRequest();
request.setName("Spain");
assertThat(ws.marshalSendAndReceive("http://localhost:" + port + "/ws", request)).isNotNull();
}
}