Merge remote-tracking branch 'origin/master'

This commit is contained in:
Alex Theedom 2017-01-24 09:59:27 +00:00
commit e02f7825a3
39 changed files with 635 additions and 333 deletions

View File

@ -0,0 +1,13 @@
package com.baeldung.intro;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.intro.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@RequestMapping("/")
public String root(){
return "Index Page";
}
@RequestMapping("/local")
public String local(){
return "/local";
}
}

View File

@ -0,0 +1,8 @@
<html>
<head>
<title>RESOURCE NOT FOUND</title>
</head>
<body>
<h1>404 RESOURCE NOT FOUND</h1>
</body>
</html>

View File

@ -0,0 +1,39 @@
package com.baeldung.intro;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class AppTest {
@Autowired
private MockMvc mvc;
@Test
public void getIndex() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Index Page")));
}
@Test
public void getLocal() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("/local")));
}
}

View File

@ -8,7 +8,8 @@
<version>1.0.0-SNAPSHOT</version>
<modules>
<module>spring-cloud-rest-server</module>
<module>spring-cloud-rest-client</module>
<module>spring-cloud-rest-client-1</module>
<module>spring-cloud-rest-client-2</module>
</modules>
<packaging>pom</packaging>

View File

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>spring-cloud-rest-client</artifactId>
<artifactId>spring-cloud-rest-client-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

View File

@ -0,0 +1,107 @@
<?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>org.baeldung</groupId>
<artifactId>spring-cloud-rest-client-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-cloud-rest</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<rest-assured.version>3.0.1</rest-assured.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR4</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>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,8 @@
package org.baeldung;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
@EnableRedisHttpSession
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
}

View File

@ -0,0 +1,14 @@
package org.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class SpringCloudRestClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudRestClientApplication.class, args);
}
}

View File

@ -0,0 +1,13 @@
package org.baeldung.persistence.dao;
import org.baeldung.persistence.model.BookReview;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(collectionResourceRel = "reviews", path = "reviews")
public interface BookReviewRepository extends CrudRepository<BookReview, Long> {
Page<BookReview> findByBookId(@Param("bookId") long bookId, Pageable pageable);
}

View File

