Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Christian Rädel 2016-09-25 10:01:57 +02:00
commit f423da51f9
110 changed files with 1909 additions and 1004 deletions
core-java-9/src/test/java/com/baeldung/java9
core-java/src/test/java/org/baeldung/java/collections
feign-client
README.mdpom.xml
src
main
test/java/com/baeldung/feign/clients
flyway-migration
log4j
pom.xml
src/main/java/com/baeldung/slf4j
pom.xml
selenium-junit-testng
pom.xml
src
main/java/com/baeldung/selenium
test/java/com/baeldung/selenium
test/com
baeldun/selenium/testng
baeldung/selenium/junit
spring-cloud-config
client-config
docker
spring-cloud-config-client
pom.xml
src/main
java/com/baeldung/spring/cloud/config/client
resources
spring-cloud-config-server
spring-cloud-eureka
pom.xml
spring-cloud-eureka-client/src/main
java/com/baeldung/spring/cloud/eureka/client
resources
spring-cloud-eureka-feign-client
pom.xml
src/main
java/com/baeldung/spring/cloud/feign/client
resources
spring-cloud-eureka-server/src/main/resources
spring-cloud-hystrix
pom.xml
spring-cloud-hystrix-feign-rest-consumer
pom.xml
src/main
java/com/baeldung/spring/cloud/hystrix/rest/consumer
resources
spring-cloud-hystrix-rest-consumer
pom.xml
src/main
java/com/baeldung/spring/cloud/hystrix/rest/consumer
resources
spring-cloud-hystrix-rest-producer
pom.xml
src/main
java/com/baeldung/spring/cloud/hystrix/rest/producer
resources
spring-cloud
pom.xml
spring-cloud-integration
part-1
application-config
config
pom.xml
src/main
java/com/baeldung/spring/cloud/integration/config
resources
discovery
pom.xml
src/main
java/com/baeldung/spring/cloud/integration/discovery
resources
gateway
pom.xml
src/main
java/com/baeldung/spring/cloud/integration/resource
resources
pom.xml
resource
pom.xml
src/main
java/com/baeldung/spring/cloud/integration/resource
resources
pom.xml
spring-data-elasticsearch
pom.xml
src
main/java/com/baeldung/elasticsearch
test/java/com/baeldung/elasticsearch
spring-data-rest
spring-rest
pom.xml
src
main/java/org/baeldung/web/controller/status
test/java/org/baeldung/web/test
spring-security-rest-full/src/test/java/org/baeldung/security/csrf
spring-thymeleaf
pom.xml
src
main
java/com/baeldung/thymeleaf/config
webapp/WEB-INF/views
test/java/org/baeldung/security/csrf
wicket

@ -0,0 +1,58 @@
package com.baeldung.java8;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
public class Java9OptionalsStreamTest {
private static List<Optional<String>> listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));
@Test
public void filterOutPresentOptionalsWithFilter() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
@Test
public void filterOutPresentOptionalsWithFlatMap() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream()
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
.collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
@Test
public void filterOutPresentOptionalsWithJava9() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
}

@ -18,18 +18,18 @@ public class ArrayListTest {
@Before
public void setUp() {
List<String> xs = LongStream.range(0, 16)
List<String> list = LongStream.range(0, 16)
.boxed()
.map(Long::toHexString)
.collect(toCollection(ArrayList::new));
stringsToSearch = new ArrayList<>(xs);
stringsToSearch.addAll(xs);
stringsToSearch = new ArrayList<>(list);
stringsToSearch.addAll(list);
}
@Test
public void givenNewArrayList_whenCheckCapacity_thenDefaultValue() {
List<String> xs = new ArrayList<>();
assertTrue(xs.isEmpty());
List<String> list = new ArrayList<>();
assertTrue(list.isEmpty());
}
@Test
@ -37,29 +37,29 @@ public class ArrayListTest {
Collection<Integer> numbers =
IntStream.range(0, 10).boxed().collect(toSet());
List<Integer> xs = new ArrayList<>(numbers);
assertEquals(10, xs.size());
assertTrue(numbers.containsAll(xs));
List<Integer> list = new ArrayList<>(numbers);
assertEquals(10, list.size());
assertTrue(numbers.containsAll(list));
}
@Test
public void givenElement_whenAddToArrayList_thenIsAdded() {
List<Long> xs = new ArrayList<>();
List<Long> list = new ArrayList<>();
xs.add(1L);
xs.add(2L);
xs.add(1, 3L);
list.add(1L);
list.add(2L);
list.add(1, 3L);
assertThat(Arrays.asList(1L, 3L, 2L), equalTo(xs));
assertThat(Arrays.asList(1L, 3L, 2L), equalTo(list));
}
@Test
public void givenCollection_whenAddToArrayList_thenIsAdded() {
List<Long> xs = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
LongStream.range(4, 10).boxed()
.collect(collectingAndThen(toCollection(ArrayList::new), ys -> xs.addAll(0, ys)));
.collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys)));
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(xs));
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list));
}
@Test
@ -106,27 +106,27 @@ public class ArrayListTest {
@Test
public void givenIndex_whenRemove_thenCorrectElementRemoved() {
List<Integer> xs = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
Collections.reverse(xs);
List<Integer> list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
Collections.reverse(list);
xs.remove(0);
assertThat(xs.get(0), equalTo(8));
list.remove(0);
assertThat(list.get(0), equalTo(8));
xs.remove(Integer.valueOf(0));
assertFalse(xs.contains(0));
list.remove(Integer.valueOf(0));
assertFalse(list.contains(0));
}
@Test
public void givenListIterator_whenReverseTraversal_thenRetrieveElementsInOppositeOrder() {
List<Integer> xs = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
ListIterator<Integer> it = xs.listIterator(xs.size());
List<Integer> result = new ArrayList<>(xs.size());
List<Integer> list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
ListIterator<Integer> it = list.listIterator(list.size());
List<Integer> result = new ArrayList<>(list.size());
while (it.hasPrevious()) {
result.add(it.previous());
}
Collections.reverse(xs);
assertThat(result, equalTo(xs));
Collections.reverse(list);
assertThat(result, equalTo(list));
}
@Test

5
feign-client/README.md Normal file

@ -0,0 +1,5 @@
## Feign Hypermedia Client ##
This is the implementation of a [spring-hypermedia-api][1] client using Feign.
[1]: https://github.com/eugenp/spring-hypermedia-api

99
feign-client/pom.xml Normal file

@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>com.baeldung.feign</groupId>
<artifactId>feign-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>9.3.1</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>9.3.1</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
<version>9.3.1</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
<version>9.3.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.0.RELEASE</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

@ -0,0 +1,26 @@
package com.baeldung.feign;
import com.baeldung.feign.clients.BookClient;
import feign.Feign;
import feign.Logger;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import feign.okhttp.OkHttpClient;
import feign.slf4j.Slf4jLogger;
import lombok.Getter;
@Getter
public class BookControllerFeignClientBuilder {
private BookClient bookClient = createClient(BookClient.class,
"http://localhost:8081/api/books");
private static <T> T createClient(Class<T> type, String uri) {
return Feign.builder()
.client(new OkHttpClient())
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger(type))
.logLevel(Logger.Level.FULL)
.target(type, uri);
}
}