@ -0,0 +1,128 @@
package org.baeldung.persistence.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class BookReview {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String content;
private int rating;
@Column(nullable = false)
private Long bookId;
//
public BookReview() {
super();
}
public BookReview(String content, int rating, long bookId) {
super();
this.content = content;
this.rating = rating;
this.bookId = bookId;
}
//
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public Long getBookId() {
return bookId;
}
public void setBookId(Long bookId) {
this.bookId = bookId;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + (int) (bookId ^ (bookId >>> 32));
result = (prime * result) + ((content == null) ? 0 : content.hashCode());
result = (prime * result) + (int) (id ^ (id >>> 32));
result = (prime * result) + rating;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final BookReview other = (BookReview) obj;
if (bookId != other.bookId) {
return false;
}
if (content == null) {
if (other.content != null) {
return false;
}
} else if (!content.equals(other.content)) {
return false;
}
if (id != other.id) {
return false;
}
if (rating != other.rating) {
return false;
}
return true;
}
//
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("BookReview [id=")
.append(id)
.append(", content=")
.append(content)
.append(", rating=")
.append(rating)
.append(", bookId=")
.append(bookId)
.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,19 @@
#### cloud
spring.application.name=spring-cloud-eureka-client
server.port=0
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://system:systemPass@localhost:8761/eureka}
eureka.instance.preferIpAddress=true
#### persistence
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:cloud_rest;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
#### security
security.basic.enabled=true
security.basic.path=/**
security.user.name=user
security.user.password=userPass
security.user.role=USER
security.sessions=always

View File

@ -0,0 +1,162 @@
package org.baeldung;
import static io.restassured.RestAssured.preemptive;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang3.RandomStringUtils.randomNumeric;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.baeldung.persistence.model.BookReview;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SpringCloudRestClientApplication.class }, webEnvironment = WebEnvironment.DEFINED_PORT)
public class RestApiLiveTest {
private static final String API_URI = "http://localhost:8084/reviews";
@Before
public void setUp() {
RestAssured.authentication = preemptive().basic("user", "userPass");
}
// GET
@Test
public void whenGetAllReviews_thenOK() {
final Response response = RestAssured.get(API_URI);
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
}
@Test
public void whenGetCreatedReviewById_thenOK() {
final BookReview review = createRandomReview();
final String location = createReviewAsUri(review);
final Response response = RestAssured.get(location);
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
assertEquals(review.getContent(), response.jsonPath()
.get("content"));
}
@Test
public void whenGetCreatedReviewByName_thenOK() {
final BookReview review = createRandomReview();
createReviewAsUri(review);
final Response response = RestAssured.get(API_URI + "/search/findByBookId?bookId=" + review.getBookId());
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
assertTrue(response.jsonPath()
.getLong("page.totalElements") > 0);
}
@Test
public void whenGetNotExistReviewById_thenNotFound() {
final Response response = RestAssured.get(API_URI + "/" + randomNumeric(4));
assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode());
}
@Test
public void whenGetNotExistReviewByName_thenNotFound() {
final Response response = RestAssured.get(API_URI + "/search/findByBookId?bookId=" + randomNumeric(4));
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
assertTrue(response.jsonPath()
.getLong("page.totalElements") == 0);
}
// POST
@Test
public void whenCreateNewReview_thenCreated() {
final BookReview review = createRandomReview();
final Response response = RestAssured.given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(review)
.post(API_URI);
assertEquals(HttpStatus.CREATED.value(), response.getStatusCode());
}
@Test
public void whenInvalidReview_thenError() {
final BookReview review = createRandomReview();
review.setBookId(null);
final Response response = RestAssured.given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(review)
.post(API_URI);
assertEquals(HttpStatus.CONFLICT.value(), response.getStatusCode());
}
@Test
public void whenUpdateCreatedReview_thenUpdated() {
// create
final BookReview review = createRandomReview();
final String location = createReviewAsUri(review);
// update
review.setRating(4);
Response response = RestAssured.given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(review)
.put(location);
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
// check if changes saved
response = RestAssured.get(location);
assertEquals(HttpStatus.OK.value(), response.getStatusCode());
assertEquals(4, response.jsonPath()
.getInt("rating"));
}
@Test
public void whenDeleteCreatedReview_thenOk() {
// create
final BookReview review = createRandomReview();
final String location = createReviewAsUri(review);
// delete
Response response = RestAssured.delete(location);
assertEquals(HttpStatus.NO_CONTENT.value(), response.getStatusCode());
// confirm it was deleted
response = RestAssured.get(location);
assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode());
}
@Test
public void whenDeleteNotExistReview_thenError() {
final Response response = RestAssured.delete(API_URI + "/" + randomNumeric(4));
assertEquals(HttpStatus.NOT_FOUND.value(), response.getStatusCode());
}
// =============================== Util
private BookReview createRandomReview() {
final BookReview review = new BookReview();
review.setContent(randomAlphabetic(10));
review.setRating(3);
review.setBookId(1L);
return review;
}
private String createReviewAsUri(BookReview review) {
final Response response = RestAssured.given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(review)
.post(API_URI);
return response.jsonPath()
.get("_links.self.href");
}
}

View File

@ -0,0 +1,16 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringCloudRestClientApplicationTests {
@Test
public void contextLoads() {
}
}

View File

@ -0,0 +1,19 @@
#### cloud
spring.application.name=spring-cloud-eureka-client
server.port=8084
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://system:systemPass@localhost:8761/eureka}
eureka.instance.preferIpAddress=true
#### persistence
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:cloud_rest;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
#### security
security.basic.enabled=true
security.basic.path=/**
security.user.name=user
security.user.password=userPass
security.user.role=USER
security.sessions=always

View File

@ -3,65 +3,24 @@
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
</parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-remoting</artifactId>
<version>1.0-SNAPSHOT</version>
<description>Parent for all projects related to Spring Remoting.</description>
<packaging>pom</packaging>
<properties>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-war-plugin.version>3.0.0</maven-war-plugin.version>
<servlet.version>3.1.0</servlet.version>
<logback.version>1.1.8</logback.version>
<spring.version>4.3.5.RELEASE</spring.version>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- logback -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!-- companion modules -->
<dependency>
<groupId>${project.groupId}</groupId>
@ -73,35 +32,6 @@
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<debug>true</debug>
<optimize>true</optimize>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<showDeprecation>true</showDeprecation>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
<!-- This special setup for maven-war-plugin is needed to use Servlet 3 annotation based configuration, where a WEB-INF/web.xml is not strictl needed. -->
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<modules>
<module>remoting-http</module>
</modules>

View File

@ -1,26 +0,0 @@
package com.baeldung.api;
import java.io.Serializable;
public class Address implements Serializable{
private String address;
private String countryCode;
public Address(String address, String countryCode) {
this.address = address;
this.countryCode = countryCode;
}
public String getAddress() {
return address;
}
public String getCountryCode() {
return countryCode;
}
@Override public String toString() {
return address + " (" + countryCode + ")";
}
}

View File

@ -1,52 +1,17 @@
package com.baeldung.api;
import java.io.Serializable;
import java.time.LocalDateTime;
import static java.lang.String.format;
public class Booking implements Serializable {
private int costInCent;
private int etaInSeconds;
private String bookingCode;
private LocalDateTime pickUptime;
private Address pickUpAddress;
private Address dropOffAddress;
public Booking(Address pickUpAddress, LocalDateTime pickUptime, Address dropOffAddress, int costInCent, int etaInSeconds, String bookingCode) {
this.costInCent = costInCent;
this.etaInSeconds = etaInSeconds;
this.bookingCode = bookingCode;
this.pickUptime = pickUptime;
this.pickUpAddress = pickUpAddress;
this.dropOffAddress = dropOffAddress;
}
public int getCostInCent() {
return costInCent;
}
public int getEtaInSeconds() {
return etaInSeconds;
}
public String getBookingCode() {
return bookingCode;
}
public LocalDateTime getPickUptime() {
return pickUptime;
}
public Address getDropOffAddress() {
return dropOffAddress;
}
@Override public String toString() {
return String.format("Booking: pick up @ %tr in %s, drop down in %s after %d minutes, %.2f $.", pickUptime, pickUpAddress, dropOffAddress, etaInSeconds / 60, costInCent / 100.0);
return format("Ride confirmed: code '%s'.", bookingCode);
}
public static void main(String[] args) throws InterruptedException {
System.out.println(new Booking(new Address("a", "b"),
LocalDateTime.now(), new Address("c", "d"), 123_00, 600, "abc"));
public Booking(String bookingCode) {
this.bookingCode = bookingCode;
}
}

View File

@ -1,5 +1,5 @@
package com.baeldung.api;
public interface CabBookingService {
Booking bookPickUp(Address pickUpLocation, Address dropOffLocation, int pax) throws BookingException;
Booking bookRide(String pickUpLocation) throws BookingException;
}

View File

@ -9,22 +9,22 @@
<artifactId>spring-remoting-http</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>spring-remoting-http-client</artifactId>
<description>Shows how to invoke a remote service using Spring Remoting.</description>
<description>Shows how to invoke a remote service using Spring Remoting HTTP.</description>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- companion modules -->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>api</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -1,21 +0,0 @@
package com.baeldug.client;
import com.baeldung.api.*;
public class CabBookingClient {
private CabBookingService cabService;
public CabBookingClient(CabBookingService cabService) {
this.cabService = cabService;
}
public void run() throws BookingException {
Address pickUp = new Address("13 Seagate Blvd, Key Largo, FL 33037", "US");
Address dropDown = new Address("91831 Overseas Hwy, Tavernier, FL 33070", "US");
System.out.println( cabService.bookPickUp(pickUp, dropDown, 3) );
}
}

View File

@ -0,0 +1,28 @@
package com.baeldug.client;
import com.baeldung.api.BookingException;
import com.baeldung.api.CabBookingService;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean;
import static java.lang.System.out;
@Configuration
public class Client {
@Bean
public HttpInvokerProxyFactoryBean invoker() {
HttpInvokerProxyFactoryBean invoker = new HttpInvokerProxyFactoryBean();
invoker.setServiceUrl("http://localhost:8080/booking");
invoker.setServiceInterface(CabBookingService.class);
return invoker;
}
public static void main(String[] args) throws BookingException {
CabBookingService service = SpringApplication.run(Client.class, args).getBean(CabBookingService.class);
out.println(service.bookRide("13 Seagate Blvd, Key Largo, FL 33037"));
}
}

View File

@ -1,34 +0,0 @@
package com.baeldug.client;
import com.baeldung.api.CabBookingService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean;
@Configuration
public class Main {
@Bean
public HttpInvokerProxyFactoryBean invoker() {
HttpInvokerProxyFactoryBean invoker = new HttpInvokerProxyFactoryBean();
invoker.setServiceUrl("http://localhost:9090/spring-remoting-http-server/booking");
invoker.setServiceInterface(CabBookingService.class);
return invoker;
}
@Bean
public CabBookingClient client(CabBookingService service){
return new CabBookingClient(service);
}
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext rootContext =
new AnnotationConfigApplicationContext();
rootContext.scan(Main.class.getPackage().getName());
rootContext.refresh();
CabBookingClient bean = rootContext.getBean(CabBookingClient.class);
bean.run();
}
}

View File

@ -9,9 +9,8 @@
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>spring-remoting-http</artifactId>
<description>Parent for all modules related to HTTP Spring Remoting</description>
<description>Parent for all modules related to HTTP Spring Remoting.</description>
<packaging>pom</packaging>
<modules>
<module>server</module>
<module>client</module>

View File

@ -8,58 +8,16 @@
<artifactId>spring-remoting-http</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<packaging>war</packaging>
<artifactId>spring-remoting-http-server</artifactId>
<description>Shows how to expose a service using Spring Remoting</description>
<properties>
<tomcat7-maven-plugin.version>2.2</tomcat7-maven-plugin.version>
</properties>
<description>Shows how to expose a service using Spring Remoting HTTP.</description>
<dependencies>
<!-- spring -->
<!-- spring-webmvc is mainly needed to have access to the Spring's DispatcherServler -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- companion modules -->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>api</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>${tomcat7-maven-plugin.version}</version>
<configuration>
<port>9090</port>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,10 +0,0 @@
package com.baeldung.server;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CabBookingConfig {
}

View File

@ -1,34 +0,0 @@
package com.baeldung.server;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
public class CabBookingInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.register(CabBookingConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext =
new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
}

View File

@ -1,27 +1,16 @@
package com.baeldung.server;
import com.baeldung.api.Address;
import com.baeldung.api.Booking;
import com.baeldung.api.BookingException;
import com.baeldung.api.CabBookingService;
import java.time.LocalDateTime;
import static java.lang.Math.random;
import static java.time.LocalDateTime.now;
import static java.time.temporal.ChronoUnit.MINUTES;
import static java.util.UUID.randomUUID;
public class CabBookingServiceImpl implements CabBookingService {
@Override public Booking bookPickUp(Address pickUpLocation, Address dropOffLocation, int pax) throws BookingException {
if (random() < 0.3) {
throw new BookingException("Cab unavailable");
}
int tripTimeInMinutes = (int) (5 + random() * 15);
int costInCent = 15_00 + tripTimeInMinutes * 5 * pax;
LocalDateTime pickUpDate = now().plus(15L * (long) (random() * 10), MINUTES);
return new Booking(pickUpLocation, pickUpDate, dropOffLocation, costInCent, tripTimeInMinutes * 60, randomUUID().toString());
@Override public Booking bookRide(String pickUpLocation) throws BookingException {
if (random() < 0.3) throw new BookingException("Cab unavailable");
return new Booking(randomUUID().toString());
}
}

View File

@ -1,12 +1,17 @@
package com.baeldung.server;
import com.baeldung.api.CabBookingService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter;
@Configuration
public class DispatcherConfig {
@ComponentScan
@EnableAutoConfiguration
public class Server {
@Bean(name = "/booking") HttpInvokerServiceExporter accountService() {
HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
@ -15,4 +20,8 @@ public class DispatcherConfig {
return exporter;
}
}
public static void main(String[] args) {
SpringApplication.run(Server.class, args);
}
}

View File

@ -1,16 +0,0 @@
<configuration scan="true" scanPeriod="1 minute">
<variable
name="logPattern"
value="%-30(%d{MMM dd YYYY HH:mm:ss.SSS} [%thread]) %-5level %logger{5} [%file:%line] - %msg%n"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${logPattern}</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT"/>
</root>
</configuration>