@ -0,0 +1,21 @@
package com.baeldung.feign.clients;
import com.baeldung.feign.models.Book;
import com.baeldung.feign.models.BookResource;
import feign.Headers;
import feign.Param;
import feign.RequestLine;
import java.util.List;
public interface BookClient {
@RequestLine("GET /{isbn}")
BookResource findByIsbn(@Param("isbn") String isbn);
@RequestLine("GET")
List<BookResource> findAll();
@RequestLine("POST")
@Headers("Content-Type: application/json")
void create(Book book);
}

@ -0,0 +1,18 @@
package com.baeldung.feign.models;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Book {
private String isbn;
private String author;
private String title;
private String synopsis;
private String language;
}

@ -0,0 +1,14 @@
package com.baeldung.feign.models;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class BookResource {
private Book book;
}

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}:%n[+] %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

@ -0,0 +1,58 @@
package com.baeldung.feign.clients;
import com.baeldung.feign.BookControllerFeignClientBuilder;
import com.baeldung.feign.models.Book;
import com.baeldung.feign.models.BookResource;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@Slf4j
@RunWith(JUnit4.class)
public class BookClientTest {
private BookClient bookClient;
@Before
public void setup() {
BookControllerFeignClientBuilder feignClientBuilder = new BookControllerFeignClientBuilder();
bookClient = feignClientBuilder.getBookClient();
}
@Test
public void givenBookClient_shouldRunSuccessfully() throws Exception {
List<Book> books = bookClient.findAll().stream()
.map(BookResource::getBook)
.collect(Collectors.toList());
assertTrue(books.size() > 2);
log.info("{}", books);
}
@Test
public void givenBookClient_shouldFindOneBook() throws Exception {
Book book = bookClient.findByIsbn("0151072558").getBook();
assertThat(book.getAuthor(), containsString("Orwell"));
log.info("{}", book);
}
@Test
public void givenBookClient_shouldPostBook() throws Exception {
String isbn = UUID.randomUUID().toString();
Book book = new Book(isbn, "Me", "It's me!", null, null);
bookClient.create(book);
book = bookClient.findByIsbn(isbn).getBook();
assertThat(book.getAuthor(), is("Me"));
log.info("{}", book);
}
}

@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS `department` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(20)
)ENGINE=InnoDB DEFAULT CHARSET=UTF8;
ALTER TABLE `employee` ADD `dept_id` int AFTER `email`;

@ -23,6 +23,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>

@ -15,7 +15,13 @@
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- SLF4J - Log4J dependency
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
-->
<!--log4j2 dependencies-->
<dependency>
@ -28,22 +34,34 @@
<artifactId>log4j-core</artifactId>
<version>2.6</version>
</dependency>
<!--disruptor for log4j2 async logging-->
<!--disruptor for log4j2 async logging-->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.4</version>
</dependency>
<!-- SLF4J - Log4J2 dependency
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.6.2</version>
</dependency>
-->
<!--logback dependencies-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<!-- SLF4J - JCL dependency
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jcl</artifactId>
<version>1.7.21</version>
</dependency>
-->
</dependencies>
<build>
<plugins>

@ -0,0 +1,20 @@
package com.baeldung.slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* To switch between logging frameworks you need only to uncomment needed framework dependencies in pom.xml
*/
public class Slf4jExample {
private static Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
public static void main(String[] args) {
logger.debug("Debug log message");
logger.info("Info log message");
logger.error("Error log message");
String variable = "Hello John";
logger.debug("Printing variable value {} ", variable);
}
}

@ -31,6 +31,7 @@
<module>deltaspike</module>
<module>enterprise-patterns</module>
<module>feign-client</module>
<!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build -->
<module>gson</module>
@ -129,6 +130,7 @@
<module>lombok</module>
<module>redis</module>
<module>wicket</module>
<module>xstream</module>
<module>java-cassandra</module>
</modules>

@ -0,0 +1,36 @@
<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>com.baeldung</groupId>
<artifactId>selenium-junit-testng</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.10</version>
</dependency>
</dependencies>
</project>

@ -0,0 +1,29 @@
package main.java.com.baeldung.selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumExample {
private WebDriver webDriver;
private final String url = "http://www.baeldung.com/";
private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials";
public SeleniumExample() {
webDriver = new FirefoxDriver();
webDriver.get(url);
}
public void closeWindow() {
webDriver.close();
}
public String getActualTitle() {
return webDriver.getTitle();
}
public String getExpectedTitle() {
return expectedTitle;
}
}

@ -0,0 +1,30 @@
package test.java.com.baeldung.selenium.junit;
import static org.testng.Assert.assertEquals;
import main.java.com.baeldung.selenium.SeleniumExample;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestSeleniumWithJUnit {
private SeleniumExample seleniumExample;
@Before
public void setUp() {
seleniumExample = new SeleniumExample();
}
@After
public void tearDown() {
seleniumExample.closeWindow();
}
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
String expectedTitle = seleniumExample.getExpectedTitle();
String actualTitle = seleniumExample.getActualTitle();
assertEquals(actualTitle, expectedTitle);
}
}

@ -0,0 +1,30 @@
package test.java.com.baeldung.selenium.testng;
import static org.testng.Assert.assertEquals;
import main.java.com.baeldung.selenium.SeleniumExample;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class TestSeleniumWithTestNG {
private SeleniumExample seleniumExample;
@BeforeSuite
public void setUp() {
seleniumExample = new SeleniumExample();
}
@AfterSuite
public void tearDown() {
seleniumExample.closeWindow();
}
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
String expectedTitle = seleniumExample.getExpectedTitle();
String actualTitle = seleniumExample.getActualTitle();
assertEquals(actualTitle, expectedTitle);
}
}

@ -0,0 +1,34 @@
package com.baeldun.selenium.testng;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class TestSeleniumWithTestNG {
private WebDriver webDriver;
private final String url = "http://www.baeldung.com/";
private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials";
@BeforeSuite
public void setUp() {
webDriver = new FirefoxDriver();
webDriver.get(url);
}
@AfterSuite
public void tearDown() {
webDriver.close();
}
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
String actualTitleReturned = webDriver.getTitle();
assertNotNull(actualTitleReturned);
assertEquals(expectedTitle, actualTitleReturned);
}
}

@ -0,0 +1,34 @@
package com.baeldung.selenium.junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestSeleniumWithJUnit {
private WebDriver webDriver;
private final String url = "http://www.baeldung.com/";
private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials";
@Before
public void setUp() {
webDriver = new FirefoxDriver();
webDriver.get(url);
}
@After
public void tearDown() {
webDriver.close();
}
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
String actualTitleReturned = webDriver.getTitle();
assertNotNull(actualTitleReturned);
assertEquals(expectedTitle, actualTitleReturned);
}
}

@ -1,2 +0,0 @@
user.role=Developer
user.password=pass

@ -1,4 +0,0 @@
FROM alpine:edge
MAINTAINER baeldung.com
RUN apk add --no-cache openjdk8
COPY files/UnlimitedJCEPolicyJDK8/* /usr/lib/jvm/java-1.8-openjdk/jre/lib/security/

@ -1,41 +0,0 @@
version: '2'
services:
config-server:
build:
context: .
dockerfile: Dockerfile.server
image: config-server:latest
expose:
- 8888
networks:
- spring-cloud-network
volumes:
- spring-cloud-config-repo:/var/lib/spring-cloud/config-repo
logging:
driver: json-file
config-client:
build:
context: .
dockerfile: Dockerfile.client
image: config-client:latest
entrypoint: /opt/spring-cloud/bin/config-client-entrypoint.sh
environment:
SPRING_APPLICATION_JSON: '{"spring": {"cloud": {"config": {"uri": "http://config-server:8888"}}}}'
expose:
- 8080
ports:
- 8080
networks:
- spring-cloud-network
links:
- config-server:config-server
depends_on:
- config-server
logging:
driver: json-file
networks:
spring-cloud-network:
driver: bridge
volumes:
spring-cloud-config-repo:
external: true

@ -1,43 +0,0 @@
version: '2'
services:
config-server:
container_name: config-server
build:
context: .
dockerfile: Dockerfile.server
image: config-server:latest
expose:
- 8888
networks:
- spring-cloud-network
volumes:
- spring-cloud-config-repo:/var/lib/spring-cloud/config-repo
logging:
driver: json-file
config-client:
container_name: config-client
build:
context: .
dockerfile: Dockerfile.client
image: config-client:latest
entrypoint: /opt/spring-cloud/bin/config-client-entrypoint.sh
environment:
SPRING_APPLICATION_JSON: '{"spring": {"cloud": {"config": {"uri": "http://config-server:8888"}}}}'
expose:
- 8080
ports:
- 8080:8080
networks:
- spring-cloud-network
links:
- config-server:config-server
depends_on:
- config-server
logging:
driver: json-file
networks:
spring-cloud-network:
driver: bridge
volumes:
spring-cloud-config-repo:
external: true

@ -1,40 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-config</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>spring-cloud-config-client</artifactId>
<packaging>jar</packaging>
<name>spring-cloud-config-client</name>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
<version>1.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<outputDirectory>../docker/files</outputDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -1,29 +0,0 @@
package com.baeldung.spring.cloud.config.client;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class ConfigClient {
@Value("${user.role}")
private String role;
@Value("${user.password}")
private String password;
public static void main(String[] args) {
SpringApplication.run(ConfigClient.class, args);
}
@RequestMapping(value = "/whoami/{username}", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
public String whoami(@PathVariable("username") String username) {
return String.format("Hello %s! You are a(n) %s and your password is '%s'.\n", username, role, password);
}
}

@ -1,5 +0,0 @@
spring.application.name=config-client
spring.profiles.active=development
spring.cloud.config.uri=http://localhost:${PORT:8888}
spring.cloud.config.username=root
spring.cloud.config.password=s3cr3t

@ -1,44 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-config</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>spring-cloud-config-server</artifactId>
<name>spring-cloud-config-server</name>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<version>1.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<outputDirectory>../docker/files</outputDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -1,10 +0,0 @@
server.port=${PORT:8888}
spring.cloud.config.server.git.uri=${CONFIG_REPO}
spring.cloud.config.server.git.clone-on-start=false
spring.cloud.config.fail-fast=true
security.user.name=root
security.user.password=s3cr3t
encrypt.key-store.location=classpath:/config-server.jks
encrypt.key-store.password=my-s70r3-s3cr3t
encrypt.key-store.alias=config-server-key
encrypt.key-store.secret=my-k34-s3cr3t

@ -1,50 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-eureka</artifactId>
<version>1.0.0-SNAPSHOT</version>
<modules>
<module>spring-cloud-eureka-server</module>
<module>spring-cloud-eureka-client</module>
<module>spring-cloud-eureka-feign-client</module>
</modules>
<packaging>pom</packaging>
<name>Spring Cloud Eureka</name>
<description>Spring Cloud Eureka Server and Sample Clients</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.0.RELEASE</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

@ -1,32 +0,0 @@
package com.baeldung.spring.cloud.eureka.client;
import com.netflix.discovery.EurekaClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
@RestController
public class EurekaClientApplication implements GreetingController {
@Autowired
@Lazy
private EurekaClient eurekaClient;
@Value("${spring.application.name}")
private String appName;
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
@Override
public String greeting() {
return String.format("Hello from '%s'!", eurekaClient.getApplication(appName).getName());
}
}

@ -1,8 +0,0 @@
package com.baeldung.spring.cloud.eureka.client;
import org.springframework.web.bind.annotation.RequestMapping;
public interface GreetingController {
@RequestMapping("/greeting")
String greeting();
}

@ -1,13 +0,0 @@
spring:
application:
name: spring-cloud-eureka-client
server:
port: 0
eureka:
client:
serviceUrl:
defaultZone: ${EUREKA_URI:http://localhost:8761/eureka}
instance:
preferIpAddress: true

@ -1,67 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>spring-cloud-eureka-feign-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring Cloud Eureka Feign Client</name>
<description>Spring Cloud Eureka - Sample Feign Client</description>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-eureka</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-eureka-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,29 +0,0 @@
package com.baeldung.spring.cloud.feign.client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@Controller
public class FeignClientApplication {
@Autowired
private GreetingClient greetingClient;
public static void main(String[] args) {
SpringApplication.run(FeignClientApplication.class, args);
}
@RequestMapping("/get-greeting")
public String greeting(Model model) {
model.addAttribute("greeting", greetingClient.greeting());
return "greeting-view";
}
}

@ -1,8 +0,0 @@
package com.baeldung.spring.cloud.feign.client;
import com.baeldung.spring.cloud.eureka.client.GreetingController;
import org.springframework.cloud.netflix.feign.FeignClient;
@FeignClient("spring-cloud-eureka-client")
public interface GreetingClient extends GreetingController {
}

@ -1,11 +0,0 @@
spring:
application:
name: spring-cloud-eureka-feign-client
server:
port: 8080
eureka:
client:
serviceUrl:
defaultZone: ${EUREKA_URI:http://localhost:8761/eureka}

@ -1,9 +0,0 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Greeting Page</title>
</head>
<body>
<h2 th:text="${greeting}"/>
</body>
</html>

@ -1,7 +0,0 @@
server:
port: 8761
eureka:
client:
registerWithEureka: false
fetchRegistry: false

@ -1,50 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-hystrix</artifactId>
<version>1.0.0-SNAPSHOT</version>
<modules>
<module>spring-cloud-hystrix-rest-producer</module>
<module>spring-cloud-hystrix-rest-consumer</module>
<module>spring-cloud-hystrix-feign-rest-consumer</module>
</modules>
<packaging>pom</packaging>
<name>Spring Cloud Hystrix</name>
<description>Spring Cloud Hystrix Demo</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.0.RELEASE</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

@ -1,82 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>spring-cloud-hystrix-feign-rest-consumer</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring Cloud Hystrix Feign REST Consumer</name>
<description>Spring Cloud Hystrix Feign Sample Implementation</description>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-hystrix</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-hystrix-rest-producer</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,21 +0,0 @@
package com.baeldung.spring.cloud.hystrix.rest.consumer;
import com.baeldung.spring.cloud.hystrix.rest.producer.GreetingController;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(
name = "rest-producer",
url = "http://localhost:9090",
fallback = GreetingClient.GreetingClientFallback.class
)
public interface GreetingClient extends GreetingController {
@Component
public static class GreetingClientFallback implements GreetingClient {
@Override
public String greeting(@PathVariable("username") String username) {
return "Hello User!";
}
}
}

@ -1,32 +0,0 @@
package com.baeldung.spring.cloud.hystrix.rest.consumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@SpringBootApplication
@EnableCircuitBreaker
@EnableHystrixDashboard
@EnableFeignClients
@Controller
public class RestConsumerFeignApplication {
@Autowired
private GreetingClient greetingClient;
public static void main(String[] args) {
SpringApplication.run(RestConsumerFeignApplication.class, args);
}
@RequestMapping("/get-greeting/{username}")
public String getGreeting(Model model, @PathVariable("username") String username) {
model.addAttribute("greeting", greetingClient.greeting(username));
return "greeting-view";
}
}

@ -1,9 +0,0 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Greetings from Hystrix</title>
</head>
<body>
<h2 th:text="${greeting}"/>
</body>
</html>

@ -1,72 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>spring-cloud-hystrix-rest-consumer</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring Cloud Hystrix REST Consumer</name>
<description>Spring Cloud Hystrix Sample Implementation</description>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-hystrix</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,18 +0,0 @@
package com.baeldung.spring.cloud.hystrix.rest.consumer;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class GreetingService {
@HystrixCommand(fallbackMethod = "defaultGreeting")
public String getGreeting(String username) {
return new RestTemplate().getForObject("http://localhost:9090/greeting/{username}", String.class, username);
}
private String defaultGreeting(String username) {
return "Hello User!";
}
}

@ -1,31 +0,0 @@
package com.baeldung.spring.cloud.hystrix.rest.consumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@SpringBootApplication
@EnableCircuitBreaker
@EnableHystrixDashboard
@Controller
public class RestConsumerApplication {
@Autowired
private GreetingService greetingService;
public static void main(String[] args) {
SpringApplication.run(RestConsumerApplication.class, args);
}
@RequestMapping("/get-greeting/{username}")
public String getGreeting(Model model, @PathVariable("username") String username) {
model.addAttribute("greeting", greetingService.getGreeting(username));
return "greeting-view";
}
}

@ -1,9 +0,0 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Greetings from Hystrix</title>
</head>
<body>
<h2 th:text="${greeting}"/>
</body>
</html>

@ -1,40 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>spring-cloud-hystrix-rest-producer</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring Cloud Hystrix REST Producer</name>
<description>Spring Cloud Hystrix Sample REST Producer Implementation</description>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-hystrix</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,10 +0,0 @@
package com.baeldung.spring.cloud.hystrix.rest.producer;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
public interface GreetingController {
@RequestMapping("/greeting/{username}")
String greeting(@PathVariable("username") String username);
}

@ -1,20 +0,0 @@
package com.baeldung.spring.cloud.hystrix.rest.producer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class RestProducerApplication implements GreetingController {
public static void main(String[] args) {
SpringApplication.run(RestProducerApplication.class, args);
}
@Override
public String greeting(@PathVariable("username") String username) {
return String.format("Hello %s!\n", username);
}
}

@ -1,2 +0,0 @@
spring.application.name=rest-producer
server.port=9090

@ -10,6 +10,7 @@
<module>spring-cloud-config</module>
<module>spring-cloud-eureka</module>
<module>spring-cloud-hystrix</module>
<module>spring-cloud-integration</module>
</modules>
<packaging>pom</packaging>

@ -0,0 +1,8 @@
spring.application.name=discovery
server.port=8082
eureka.instance.hostname=localhost
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

@ -0,0 +1,10 @@
spring.application.name=gateway
server.port=8080
eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/
zuul.routes.resource.path=/resource/**
hystrix.command.resource.execution.isolation.thread.timeoutInMilliseconds: 5000

@ -0,0 +1,8 @@
spring.application.name=resource
server.port=8083
resource.returnString=hello cloud
eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/

@ -0,0 +1,54 @@
<?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>config</artifactId>
<version>1.0.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.RELEASE</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>

@ -1,15 +1,15 @@
package com.baeldung.spring.cloud.config.server;
package com.baeldung.spring.cloud.integration.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableConfigServer
@EnableWebSecurity
public class ConfigServer {
@EnableEurekaClient
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServer.class, args);
SpringApplication.run(ConfigApplication.class, args);
}
}

@ -0,0 +1,8 @@
server.port=8081
spring.application.name=config
spring.cloud.config.server.git.uri=file:///${user.home}/application-config
eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka

@ -1,27 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
<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>spring-cloud-eureka-server</artifactId>
<artifactId>discovery</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring Cloud Eureka Server</name>
<description>Spring Cloud Eureka Server Demo</description>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-eureka</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
@ -29,8 +34,8 @@
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.SR4</version>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -39,14 +44,10 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
</project>

@ -1,4 +1,4 @@
package com.baeldung.spring.cloud.eureka.server;
package com.baeldung.spring.cloud.integration.discovery;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -6,8 +6,8 @@ import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public class DiscoveryApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
SpringApplication.run(DiscoveryApplication.class, args);
}
}

@ -0,0 +1,2 @@
spring.cloud.config.name=discovery
spring.cloud.config.uri=http://localhost:8081

@ -0,0 +1,57 @@
<?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>gateway</artifactId>
<version>1.0.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.RELEASE</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,15 @@
package com.baeldung.spring.cloud.integration.resource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}

@ -0,0 +1,5 @@
spring.cloud.config.name=gateway
spring.cloud.config.discovery.service-id=config
spring.cloud.config.discovery.enabled=true
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/

@ -0,0 +1,25 @@
<?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>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-integration</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>config</module>
<module>discovery</module>
<module>gateway</module>
<module>resource</module>
</modules>
<artifactId>part-1</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
</project>

@ -1,32 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
<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>spring-cloud-eureka-client</artifactId>
<artifactId>resource</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring Cloud Eureka Client</name>
<description>Spring Cloud Eureka Sample Client</description>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-eureka</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
@ -34,8 +38,8 @@
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.SR4</version>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -44,14 +48,10 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
</project>

@ -0,0 +1,25 @@
package com.baeldung.spring.cloud.integration.resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
@RestController
public class ResourceApplication {
public static void main(String[] args) {
SpringApplication.run(ResourceApplication.class, args);
}
@Value("${resource.returnString}")
private String returnString;
@RequestMapping("/hello/cloud")
public String getString() {
return returnString;
}
}

@ -0,0 +1,5 @@
spring.cloud.config.name=resource
spring.cloud.config.discovery.service-id=config
spring.cloud.config.discovery.enabled=true
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/

@ -0,0 +1,15 @@
<?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>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-integration</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>part-1</module>
</modules>
</project>

@ -69,6 +69,17 @@
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
</dependencies>
<build>
<plugins>

@ -0,0 +1,52 @@
package com.baeldung.elasticsearch;
import java.util.Date;
public class Person {
private int age;
private String fullName;
private Date dateOfBirth;
public Person() {
}
public Person(int age, String fullName, Date dateOfBirth) {
super();
this.age = age;
this.fullName = fullName;
this.dateOfBirth = dateOfBirth;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
@Override
public String toString() {
return "Person [age=" + age + ", fullName=" + fullName + ", dateOfBirth=" + dateOfBirth + "]";
}
}

@ -0,0 +1,127 @@
package com.baeldung.elasticsearch;
import static org.elasticsearch.node.NodeBuilder.*;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.node.Node;
import org.elasticsearch.search.SearchHit;
import org.junit.Before;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
public class ElasticSearchUnitTests {
private List<Person> listOfPersons = new ArrayList<Person>();
String jsonString = null;
Client client = null;
@Before
public void setUp() {
Person person1 = new Person(10, "John Doe", new Date());
Person person2 = new Person(25, "Janette Doe", new Date());
listOfPersons.add(person1);
listOfPersons.add(person2);
jsonString = JSON.toJSONString(listOfPersons);
Node node = nodeBuilder().clusterName("elasticsearch").client(true).node();
client = node.client();
}
@Test
public void givenJsonString_whenJavaObject_thenIndexDocument() {
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
IndexResponse response = client.prepareIndex("people", "Doe")
.setSource(jsonObject).get();
String index = response.getIndex();
String type = response.getType();
assertTrue(response.isCreated());
assertEquals(index, "people");
assertEquals(type, "Doe");
}
@Test
public void givenDocumentId_whenJavaObject_thenDeleteDocument() {
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
IndexResponse response = client.prepareIndex("people", "Doe")
.setSource(jsonObject).get();
String id = response.getId();
DeleteResponse deleteResponse = client.prepareDelete("people", "Doe", id).get();
assertTrue(deleteResponse.isFound());
}
@Test
public void givenSearchRequest_whenMatchAll_thenReturnAllResults() {
SearchResponse response = client.prepareSearch().execute().actionGet();
SearchHit[] searchHits = response.getHits().getHits();
List<Person> results = new ArrayList<Person>();
for (SearchHit hit : searchHits) {
String sourceAsString = hit.getSourceAsString();
Person person = JSON.parseObject(sourceAsString, Person.class);
results.add(person);
}
}
@Test
public void givenSearchParamters_thenReturnResults() {
boolean isExecutedSuccessfully = true;
SearchResponse response = client.prepareSearch()
.setTypes()
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setPostFilter(QueryBuilders.rangeQuery("age").from(5).to(15))
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet();
SearchResponse response2 = client.prepareSearch()
.setTypes()
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette"))
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet();
SearchResponse response3 = client.prepareSearch()
.setTypes()
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setPostFilter(QueryBuilders.matchQuery("John", "Name*"))
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet();
try {
response2.getHits();
response3.getHits();
List<SearchHit> searchHits = Arrays.asList(response.getHits().getHits());
final List<Person> results = new ArrayList<Person>();
searchHits.forEach(hit -> results.add(JSON.parseObject(hit.getSourceAsString(), Person.class)));
} catch (Exception e) {
isExecutedSuccessfully = false;
}
assertTrue(isExecutedSuccessfully);
}
@Test
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("fullName", "Test")
.field("salary", "11500")
.field("age", "10")
.endObject();
IndexResponse response = client.prepareIndex("people", "Doe")
.setSource(builder).get();
assertTrue(response.isCreated());
}
}

@ -1,6 +1,6 @@
<?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">
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>com.baeldung</groupId>
@ -15,7 +15,7 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>

@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringDataRestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataRestApplication.class, args);
}
public static void main(String[] args) {
SpringApplication.run(SpringDataRestApplication.class, args);
}
}

@ -1,12 +0,0 @@
package com.baeldung;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.List;
@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends PagingAndSortingRepository<WebsiteUser, Long> {
List<WebsiteUser> findByName(@Param("name") String name);
}

@ -0,0 +1,30 @@
package com.baeldung.config;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.event.ValidatingRepositoryEventListener;
import org.springframework.validation.Validator;
@Configuration
public class ValidatorEventRegister implements InitializingBean {
@Autowired
ValidatingRepositoryEventListener validatingRepositoryEventListener;
@Autowired
private Map<String, Validator> validators;
@Override
public void afterPropertiesSet() throws Exception {
List<String> events = Arrays.asList("beforeCreate", "afterCreate", "beforeSave", "afterSave", "beforeLinkSave", "afterLinkSave", "beforeDelete", "afterDelete");
for (Map.Entry<String, Validator> entry : validators.entrySet()) {
events.stream().filter(p -> entry.getKey().startsWith(p)).findFirst().ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue()));
}
}
}

@ -0,0 +1,25 @@
package com.baeldung.exception.handlers;
import java.util.stream.Collectors;
import org.springframework.data.rest.core.RepositoryConstraintViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ RepositoryConstraintViolationException.class })
public ResponseEntity<Object> handleAccessDeniedException(Exception ex, WebRequest request) {
RepositoryConstraintViolationException nevEx = (RepositoryConstraintViolationException) ex;
String errors = nevEx.getErrors().getAllErrors().stream().map(p -> p.toString()).collect(Collectors.joining("\n"));
return new ResponseEntity<Object>(errors, new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE);
}
}

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;

@ -0,0 +1,11 @@
package com.baeldung.repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import com.baeldung.models.WebsiteUser;
@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends CrudRepository<WebsiteUser, Long> {
}

@ -0,0 +1,33 @@
package com.baeldung.validators;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.baeldung.models.WebsiteUser;
@Component("beforeCreateWebsiteUserValidator")
public class WebsiteUserValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return WebsiteUser.class.equals(clazz);
}
@Override
public void validate(Object obj, Errors errors) {
WebsiteUser user = (WebsiteUser) obj;
if (checkInputString(user.getName())) {
errors.rejectValue("name", "name.empty");
}
if (checkInputString(user.getEmail())) {
errors.rejectValue("email", "email.empty");
}
}
private boolean checkInputString(String input) {
return (input == null || input.trim().length() == 0);
}
}

@ -0,0 +1,100 @@
package com.baeldung.validator;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.SpringDataRestApplication;
import com.baeldung.models.WebsiteUser;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringDataRestApplication.class)
@WebAppConfiguration
public class SpringDataRestValidatorTest {
public static final String URL = "http://localhost";
private MockMvc mockMvc;
@Autowired
protected WebApplicationContext wac;
@Before
public void setup() {
mockMvc = webAppContextSetup(wac).build();
}
@Test
public void whenStartingApplication_thenCorrectStatusCode() throws Exception {
mockMvc.perform(get("/users")).andExpect(status().is2xxSuccessful());
};
@Test
public void whenAddingNewCorrectUser_thenCorrectStatusCodeAndResponse() throws Exception {
WebsiteUser user = new WebsiteUser();
user.setEmail("john.doe@john.com");
user.setName("John Doe");
mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user)))
.andExpect(status().is2xxSuccessful())
.andExpect(redirectedUrl("http://localhost/users/1"));
}
@Test
public void whenAddingNewUserWithoutName_thenErrorStatusCodeAndResponse() throws Exception {
WebsiteUser user = new WebsiteUser();
user.setEmail("john.doe@john.com");
mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user)))
.andExpect(status().isNotAcceptable())
.andExpect(redirectedUrl(null));
}
@Test
public void whenAddingNewUserWithEmptyName_thenErrorStatusCodeAndResponse() throws Exception {
WebsiteUser user = new WebsiteUser();
user.setEmail("john.doe@john.com");
user.setName("");
mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user)))
.andExpect(status().isNotAcceptable())
.andExpect(redirectedUrl(null));
}
@Test
public void whenAddingNewUserWithoutEmail_thenErrorStatusCodeAndResponse() throws Exception {
WebsiteUser user = new WebsiteUser();
user.setName("John Doe");
mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user)))
.andExpect(status().isNotAcceptable())
.andExpect(redirectedUrl(null));
}
@Test
public void whenAddingNewUserWithEmptyEmail_thenErrorStatusCodeAndResponse() throws Exception {
WebsiteUser user = new WebsiteUser();
user.setName("John Doe");
user.setEmail("");
mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user)))
.andExpect(status().isNotAcceptable())
.andExpect(redirectedUrl(null));
}
}

@ -182,7 +182,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
@ -192,16 +191,14 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<!-- <exclude>**/*ProductionTest.java</exclude> -->
<exclude>**/*LiveTest.java</exclude>
</excludes>
<systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
@ -216,7 +213,7 @@
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<containerId>tomcat8x</containerId>
<type>embedded</type>
<systemProperties>
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
@ -234,6 +231,61 @@
</build>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<executions>
<execution>
<id>start-server</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
<systemPropertyVariables>
<webTarget>cargo</webTarget>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- Spring -->
@ -266,7 +318,7 @@
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
<cargo-maven2-plugin.version>1.6.0</cargo-maven2-plugin.version>
</properties>

@ -5,5 +5,6 @@ import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.FORBIDDEN, reason="To show an example of a custom message")
public class ForbiddenException extends RuntimeException {
private static final long serialVersionUID = 6826605655586311552L;
}

@ -7,7 +7,7 @@ import org.junit.Test;
import com.jayway.restassured.RestAssured;
public class RequestMappingLiveTest {
private static String BASE_URI = "http://localhost:8080/spring-rest/ex/";
private static String BASE_URI = "http://localhost:8082/spring-rest/ex/";
@Test
public void givenSimplePath_whenGetFoos_thenOk() {

@ -21,9 +21,9 @@ import org.springframework.web.client.RestTemplate;
/**
* Integration Test class. Tests methods hits the server's rest services.
*/
public class SpringHttpMessageConvertersIntegrationTestsCase {
public class SpringHttpMessageConvertersLiveTest {
private static String BASE_URI = "http://localhost:8080/spring-rest/";
private static String BASE_URI = "http://localhost:8082/spring-rest/";
/**
* Without specifying Accept Header, uses the default response from the

@ -14,6 +14,7 @@ import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import com.fasterxml.jackson.core.JsonProcessingException;
@ -21,6 +22,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@Transactional
public class CsrfAbstractIntegrationTest {
@Autowired

@ -8,24 +8,24 @@
<properties>
<java-version>1.7</java-version>
<!-- spring -->
<org.springframework-version>4.1.8.RELEASE</org.springframework-version>
<org.springframework-version>4.3.3.RELEASE</org.springframework-version>
<javax.servlet-version>3.0.1</javax.servlet-version>
<!-- logging -->
<org.slf4j.version>1.7.12</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<org.slf4j.version>1.7.12</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<!-- thymeleaf -->
<org.thymeleaf-version>2.1.4.RELEASE</org.thymeleaf-version>
<!-- validation -->
<javax.validation-version>1.1.0.Final</javax.validation-version>
<org.hibernate-version>5.1.2.Final</org.hibernate-version>
<!-- Maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
@ -45,6 +45,17 @@
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<!-- Thymeleaf -->
<dependency>
<groupId>org.thymeleaf</groupId>
@ -57,29 +68,29 @@
<version>${org.thymeleaf-version}</version>
</dependency>
<!-- Logging -->
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
@ -98,6 +109,31 @@
<artifactId>hibernate-validator</artifactId>
<version>${org.hibernate-version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-test -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
@ -129,25 +165,25 @@
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
<systemProperties>
</systemProperties>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
<systemProperties>
</systemProperties>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,11 @@
package com.baeldung.thymeleaf.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class InitSecurity extends AbstractSecurityWebApplicationInitializer {
public InitSecurity() {
super(WebMVCSecurity.class);
}
}

@ -20,7 +20,7 @@ public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebMVCConfig.class };
return new Class<?>[] { WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class };
}
@Override

@ -1,6 +1,5 @@
package com.baeldung.thymeleaf.config;
import com.baeldung.thymeleaf.formatter.NameFormatter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@ -14,6 +13,8 @@ import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import com.baeldung.thymeleaf.formatter.NameFormatter;
@Configuration
@EnableWebMvc
@ComponentScan({ "com.baeldung.thymeleaf" })

@ -0,0 +1,49 @@
package com.baeldung.thymeleaf.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebMVCSecurity extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
public WebMVCSecurity() {
super();
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER");
}
@Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
;
}
}

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<form action="http://localhost:8080/spring-thymeleaf/saveStudent" method="post">
<input type="hidden" name="payload" value="CSRF attack!"/>
<input type="submit" />
</form>
</body>
</html>

@ -0,0 +1,63 @@
package org.baeldung.security.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.servlet.Filter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.thymeleaf.config.InitSecurity;
import com.baeldung.thymeleaf.config.WebApp;
import com.baeldung.thymeleaf.config.WebMVCConfig;
import com.baeldung.thymeleaf.config.WebMVCSecurity;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class })
public class CsrfEnabledIntegrationTest {
@Autowired
WebApplicationContext wac;
@Autowired
MockHttpSession session;
private MockMvc mockMvc;
@Autowired
private Filter springSecurityFilterChain;
protected RequestPostProcessor testUser() {
return user("user1").password("user1Pass").roles("USER");
}
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
}
@Test
public void addStudentWithoutCSRF() throws Exception {
mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser())).andExpect(status().isForbidden());
}
@Test
public void addStudentWithCSRF() throws Exception {
mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser()).with(csrf())).andExpect(status().isOk());
}
}

4
wicket/README.md Normal file

@ -0,0 +1,4 @@
From the same directory where pom.xml is, execute the following command to run the project:
mvn jetty:run

Some files were not shown because too many files have changed in this diff Show More