From 429bbbbaf14a8016c09f0fba0c8ff347e6270f26 Mon Sep 17 00:00:00 2001 From: db Date: Tue, 26 Jun 2018 01:41:28 +0100 Subject: [PATCH 01/38] Server Sent Events example using Spring Webflux and React --- .../sse/controller/EventController.java | 26 ++++++++++++ .../reactive/sse/model/EventSubscription.java | 22 ++++++++++ .../service/EventSubscriptionsService.java | 41 +++++++++++++++++++ .../service/emitter/DateEmitterService.java | 27 ++++++++++++ .../src/main/resources/static/app.js | 36 ++++++++++++++++ .../src/main/resources/static/sse-index.html | 19 +++++++++ .../reactive/sse/ServerSentEventsTest.java | 39 ++++++++++++++++++ 7 files changed, 210 insertions(+) create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/sse/controller/EventController.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/sse/model/EventSubscription.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/EventSubscriptionsService.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/emitter/DateEmitterService.java create mode 100644 spring-5-reactive/src/main/resources/static/app.js create mode 100644 spring-5-reactive/src/main/resources/static/sse-index.html create mode 100644 spring-5-reactive/src/test/java/com/baeldung/reactive/sse/ServerSentEventsTest.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/controller/EventController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/controller/EventController.java new file mode 100644 index 0000000000..e692aa3a74 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/controller/EventController.java @@ -0,0 +1,26 @@ +package com.baeldung.reactive.sse.controller; + + +import com.baeldung.reactive.sse.service.EventSubscriptionsService; +import org.springframework.http.MediaType; +import org.springframework.http.codec.ServerSentEvent; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Flux; + +@RestController +public class EventController { + + private EventSubscriptionsService eventSubscriptionsService; + + public EventController(EventSubscriptionsService eventSubscriptionsService) { + this.eventSubscriptionsService = eventSubscriptionsService; + } + + @GetMapping( + produces = MediaType.TEXT_EVENT_STREAM_VALUE, + value = "/sse/events") + public Flux events() { + return eventSubscriptionsService.subscribe(); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/model/EventSubscription.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/model/EventSubscription.java new file mode 100644 index 0000000000..4d3ce27156 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/model/EventSubscription.java @@ -0,0 +1,22 @@ +package com.baeldung.reactive.sse.model; + +import org.springframework.http.codec.ServerSentEvent; +import reactor.core.publisher.DirectProcessor; +import reactor.core.publisher.Flux; + +public class EventSubscription { + + private DirectProcessor directProcessor; + + public EventSubscription() { + this.directProcessor = DirectProcessor.create(); + } + + public void emit(ServerSentEvent e) { + directProcessor.onNext(e); + } + + public Flux subscribe() { + return directProcessor; + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/EventSubscriptionsService.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/EventSubscriptionsService.java new file mode 100644 index 0000000000..f245ce6184 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/EventSubscriptionsService.java @@ -0,0 +1,41 @@ +package com.baeldung.reactive.sse.service; + +import com.baeldung.reactive.sse.model.EventSubscription; +import org.springframework.http.codec.ServerSentEvent; +import org.springframework.stereotype.Service; +import reactor.core.publisher.Flux; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +@Service +public class EventSubscriptionsService { + + private List listeners; + + public EventSubscriptionsService() { + this.listeners = new ArrayList<>(); + } + + public Flux subscribe() { + EventSubscription e = new EventSubscription(); + listeners.add(e); + + return e.subscribe(); + } + + public void sendDateEvent(Date date) { + for (EventSubscription e : listeners) { + try { + e.emit(ServerSentEvent.builder(date) + .event("date") + .id(UUID.randomUUID().toString()) + .build()); + } catch (Exception ex) { + listeners.remove(e); + } + } + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/emitter/DateEmitterService.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/emitter/DateEmitterService.java new file mode 100644 index 0000000000..29b70865dc --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/emitter/DateEmitterService.java @@ -0,0 +1,27 @@ +package com.baeldung.reactive.sse.service.emitter; + +import com.baeldung.reactive.sse.service.EventSubscriptionsService; +import org.springframework.stereotype.Service; +import reactor.core.publisher.Flux; + +import javax.annotation.PostConstruct; +import java.time.Duration; +import java.util.Date; +import java.util.stream.Stream; + +@Service +public class DateEmitterService { + + private EventSubscriptionsService eventSubscriptionsService; + + public DateEmitterService(EventSubscriptionsService eventSubscriptionsService) { + this.eventSubscriptionsService = eventSubscriptionsService; + } + + @PostConstruct + public void init() { + Flux.fromStream(Stream.generate(Date::new)) + .delayElements(Duration.ofSeconds(1)) + .subscribe(data -> eventSubscriptionsService.sendDateEvent(new Date())); + } +} diff --git a/spring-5-reactive/src/main/resources/static/app.js b/spring-5-reactive/src/main/resources/static/app.js new file mode 100644 index 0000000000..2af2ae5844 --- /dev/null +++ b/spring-5-reactive/src/main/resources/static/app.js @@ -0,0 +1,36 @@ +let Clock = React.createClass({ + + getInitialState: function() { + const self = this; + const ev = new EventSource("http://localhost:8080/sse/events"); + + self.setState({currentDate : moment(new Date()).format("MMMM Do YYYY, h:mm:ss a")}); + + ev.addEventListener("date", function(e) { + self.setState({currentDate : moment(JSON.parse(e.data).date).format("MMMM Do YYYY, h:mm:ss a")}); + }, false); + + return {currentDate: moment(new Date()).format("MMMM Do YYYY, h:mm:ss a") }; + }, + + render() { + return ( +

+ Current time: {this.state.currentDate} +

+ ); + } + +}); + +let App = React.createClass({ + render() { + return ( +
+ +
+ ); + } +}); + +ReactDOM.render(, document.getElementById('root') ); \ No newline at end of file diff --git a/spring-5-reactive/src/main/resources/static/sse-index.html b/spring-5-reactive/src/main/resources/static/sse-index.html new file mode 100644 index 0000000000..875c8176af --- /dev/null +++ b/spring-5-reactive/src/main/resources/static/sse-index.html @@ -0,0 +1,19 @@ + + + + + React + Spring + + + +
+ + + + + + + + + + \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/sse/ServerSentEventsTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/sse/ServerSentEventsTest.java new file mode 100644 index 0000000000..48e8c23c37 --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/sse/ServerSentEventsTest.java @@ -0,0 +1,39 @@ +package com.baeldung.reactive.sse; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ServerSentEventsTest { + + @Autowired + private WebTestClient webClient; + + @Test + public void contextLoads() { + } + + @Test + public void givenValidRequest_shouldReceiveOk() throws Exception { + + webClient.get().uri("/events").accept(MediaType.TEXT_EVENT_STREAM) + .exchange() + .expectStatus().isOk(); + } + + @Test + public void givenInvalidHttpVerb_shouldReceiveMethodNotAllowedError() throws Exception { + + webClient.post().uri("/events").accept(MediaType.TEXT_EVENT_STREAM) + .exchange() + .expectStatus().isEqualTo(HttpStatus.METHOD_NOT_ALLOWED); + } + +} From 172642e190d47c76a14a40b7053a6df9524c746f Mon Sep 17 00:00:00 2001 From: Philippe Date: Tue, 26 Jun 2018 01:10:00 -0300 Subject: [PATCH 02/38] BAEL-1474 Take2 --- .../src/docker/docker-compose.yml | 23 -- .../spring/amqp/AmqpReactiveController.java | 307 ++++++++++++++++++ .../amqp/MessageListenerContainerFactory.java | 29 ++ 3 files changed, 336 insertions(+), 23 deletions(-) delete mode 100755 spring-webflux-amqp/src/docker/docker-compose.yml create mode 100644 spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/AmqpReactiveController.java create mode 100644 spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/MessageListenerContainerFactory.java diff --git a/spring-webflux-amqp/src/docker/docker-compose.yml b/spring-webflux-amqp/src/docker/docker-compose.yml deleted file mode 100755 index 03292aeb63..0000000000 --- a/spring-webflux-amqp/src/docker/docker-compose.yml +++ /dev/null @@ -1,23 +0,0 @@ -## -## Create a simple RabbitMQ environment with multiple clients -## -version: "3" - -services: - -## -## RabitMQ server -## - rabbitmq: - image: rabbitmq:3 - hostname: rabbit - environment: - RABBITMQ_ERLANG_COOKIE: test - ports: - - "5672:5672" - volumes: - - rabbitmq-data:/var/lib/rabbitmq - -volumes: - rabbitmq-data: - diff --git a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/AmqpReactiveController.java b/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/AmqpReactiveController.java new file mode 100644 index 0000000000..52f6d924fa --- /dev/null +++ b/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/AmqpReactiveController.java @@ -0,0 +1,307 @@ +package org.baeldung.spring.amqp; + +import java.time.Duration; +import java.util.Date; + +import javax.annotation.PostConstruct; + +import org.baeldung.spring.amqp.DestinationsConfig.DestinationInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.core.AmqpAdmin; +import org.springframework.amqp.core.AmqpTemplate; +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.Exchange; +import org.springframework.amqp.core.ExchangeBuilder; +import org.springframework.amqp.core.MessageListener; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.QueueBuilder; +import org.springframework.amqp.rabbit.listener.MessageListenerContainer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +@RestController +public class AmqpReactiveController { + + private static Logger log = LoggerFactory.getLogger(AmqpReactiveController.class); + + @Autowired + private AmqpTemplate amqpTemplate; + + @Autowired + private AmqpAdmin amqpAdmin; + + @Autowired + private DestinationsConfig destinationsConfig; + + @Autowired + private MessageListenerContainerFactory messageListenerContainerFactory; + + @PostConstruct + public void setupQueueDestinations() { + + log.info("[I48] Creating Destinations..."); + + destinationsConfig.getQueues() + .forEach((key, destination) -> { + + log.info("[I54] Creating directExchange: key={}, name={}, routingKey={}", key, destination.getExchange(), destination.getRoutingKey()); + + Exchange ex = ExchangeBuilder.directExchange(destination.getExchange()) + .durable(true) + .build(); + + amqpAdmin.declareExchange(ex); + + Queue q = QueueBuilder.durable(destination.getRoutingKey()) + .build(); + + amqpAdmin.declareQueue(q); + + Binding b = BindingBuilder.bind(q) + .to(ex) + .with(destination.getRoutingKey()) + .noargs(); + + amqpAdmin.declareBinding(b); + + log.info("[I70] Binding successfully created."); + + }); + } + + @PostConstruct + public void setupTopicDestinations() { + + // For topic each consumer will have its own Queue, so no binding + destinationsConfig.getTopics() + .forEach((key, destination) -> { + + log.info("[I98] Creating TopicExchange: name={}, exchange={}", key, destination.getExchange()); + + Exchange ex = ExchangeBuilder.topicExchange(destination.getExchange()) + .durable(true) + .build(); + + amqpAdmin.declareExchange(ex); + + log.info("[I107] Topic Exchange successfully created."); + + }); + } + + @PostMapping(value = "/queue/{name}") + public Mono> sendMessageToQueue(@PathVariable String name, @RequestBody String payload) { + + // Lookup exchange details + final DestinationInfo d = destinationsConfig.getQueues() + .get(name); + + if (d == null) { + // Destination not found. + return Mono.just(ResponseEntity.notFound() + .build()); + } + + return Mono.fromCallable(() -> { + + log.info("[I51] sendMessageToQueue: queue={}, routingKey={}", d.getExchange(), d.getRoutingKey()); + amqpTemplate.convertAndSend(d.getExchange(), d.getRoutingKey(), payload); + + return ResponseEntity.accepted() + .build(); + + }); + + } + + /** + * Receive messages for the given queue + * @param name + * @param errorHandler + * @return + */ + @GetMapping(value = "/queue/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux receiveMessagesFromQueue(@PathVariable String name) { + + DestinationInfo d = destinationsConfig.getQueues() + .get(name); + + if (d == null) { + return Flux.just(ResponseEntity.notFound() + .build()); + } + + MessageListenerContainer mlc = messageListenerContainerFactory.createMessageListenerContainer(d.getRoutingKey()); + + Flux f = Flux. create(emitter -> { + + log.info("[I168] Adding listener, queue={}", d.getRoutingKey()); + mlc.setupMessageListener((MessageListener) m -> { + + String qname = m.getMessageProperties() + .getConsumerQueue(); + + log.info("[I137] Message received, queue={}", qname); + + if (emitter.isCancelled()) { + log.info("[I166] cancelled, queue={}", qname); + mlc.stop(); + return; + } + + String payload = new String(m.getBody()); + emitter.next(payload); + + log.info("[I176] Message sent to client, queue={}", qname); + + }); + + emitter.onRequest(v -> { + log.info("[I171] Starting container, queue={}", d.getRoutingKey()); + mlc.start(); + }); + + emitter.onDispose(() -> { + log.info("[I176] onDispose: queue={}", d.getRoutingKey()); + mlc.stop(); + }); + + log.info("[I171] Container started, queue={}", d.getRoutingKey()); + + }); + + + return Flux.interval(Duration.ofSeconds(5)) + .map(v -> { + log.info("[I209] sending keepalive message..."); + return "No news is good news"; + }) + .mergeWith(f); + } + + /** + * send message to a given topic + * @param name + * @param payload + * @return + */ + @PostMapping(value = "/topic/{name}") + public Mono> sendMessageToTopic(@PathVariable String name, @RequestBody String payload) { + + // Lookup exchange details + final DestinationInfo d = destinationsConfig.getTopics() + .get(name); + if (d == null) { + // Destination not found. + return Mono.just(ResponseEntity.notFound() + .build()); + } + + return Mono.fromCallable(() -> { + + log.info("[I51] sendMessageToTopic: topic={}, routingKey={}", d.getExchange(), d.getRoutingKey()); + amqpTemplate.convertAndSend(d.getExchange(), d.getRoutingKey(), payload); + + return ResponseEntity.accepted() + .build(); + + }); + } + + @GetMapping(value = "/topic/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux receiveMessagesFromTopic(@PathVariable String name) { + + DestinationInfo d = destinationsConfig.getTopics() + .get(name); + + if (d == null) { + return Flux.just(ResponseEntity.notFound() + .build()); + } + + Queue topicQueue = createTopicQueue(d); + String qname = topicQueue.getName(); + + MessageListenerContainer mlc = messageListenerContainerFactory.createMessageListenerContainer(qname); + + Flux f = Flux. create(emitter -> { + + log.info("[I168] Adding listener, queue={}", qname); + + mlc.setupMessageListener((MessageListener) m -> { + + log.info("[I137] Message received, queue={}", qname); + + if (emitter.isCancelled()) { + log.info("[I166] cancelled, queue={}", qname); + mlc.stop(); + return; + } + + String payload = new String(m.getBody()); + emitter.next(payload); + + log.info("[I176] Message sent to client, queue={}", qname); + + }); + + emitter.onRequest(v -> { + log.info("[I171] Starting container, queue={}", qname); + mlc.start(); + }); + + emitter.onDispose(() -> { + log.info("[I176] onDispose: queue={}", qname); + amqpAdmin.deleteQueue(qname); + mlc.stop(); + }); + + log.info("[I171] Container started, queue={}", qname); + + }); + + return Flux.interval(Duration.ofSeconds(5)) + .map(v -> { + log.info("[I209] sending keepalive message..."); + return "No news is good news"; + }) + .mergeWith(f); + + } + + private Queue createTopicQueue(DestinationInfo destination) { + + Exchange ex = ExchangeBuilder.topicExchange(destination.getExchange()) + .durable(true) + .build(); + + amqpAdmin.declareExchange(ex); + + Queue q = QueueBuilder.nonDurable() + .build(); + + amqpAdmin.declareQueue(q); + + Binding b = BindingBuilder.bind(q) + .to(ex) + .with(destination.getRoutingKey()) + .noargs(); + + amqpAdmin.declareBinding(b); + + return q; + } + +} diff --git a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/MessageListenerContainerFactory.java b/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/MessageListenerContainerFactory.java new file mode 100644 index 0000000000..29b8d28a80 --- /dev/null +++ b/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/MessageListenerContainerFactory.java @@ -0,0 +1,29 @@ +package org.baeldung.spring.amqp; + +import org.springframework.amqp.core.AcknowledgeMode; +import org.springframework.amqp.rabbit.connection.ConnectionFactory; +import org.springframework.amqp.rabbit.listener.MessageListenerContainer; +import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class MessageListenerContainerFactory { + + @Autowired + private ConnectionFactory connectionFactory; + + public MessageListenerContainerFactory() { + } + + public MessageListenerContainer createMessageListenerContainer(String queueName) { + + SimpleMessageListenerContainer mlc = new SimpleMessageListenerContainer(connectionFactory); + + mlc.addQueueNames(queueName); + mlc.setAcknowledgeMode(AcknowledgeMode.AUTO); + + return mlc; + } + +} From 652cf1e49c2be1a74b38b20319a374cc13f72678 Mon Sep 17 00:00:00 2001 From: Philippe Date: Sat, 30 Jun 2018 00:14:05 +0200 Subject: [PATCH 03/38] Remove extra code --- .../amqp/SpringWebfluxAmqpApplication.java | 255 ------------------ 1 file changed, 255 deletions(-) diff --git a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java b/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java index eb3b858ddc..30614e7ee6 100755 --- a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java +++ b/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java @@ -1,270 +1,15 @@ package org.baeldung.spring.amqp; -import java.util.stream.Stream; - -import org.baeldung.spring.amqp.DestinationsConfig.DestinationInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.amqp.AmqpException; -import org.springframework.amqp.core.AmqpAdmin; -import org.springframework.amqp.core.AmqpTemplate; -import org.springframework.amqp.core.Binding; -import org.springframework.amqp.core.BindingBuilder; -import org.springframework.amqp.core.Exchange; -import org.springframework.amqp.core.ExchangeBuilder; -import org.springframework.amqp.core.Queue; -import org.springframework.amqp.core.QueueBuilder; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Schedulers; @SpringBootApplication @EnableConfigurationProperties(DestinationsConfig.class) -@RestController public class SpringWebfluxAmqpApplication { - private static Logger log = LoggerFactory.getLogger(SpringWebfluxAmqpApplication.class); - - @Autowired - private AmqpTemplate amqpTemplate; - - @Autowired - private AmqpAdmin amqpAdmin; - - @Autowired - private DestinationsConfig destinationsConfig; - - public static void main(String[] args) { SpringApplication.run(SpringWebfluxAmqpApplication.class, args); } - - @Bean - public CommandLineRunner setupQueueDestinations(AmqpAdmin amqpAdmin,DestinationsConfig destinationsConfig) { - - return (args) -> { - - log.info("[I48] Creating Destinations..."); - - destinationsConfig.getQueues() - .forEach((key, destination) -> { - - log.info("[I54] Creating directExchange: key={}, name={}, routingKey={}", key, destination.getExchange(), destination.getRoutingKey()); - - Exchange ex = ExchangeBuilder - .directExchange(destination.getExchange()) - .durable(true) - .build(); - - amqpAdmin.declareExchange(ex); - - Queue q = QueueBuilder - .durable(destination.getRoutingKey()) - .build(); - - amqpAdmin.declareQueue(q); - - Binding b = BindingBuilder.bind(q) - .to(ex) - .with(destination.getRoutingKey()) - .noargs(); - amqpAdmin.declareBinding(b); - - log.info("[I70] Binding successfully created."); - - }); - - }; - - } - - @Bean - public CommandLineRunner setupTopicDestinations(AmqpAdmin amqpAdmin, DestinationsConfig destinationsConfig) { - - return (args) -> { - - // For topic each consumer will have its own Queue, so no binding - destinationsConfig.getTopics() - .forEach((key, destination) -> { - - log.info("[I98] Creating TopicExchange: name={}, exchange={}", key, destination.getExchange()); - - Exchange ex = ExchangeBuilder.topicExchange(destination.getExchange()) - .durable(true) - .build(); - - amqpAdmin.declareExchange(ex); - - log.info("[I107] Topic Exchange successfully created."); - - }); - }; - } - - @PostMapping(value = "/queue/{name}") - public Mono> sendMessageToQueue(@PathVariable String name, @RequestBody String payload) { - - // Lookup exchange details - final DestinationInfo d = destinationsConfig.getQueues() - .get(name); - if (d == null) { - // Destination not found. - return Mono.just(ResponseEntity.notFound().build()); - } - - return Mono.fromCallable(() -> { - - log.info("[I51] sendMessageToQueue: queue={}, routingKey={}", d.getExchange(), d.getRoutingKey()); - amqpTemplate.convertAndSend(d.getExchange(), d.getRoutingKey(), payload); - - return ResponseEntity.accepted().build(); - - }); - - } - - - /** - * Receive messages for the given queue - * @param name - * @return - */ - @GetMapping(value = "/queue/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) - public Flux receiveMessagesFromQueue(@PathVariable String name) { - - final DestinationInfo d = destinationsConfig.getQueues().get(name); - - if (d == null) { - return Flux.just(ResponseEntity.notFound().build()); - } - - Stream s = Stream.generate(() -> { - String queueName = d.getRoutingKey(); - - log.info("[I137] Polling {}", queueName); - - Object payload = amqpTemplate.receiveAndConvert(queueName,5000); - if ( payload == null ) { - payload = "No news is good news..."; - } - - return payload.toString(); - }); - - - return Flux - .fromStream(s) - .subscribeOn(Schedulers.elastic()); - - } - - /** - * send message to a given topic - * @param name - * @param payload - * @return - */ - @PostMapping(value = "/topic/{name}") - public Mono> sendMessageToTopic(@PathVariable String name, @RequestBody String payload) { - - // Lookup exchange details - final DestinationInfo d = destinationsConfig.getTopics().get(name); - if (d == null) { - // Destination not found. - return Mono.just(ResponseEntity.notFound().build()); - } - - return Mono.fromCallable(() -> { - - log.info("[I51] sendMessageToTopic: topic={}, routingKey={}", d.getExchange(), d.getRoutingKey()); - amqpTemplate.convertAndSend(d.getExchange(), d.getRoutingKey(), payload); - - return ResponseEntity.accepted().build(); - - }); - } - - - @GetMapping(value = "/topic/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) - public Flux receiveMessagesFromTopic(@PathVariable String name) { - - DestinationInfo d = destinationsConfig.getTopics().get(name); - - if (d == null) { - return Flux.just(ResponseEntity.notFound().build()); - } - - final Queue topicQueue = createTopicQueue(d); - - Stream s = Stream.generate(() -> { - String queueName = topicQueue.getName(); - - log.info("[I137] Polling {}", queueName); - - try { - Object payload = amqpTemplate.receiveAndConvert(queueName,5000); - if ( payload == null ) { - payload = "No news is good news..."; - } - - return payload.toString(); - } - catch(AmqpException ex) { - log.warn("[W247] Received an AMQP Exception: {}", ex.getMessage()); - return null; - } - }); - - - return Flux.fromStream(s) - .doOnCancel(() -> { - log.info("[I250] doOnCancel()"); - amqpAdmin.deleteQueue(topicQueue.getName()); - }) - .subscribeOn(Schedulers.elastic()); - - - } - - - private Queue createTopicQueue(DestinationInfo destination) { - - Exchange ex = ExchangeBuilder.topicExchange(destination.getExchange()) - .durable(true) - .build(); - - amqpAdmin.declareExchange(ex); - - // Create a durable queue - Queue q = QueueBuilder - .durable() - .build(); - - amqpAdmin.declareQueue(q); - - Binding b = BindingBuilder.bind(q) - .to(ex) - .with(destination.getRoutingKey()) - .noargs(); - - amqpAdmin.declareBinding(b); - - return q; - } - } From 69bb8daf0c0a5532df785670929cf1159107a420 Mon Sep 17 00:00:00 2001 From: db Date: Fri, 13 Jul 2018 22:16:18 +0100 Subject: [PATCH 04/38] spring security custom AuthenticationFailureHandler --- spring-boot-security/pom.xml | 23 ++++- .../SpringBootSecurityApplication.java | 12 +++ .../configuration/SecurityConfiguration.java | 40 +++++++++ .../CustomAuthenticationFailureHandler.java | 28 ++++++ .../form_login/FormLoginIntegrationTest.java | 87 +++++++++++++++++++ 5 files changed, 187 insertions(+), 3 deletions(-) create mode 100644 spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/SpringBootSecurityApplication.java create mode 100644 spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/configuration/SecurityConfiguration.java create mode 100644 spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/security/CustomAuthenticationFailureHandler.java create mode 100644 spring-boot-security/src/test/java/com/baeldung/springbootsecurity/form_login/FormLoginIntegrationTest.java diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml index 8763c210c8..b10f8e6e47 100644 --- a/spring-boot-security/pom.xml +++ b/spring-boot-security/pom.xml @@ -10,9 +10,10 @@ Spring Boot Security Auto-Configuration - com.baeldung - parent-modules - 1.0.0-SNAPSHOT + org.springframework.boot + spring-boot-starter-parent + 1.5.9.RELEASE + @@ -55,6 +56,11 @@ spring-security-test test + + org.springframework.security + spring-security-test + test + @@ -62,6 +68,16 @@ org.springframework.boot spring-boot-maven-plugin + + + + repackage + + + com.baeldung.springbootsecurity.basic_auth.SpringBootSecurityApplication + + + @@ -69,6 +85,7 @@ UTF-8 UTF-8 + 1.8 diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/SpringBootSecurityApplication.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/SpringBootSecurityApplication.java new file mode 100644 index 0000000000..9f4796e1f9 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/SpringBootSecurityApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.springbootsecurity.form_login; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecurity.form_login") +public class SpringBootSecurityApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootSecurityApplication.class, args); + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/configuration/SecurityConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/configuration/SecurityConfiguration.java new file mode 100644 index 0000000000..1f5c53eb2b --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/configuration/SecurityConfiguration.java @@ -0,0 +1,40 @@ +package com.baeldung.springbootsecurity.form_login.configuration; + +import com.baeldung.springbootsecurity.form_login.security.CustomAuthenticationFailureHandler; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; + +@Configuration +@EnableWebSecurity +public class SecurityConfiguration extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth + .inMemoryAuthentication() + .withUser("baeldung") + .password("baeldung") + .roles("USER"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .anyRequest() + .authenticated() + .and() + .formLogin() + .failureHandler(customAuthenticationFailureHandler()); + } + + @Bean + public AuthenticationFailureHandler customAuthenticationFailureHandler() { + return new CustomAuthenticationFailureHandler(); + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/security/CustomAuthenticationFailureHandler.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/security/CustomAuthenticationFailureHandler.java new file mode 100644 index 0000000000..2617c1f475 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/security/CustomAuthenticationFailureHandler.java @@ -0,0 +1,28 @@ +package com.baeldung.springbootsecurity.form_login.security; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; + +public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler { + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + Map data = new HashMap<>(); + data.put("timestamp", Calendar.getInstance().getTime()); + data.put("exception", exception.getMessage()); + + response.getOutputStream().println(objectMapper.writeValueAsString(data)); + } +} diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/form_login/FormLoginIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/form_login/FormLoginIntegrationTest.java new file mode 100644 index 0000000000..d5b5d8637b --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/form_login/FormLoginIntegrationTest.java @@ -0,0 +1,87 @@ +package com.baeldung.springbootsecurity.form_login; + +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.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import javax.servlet.Filter; + +import static org.junit.Assert.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; +import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; +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.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = com.baeldung.springbootsecurity.form_login.SpringBootSecurityApplication.class) +public class FormLoginIntegrationTest { + + @Autowired + private WebApplicationContext context; + + @Autowired + private Filter springSecurityFilterChain; + + private MockMvc mvc; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .addFilters(springSecurityFilterChain) + .build(); + } + + @Test + public void givenRequestWithoutSessionOrCsrfToken_shouldFailWith403() throws Exception { + mvc + .perform(post("/")) + .andExpect(status().isForbidden()); + } + + @Test + public void givenRequestWithInvalidCsrfToken_shouldFailWith403() throws Exception { + mvc + .perform(post("/").with(csrf().useInvalidToken())) + .andExpect(status().isForbidden()); + } + + @Test + public void givenRequestWithValidCsrfTokenAndWithoutSessionToken_shouldReceive302WithLocationHeaderToLoginPage() throws Exception { + MvcResult mvcResult = mvc.perform(post("/").with(csrf())).andReturn(); + assertTrue(mvcResult.getResponse().getStatus() == 302); + assertTrue(mvcResult.getResponse().getHeader("Location").contains("login")); + } + + @Test + public void givenValidRequestWithValidCredentials_shouldLoginSuccessfully() throws Exception { + mvc + .perform(formLogin().user("baeldung").password("baeldung")) + .andExpect(status().isFound()) + .andExpect(redirectedUrl("/")) + .andExpect(authenticated().withUsername("baeldung")); + } + + @Test + public void givenValidRequestWithInvalidCredentials_shouldFailWith401() throws Exception { + MvcResult result = mvc + .perform(formLogin().user("random").password("random")) + .andExpect(status().isUnauthorized()) + .andDo(print()) + .andExpect(unauthenticated()) + .andReturn(); + + assertTrue(result.getResponse().getContentAsString().contains("Bad credentials")); + } +} From a9a0a3978ec55b695dbf073f768dbe831cf72621 Mon Sep 17 00:00:00 2001 From: db Date: Sat, 14 Jul 2018 16:01:28 +0100 Subject: [PATCH 05/38] refactor --- spring-boot-security/pom.xml | 20 ++++--------- .../configuration/SecurityConfiguration.java | 29 ++++++++++++++++++- .../CustomAuthenticationFailureHandler.java | 28 ------------------ 3 files changed, 33 insertions(+), 44 deletions(-) delete mode 100644 spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/security/CustomAuthenticationFailureHandler.java diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml index b10f8e6e47..130bd52235 100644 --- a/spring-boot-security/pom.xml +++ b/spring-boot-security/pom.xml @@ -10,10 +10,9 @@ Spring Boot Security Auto-Configuration - org.springframework.boot - spring-boot-starter-parent - 1.5.9.RELEASE - + com.baeldung + parent-modules + 1.0.0-SNAPSHOT @@ -21,7 +20,7 @@ org.springframework.boot spring-boot-dependencies - 1.5.9.RELEASE + ${spring-boot.version} pom import @@ -68,16 +67,6 @@ org.springframework.boot spring-boot-maven-plugin - - - - repackage - - - com.baeldung.springbootsecurity.basic_auth.SpringBootSecurityApplication - - - @@ -86,6 +75,7 @@ UTF-8 UTF-8 1.8 + 1.5.9.RELEASE diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/configuration/SecurityConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/configuration/SecurityConfiguration.java index 1f5c53eb2b..6ab522ef00 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/configuration/SecurityConfiguration.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/configuration/SecurityConfiguration.java @@ -1,14 +1,24 @@ package com.baeldung.springbootsecurity.form_login.configuration; -import com.baeldung.springbootsecurity.form_login.security.CustomAuthenticationFailureHandler; +import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpStatus; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; + @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @@ -37,4 +47,21 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { public AuthenticationFailureHandler customAuthenticationFailureHandler() { return new CustomAuthenticationFailureHandler(); } + + /** + * Custom AuthenticationFailureHandler + */ + public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler { + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + Map data = new HashMap<>(); + data.put("timestamp", Calendar.getInstance().getTime()); + data.put("exception", exception.getMessage()); + + response.getOutputStream().println(objectMapper.writeValueAsString(data)); + } + } } diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/security/CustomAuthenticationFailureHandler.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/security/CustomAuthenticationFailureHandler.java deleted file mode 100644 index 2617c1f475..0000000000 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/security/CustomAuthenticationFailureHandler.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.springbootsecurity.form_login.security; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.http.HttpStatus; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.authentication.AuthenticationFailureHandler; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Map; - -public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler { - private final ObjectMapper objectMapper = new ObjectMapper(); - - @Override - public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { - response.setStatus(HttpStatus.UNAUTHORIZED.value()); - Map data = new HashMap<>(); - data.put("timestamp", Calendar.getInstance().getTime()); - data.put("exception", exception.getMessage()); - - response.getOutputStream().println(objectMapper.writeValueAsString(data)); - } -} From f18ad815a3af6666e4b7ca2c62401e0e5d59fb43 Mon Sep 17 00:00:00 2001 From: db Date: Sat, 14 Jul 2018 16:10:57 +0100 Subject: [PATCH 06/38] moved SSE to branch --- .../sse/controller/EventController.java | 26 ------------ .../reactive/sse/model/EventSubscription.java | 22 ---------- .../service/EventSubscriptionsService.java | 41 ------------------- .../service/emitter/DateEmitterService.java | 27 ------------ .../src/main/resources/static/app.js | 36 ---------------- .../src/main/resources/static/sse-index.html | 19 --------- .../reactive/sse/ServerSentEventsTest.java | 39 ------------------ 7 files changed, 210 deletions(-) delete mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/sse/controller/EventController.java delete mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/sse/model/EventSubscription.java delete mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/EventSubscriptionsService.java delete mode 100644 spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/emitter/DateEmitterService.java delete mode 100644 spring-5-reactive/src/main/resources/static/app.js delete mode 100644 spring-5-reactive/src/main/resources/static/sse-index.html delete mode 100644 spring-5-reactive/src/test/java/com/baeldung/reactive/sse/ServerSentEventsTest.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/controller/EventController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/controller/EventController.java deleted file mode 100644 index e692aa3a74..0000000000 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/controller/EventController.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.reactive.sse.controller; - - -import com.baeldung.reactive.sse.service.EventSubscriptionsService; -import org.springframework.http.MediaType; -import org.springframework.http.codec.ServerSentEvent; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; -import reactor.core.publisher.Flux; - -@RestController -public class EventController { - - private EventSubscriptionsService eventSubscriptionsService; - - public EventController(EventSubscriptionsService eventSubscriptionsService) { - this.eventSubscriptionsService = eventSubscriptionsService; - } - - @GetMapping( - produces = MediaType.TEXT_EVENT_STREAM_VALUE, - value = "/sse/events") - public Flux events() { - return eventSubscriptionsService.subscribe(); - } -} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/model/EventSubscription.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/model/EventSubscription.java deleted file mode 100644 index 4d3ce27156..0000000000 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/model/EventSubscription.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.reactive.sse.model; - -import org.springframework.http.codec.ServerSentEvent; -import reactor.core.publisher.DirectProcessor; -import reactor.core.publisher.Flux; - -public class EventSubscription { - - private DirectProcessor directProcessor; - - public EventSubscription() { - this.directProcessor = DirectProcessor.create(); - } - - public void emit(ServerSentEvent e) { - directProcessor.onNext(e); - } - - public Flux subscribe() { - return directProcessor; - } -} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/EventSubscriptionsService.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/EventSubscriptionsService.java deleted file mode 100644 index f245ce6184..0000000000 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/EventSubscriptionsService.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.reactive.sse.service; - -import com.baeldung.reactive.sse.model.EventSubscription; -import org.springframework.http.codec.ServerSentEvent; -import org.springframework.stereotype.Service; -import reactor.core.publisher.Flux; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.UUID; - -@Service -public class EventSubscriptionsService { - - private List listeners; - - public EventSubscriptionsService() { - this.listeners = new ArrayList<>(); - } - - public Flux subscribe() { - EventSubscription e = new EventSubscription(); - listeners.add(e); - - return e.subscribe(); - } - - public void sendDateEvent(Date date) { - for (EventSubscription e : listeners) { - try { - e.emit(ServerSentEvent.builder(date) - .event("date") - .id(UUID.randomUUID().toString()) - .build()); - } catch (Exception ex) { - listeners.remove(e); - } - } - } -} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/emitter/DateEmitterService.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/emitter/DateEmitterService.java deleted file mode 100644 index 29b70865dc..0000000000 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/sse/service/emitter/DateEmitterService.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.reactive.sse.service.emitter; - -import com.baeldung.reactive.sse.service.EventSubscriptionsService; -import org.springframework.stereotype.Service; -import reactor.core.publisher.Flux; - -import javax.annotation.PostConstruct; -import java.time.Duration; -import java.util.Date; -import java.util.stream.Stream; - -@Service -public class DateEmitterService { - - private EventSubscriptionsService eventSubscriptionsService; - - public DateEmitterService(EventSubscriptionsService eventSubscriptionsService) { - this.eventSubscriptionsService = eventSubscriptionsService; - } - - @PostConstruct - public void init() { - Flux.fromStream(Stream.generate(Date::new)) - .delayElements(Duration.ofSeconds(1)) - .subscribe(data -> eventSubscriptionsService.sendDateEvent(new Date())); - } -} diff --git a/spring-5-reactive/src/main/resources/static/app.js b/spring-5-reactive/src/main/resources/static/app.js deleted file mode 100644 index 2af2ae5844..0000000000 --- a/spring-5-reactive/src/main/resources/static/app.js +++ /dev/null @@ -1,36 +0,0 @@ -let Clock = React.createClass({ - - getInitialState: function() { - const self = this; - const ev = new EventSource("http://localhost:8080/sse/events"); - - self.setState({currentDate : moment(new Date()).format("MMMM Do YYYY, h:mm:ss a")}); - - ev.addEventListener("date", function(e) { - self.setState({currentDate : moment(JSON.parse(e.data).date).format("MMMM Do YYYY, h:mm:ss a")}); - }, false); - - return {currentDate: moment(new Date()).format("MMMM Do YYYY, h:mm:ss a") }; - }, - - render() { - return ( -

- Current time: {this.state.currentDate} -

- ); - } - -}); - -let App = React.createClass({ - render() { - return ( -
- -
- ); - } -}); - -ReactDOM.render(, document.getElementById('root') ); \ No newline at end of file diff --git a/spring-5-reactive/src/main/resources/static/sse-index.html b/spring-5-reactive/src/main/resources/static/sse-index.html deleted file mode 100644 index 875c8176af..0000000000 --- a/spring-5-reactive/src/main/resources/static/sse-index.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - React + Spring - - - -
- - - - - - - - - - \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/sse/ServerSentEventsTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/sse/ServerSentEventsTest.java deleted file mode 100644 index 48e8c23c37..0000000000 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/sse/ServerSentEventsTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.reactive.sse; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.reactive.server.WebTestClient; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class ServerSentEventsTest { - - @Autowired - private WebTestClient webClient; - - @Test - public void contextLoads() { - } - - @Test - public void givenValidRequest_shouldReceiveOk() throws Exception { - - webClient.get().uri("/events").accept(MediaType.TEXT_EVENT_STREAM) - .exchange() - .expectStatus().isOk(); - } - - @Test - public void givenInvalidHttpVerb_shouldReceiveMethodNotAllowedError() throws Exception { - - webClient.post().uri("/events").accept(MediaType.TEXT_EVENT_STREAM) - .exchange() - .expectStatus().isEqualTo(HttpStatus.METHOD_NOT_ALLOWED); - } - -} From 509998a7c6b769ee4ff66bbe352d6b9afef47181 Mon Sep 17 00:00:00 2001 From: db Date: Sun, 15 Jul 2018 09:24:32 +0100 Subject: [PATCH 07/38] remove pom properties --- spring-boot-security/pom.xml | 3 --- 1 file changed, 3 deletions(-) diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml index 130bd52235..1f904d0a67 100644 --- a/spring-boot-security/pom.xml +++ b/spring-boot-security/pom.xml @@ -72,9 +72,6 @@ - UTF-8 - UTF-8 - 1.8 1.5.9.RELEASE From aa0af30497bfc2b8699ba5a890d6ba6494f441d6 Mon Sep 17 00:00:00 2001 From: db Date: Wed, 18 Jul 2018 12:40:56 +0100 Subject: [PATCH 08/38] moved AuthenticationFailureHandler example to spring-security-mvc-login --- .../SpringBootSecurityApplication.java | 12 --- .../configuration/SecurityConfiguration.java | 67 -------------- .../form_login/FormLoginIntegrationTest.java | 87 ------------------- .../form_login/FormLoginUnitTest.java | 87 ------------------- .../CustomAuthenticationFailureHandler.java | 22 +++++ .../baeldung/spring/SecSecurityConfig.java | 51 ++++++----- .../src/main/resources/webSecurityConfig.xml | 8 +- .../baeldung/security/FormLoginUnitTest.java | 63 ++++++++++++++ 8 files changed, 119 insertions(+), 278 deletions(-) delete mode 100644 spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/SpringBootSecurityApplication.java delete mode 100644 spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/configuration/SecurityConfiguration.java delete mode 100644 spring-boot-security/src/test/java/com/baeldung/springbootsecurity/form_login/FormLoginIntegrationTest.java delete mode 100644 spring-boot-security/src/test/java/com/baeldung/springbootsecurity/form_login/FormLoginUnitTest.java create mode 100644 spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java create mode 100644 spring-security-mvc-login/src/test/java/org/baeldung/security/FormLoginUnitTest.java diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/SpringBootSecurityApplication.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/SpringBootSecurityApplication.java deleted file mode 100644 index 9f4796e1f9..0000000000 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/SpringBootSecurityApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.springbootsecurity.form_login; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecurity.form_login") -public class SpringBootSecurityApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringBootSecurityApplication.class, args); - } -} diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/configuration/SecurityConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/configuration/SecurityConfiguration.java deleted file mode 100644 index 6ab522ef00..0000000000 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/form_login/configuration/SecurityConfiguration.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.springbootsecurity.form_login.configuration; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpStatus; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.authentication.AuthenticationFailureHandler; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Map; - -@Configuration -@EnableWebSecurity -public class SecurityConfiguration extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth - .inMemoryAuthentication() - .withUser("baeldung") - .password("baeldung") - .roles("USER"); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .anyRequest() - .authenticated() - .and() - .formLogin() - .failureHandler(customAuthenticationFailureHandler()); - } - - @Bean - public AuthenticationFailureHandler customAuthenticationFailureHandler() { - return new CustomAuthenticationFailureHandler(); - } - - /** - * Custom AuthenticationFailureHandler - */ - public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler { - private final ObjectMapper objectMapper = new ObjectMapper(); - - @Override - public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { - response.setStatus(HttpStatus.UNAUTHORIZED.value()); - Map data = new HashMap<>(); - data.put("timestamp", Calendar.getInstance().getTime()); - data.put("exception", exception.getMessage()); - - response.getOutputStream().println(objectMapper.writeValueAsString(data)); - } - } -} diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/form_login/FormLoginIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/form_login/FormLoginIntegrationTest.java deleted file mode 100644 index d5b5d8637b..0000000000 --- a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/form_login/FormLoginIntegrationTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.springbootsecurity.form_login; - -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.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import javax.servlet.Filter; - -import static org.junit.Assert.assertTrue; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; -import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; -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.redirectedUrl; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = com.baeldung.springbootsecurity.form_login.SpringBootSecurityApplication.class) -public class FormLoginIntegrationTest { - - @Autowired - private WebApplicationContext context; - - @Autowired - private Filter springSecurityFilterChain; - - private MockMvc mvc; - - @Before - public void setup() { - mvc = MockMvcBuilders - .webAppContextSetup(context) - .addFilters(springSecurityFilterChain) - .build(); - } - - @Test - public void givenRequestWithoutSessionOrCsrfToken_shouldFailWith403() throws Exception { - mvc - .perform(post("/")) - .andExpect(status().isForbidden()); - } - - @Test - public void givenRequestWithInvalidCsrfToken_shouldFailWith403() throws Exception { - mvc - .perform(post("/").with(csrf().useInvalidToken())) - .andExpect(status().isForbidden()); - } - - @Test - public void givenRequestWithValidCsrfTokenAndWithoutSessionToken_shouldReceive302WithLocationHeaderToLoginPage() throws Exception { - MvcResult mvcResult = mvc.perform(post("/").with(csrf())).andReturn(); - assertTrue(mvcResult.getResponse().getStatus() == 302); - assertTrue(mvcResult.getResponse().getHeader("Location").contains("login")); - } - - @Test - public void givenValidRequestWithValidCredentials_shouldLoginSuccessfully() throws Exception { - mvc - .perform(formLogin().user("baeldung").password("baeldung")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl("/")) - .andExpect(authenticated().withUsername("baeldung")); - } - - @Test - public void givenValidRequestWithInvalidCredentials_shouldFailWith401() throws Exception { - MvcResult result = mvc - .perform(formLogin().user("random").password("random")) - .andExpect(status().isUnauthorized()) - .andDo(print()) - .andExpect(unauthenticated()) - .andReturn(); - - assertTrue(result.getResponse().getContentAsString().contains("Bad credentials")); - } -} diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/form_login/FormLoginUnitTest.java b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/form_login/FormLoginUnitTest.java deleted file mode 100644 index d518f3b0c2..0000000000 --- a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/form_login/FormLoginUnitTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.springbootsecurity.form_login; - -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.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import javax.servlet.Filter; - -import static org.junit.Assert.assertTrue; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; -import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; -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.redirectedUrl; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = com.baeldung.springbootsecurity.form_login.SpringBootSecurityApplication.class) -public class FormLoginUnitTest { - - @Autowired - private WebApplicationContext context; - - @Autowired - private Filter springSecurityFilterChain; - - private MockMvc mvc; - - @Before - public void setup() { - mvc = MockMvcBuilders - .webAppContextSetup(context) - .addFilters(springSecurityFilterChain) - .build(); - } - - @Test - public void givenRequestWithoutSessionOrCsrfToken_shouldFailWith403() throws Exception { - mvc - .perform(post("/")) - .andExpect(status().isForbidden()); - } - - @Test - public void givenRequestWithInvalidCsrfToken_shouldFailWith403() throws Exception { - mvc - .perform(post("/").with(csrf().useInvalidToken())) - .andExpect(status().isForbidden()); - } - - @Test - public void givenRequestWithValidCsrfTokenAndWithoutSessionToken_shouldReceive302WithLocationHeaderToLoginPage() throws Exception { - MvcResult mvcResult = mvc.perform(post("/").with(csrf())).andReturn(); - assertTrue(mvcResult.getResponse().getStatus() == 302); - assertTrue(mvcResult.getResponse().getHeader("Location").contains("login")); - } - - @Test - public void givenValidRequestWithValidCredentials_shouldLoginSuccessfully() throws Exception { - mvc - .perform(formLogin().user("baeldung").password("baeldung")) - .andExpect(status().isFound()) - .andExpect(redirectedUrl("/")) - .andExpect(authenticated().withUsername("baeldung")); - } - - @Test - public void givenValidRequestWithInvalidCredentials_shouldFailWith401() throws Exception { - MvcResult result = mvc - .perform(formLogin().user("random").password("random")) - .andExpect(status().isUnauthorized()) - .andDo(print()) - .andExpect(unauthenticated()) - .andReturn(); - - assertTrue(result.getResponse().getContentAsString().contains("Bad credentials")); - } -} diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java new file mode 100644 index 0000000000..5eddf3883e --- /dev/null +++ b/spring-security-mvc-login/src/main/java/org/baeldung/security/CustomAuthenticationFailureHandler.java @@ -0,0 +1,22 @@ +package org.baeldung.security; + +import org.springframework.http.HttpStatus; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Calendar; + +public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler { + + @Override + public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { + httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); + + String jsonPayload = "{\"message\" : \"%s\", \"timestamp\" : \"%s\" }"; + httpServletResponse.getOutputStream().println(String.format(jsonPayload, e.getMessage(), Calendar.getInstance().getTime())); + } +} diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java index d9a43d48d0..accc7c9afd 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -1,6 +1,7 @@ package org.baeldung.spring; import org.baeldung.security.CustomAccessDeniedHandler; +import org.baeldung.security.CustomAuthenticationFailureHandler; import org.baeldung.security.CustomLogoutSuccessHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -10,6 +11,7 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; @Configuration @@ -26,11 +28,11 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(final AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.inMemoryAuthentication() - .withUser("user1").password("user1Pass").roles("USER") - .and() - .withUser("user2").password("user2Pass").roles("USER") - .and() - .withUser("admin").password("adminPass").roles("ADMIN"); + .withUser("user1").password("user1Pass").roles("USER") + .and() + .withUser("user2").password("user2Pass").roles("USER") + .and() + .withUser("admin").password("adminPass").roles("ADMIN"); // @formatter:on } @@ -38,23 +40,24 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(final HttpSecurity http) throws Exception { // @formatter:off http - .csrf().disable() - .authorizeRequests() - .antMatchers("/admin/**").hasRole("ADMIN") - .antMatchers("/anonymous*").anonymous() - .antMatchers("/login*").permitAll() - .anyRequest().authenticated() - .and() - .formLogin() - .loginPage("/login.html") - .loginProcessingUrl("/perform_login") - .defaultSuccessUrl("/homepage.html",true) - .failureUrl("/login.html?error=true") - .and() - .logout() - .logoutUrl("/perform_logout") - .deleteCookies("JSESSIONID") - .logoutSuccessHandler(logoutSuccessHandler()); + .csrf().disable() + .authorizeRequests() + .antMatchers("/admin/**").hasRole("ADMIN") + .antMatchers("/anonymous*").anonymous() + .antMatchers("/login*").permitAll() + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login.html") + .loginProcessingUrl("/perform_login") + .defaultSuccessUrl("/homepage.html", true) + //.failureUrl("/login.html?error=true") + .failureHandler(authenticationFailureHandler()) + .and() + .logout() + .logoutUrl("/perform_logout") + .deleteCookies("JSESSIONID") + .logoutSuccessHandler(logoutSuccessHandler()); //.and() //.exceptionHandling().accessDeniedPage("/accessDenied"); //.exceptionHandling().accessDeniedHandler(accessDeniedHandler()); @@ -71,4 +74,8 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { return new CustomAccessDeniedHandler(); } + @Bean + public AuthenticationFailureHandler authenticationFailureHandler() { + return new CustomAuthenticationFailureHandler(); + } } diff --git a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml index f0fa956934..189522889f 100644 --- a/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-login/src/main/resources/webSecurityConfig.xml @@ -15,20 +15,22 @@ - + - + + + diff --git a/spring-security-mvc-login/src/test/java/org/baeldung/security/FormLoginUnitTest.java b/spring-security-mvc-login/src/test/java/org/baeldung/security/FormLoginUnitTest.java new file mode 100644 index 0000000000..4b3a091e6c --- /dev/null +++ b/spring-security-mvc-login/src/test/java/org/baeldung/security/FormLoginUnitTest.java @@ -0,0 +1,63 @@ +package org.baeldung.security; + +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +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.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import javax.servlet.Filter; + +import static org.junit.Assert.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {SecSecurityConfig.class}) +@WebAppConfiguration +public class FormLoginUnitTest { + + @Autowired + private WebApplicationContext context; + + @Autowired + private Filter springSecurityFilterChain; + + private MockMvc mvc; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .addFilters(springSecurityFilterChain) + .build(); + } + + @Test + public void givenValidRequestWithValidCredentials_shouldLoginSuccessfully() throws Exception { + mvc + .perform(formLogin("/perform_login").user("user1").password("user1Pass")) + .andExpect(status().isFound()) + .andExpect(authenticated().withUsername("user1")); + } + + @Test + public void givenValidRequestWithInvalidCredentials_shouldFailWith401() throws Exception { + MvcResult result = mvc + .perform(formLogin("/perform_login").user("random").password("random")).andReturn(); + /*.andExpect(status().isUnauthorized()) + .andDo(print()) + .andExpect(unauthenticated()) + .andReturn();*/ + + assertTrue(result.getResponse().getContentAsString().contains("Bad credentials")); + } +} From 40dde25b799f03be6135c640b2e16661d5b11c59 Mon Sep 17 00:00:00 2001 From: Philippe Date: Fri, 20 Jul 2018 18:37:02 -0300 Subject: [PATCH 09/38] BAEL-1992 --- mqtt/pom.xml | 23 ++++ .../mqtt/EngineTemperatureSensor.java | 49 ++++++++ .../mqtt/EngineTemperatureSensorLiveTest.java | 108 ++++++++++++++++++ 3 files changed, 180 insertions(+) create mode 100644 mqtt/pom.xml create mode 100644 mqtt/src/main/java/com/baeldung/mqtt/EngineTemperatureSensor.java create mode 100644 mqtt/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java diff --git a/mqtt/pom.xml b/mqtt/pom.xml new file mode 100644 index 0000000000..346433aa69 --- /dev/null +++ b/mqtt/pom.xml @@ -0,0 +1,23 @@ + + 4.0.0 + org.baeldung + mqtt + 0.0.1-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.eclipse.paho + org.eclipse.paho.client.mqttv3 + 1.2.0 + + + + + diff --git a/mqtt/src/main/java/com/baeldung/mqtt/EngineTemperatureSensor.java b/mqtt/src/main/java/com/baeldung/mqtt/EngineTemperatureSensor.java new file mode 100644 index 0000000000..98111edb94 --- /dev/null +++ b/mqtt/src/main/java/com/baeldung/mqtt/EngineTemperatureSensor.java @@ -0,0 +1,49 @@ +package com.baeldung.mqtt; + +import java.util.Random; +import java.util.concurrent.Callable; + +import org.eclipse.paho.client.mqttv3.IMqttClient; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EngineTemperatureSensor implements Callable { + + private static final Logger log = LoggerFactory.getLogger(EngineTemperatureSensor.class); + public static final String TOPIC = "engine/temperature"; + + private IMqttClient client; + private Random rnd = new Random(); + + public EngineTemperatureSensor(IMqttClient client) { + this.client = client; + } + + @Override + public Void call() throws Exception { + + if ( !client.isConnected()) { + log.info("[I31] Client not connected."); + return null; + } + + MqttMessage msg = readEngineTemp(); + msg.setQos(0); + msg.setRetained(true); + client.publish(TOPIC,msg); + + return null; + } + + /** + * This method simulates reading the engine temperature + * @return + */ + private MqttMessage readEngineTemp() { + double temp = 80 + rnd.nextDouble() * 20.0; + byte[] payload = String.format("T:%04.2f",temp).getBytes(); + MqttMessage msg = new MqttMessage(payload); + return msg; + } +} \ No newline at end of file diff --git a/mqtt/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java b/mqtt/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java new file mode 100644 index 0000000000..94031b5415 --- /dev/null +++ b/mqtt/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java @@ -0,0 +1,108 @@ +package com.baeldung.mqtt; + + + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EngineTemperatureSensorLiveTest { + + private static Logger log = LoggerFactory.getLogger(EngineTemperatureSensorLiveTest.class); + + @Test + public void whenSendSingleMessage_thenSuccess() throws Exception { + + String senderId = UUID.randomUUID().toString(); + MqttClient sender = new MqttClient("tcp://iot.eclipse.org:1883",senderId); + + String receiverId = UUID.randomUUID().toString(); + MqttClient receiver = new MqttClient("tcp://iot.eclipse.org:1883",receiverId); + + + MqttConnectOptions options = new MqttConnectOptions(); + options.setAutomaticReconnect(true); + options.setCleanSession(true); + options.setConnectionTimeout(10); + + + receiver.connect(options); + sender.connect(options); + + CountDownLatch receivedSignal = new CountDownLatch(1); + + receiver.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> { + log.info("[I41] Message received: topic={}, payload={}", topic, new String(msg.getPayload())); + receivedSignal.countDown(); + }); + + + Callable target = new EngineTemperatureSensor(sender); + target.call(); + + receivedSignal.await(1, TimeUnit.MINUTES); + + log.info("[I51] Success !"); + } + + @Test + public void whenSendMultipleMessages_thenSuccess() throws Exception { + + String senderId = UUID.randomUUID().toString(); + MqttClient sender = new MqttClient("tcp://iot.eclipse.org:1883",senderId); + + String receiverId = UUID.randomUUID().toString(); + MqttClient receiver = new MqttClient("tcp://iot.eclipse.org:1883",receiverId); + + + MqttConnectOptions options = new MqttConnectOptions(); + options.setAutomaticReconnect(true); + options.setCleanSession(true); + options.setConnectionTimeout(10); + + + sender.connect(options); + receiver.connect(options); + + CountDownLatch receivedSignal = new CountDownLatch(10); + + receiver.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> { + log.info("[I41] Message received: topic={}, payload={}", topic, new String(msg.getPayload())); + receivedSignal.countDown(); + }); + + + Callable target = new EngineTemperatureSensor(sender); + + ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); + executor.scheduleAtFixedRate(() -> { + try { + target.call(); + } + catch(Exception ex) { + throw new RuntimeException(ex); + } + }, 1, 1, TimeUnit.SECONDS); + + + receivedSignal.await(1, TimeUnit.DAYS); + executor.shutdown(); + + assertTrue(receivedSignal.getCount() == 0 , "Countdown should be zero"); + + log.info("[I51] Success !"); + } + + +} From 8b5232c1b6300e3504813530b729f76ab9be5556 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 25 Jul 2018 22:53:14 +0300 Subject: [PATCH 10/38] add security exc --- .../reactive/security/SecurityConfig.java | 35 ++++++++++++------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java index cb1e7d1312..d3468f0a0f 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/security/SecurityConfig.java @@ -1,5 +1,6 @@ package com.baeldung.reactive.security; +import org.springframework.boot.actuate.autoconfigure.security.reactive.EndpointRequest; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; @@ -9,6 +10,8 @@ import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.server.SecurityWebFilterChain; +import com.baeldung.reactive.actuator.FeaturesEndpoint; + @EnableWebFluxSecurity @EnableReactiveMethodSecurity public class SecurityConfig { @@ -16,25 +19,33 @@ public class SecurityConfig { @Bean public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { return http.authorizeExchange() - .pathMatchers("/admin").hasAuthority("ROLE_ADMIN") - .anyExchange().permitAll() - .and().formLogin() - .and().build(); + .pathMatchers("/admin") + .hasAuthority("ROLE_ADMIN") + .matchers(EndpointRequest.to(FeaturesEndpoint.class)) + .permitAll() + .anyExchange() + .permitAll() + .and() + .formLogin() + .and() + .csrf() + .disable() + .build(); } @Bean public MapReactiveUserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() - .username("user") - .password("password") - .roles("USER") - .build(); + .username("user") + .password("password") + .roles("USER") + .build(); UserDetails admin = User.withDefaultPasswordEncoder() - .username("admin") - .password("password") - .roles("ADMIN") - .build(); + .username("admin") + .password("password") + .roles("ADMIN") + .build(); return new MapReactiveUserDetailsService(user, admin); } From 4ee81a2fd9f06b30b55d029ac4e4a97f2fb1c5df Mon Sep 17 00:00:00 2001 From: myluckagain Date: Thu, 26 Jul 2018 11:12:23 +0500 Subject: [PATCH 11/38] BAEL-2030 remove first element from list (#4803) --- .../RemoveFirstElementUnitTest.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java new file mode 100644 index 0000000000..09f0bb248c --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.list.removefirst; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class RemoveFirstElementUnitTest { + + private List list = new ArrayList<>(); + private LinkedList linkedList = new LinkedList<>(); + + @Before + public void init() { + + list.add("cat"); + list.add("dog"); + list.add("pig"); + list.add("cow"); + list.add("goat"); + + linkedList.add("cat"); + linkedList.add("dog"); + linkedList.add("pig"); + linkedList.add("cow"); + linkedList.add("goat"); + } + + @Test + public void givenList_whenRemoveFirst_thenRemoved() { + list.remove(0); + + assertThat(list, hasSize(4)); + assertThat(list, not(contains("cat"))); + } + + @Test + public void givenLinkedList_whenRemoveFirst_thenRemoved() { + + linkedList.removeFirst(); + + assertThat(linkedList, hasSize(4)); + assertThat(linkedList, not(contains("cat"))); + } + +} From a92283f0ddbf94af8cbcf424631df15451f239ce Mon Sep 17 00:00:00 2001 From: Sjmillington Date: Thu, 26 Jul 2018 16:19:07 +0100 Subject: [PATCH 12/38] BAEL-2042 JavaFaker unit tests --- java-faker/pom.xml | 29 +++++ .../test/java/com/baeldung/JavaFakerTest.java | 115 ++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 java-faker/pom.xml create mode 100644 java-faker/src/test/java/com/baeldung/JavaFakerTest.java diff --git a/java-faker/pom.xml b/java-faker/pom.xml new file mode 100644 index 0000000000..4ac5368e24 --- /dev/null +++ b/java-faker/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + com.baeldung + java-faker + 1.0-SNAPSHOT + + + + com.github.javafaker + javafaker + 0.15 + + + + + junit + junit + 4.12 + test + + + + + + diff --git a/java-faker/src/test/java/com/baeldung/JavaFakerTest.java b/java-faker/src/test/java/com/baeldung/JavaFakerTest.java new file mode 100644 index 0000000000..8d89fa0ab2 --- /dev/null +++ b/java-faker/src/test/java/com/baeldung/JavaFakerTest.java @@ -0,0 +1,115 @@ +package com.baeldung; + +import com.github.javafaker.Faker; +import com.github.javafaker.service.FakeValuesService; +import com.github.javafaker.service.FakerIDN; +import com.github.javafaker.service.LocaleDoesNotExistException; +import com.github.javafaker.service.RandomService; +import javafx.scene.Parent; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.Locale; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +public class JavaFakerTest { + + private Faker faker; + + @Before + public void setUp() throws Exception { + faker = new Faker(); + } + + @Test + public void givenJavaFaker_whenAddressObjectCalled_checkValidAddressInfoGiven() throws Exception { + + Faker faker = new Faker(); + + String streetName = faker.address().streetName(); + String number = faker.address().buildingNumber(); + String city = faker.address().city(); + String country = faker.address().country(); + + System.out.println(String.format("%s\n%s\n%s\n%s", + number, + streetName, + city, + country)); + + } + + @Test + public void givenJavaFakersWithSameSeed_whenNameCalled_CheckSameName() throws Exception { + + Faker faker1 = new Faker(new Random(24)); + Faker faker2 = new Faker(new Random(24)); + + assertEquals(faker1.name().firstName(), faker2.name().firstName()); + } + + @Test + public void givenJavaFakersWithDifferentLocals_checkZipCodesMatchRegex() throws Exception { + + Faker ukFaker = new Faker(new Locale("en-GB")); + Faker usFaker = new Faker(new Locale("en-US")); + + System.out.println(String.format("American zipcode: %s", usFaker.address().zipCode())); + System.out.println(String.format("British postcode: %s", ukFaker.address().zipCode())); + + Pattern ukPattern = Pattern.compile("([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\\s?[0-9][A-Za-z]{2})"); + Matcher ukMatcher = ukPattern.matcher(ukFaker.address().zipCode()); + + assertTrue(ukMatcher.find()); + + Matcher usMatcher = Pattern.compile("^\\d{5}(?:[-\\s]\\d{4})?$").matcher(usFaker.address().zipCode()); + + assertTrue(usMatcher.find()); + + } + + @Test + public void givenJavaFakerService_testFakersCreated() throws Exception { + + RandomService randomService = new RandomService(); + + System.out.println(randomService.nextBoolean()); + System.out.println(randomService.nextDouble()); + + Faker faker = new Faker(new Random(randomService.nextLong())); + + System.out.println(faker.address().city()); + + } + + @Test + public void testFakeValuesService() throws Exception { + + FakeValuesService fakeValuesService = new FakeValuesService(new Locale("en-GB"), new RandomService()); + + String email = fakeValuesService.bothify("????##@gmail.com"); + Matcher emailMatcher = Pattern.compile("\\w{4}\\d{2}@gmail.com").matcher(email); + assertTrue(emailMatcher.find()); + + String alphaNumericString = fakeValuesService.regexify("[a-z1-9]{10}"); + Matcher alphaNumericMatcher = Pattern.compile("[a-z1-9]{10}").matcher(alphaNumericString); + assertTrue(alphaNumericMatcher.find()); + + } + + + @Test(expected = LocaleDoesNotExistException.class) + public void givenWrongLocale_whenFakerIsInitialised_testLocaleDoesNotExistExceptionIsThrown() throws Exception { + + Faker wrongLocaleFaker = new Faker(new Locale("en-seaWorld")); + + } +} From 015240a99e54780f391ac3784557c3ce3a219c31 Mon Sep 17 00:00:00 2001 From: Sjmillington Date: Thu, 26 Jul 2018 19:17:51 +0100 Subject: [PATCH 13/38] Moved javafaker unit tests to testing-modules --- {java-faker => testing-modules/java-faker}/pom.xml | 0 .../java-faker}/src/test/java/com/baeldung/JavaFakerTest.java | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {java-faker => testing-modules/java-faker}/pom.xml (100%) rename {java-faker => testing-modules/java-faker}/src/test/java/com/baeldung/JavaFakerTest.java (100%) diff --git a/java-faker/pom.xml b/testing-modules/java-faker/pom.xml similarity index 100% rename from java-faker/pom.xml rename to testing-modules/java-faker/pom.xml diff --git a/java-faker/src/test/java/com/baeldung/JavaFakerTest.java b/testing-modules/java-faker/src/test/java/com/baeldung/JavaFakerTest.java similarity index 100% rename from java-faker/src/test/java/com/baeldung/JavaFakerTest.java rename to testing-modules/java-faker/src/test/java/com/baeldung/JavaFakerTest.java From 729f1efd8998d875cae64f7894fc5e0e62fded9e Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 26 Jul 2018 22:35:35 +0300 Subject: [PATCH 14/38] Update PushController.java --- .../com/baeldung/spring/controller/push/PushController.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/push/PushController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/push/PushController.java index b557c65c93..88448d4885 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/push/PushController.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/push/PushController.java @@ -11,9 +11,7 @@ public class PushController { @GetMapping(path = "/demoWithPush") public String demoWithPush(PushBuilder pushBuilder) { if (null != pushBuilder) { - pushBuilder.path("resources/logo.png") - .addHeader("Content-Type", "image/png") - .push(); + pushBuilder.path("resources/logo.png").push(); } return "demo"; } @@ -22,4 +20,4 @@ public class PushController { public String demoWithoutPush() { return "demo"; } -} \ No newline at end of file +} From 5b489423d8ca1cc785e00b26f88689b58f55a4a2 Mon Sep 17 00:00:00 2001 From: geroza Date: Tue, 24 Jul 2018 00:40:13 -0300 Subject: [PATCH 15/38] * added examples of filtering collections using Streams, Apache CollectionUtils, Guava and Eclipse Collections --- core-java-collections/pom.xml | 17 +++++++ .../CollectionUtilsCollectionFilter.java | 22 +++++++++ .../EclipseCollectionsCollectionFilter.java | 32 +++++++++++++ .../java/filtering/GuavaCollectionFilter.java | 22 +++++++++ .../filtering/StreamsCollectionFilter.java | 37 +++++++++++++++ .../filtering/CollectionFiltersUnitTest.java | 46 +++++++++++++++++++ 6 files changed, 176 insertions(+) create mode 100644 core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java create mode 100644 core-java-collections/src/main/java/com/baeldung/java/filtering/EclipseCollectionsCollectionFilter.java create mode 100644 core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java create mode 100644 core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java create mode 100644 core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml index a5aea49c14..d63f4d2a45 100644 --- a/core-java-collections/pom.xml +++ b/core-java-collections/pom.xml @@ -36,15 +36,32 @@ commons-lang3 ${commons-lang3.version} + + org.eclipse.collections + eclipse-collections-api + 9.2.0 + + + org.eclipse.collections + eclipse-collections + 9.2.0 + org.assertj assertj-core ${assertj.version} test + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + 1.2.0 3.5 4.1 4.01 diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java new file mode 100644 index 0000000000..4d6a3d62fd --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java @@ -0,0 +1,22 @@ +package com.baeldung.java.filtering; + +import java.util.Collection; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.Predicate; + +public class CollectionUtilsCollectionFilter { + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate apacheEventNumberPredicate = new Predicate() { + + @Override + public boolean evaluate(Integer object) { + return object % 2 == 0; + } + }; + + CollectionUtils.filter(baseCollection, apacheEventNumberPredicate); + return baseCollection; + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/EclipseCollectionsCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/EclipseCollectionsCollectionFilter.java new file mode 100644 index 0000000000..981d6ca241 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/EclipseCollectionsCollectionFilter.java @@ -0,0 +1,32 @@ +package com.baeldung.java.filtering; + +import java.util.Collection; + +import org.eclipse.collections.api.block.predicate.Predicate; +import org.eclipse.collections.impl.factory.Lists; +import org.eclipse.collections.impl.utility.Iterate; + +public class EclipseCollectionsCollectionFilter { + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate eclipsePredicate = item -> item % 2 == 0; + Collection filteredList = Lists.mutable.ofAll(baseCollection) + .select(eclipsePredicate); + + return filteredList; + } + + static public Collection findEvenNumbersUsingIterate(Collection baseCollection) { + Predicate eclipsePredicate = new Predicate() { + private static final long serialVersionUID = 1L; + + @Override + public boolean accept(Integer arg0) { + return arg0 % 2 == 0; + } + }; + Collection filteredList = Iterate.select(baseCollection, eclipsePredicate); + + return filteredList; + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java new file mode 100644 index 0000000000..f5a27f0bdb --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java @@ -0,0 +1,22 @@ +package com.baeldung.java.filtering; + +import java.util.Collection; + +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; + +public class GuavaCollectionFilter { + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate guavaPredicate = new Predicate() { + + @Override + public boolean apply(Integer input) { + return input % 2 == 0; + } + }; + Collection filteredCollection = Collections2.filter(baseCollection, guavaPredicate); + return filteredCollection; + } + +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java new file mode 100644 index 0000000000..d51283de55 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java @@ -0,0 +1,37 @@ +package com.baeldung.java.filtering; + +import java.util.Collection; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +public class StreamsCollectionFilter { + + public static Collection filterCollectionHelperMethod(Collection baseCollection, Predicate predicate) { + return baseCollection.stream() + .filter(predicate) + .collect(Collectors.toList()); + } + + static public Collection findEvenNumbersUsingHelperMethod(Collection baseCollection) { + return filterCollectionHelperMethod(baseCollection, item -> item % 2 == 0); + } + + static public Collection findEvenNumbersUsingLambda(Collection baseCollection) { + return baseCollection.stream() + .filter(item -> item % 2 == 0) + .collect(Collectors.toList()); + } + + static public Collection findEvenNumbersUsingPredicate(Collection baseCollection) { + Predicate evenNumberPredicate = new Predicate() { + @Override + public boolean test(Integer i) { + return i % 2 == 0; + } + }; + + return baseCollection.stream() + .filter(evenNumberPredicate) + .collect(Collectors.toList()); + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java new file mode 100644 index 0000000000..c85b7a526d --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.java.filtering; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +public class CollectionFiltersUnitTest { + + private static final Collection BASE_INTEGER_COLLECTION = Arrays.asList(9, 14, 2, 7, 1, 5, 8); + private static final Collection EXPECTED_EVEN_FILTERED_COLLECTION = Arrays.asList(14, 2, 8); + + @Test + public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() { + final Collection baseStrings = Arrays.asList("java", "baeldung", "type", "example", "other"); + + Collection filtered = StreamsCollectionFilter.filterCollectionHelperMethod(baseStrings, item -> item.length() == 4); + + assertThat(filtered).containsExactlyInAnyOrder("java", "type"); + } + + @Test + public void givenAnIntegerCollection_whenFilteringEvenValues_thenObtainTheFilteredCollectionForAllCases() { + Collection filteredWithStreams1 = StreamsCollectionFilter.findEvenNumbersUsingLambda(BASE_INTEGER_COLLECTION); + Collection filteredWithStreams2 = StreamsCollectionFilter.findEvenNumbersUsingPredicate(BASE_INTEGER_COLLECTION); + Collection filteredWithCollectionUtils = CollectionUtilsCollectionFilter.findEvenNumbers(new ArrayList<>(BASE_INTEGER_COLLECTION)); + Collection filteredWithEclipseCollections = EclipseCollectionsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); + Collection filteredWithEclipseCollectionsUsingIterate = EclipseCollectionsCollectionFilter.findEvenNumbersUsingIterate(BASE_INTEGER_COLLECTION); + Collection filteredWithGuava = GuavaCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); + + assertThat(filteredWithStreams1).hasSameElementsAs(filteredWithStreams2) + .hasSameElementsAs(filteredWithCollectionUtils) + .hasSameElementsAs(filteredWithEclipseCollections) + .hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate) + .hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate) + .hasSameElementsAs(filteredWithGuava) + .hasSameElementsAs(EXPECTED_EVEN_FILTERED_COLLECTION); + } + +} From 6b2fb615a746b979a1c08b85793fa29f9996edf8 Mon Sep 17 00:00:00 2001 From: geroza Date: Wed, 25 Jul 2018 11:41:51 -0300 Subject: [PATCH 16/38] * Added examples for java-9 filtering collector --- core-java-9/pom.xml | 14 +++++ .../StreamsGroupingCollectionFilter.java | 27 ++++++++++ .../stream/CollectionFilterUnitTest.java | 53 +++++++++++++++++++ 3 files changed, 94 insertions(+) create mode 100644 core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java create mode 100644 core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml index 4ba06f7c0d..f22d0a3ed9 100644 --- a/core-java-9/pom.xml +++ b/core-java-9/pom.xml @@ -19,11 +19,23 @@ ${awaitility.version} test + + org.assertj + assertj-core + ${assertj.version} + test + com.google.guava guava ${guava.version} + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + @@ -50,6 +62,8 @@ + 3.10.0 + 1.2.0 1.7.0 1.9 1.9 diff --git a/core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java b/core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java new file mode 100644 index 0000000000..84d2e63c6c --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java @@ -0,0 +1,27 @@ +package com.baeldung.java9.language.stream; + +import static java.util.stream.Collectors.filtering; +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.toList; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +public class StreamsGroupingCollectionFilter { + + static public Map> findEvenNumbersAfterGroupingByQuantityOfDigits(Collection baseCollection) { + Function getQuantityOfDigits = item -> (int) Math.log10(item) + 1; + + return baseCollection.stream() + .collect(groupingBy(getQuantityOfDigits, filtering(item -> item % 2 == 0, toList()))); + } + + static public Map> findEvenNumbersBeforeGroupingByQuantityOfDigits(Collection baseCollection) { + + return baseCollection.stream() + .filter(item -> item % 2 == 0) + .collect(groupingBy(item -> (int) Math.log10(item) + 1, toList())); + } +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java new file mode 100644 index 0000000000..0a6424fa81 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.java9.language.stream; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +public class CollectionFilterUnitTest { + + private static final Collection BASE_INTEGER_COLLECTION = Arrays.asList(9, 12, 55, 56, 101, 115, 8002, 223, 2668, 19, 8); + private static final Map> EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP = createExpectedFilterAfterGroupingMap(); + + private static Map> createExpectedFilterAfterGroupingMap() { + Map> map = new HashMap<>(); + map.put(1, Arrays.asList(8)); + map.put(2, Arrays.asList(12, 56)); + map.put(3, Collections.emptyList()); + map.put(4, Arrays.asList(8002, 2668)); + return map; + + } + + private static final Map> EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP = createExpectedFilterBeforeGroupingMap(); + + private static Map> createExpectedFilterBeforeGroupingMap() { + Map> map = new HashMap<>(); + map.put(1, Arrays.asList(8)); + map.put(2, Arrays.asList(12, 56)); + map.put(4, Arrays.asList(8002, 2668)); + return map; + + } + + @Test + public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() { + Map> filteredAfterGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersAfterGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION); + Map> filteredBeforeGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersBeforeGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION); + + assertThat(filteredAfterGroupingMap).containsAllEntriesOf(EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP); + assertThat(filteredBeforeGroupingMap).doesNotContainKey(3) + .containsAllEntriesOf(EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP); + } + +} From 81027b7fbd3f67e4809d29e6b8218653c23ca12d Mon Sep 17 00:00:00 2001 From: geroza Date: Wed, 25 Jul 2018 17:36:17 -0300 Subject: [PATCH 17/38] * minor fixes and cleaning duties --- .../stream/CollectionFilterUnitTest.java | 2 -- core-java-collections/pom.xml | 5 +++-- .../CollectionUtilsCollectionFilter.java | 8 +------- .../java/filtering/GuavaCollectionFilter.java | 7 +------ .../java/filtering/StreamsCollectionFilter.java | 17 +++-------------- .../filtering/CollectionFiltersUnitTest.java | 6 ++---- 6 files changed, 10 insertions(+), 35 deletions(-) diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java index 0a6424fa81..1b9315678a 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java @@ -18,7 +18,6 @@ public class CollectionFilterUnitTest { private static final Collection BASE_INTEGER_COLLECTION = Arrays.asList(9, 12, 55, 56, 101, 115, 8002, 223, 2668, 19, 8); private static final Map> EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP = createExpectedFilterAfterGroupingMap(); - private static Map> createExpectedFilterAfterGroupingMap() { Map> map = new HashMap<>(); map.put(1, Arrays.asList(8)); @@ -30,7 +29,6 @@ public class CollectionFilterUnitTest { } private static final Map> EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP = createExpectedFilterBeforeGroupingMap(); - private static Map> createExpectedFilterBeforeGroupingMap() { Map> map = new HashMap<>(); map.put(1, Arrays.asList(8)); diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml index d63f4d2a45..ff06714bfe 100644 --- a/core-java-collections/pom.xml +++ b/core-java-collections/pom.xml @@ -39,12 +39,12 @@ org.eclipse.collections eclipse-collections-api - 9.2.0 + ${eclipse.collections.version} org.eclipse.collections eclipse-collections - 9.2.0 + ${eclipse.collections.version} org.assertj @@ -67,5 +67,6 @@ 4.01 1.7.0 3.6.1 + 9.2.0 diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java index 4d6a3d62fd..58f9f6af54 100644 --- a/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/CollectionUtilsCollectionFilter.java @@ -8,13 +8,7 @@ import org.apache.commons.collections4.Predicate; public class CollectionUtilsCollectionFilter { static public Collection findEvenNumbers(Collection baseCollection) { - Predicate apacheEventNumberPredicate = new Predicate() { - - @Override - public boolean evaluate(Integer object) { - return object % 2 == 0; - } - }; + Predicate apacheEventNumberPredicate = item -> item % 2 == 0; CollectionUtils.filter(baseCollection, apacheEventNumberPredicate); return baseCollection; diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java index f5a27f0bdb..88338fd6d4 100644 --- a/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/GuavaCollectionFilter.java @@ -8,13 +8,8 @@ import com.google.common.collect.Collections2; public class GuavaCollectionFilter { static public Collection findEvenNumbers(Collection baseCollection) { - Predicate guavaPredicate = new Predicate() { + Predicate guavaPredicate = item -> item % 2 == 0; - @Override - public boolean apply(Integer input) { - return input % 2 == 0; - } - }; Collection filteredCollection = Collections2.filter(baseCollection, guavaPredicate); return filteredCollection; } diff --git a/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java b/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java index d51283de55..f074f74199 100644 --- a/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java +++ b/core-java-collections/src/main/java/com/baeldung/java/filtering/StreamsCollectionFilter.java @@ -16,22 +16,11 @@ public class StreamsCollectionFilter { return filterCollectionHelperMethod(baseCollection, item -> item % 2 == 0); } - static public Collection findEvenNumbersUsingLambda(Collection baseCollection) { - return baseCollection.stream() - .filter(item -> item % 2 == 0) - .collect(Collectors.toList()); - } - - static public Collection findEvenNumbersUsingPredicate(Collection baseCollection) { - Predicate evenNumberPredicate = new Predicate() { - @Override - public boolean test(Integer i) { - return i % 2 == 0; - } - }; + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate streamsPredicate = item -> item % 2 == 0; return baseCollection.stream() - .filter(evenNumberPredicate) + .filter(streamsPredicate) .collect(Collectors.toList()); } } diff --git a/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java index c85b7a526d..b30805d471 100644 --- a/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/java/filtering/CollectionFiltersUnitTest.java @@ -27,15 +27,13 @@ public class CollectionFiltersUnitTest { @Test public void givenAnIntegerCollection_whenFilteringEvenValues_thenObtainTheFilteredCollectionForAllCases() { - Collection filteredWithStreams1 = StreamsCollectionFilter.findEvenNumbersUsingLambda(BASE_INTEGER_COLLECTION); - Collection filteredWithStreams2 = StreamsCollectionFilter.findEvenNumbersUsingPredicate(BASE_INTEGER_COLLECTION); + Collection filteredWithStreams1 = StreamsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); Collection filteredWithCollectionUtils = CollectionUtilsCollectionFilter.findEvenNumbers(new ArrayList<>(BASE_INTEGER_COLLECTION)); Collection filteredWithEclipseCollections = EclipseCollectionsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); Collection filteredWithEclipseCollectionsUsingIterate = EclipseCollectionsCollectionFilter.findEvenNumbersUsingIterate(BASE_INTEGER_COLLECTION); Collection filteredWithGuava = GuavaCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); - assertThat(filteredWithStreams1).hasSameElementsAs(filteredWithStreams2) - .hasSameElementsAs(filteredWithCollectionUtils) + assertThat(filteredWithStreams1).hasSameElementsAs(filteredWithCollectionUtils) .hasSameElementsAs(filteredWithEclipseCollections) .hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate) .hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate) From a1ba371c73f10635ce02939db16ad9bba7978940 Mon Sep 17 00:00:00 2001 From: Felipe Santiago Corro Date: Thu, 26 Jul 2018 17:19:03 -0300 Subject: [PATCH 18/38] add elements to list (#4814) --- .../baeldung/list/AddElementsUnitTest.java | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java b/core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java new file mode 100644 index 0000000000..93c28812bd --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.list; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.*; + +import static org.junit.Assert.*; + +public class AddElementsUnitTest { + + List flowers; + + @Before + public void init() { + this.flowers = new ArrayList<>(Arrays.asList( + new Flower("Poppy", 12), + new Flower("Anemone", 8), + new Flower("Catmint", 12))); + } + + @Test + public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() { + List anotherList = new ArrayList<>(); + anotherList.addAll(flowers); + + assertEquals(anotherList.size(), flowers.size()); + Assert.assertTrue(anotherList.containsAll(flowers)); + } + + @Test + public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() { + List anotherList = new ArrayList<>(); + anotherList.addAll(flowers); + + Flower flower = anotherList.get(0); + flower.setPetals(flowers.get(0).getPetals() * 3); + + assertEquals(anotherList.size(), flowers.size()); + Assert.assertTrue(anotherList.containsAll(flowers)); + } + + @Test + public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() { + List target = new ArrayList<>(); + + Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0)); + + assertEquals(target.size(), 4); + } + + @Test + public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() { + List flowerVase = new ArrayList<>(); + + flowers.stream() + .skip(1) + .forEachOrdered(flowerVase::add); + + assertEquals(flowerVase.size() + 1, flowers.size()); + assertFalse(flowerVase.containsAll(flowers)); + } + + @Test + public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() { + List flowerVase = new ArrayList<>(); + + flowers.stream() + .filter(f -> f.getPetals() > 10) + .forEachOrdered(flowerVase::add); + + assertEquals(flowerVase.size() + 1, flowers.size()); + assertFalse(flowerVase.containsAll(flowers)); + } + + @Test + public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() { + List target = new ArrayList<>(); + + Optional.ofNullable(flowers) + .ifPresent(target::addAll); + + assertNotNull(target); + assertEquals(target.size(), 3); + } +} From 7070f25400c070ec499461a795b424b802665047 Mon Sep 17 00:00:00 2001 From: Shreyash Date: Fri, 27 Jul 2018 02:27:19 +0530 Subject: [PATCH 19/38] BAEL-1960: Custom appender for log4j (#4731) * BAEL-1960: Custom appender for log4j * Changes as per suggestion to BAEL-1960 * Changes as [er review for BAEL-1960 * Changes for formatting as per suggestion. * BAEL-1960. Copied pom.xml from master and pasted my changes against it. * Chnages for spaces instead of tabs. * Changes for spaces instead of tabs. --- logging-modules/log4j2/pom.xml | 9 +++- .../logging/log4j2/appender/MapAppender.java | 54 +++++++++++++++++++ .../appender/MapAppenderIntegrationTest.java | 35 ++++++++++++ .../log4j2/src/test/resources/log4j2.xml | 6 ++- 4 files changed, 101 insertions(+), 3 deletions(-) create mode 100644 logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/appender/MapAppender.java create mode 100644 logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java diff --git a/logging-modules/log4j2/pom.xml b/logging-modules/log4j2/pom.xml index 89d37e789c..65da318636 100644 --- a/logging-modules/log4j2/pom.xml +++ b/logging-modules/log4j2/pom.xml @@ -18,6 +18,13 @@ log4j-core ${log4j-core.version} + + + + org.apache.logging.log4j + log4j-api + ${log4j-core.version} + @@ -114,4 +121,4 @@ yyyyMMddHHmmss - + \ No newline at end of file diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/appender/MapAppender.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/appender/MapAppender.java new file mode 100644 index 0000000000..2015b6d573 --- /dev/null +++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/appender/MapAppender.java @@ -0,0 +1,54 @@ +/** + * + */ +package com.baeldung.logging.log4j2.appender; + +import java.time.Instant; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.Core; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginAttribute; +import org.apache.logging.log4j.core.config.plugins.PluginElement; +import org.apache.logging.log4j.core.config.plugins.PluginFactory; + +@Plugin(name = "MapAppender", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE) +public class MapAppender extends AbstractAppender { + + private ConcurrentMap eventMap = new ConcurrentHashMap<>(); + + protected MapAppender(String name, Filter filter) { + super(name, filter, null); + } + + @PluginFactory + public static MapAppender createAppender(@PluginAttribute("name") String name, @PluginElement("Filter") final Filter filter) { + return new MapAppender(name, filter); + } + + @Override + public void append(LogEvent event) { + if (event.getLevel() + .isLessSpecificThan(Level.WARN)) { + error("Unable to log less than WARN level."); + return; + } + eventMap.put(Instant.now() + .toString(), event); + } + + public ConcurrentMap getEventMap() { + return eventMap; + } + + public void setEventMap(ConcurrentMap eventMap) { + this.eventMap = eventMap; + } + +} diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java new file mode 100644 index 0000000000..020aaafc74 --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.logging.log4j2.appender; + +import static org.junit.Assert.assertEquals; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.Configuration; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class MapAppenderIntegrationTest { + + private Logger logger; + + @Before + public void setup() { + logger = LogManager.getLogger(MapAppenderIntegrationTest.class); + } + + @Test + public void whenLoggerEmitsLoggingEvent_thenAppenderReceivesEvent() throws Exception { + logger.info("Test from {}", this.getClass() + .getSimpleName()); + LoggerContext context = LoggerContext.getContext(false); + Configuration config = context.getConfiguration(); + MapAppender appender = config.getAppender("MapAppender"); + assertEquals(appender.getEventMap() + .size(), 1); + } + +} diff --git a/logging-modules/log4j2/src/test/resources/log4j2.xml b/logging-modules/log4j2/src/test/resources/log4j2.xml index 83b664a507..246ffb0707 100644 --- a/logging-modules/log4j2/src/test/resources/log4j2.xml +++ b/logging-modules/log4j2/src/test/resources/log4j2.xml @@ -1,6 +1,6 @@ - + @@ -50,6 +50,7 @@ size="17 kB" /> + + \ No newline at end of file From 2a773d637cb456908990a7aec1c0b7eedf24d62a Mon Sep 17 00:00:00 2001 From: db Date: Fri, 27 Jul 2018 02:33:14 +0100 Subject: [PATCH 20/38] PrincipalExtractor and AuthoritiesExtractor example --- spring-security-sso/pom.xml | 1 + .../pom.xml | 53 +++++++++++++++++++ .../main/java/org/baeldung/Application.java | 18 +++++++ .../configuration/SecurityConfig.java | 38 +++++++++++++ .../extractor/CustomAuthoritiesExtractor.java | 27 ++++++++++ .../extractor/CustomPrincipalExtractor.java | 13 +++++ .../src/main/resources/application.yml | 14 +++++ .../src/main/resources/templates/index.html | 21 ++++++++ .../src/test/java/ApplicationUnitTest.java | 53 +++++++++++++++++++ 9 files changed, 238 insertions(+) create mode 100644 spring-security-sso/spring-security-principal-authorities-extractor/pom.xml create mode 100644 spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/Application.java create mode 100644 spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/configuration/SecurityConfig.java create mode 100644 spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomAuthoritiesExtractor.java create mode 100644 spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomPrincipalExtractor.java create mode 100644 spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/application.yml create mode 100644 spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/templates/index.html create mode 100644 spring-security-sso/spring-security-principal-authorities-extractor/src/test/java/ApplicationUnitTest.java diff --git a/spring-security-sso/pom.xml b/spring-security-sso/pom.xml index 764e899640..0cf468c2e3 100644 --- a/spring-security-sso/pom.xml +++ b/spring-security-sso/pom.xml @@ -19,6 +19,7 @@ spring-security-sso-auth-server spring-security-sso-ui spring-security-sso-ui-2 + spring-security-principal-authorities-extractor diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/pom.xml b/spring-security-sso/spring-security-principal-authorities-extractor/pom.xml new file mode 100644 index 0000000000..5bd8de9c16 --- /dev/null +++ b/spring-security-sso/spring-security-principal-authorities-extractor/pom.xml @@ -0,0 +1,53 @@ + + + + spring-security-sso + org.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + spring-security-principal-authorities-extractor + + + + org.springframework.boot + spring-boot-starter-security + + + + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure + ${oauth-auto.version} + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity4 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.security + spring-security-test + test + + + \ No newline at end of file diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/Application.java b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/Application.java new file mode 100644 index 0000000000..0dfbbef86e --- /dev/null +++ b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/Application.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +@SpringBootApplication +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @GetMapping("/") + public String homePage(Model model) { + return "index"; + } +} diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/configuration/SecurityConfig.java b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/configuration/SecurityConfig.java new file mode 100644 index 0000000000..4de1932392 --- /dev/null +++ b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/configuration/SecurityConfig.java @@ -0,0 +1,38 @@ +package org.baeldung.configuration; + +import org.baeldung.extractor.CustomAuthoritiesExtractor; +import org.baeldung.extractor.CustomPrincipalExtractor; +import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; +import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor; +import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableOAuth2Sso +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/login**") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin().disable(); + } + + @Bean + public PrincipalExtractor principalExtractor() { + return new CustomPrincipalExtractor(); + } + + @Bean + public AuthoritiesExtractor authoritiesExtractor() { + return new CustomAuthoritiesExtractor(); + } +} diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomAuthoritiesExtractor.java b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomAuthoritiesExtractor.java new file mode 100644 index 0000000000..c1a78634aa --- /dev/null +++ b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomAuthoritiesExtractor.java @@ -0,0 +1,27 @@ +package org.baeldung.extractor; + +import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.AuthorityUtils; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +public class CustomAuthoritiesExtractor implements AuthoritiesExtractor { + private static final List GITHUB_FREE_AUTHORITIES = AuthorityUtils.commaSeparatedStringToAuthorityList("GITHUB_USER,GITHUB_USER_FREE"); + private static final List GITHUB_SUBSCRIBED_AUTHORITIES = AuthorityUtils.commaSeparatedStringToAuthorityList("GITHUB_USER,GITHUB_USER_SUBSCRIBED"); + + @Override + public List extractAuthorities(Map map) { + if (Objects.nonNull(map.get("plan"))) { + if (!((LinkedHashMap) map.get("plan")) + .get("name") + .equals("free")) { + return GITHUB_SUBSCRIBED_AUTHORITIES; + } + } + return GITHUB_FREE_AUTHORITIES; + } +} diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomPrincipalExtractor.java b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomPrincipalExtractor.java new file mode 100644 index 0000000000..d356c07e3b --- /dev/null +++ b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomPrincipalExtractor.java @@ -0,0 +1,13 @@ +package org.baeldung.extractor; + +import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor; + +import java.util.Map; + +public class CustomPrincipalExtractor implements PrincipalExtractor { + + @Override + public Object extractPrincipal(Map map) { + return map.get("login"); + } +} diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/application.yml b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/application.yml new file mode 100644 index 0000000000..324df694df --- /dev/null +++ b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/application.yml @@ -0,0 +1,14 @@ +security: + oauth2: + client: + clientId: 89a7c4facbb3434d599d + clientSecret: 9b3b08e4a340bd20e866787e4645b54f73d74b6a + accessTokenUri: https://github.com/login/oauth/access_token + userAuthorizationUri: https://github.com/login/oauth/authorize + clientAuthenticationScheme: form + scope: read:user,user:email + resource: + userInfoUri: https://api.github.com/user +spring: + thymeleaf: + cache: false \ No newline at end of file diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/templates/index.html b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/templates/index.html new file mode 100644 index 0000000000..414dd54a42 --- /dev/null +++ b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/templates/index.html @@ -0,0 +1,21 @@ + + + + + Spring Security Principal and Authorities extractor + + + + +
+
+

Secured Page

+ Authenticated username: +
+ Authorities: +
+
+
+ + \ No newline at end of file diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/test/java/ApplicationUnitTest.java b/spring-security-sso/spring-security-principal-authorities-extractor/src/test/java/ApplicationUnitTest.java new file mode 100644 index 0000000000..c14cbc9866 --- /dev/null +++ b/spring-security-sso/spring-security-principal-authorities-extractor/src/test/java/ApplicationUnitTest.java @@ -0,0 +1,53 @@ +import org.baeldung.Application; +import org.baeldung.configuration.SecurityConfig; +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.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import javax.servlet.Filter; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ContextConfiguration(classes = {SecurityConfig.class}) +public class ApplicationUnitTest { + + @Autowired + private WebApplicationContext context; + + @Autowired + private Filter springSecurityFilterChain; + + private MockMvc mvc; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .addFilters(springSecurityFilterChain) + .build(); + } + + @Test + public void contextLoads() throws Exception { + } + + @Test + public void givenValidRequestWithoutAuthentication_shouldFailWith302() throws Exception { + mvc + .perform(get("/")) + .andExpect(status().isFound()) + .andReturn(); + } + +} From ffbeb78ee1b6d7899a33f18dc9adc9ae03d6bcb4 Mon Sep 17 00:00:00 2001 From: Mher Baghinyan Date: Fri, 27 Jul 2018 21:00:13 +0400 Subject: [PATCH 21/38] Bael 1743 improved (#4826) * compile only for firefox * added parent module * changed artifact id --- google-web-toolkit/pom.xml | 8 +++++++- .../src/main/java/com/baeldung/Google_web_toolkit.gwt.xml | 2 ++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml index e392ce4e8c..b2f7cab355 100644 --- a/google-web-toolkit/pom.xml +++ b/google-web-toolkit/pom.xml @@ -6,10 +6,16 @@ 4.0.0 com.baeldung - google-web-toolkit + google_web_toolkit war 1.0-SNAPSHOT + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + diff --git a/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml b/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml index 1d8ca819d9..9bd74ccb50 100644 --- a/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml +++ b/google-web-toolkit/src/main/java/com/baeldung/Google_web_toolkit.gwt.xml @@ -22,6 +22,8 @@ + + From 0a1e10b128551eb0a5b459893d443cc3b28c6818 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Fri, 27 Jul 2018 22:56:18 +0300 Subject: [PATCH 22/38] commenting out problematic modules in the integration-lite build --- pom.xml | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/pom.xml b/pom.xml index 06ec82e5f0..7386eed4a6 100644 --- a/pom.xml +++ b/pom.xml @@ -906,7 +906,7 @@ linkrest logging-modules/log-mdc logging-modules/log4j - logging-modules/log4j2 + logging-modules/logback lombok mapstruct @@ -962,19 +962,19 @@ spring-cucumber spring-ejb spring-aop - spring-data-couchbase-2 + persistence-modules/spring-data-dynamodb spring-data-keyvalue spring-data-mongodb persistence-modules/spring-data-neo4j - persistence-modules/spring-data-redis + spring-data-rest persistence-modules/spring-data-solr spring-dispatcher-servlet spring-exceptions spring-freemarker persistence-modules/spring-hibernate-3 - spring-hibernate4 + persistence-modules/spring-hibernate-5 persistence-modules/spring-data-eclipselink spring-integration @@ -1041,13 +1041,13 @@ testing-modules/testing testing-modules/testng video-tutorials - xml + xmlunit-2 struts-2 apache-velocity apache-solrj rabbitmq - vertx + persistence-modules/spring-data-gemfire mybatis spring-drools @@ -1082,6 +1082,13 @@ ejb persistence-modules/java-cassandra persistence-modules/spring-data-cassandra + logging-modules/log4j2 + spring-data-couchbase-2 + persistence-modules/spring-data-redis + spring-hibernate4 + xml + vertx + --> From 738e3af007bbf81bbe3432e69975283f86b8242f Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Fri, 27 Jul 2018 23:32:13 +0300 Subject: [PATCH 23/38] integratio-lite profile work --- pom.xml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 7386eed4a6..2fea45e612 100644 --- a/pom.xml +++ b/pom.xml @@ -877,7 +877,7 @@ spring-static-resources hazelcast hbase - httpclient + hystrix image-processing immutables @@ -910,7 +910,7 @@ logging-modules/logback lombok mapstruct - metrics + maven mesos-marathon msf4j @@ -1088,7 +1088,8 @@ spring-hibernate4 xml vertx - + metrics + httpclient --> From 25fb0c94c281d2e8119ff7a38a66aae3088b49c0 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sat, 28 Jul 2018 00:17:37 +0300 Subject: [PATCH 24/38] integration-lite work --- pom.xml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2fea45e612..263e4df637 100644 --- a/pom.xml +++ b/pom.xml @@ -980,7 +980,7 @@ spring-integration spring-jenkins-pipeline spring-jersey - jmeter + spring-jms spring-jooq persistence-modules/spring-jpa @@ -1090,6 +1090,8 @@ vertx metrics httpclient + + jmeter --> From fc02400f5f01084a82ba39a851e053dad946c49a Mon Sep 17 00:00:00 2001 From: Alejandro Gervasio Date: Sat, 28 Jul 2018 03:44:51 -0300 Subject: [PATCH 25/38] BAEL-1818 A Simple Guide to Connection Pooling in Java (#4823) * Initial Commit * Update parent pom.xml * Update BasicConnectionPool class * Update BasicConnectionPool class * BAEL-1818 removed code from core-java module, cleaned up a little pom files * BAEL-1818 moved the code from connectionpool.connectionpools package to connectionpool --- core-java-persistence/pom.xml | 59 ++++++ .../connectionpool}/BasicConnectionPool.java | 177 +++++++++--------- .../connectionpool}/C3poDataSource.java | 54 +++--- .../connectionpool}/ConnectionPool.java | 40 ++-- .../connectionpool}/DBCPDataSource.java | 50 ++--- .../connectionpool}/HikariCPDataSource.java | 56 +++--- .../BasicConnectionPoolUnitTest.java | 4 +- .../C3poDataSourceUnitTest.java | 1 - .../DBCPDataSourceUnitTest.java | 1 - .../HikariCPDataSourceUnitTest.java | 1 - core-java/pom.xml | 20 -- pom.xml | 25 ++- 12 files changed, 267 insertions(+), 221 deletions(-) create mode 100644 core-java-persistence/pom.xml rename {core-java/src/main/java/com/baeldung/connectionpool/connectionpools => core-java-persistence/src/main/java/com/baeldung/connectionpool}/BasicConnectionPool.java (93%) rename {core-java/src/main/java/com/baeldung/connectionpool/connectionpools => core-java-persistence/src/main/java/com/baeldung/connectionpool}/C3poDataSource.java (89%) rename {core-java/src/main/java/com/baeldung/connectionpool/connectionpools => core-java-persistence/src/main/java/com/baeldung/connectionpool}/ConnectionPool.java (66%) rename {core-java/src/main/java/com/baeldung/connectionpool/connectionpools => core-java-persistence/src/main/java/com/baeldung/connectionpool}/DBCPDataSource.java (88%) rename {core-java/src/main/java/com/baeldung/connectionpool/connectionpools => core-java-persistence/src/main/java/com/baeldung/connectionpool}/HikariCPDataSource.java (91%) rename {core-java => core-java-persistence}/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java (91%) rename {core-java => core-java-persistence}/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java (81%) rename {core-java => core-java-persistence}/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java (81%) rename {core-java => core-java-persistence}/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java (81%) diff --git a/core-java-persistence/pom.xml b/core-java-persistence/pom.xml new file mode 100644 index 0000000000..0cb142c7b8 --- /dev/null +++ b/core-java-persistence/pom.xml @@ -0,0 +1,59 @@ + + 4.0.0 + com.baeldung.core-java-persistence + core-java-persistence + 0.1.0-SNAPSHOT + jar + core-java-persistence + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2database.version} + + + org.apache.commons + commons-dbcp2 + ${commons-dbcp2.version} + + + com.zaxxer + HikariCP + ${HikariCP.version} + + + com.mchange + c3p0 + ${c3p0.version} + + + + core-java-persistence + + + src/main/resources + true + + + + + 3.10.0 + 1.4.197 + 2.4.0 + 3.2.0 + 0.9.5.2 + + \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/BasicConnectionPool.java similarity index 93% rename from core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java rename to core-java-persistence/src/main/java/com/baeldung/connectionpool/BasicConnectionPool.java index 1934d0cfc2..289db18c53 100644 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/BasicConnectionPool.java +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/BasicConnectionPool.java @@ -1,85 +1,92 @@ -package com.baeldung.connectionpool.connectionpools; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -public class BasicConnectionPool implements ConnectionPool { - - private final String url; - private final String user; - private final String password; - private final List connectionPool; - private final List usedConnections = new ArrayList<>(); - private static final int INITIAL_POOL_SIZE = 10; - private final int MAX_POOL_SIZE = 20; - - public static BasicConnectionPool create(String url, String user, String password) throws SQLException { - List pool = new ArrayList<>(INITIAL_POOL_SIZE); - for (int i = 0; i < INITIAL_POOL_SIZE; i++) { - pool.add(createConnection(url, user, password)); - } - return new BasicConnectionPool(url, user, password, pool); - } - - private BasicConnectionPool(String url, String user, String password, List connectionPool) { - this.url = url; - this.user = user; - this.password = password; - this.connectionPool = connectionPool; - } - - @Override - public Connection getConnection() throws SQLException { - if (connectionPool.isEmpty()) { - if (usedConnections.size() < MAX_POOL_SIZE) { - connectionPool.add(createConnection(url, user, password)); - } else { - throw new RuntimeException("Maximum pool size reached, no available connections!"); - } - } - - Connection connection = connectionPool.remove(connectionPool.size() - 1); - usedConnections.add(connection); - return connection; - } - - @Override - public boolean releaseConnection(Connection connection) { - connectionPool.add(connection); - return usedConnections.remove(connection); - } - - private static Connection createConnection(String url, String user, String password) throws SQLException { - return DriverManager.getConnection(url, user, password); - } - - public int getSize() { - return connectionPool.size() + usedConnections.size(); - } - - @Override - public String getUrl() { - return url; - } - - @Override - public String getUser() { - return user; - } - - @Override - public String getPassword() { - return password; - } - - public void shutdown() throws SQLException { - usedConnections.forEach(this::releaseConnection); - for (Connection c : connectionPool) { - c.close(); - } - connectionPool.clear(); - } -} +package com.baeldung.connectionpool; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class BasicConnectionPool implements ConnectionPool { + + private final String url; + private final String user; + private final String password; + private final List connectionPool; + private final List usedConnections = new ArrayList<>(); + private static final int INITIAL_POOL_SIZE = 10; + private final int MAX_POOL_SIZE = 20; + + public static BasicConnectionPool create(String url, String user, String password) throws SQLException { + List pool = new ArrayList<>(INITIAL_POOL_SIZE); + for (int i = 0; i < INITIAL_POOL_SIZE; i++) { + pool.add(createConnection(url, user, password)); + } + return new BasicConnectionPool(url, user, password, pool); + } + + private BasicConnectionPool(String url, String user, String password, List connectionPool) { + this.url = url; + this.user = user; + this.password = password; + this.connectionPool = connectionPool; + } + + @Override + public Connection getConnection() throws SQLException { + if (connectionPool.isEmpty()) { + if (usedConnections.size() < MAX_POOL_SIZE) { + connectionPool.add(createConnection(url, user, password)); + } else { + throw new RuntimeException("Maximum pool size reached, no available connections!"); + } + } + + Connection connection = connectionPool.remove(connectionPool.size() - 1); + usedConnections.add(connection); + return connection; + } + + @Override + public boolean releaseConnection(Connection connection) { + connectionPool.add(connection); + return usedConnections.remove(connection); + } + + private static Connection createConnection(String url, String user, String password) throws SQLException { + return DriverManager.getConnection(url, user, password); + } + + @Override + public int getSize() { + return connectionPool.size() + usedConnections.size(); + } + + @Override + public List getConnectionPool() { + return connectionPool; + } + + @Override + public String getUrl() { + return url; + } + + @Override + public String getUser() { + return user; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public void shutdown() throws SQLException { + usedConnections.forEach(this::releaseConnection); + for (Connection c : connectionPool) { + c.close(); + } + connectionPool.clear(); + } +} diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/C3poDataSource.java similarity index 89% rename from core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java rename to core-java-persistence/src/main/java/com/baeldung/connectionpool/C3poDataSource.java index 5b91f707a9..78642459d5 100644 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/C3poDataSource.java +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/C3poDataSource.java @@ -1,28 +1,28 @@ -package com.baeldung.connectionpool.connectionpools; - -import com.mchange.v2.c3p0.ComboPooledDataSource; -import java.beans.PropertyVetoException; -import java.sql.Connection; -import java.sql.SQLException; - -public class C3poDataSource { - - private static final ComboPooledDataSource cpds = new ComboPooledDataSource(); - - static { - try { - cpds.setDriverClass("org.h2.Driver"); - cpds.setJdbcUrl("jdbc:h2:mem:test"); - cpds.setUser("user"); - cpds.setPassword("password"); - } catch (PropertyVetoException e) { - e.printStackTrace(); - } - } - - public static Connection getConnection() throws SQLException { - return cpds.getConnection(); - } - - private C3poDataSource(){} +package com.baeldung.connectionpool; + +import com.mchange.v2.c3p0.ComboPooledDataSource; +import java.beans.PropertyVetoException; +import java.sql.Connection; +import java.sql.SQLException; + +public class C3poDataSource { + + private static final ComboPooledDataSource cpds = new ComboPooledDataSource(); + + static { + try { + cpds.setDriverClass("org.h2.Driver"); + cpds.setJdbcUrl("jdbc:h2:mem:test"); + cpds.setUser("user"); + cpds.setPassword("password"); + } catch (PropertyVetoException e) { + e.printStackTrace(); + } + } + + public static Connection getConnection() throws SQLException { + return cpds.getConnection(); + } + + private C3poDataSource(){} } \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/ConnectionPool.java similarity index 66% rename from core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java rename to core-java-persistence/src/main/java/com/baeldung/connectionpool/ConnectionPool.java index 3d5ad06c3d..fa9355721b 100644 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/ConnectionPool.java +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/ConnectionPool.java @@ -1,18 +1,24 @@ -package com.baeldung.connectionpool.connectionpools; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.List; - -public interface ConnectionPool { - - Connection getConnection() throws SQLException; - - boolean releaseConnection(Connection connection); - - String getUrl(); - - String getUser(); - - String getPassword(); +package com.baeldung.connectionpool; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; + +public interface ConnectionPool { + + Connection getConnection() throws SQLException; + + boolean releaseConnection(Connection connection); + + List getConnectionPool(); + + int getSize(); + + String getUrl(); + + String getUser(); + + String getPassword(); + + void shutdown() throws SQLException;; } \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/DBCPDataSource.java similarity index 88% rename from core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java rename to core-java-persistence/src/main/java/com/baeldung/connectionpool/DBCPDataSource.java index 2f33cde883..1e33a08d46 100644 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/DBCPDataSource.java +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/DBCPDataSource.java @@ -1,25 +1,25 @@ -package com.baeldung.connectionpool.connectionpools; - -import java.sql.Connection; -import java.sql.SQLException; -import org.apache.commons.dbcp2.BasicDataSource; - -public class DBCPDataSource { - - private static final BasicDataSource ds = new BasicDataSource(); - - static { - ds.setUrl("jdbc:h2:mem:test"); - ds.setUsername("user"); - ds.setPassword("password"); - ds.setMinIdle(5); - ds.setMaxIdle(10); - ds.setMaxOpenPreparedStatements(100); - } - - public static Connection getConnection() throws SQLException { - return ds.getConnection(); - } - - private DBCPDataSource(){} -} +package com.baeldung.connectionpool; + +import java.sql.Connection; +import java.sql.SQLException; +import org.apache.commons.dbcp2.BasicDataSource; + +public class DBCPDataSource { + + private static final BasicDataSource ds = new BasicDataSource(); + + static { + ds.setUrl("jdbc:h2:mem:test"); + ds.setUsername("user"); + ds.setPassword("password"); + ds.setMinIdle(5); + ds.setMaxIdle(10); + ds.setMaxOpenPreparedStatements(100); + } + + public static Connection getConnection() throws SQLException { + return ds.getConnection(); + } + + private DBCPDataSource(){} +} diff --git a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java b/core-java-persistence/src/main/java/com/baeldung/connectionpool/HikariCPDataSource.java similarity index 91% rename from core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java rename to core-java-persistence/src/main/java/com/baeldung/connectionpool/HikariCPDataSource.java index 5ed2de181d..cc0cc24520 100644 --- a/core-java/src/main/java/com/baeldung/connectionpool/connectionpools/HikariCPDataSource.java +++ b/core-java-persistence/src/main/java/com/baeldung/connectionpool/HikariCPDataSource.java @@ -1,28 +1,28 @@ -package com.baeldung.connectionpool.connectionpools; - -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import java.sql.Connection; -import java.sql.SQLException; - -public class HikariCPDataSource { - - private static final HikariConfig config = new HikariConfig(); - private static final HikariDataSource ds; - - static { - config.setJdbcUrl("jdbc:h2:mem:test"); - config.setUsername("user"); - config.setPassword("password"); - config.addDataSourceProperty("cachePrepStmts", "true"); - config.addDataSourceProperty("prepStmtCacheSize", "250"); - config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); - ds = new HikariDataSource(config); - } - - public static Connection getConnection() throws SQLException { - return ds.getConnection(); - } - - private HikariCPDataSource(){} -} +package com.baeldung.connectionpool; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class HikariCPDataSource { + + private static final HikariConfig config = new HikariConfig(); + private static final HikariDataSource ds; + + static { + config.setJdbcUrl("jdbc:h2:mem:test"); + config.setUsername("user"); + config.setPassword("password"); + config.addDataSourceProperty("cachePrepStmts", "true"); + config.addDataSourceProperty("prepStmtCacheSize", "250"); + config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); + ds = new HikariDataSource(config); + } + + public static Connection getConnection() throws SQLException { + return ds.getConnection(); + } + + private HikariCPDataSource(){} +} diff --git a/core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java b/core-java-persistence/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java similarity index 91% rename from core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java rename to core-java-persistence/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java index 5edc6bba94..479cd0db25 100644 --- a/core-java/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java +++ b/core-java-persistence/src/test/java/com/baeldung/connectionpool/BasicConnectionPoolUnitTest.java @@ -1,10 +1,8 @@ package com.baeldung.connectionpool; -import com.baeldung.connectionpool.connectionpools.BasicConnectionPool; -import com.baeldung.connectionpool.connectionpools.ConnectionPool; import java.sql.Connection; import java.sql.SQLException; -import java.util.List; + import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; diff --git a/core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java b/core-java-persistence/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java similarity index 81% rename from core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java rename to core-java-persistence/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java index a02daa40f6..a07fa9e74b 100644 --- a/core-java/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java +++ b/core-java-persistence/src/test/java/com/baeldung/connectionpool/C3poDataSourceUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.connectionpool; -import com.baeldung.connectionpool.connectionpools.C3poDataSource; import java.sql.SQLException; import static org.junit.Assert.assertTrue; import org.junit.Test; diff --git a/core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java b/core-java-persistence/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java similarity index 81% rename from core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java rename to core-java-persistence/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java index 9583eedf4b..43aaf330b6 100644 --- a/core-java/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java +++ b/core-java-persistence/src/test/java/com/baeldung/connectionpool/DBCPDataSourceUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.connectionpool; -import com.baeldung.connectionpool.connectionpools.DBCPDataSource; import java.sql.SQLException; import static org.junit.Assert.assertTrue; import org.junit.Test; diff --git a/core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java b/core-java-persistence/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java similarity index 81% rename from core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java rename to core-java-persistence/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java index 6b78815797..b20ce70efd 100644 --- a/core-java/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java +++ b/core-java-persistence/src/test/java/com/baeldung/connectionpool/HikariCPDataSourceUnitTest.java @@ -1,6 +1,5 @@ package com.baeldung.connectionpool; -import com.baeldung.connectionpool.connectionpools.HikariCPDataSource; import java.sql.SQLException; import static org.junit.Assert.assertTrue; import org.junit.Test; diff --git a/core-java/pom.xml b/core-java/pom.xml index 0b69685e14..b83cb478d4 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -158,21 +158,6 @@ jmimemagic ${jmime-magic.version} - - org.apache.commons - commons-dbcp2 - ${commons-dbcp2.version} - - - com.zaxxer - HikariCP - ${HikariCP.version} - - - com.mchange - c3p0 - ${c3p0.version} - org.javassist @@ -544,11 +529,6 @@ 3.10.0 - - 2.4.0 - 3.2.0 - 0.9.5.2 - 2.19.1 4.3.4.RELEASE diff --git a/pom.xml b/pom.xml index 263e4df637..1730449509 100644 --- a/pom.xml +++ b/pom.xml @@ -312,6 +312,7 @@ core-java-collections core-java-io core-java-8 + core-java-persistence core-kotlin core-groovy core-java-concurrency @@ -877,7 +878,7 @@ spring-static-resources hazelcast hbase - + hystrix image-processing immutables @@ -906,11 +907,11 @@ linkrest logging-modules/log-mdc logging-modules/log4j - + logging-modules/logback lombok mapstruct - + maven mesos-marathon msf4j @@ -962,25 +963,25 @@ spring-cucumber spring-ejb spring-aop - + persistence-modules/spring-data-dynamodb spring-data-keyvalue spring-data-mongodb persistence-modules/spring-data-neo4j - + spring-data-rest persistence-modules/spring-data-solr spring-dispatcher-servlet spring-exceptions spring-freemarker persistence-modules/spring-hibernate-3 - + persistence-modules/spring-hibernate-5 persistence-modules/spring-data-eclipselink spring-integration spring-jenkins-pipeline spring-jersey - + spring-jms spring-jooq persistence-modules/spring-jpa @@ -1041,13 +1042,13 @@ testing-modules/testing testing-modules/testng video-tutorials - + xmlunit-2 struts-2 apache-velocity apache-solrj rabbitmq - + persistence-modules/spring-data-gemfire mybatis spring-drools @@ -1090,7 +1091,7 @@ vertx metrics httpclient - + jmeter --> @@ -1233,6 +1234,4 @@ 3.8
- - - + \ No newline at end of file From 33889d0cd7bcb78efd3586e2d1082edf6d8487d2 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Sat, 28 Jul 2018 11:01:48 +0300 Subject: [PATCH 26/38] integration-lite trying out a few modules --- pom.xml | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index 1730449509..6f2351b56f 100644 --- a/pom.xml +++ b/pom.xml @@ -859,7 +859,7 @@ core-java-io core-java-8 core-groovy - core-java-concurrency + couchbase deltaspike dozer @@ -1078,6 +1078,12 @@ apache-meecrowave testing-modules/junit-abstract + spring-hibernate4 + xml + vertx + metrics + httpclient + @@ -1108,6 +1109,7 @@ core-java google-web-toolkit spring-security-mvc-custom + core-java-concurrency --> @@ -1170,7 +1172,7 @@ spring-security-mvc-custom hibernate5 spring-data-elasticsearch - + core-java-concurrency From d1f2917c3394157323a5b3668833953193228052 Mon Sep 17 00:00:00 2001 From: db Date: Sat, 28 Jul 2018 13:06:41 +0100 Subject: [PATCH 27/38] moved PrincipalExtractor and AuthoritiesExtractor example to spring-5-security module --- spring-5-security/pom.xml | 7 +++ .../ExtractorsApplication.java | 20 +++++++ .../configuration/SecurityConfig.java | 10 ++-- .../extractor/CustomAuthoritiesExtractor.java | 8 +-- .../extractor/CustomPrincipalExtractor.java | 2 +- .../application-oauth2-extractors.properties | 6 +++ .../templates/oauth2_extractors.html | 0 .../oauth2extractors/ExtractorsUnitTest.java | 9 ++-- spring-security-sso/pom.xml | 1 - .../pom.xml | 53 ------------------- .../main/java/org/baeldung/Application.java | 18 ------- .../src/main/resources/application.yml | 14 ----- 12 files changed, 50 insertions(+), 98 deletions(-) create mode 100644 spring-5-security/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java rename {spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung => spring-5-security/src/main/java/com/baeldung/oauth2extractors}/configuration/SecurityConfig.java (79%) rename {spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung => spring-5-security/src/main/java/com/baeldung/oauth2extractors}/extractor/CustomAuthoritiesExtractor.java (67%) rename {spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung => spring-5-security/src/main/java/com/baeldung/oauth2extractors}/extractor/CustomPrincipalExtractor.java (86%) create mode 100644 spring-5-security/src/main/resources/application-oauth2-extractors.properties rename spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/templates/index.html => spring-5-security/src/main/resources/templates/oauth2_extractors.html (100%) rename spring-security-sso/spring-security-principal-authorities-extractor/src/test/java/ApplicationUnitTest.java => spring-5-security/src/test/java/com/baeldung/oauth2extractors/ExtractorsUnitTest.java (85%) delete mode 100644 spring-security-sso/spring-security-principal-authorities-extractor/pom.xml delete mode 100644 spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/Application.java delete mode 100644 spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/application.yml diff --git a/spring-5-security/pom.xml b/spring-5-security/pom.xml index 8cca2ed916..d0ea46928f 100644 --- a/spring-5-security/pom.xml +++ b/spring-5-security/pom.xml @@ -58,6 +58,13 @@ spring-security-test test + + + + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure + 2.0.1.RELEASE + diff --git a/spring-5-security/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java new file mode 100644 index 0000000000..c9a18d1599 --- /dev/null +++ b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/ExtractorsApplication.java @@ -0,0 +1,20 @@ +package com.baeldung.oauth2extractors; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@SpringBootApplication +@Controller +public class ExtractorsApplication { + public static void main(String[] args) { + SpringApplication.run(ExtractorsApplication.class, args); + } + + @RequestMapping("/") + public String index() { + return "oauth2_extractors"; + } + +} diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/configuration/SecurityConfig.java b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/configuration/SecurityConfig.java similarity index 79% rename from spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/configuration/SecurityConfig.java rename to spring-5-security/src/main/java/com/baeldung/oauth2extractors/configuration/SecurityConfig.java index 4de1932392..cc1258d14b 100644 --- a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/configuration/SecurityConfig.java +++ b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/configuration/SecurityConfig.java @@ -1,16 +1,18 @@ -package org.baeldung.configuration; +package com.baeldung.oauth2extractors.configuration; -import org.baeldung.extractor.CustomAuthoritiesExtractor; -import org.baeldung.extractor.CustomPrincipalExtractor; +import com.baeldung.oauth2extractors.extractor.CustomAuthoritiesExtractor; +import com.baeldung.oauth2extractors.extractor.CustomPrincipalExtractor; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor; import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration +@PropertySource("application-oauth2-extractors.properties") @EnableOAuth2Sso public class SecurityConfig extends WebSecurityConfigurerAdapter { @@ -35,4 +37,4 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { public AuthoritiesExtractor authoritiesExtractor() { return new CustomAuthoritiesExtractor(); } -} +} \ No newline at end of file diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomAuthoritiesExtractor.java b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/CustomAuthoritiesExtractor.java similarity index 67% rename from spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomAuthoritiesExtractor.java rename to spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/CustomAuthoritiesExtractor.java index c1a78634aa..ad23f6c32f 100644 --- a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomAuthoritiesExtractor.java +++ b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/CustomAuthoritiesExtractor.java @@ -1,4 +1,4 @@ -package org.baeldung.extractor; +package com.baeldung.oauth2extractors.extractor; import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor; import org.springframework.security.core.GrantedAuthority; @@ -10,8 +10,10 @@ import java.util.Map; import java.util.Objects; public class CustomAuthoritiesExtractor implements AuthoritiesExtractor { - private static final List GITHUB_FREE_AUTHORITIES = AuthorityUtils.commaSeparatedStringToAuthorityList("GITHUB_USER,GITHUB_USER_FREE"); - private static final List GITHUB_SUBSCRIBED_AUTHORITIES = AuthorityUtils.commaSeparatedStringToAuthorityList("GITHUB_USER,GITHUB_USER_SUBSCRIBED"); + private List GITHUB_FREE_AUTHORITIES = AuthorityUtils + .commaSeparatedStringToAuthorityList("GITHUB_USER,GITHUB_USER_FREE"); + private List GITHUB_SUBSCRIBED_AUTHORITIES = AuthorityUtils + .commaSeparatedStringToAuthorityList("GITHUB_USER,GITHUB_USER_SUBSCRIBED"); @Override public List extractAuthorities(Map map) { diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomPrincipalExtractor.java b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/CustomPrincipalExtractor.java similarity index 86% rename from spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomPrincipalExtractor.java rename to spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/CustomPrincipalExtractor.java index d356c07e3b..c35522f0f3 100644 --- a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/extractor/CustomPrincipalExtractor.java +++ b/spring-5-security/src/main/java/com/baeldung/oauth2extractors/extractor/CustomPrincipalExtractor.java @@ -1,4 +1,4 @@ -package org.baeldung.extractor; +package com.baeldung.oauth2extractors.extractor; import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor; diff --git a/spring-5-security/src/main/resources/application-oauth2-extractors.properties b/spring-5-security/src/main/resources/application-oauth2-extractors.properties new file mode 100644 index 0000000000..51d6ee7d6e --- /dev/null +++ b/spring-5-security/src/main/resources/application-oauth2-extractors.properties @@ -0,0 +1,6 @@ +security.oauth2.client.client-id=89a7c4facbb3434d599d +security.oauth2.client.client-secret=9b3b08e4a340bd20e866787e4645b54f73d74b6a +security.oauth2.client.access-token-uri=https://github.com/login/oauth/access_token +security.oauth2.client.user-authorization-uri=https://github.com/login/oauth/authorize +security.oauth2.client.scope=read:user,user:email +security.oauth2.resource.user-info-uri=https://api.github.com/user \ No newline at end of file diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/templates/index.html b/spring-5-security/src/main/resources/templates/oauth2_extractors.html similarity index 100% rename from spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/templates/index.html rename to spring-5-security/src/main/resources/templates/oauth2_extractors.html diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/test/java/ApplicationUnitTest.java b/spring-5-security/src/test/java/com/baeldung/oauth2extractors/ExtractorsUnitTest.java similarity index 85% rename from spring-security-sso/spring-security-principal-authorities-extractor/src/test/java/ApplicationUnitTest.java rename to spring-5-security/src/test/java/com/baeldung/oauth2extractors/ExtractorsUnitTest.java index c14cbc9866..164bc4933f 100644 --- a/spring-security-sso/spring-security-principal-authorities-extractor/src/test/java/ApplicationUnitTest.java +++ b/spring-5-security/src/test/java/com/baeldung/oauth2extractors/ExtractorsUnitTest.java @@ -1,5 +1,6 @@ -import org.baeldung.Application; -import org.baeldung.configuration.SecurityConfig; +package com.baeldung.oauth2extractors; + +import com.baeldung.oauth2extractors.configuration.SecurityConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -18,9 +19,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = ExtractorsApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ContextConfiguration(classes = {SecurityConfig.class}) -public class ApplicationUnitTest { +public class ExtractorsUnitTest { @Autowired private WebApplicationContext context; diff --git a/spring-security-sso/pom.xml b/spring-security-sso/pom.xml index 0cf468c2e3..764e899640 100644 --- a/spring-security-sso/pom.xml +++ b/spring-security-sso/pom.xml @@ -19,7 +19,6 @@ spring-security-sso-auth-server spring-security-sso-ui spring-security-sso-ui-2 - spring-security-principal-authorities-extractor diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/pom.xml b/spring-security-sso/spring-security-principal-authorities-extractor/pom.xml deleted file mode 100644 index 5bd8de9c16..0000000000 --- a/spring-security-sso/spring-security-principal-authorities-extractor/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - spring-security-sso - org.baeldung - 1.0.0-SNAPSHOT - - 4.0.0 - - spring-security-principal-authorities-extractor - - - - org.springframework.boot - spring-boot-starter-security - - - - org.springframework.security.oauth.boot - spring-security-oauth2-autoconfigure - ${oauth-auto.version} - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - - org.thymeleaf.extras - thymeleaf-extras-springsecurity4 - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.springframework.security - spring-security-test - test - - - \ No newline at end of file diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/Application.java b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/Application.java deleted file mode 100644 index 0dfbbef86e..0000000000 --- a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/java/org/baeldung/Application.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; - -@SpringBootApplication -public class Application { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - - @GetMapping("/") - public String homePage(Model model) { - return "index"; - } -} diff --git a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/application.yml b/spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/application.yml deleted file mode 100644 index 324df694df..0000000000 --- a/spring-security-sso/spring-security-principal-authorities-extractor/src/main/resources/application.yml +++ /dev/null @@ -1,14 +0,0 @@ -security: - oauth2: - client: - clientId: 89a7c4facbb3434d599d - clientSecret: 9b3b08e4a340bd20e866787e4645b54f73d74b6a - accessTokenUri: https://github.com/login/oauth/access_token - userAuthorizationUri: https://github.com/login/oauth/authorize - clientAuthenticationScheme: form - scope: read:user,user:email - resource: - userInfoUri: https://api.github.com/user -spring: - thymeleaf: - cache: false \ No newline at end of file From 9940bf29608ce6cb0acafe046f30f77a96db0e90 Mon Sep 17 00:00:00 2001 From: db Date: Sat, 28 Jul 2018 13:09:46 +0100 Subject: [PATCH 28/38] removed comment on pom --- spring-5-security/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-5-security/pom.xml b/spring-5-security/pom.xml index d0ea46928f..7024e6f873 100644 --- a/spring-5-security/pom.xml +++ b/spring-5-security/pom.xml @@ -59,7 +59,6 @@ test - org.springframework.security.oauth.boot spring-security-oauth2-autoconfigure From a1d1d6b16f5e44e4fb7f3a693cc3c89d9cb47a34 Mon Sep 17 00:00:00 2001 From: Philippe Date: Sat, 28 Jul 2018 13:37:39 -0300 Subject: [PATCH 29/38] [refs#BAEL-1992] Minor refactoring --- mqtt/README.md | 4 ++ .../mqtt/EngineTemperatureSensorLiveTest.java | 45 ++++++++++--------- 2 files changed, 27 insertions(+), 22 deletions(-) create mode 100644 mqtt/README.md diff --git a/mqtt/README.md b/mqtt/README.md new file mode 100644 index 0000000000..5a388aab4c --- /dev/null +++ b/mqtt/README.md @@ -0,0 +1,4 @@ +### Relevant Articles: +================================ + +- [MQTT Client in Java](http://www.baeldung.com/mqtt-client) diff --git a/mqtt/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java b/mqtt/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java index 94031b5415..b1c0002888 100644 --- a/mqtt/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java +++ b/mqtt/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java @@ -24,12 +24,11 @@ public class EngineTemperatureSensorLiveTest { @Test public void whenSendSingleMessage_thenSuccess() throws Exception { - String senderId = UUID.randomUUID().toString(); - MqttClient sender = new MqttClient("tcp://iot.eclipse.org:1883",senderId); - - String receiverId = UUID.randomUUID().toString(); - MqttClient receiver = new MqttClient("tcp://iot.eclipse.org:1883",receiverId); + String publisherId = UUID.randomUUID().toString(); + MqttClient publisher = new MqttClient("tcp://iot.eclipse.org:1883",publisherId); + String subscriberId = UUID.randomUUID().toString(); + MqttClient subscriber = new MqttClient("tcp://iot.eclipse.org:1883",subscriberId); MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(true); @@ -37,33 +36,34 @@ public class EngineTemperatureSensorLiveTest { options.setConnectionTimeout(10); - receiver.connect(options); - sender.connect(options); + subscriber.connect(options); + publisher.connect(options); CountDownLatch receivedSignal = new CountDownLatch(1); - receiver.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> { - log.info("[I41] Message received: topic={}, payload={}", topic, new String(msg.getPayload())); + subscriber.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> { + byte[] payload = msg.getPayload(); + log.info("[I46] Message received: topic={}, payload={}", topic, new String(payload)); receivedSignal.countDown(); }); - Callable target = new EngineTemperatureSensor(sender); + Callable target = new EngineTemperatureSensor(publisher); target.call(); receivedSignal.await(1, TimeUnit.MINUTES); - log.info("[I51] Success !"); + log.info("[I56] Success !"); } @Test public void whenSendMultipleMessages_thenSuccess() throws Exception { - String senderId = UUID.randomUUID().toString(); - MqttClient sender = new MqttClient("tcp://iot.eclipse.org:1883",senderId); + String publisherId = UUID.randomUUID().toString(); + MqttClient publisher = new MqttClient("tcp://iot.eclipse.org:1883",publisherId); - String receiverId = UUID.randomUUID().toString(); - MqttClient receiver = new MqttClient("tcp://iot.eclipse.org:1883",receiverId); + String subscriberId = UUID.randomUUID().toString(); + MqttClient subscriber = new MqttClient("tcp://iot.eclipse.org:1883",subscriberId); MqttConnectOptions options = new MqttConnectOptions(); @@ -72,18 +72,19 @@ public class EngineTemperatureSensorLiveTest { options.setConnectionTimeout(10); - sender.connect(options); - receiver.connect(options); + publisher.connect(options); + subscriber.connect(options); CountDownLatch receivedSignal = new CountDownLatch(10); - receiver.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> { - log.info("[I41] Message received: topic={}, payload={}", topic, new String(msg.getPayload())); + subscriber.subscribe(EngineTemperatureSensor.TOPIC, (topic, msg) -> { + byte[] payload = msg.getPayload(); + log.info("[I82] Message received: topic={}, payload={}", topic, new String(payload)); receivedSignal.countDown(); }); - Callable target = new EngineTemperatureSensor(sender); + Callable target = new EngineTemperatureSensor(publisher); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); executor.scheduleAtFixedRate(() -> { @@ -96,12 +97,12 @@ public class EngineTemperatureSensorLiveTest { }, 1, 1, TimeUnit.SECONDS); - receivedSignal.await(1, TimeUnit.DAYS); + receivedSignal.await(1, TimeUnit.MINUTES); executor.shutdown(); assertTrue(receivedSignal.getCount() == 0 , "Countdown should be zero"); - log.info("[I51] Success !"); + log.info("[I105] Success !"); } From 7ff4d2ea4c9d0e21091108d9e53824d2ed520e0e Mon Sep 17 00:00:00 2001 From: Dhrubajyoti Bhattacharjee Date: Sun, 29 Jul 2018 00:14:05 +0530 Subject: [PATCH 30/38] BAEL-1983 Intialize a HashMap in Java (#4819) --- .../maps/initialize/MapsInitializer.java | 33 ++++++++ .../java/map/initialize/MapInitializer.java | 80 +++++++++++++++++++ .../initialize/MapInitializerUnitTest.java | 27 +++++++ 3 files changed, 140 insertions(+) create mode 100644 core-java-9/src/main/java/com/baeldung/java9/maps/initialize/MapsInitializer.java create mode 100644 core-java-collections/src/main/java/com/baeldung/java/map/initialize/MapInitializer.java create mode 100644 core-java-collections/src/test/java/com/baeldung/java/map/initialize/MapInitializerUnitTest.java diff --git a/core-java-9/src/main/java/com/baeldung/java9/maps/initialize/MapsInitializer.java b/core-java-9/src/main/java/com/baeldung/java9/maps/initialize/MapsInitializer.java new file mode 100644 index 0000000000..2a8ce588bb --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/maps/initialize/MapsInitializer.java @@ -0,0 +1,33 @@ +package com.baeldung.java9.maps.initialize; + +import java.util.AbstractMap; +import java.util.HashMap; +import java.util.Map; + +public class MapsInitializer { + + @SuppressWarnings("unused") + public void createMapWithMapOf() { + Map emptyMap = Map.of(); + Map singletonMap = Map.of("key1", "value"); + Map map = Map.of("key1","value1", "key2", "value2"); + } + + public void createMapWithMapEntries() { + Map map = Map.ofEntries( + new AbstractMap.SimpleEntry("name", "John"), + new AbstractMap.SimpleEntry("city", "budapest"), + new AbstractMap.SimpleEntry("zip", "000000"), + new AbstractMap.SimpleEntry("home", "1231231231") + ); + } + + @SuppressWarnings("unused") + public void createMutableMaps() { + Map map = new HashMap (Map.of("key1","value1", "key2", "value2")); + Map map2 = new HashMap ( Map.ofEntries( + new AbstractMap.SimpleEntry("name", "John"), + new AbstractMap.SimpleEntry("city", "budapest"))); + + } +} diff --git a/core-java-collections/src/main/java/com/baeldung/java/map/initialize/MapInitializer.java b/core-java-collections/src/main/java/com/baeldung/java/map/initialize/MapInitializer.java new file mode 100644 index 0000000000..4dbaceac62 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/map/initialize/MapInitializer.java @@ -0,0 +1,80 @@ +package com.baeldung.java.map.initialize; + +import java.util.AbstractMap; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class MapInitializer { + + public static Map articleMapOne; + static { + articleMapOne = new HashMap<>(); + articleMapOne.put("ar01", "Intro to Map"); + articleMapOne.put("ar02", "Some article"); + } + + public static Map createSingletonMap() { + Map passwordMap = Collections.singletonMap("username1", "password1"); + return passwordMap; + + } + + public Map createEmptyMap() { + Map emptyMap = Collections.emptyMap(); + return emptyMap; + } + + public Map createUsingDoubleBrace() { + Map doubleBraceMap = new HashMap() { + + /** + * + */ + private static final long serialVersionUID = 1L; + + { + put("key1", "value1"); + put("key2", "value2"); + } + }; + return doubleBraceMap; + } + + public Map createMapUsingStreamStringArray() { + Map map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, }) + .collect(Collectors.toMap(data -> data[0], data -> data[1])); + + return map; + } + + public Map createMapUsingStreamObjectArray() { + Map map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, }) + .collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1])); + + return map; + } + + public Map createMapUsingStreamSimpleEntry() { + Map map = Stream.of(new AbstractMap.SimpleEntry<>("idea", 1), new AbstractMap.SimpleEntry<>("mobile", 2)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + + return map; + } + + public Map createMapUsingStreamSimpleImmutableEntry() { + Map map = Stream.of(new AbstractMap.SimpleImmutableEntry<>("idea", 1), new AbstractMap.SimpleImmutableEntry<>("mobile", 2)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + + return map; + } + + public Map createImmutableMapWithStreams() { + Map map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, }) + .collect(Collectors.collectingAndThen(Collectors.toMap(data -> data[0], data -> data[1]), Collections:: unmodifiableMap)); + return map; + + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/java/map/initialize/MapInitializerUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/map/initialize/MapInitializerUnitTest.java new file mode 100644 index 0000000000..80a8983d6f --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/map/initialize/MapInitializerUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.java.map.initialize; + +import static org.junit.Assert.assertEquals; + +import java.util.Map; + +import org.junit.Test; + +public class MapInitializerUnitTest { + + @Test + public void givenStaticMap_whenUpdated_thenCorrect() { + + MapInitializer.articleMapOne.put("NewArticle1", "Convert array to List"); + + assertEquals(MapInitializer.articleMapOne.get("NewArticle1"), "Convert array to List"); + + } + + @Test(expected=UnsupportedOperationException.class) + public void givenSingleTonMap_whenEntriesAdded_throwsException() { + + Map map = MapInitializer.createSingletonMap(); + map.put("username2", "password2"); + } + +} From 61860cf7b8c411f2715a8ba57459d81c3ae38ba4 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 28 Jul 2018 22:24:38 +0300 Subject: [PATCH 31/38] move mqtt project --- libraries/pom.xml | 5 ++++ .../mqtt/EngineTemperatureSensor.java | 0 .../mqtt/EngineTemperatureSensorLiveTest.java | 0 mqtt/README.md | 4 ---- mqtt/pom.xml | 23 ------------------- 5 files changed, 5 insertions(+), 27 deletions(-) rename {mqtt => libraries}/src/main/java/com/baeldung/mqtt/EngineTemperatureSensor.java (100%) rename {mqtt => libraries}/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java (100%) delete mode 100644 mqtt/README.md delete mode 100644 mqtt/pom.xml diff --git a/libraries/pom.xml b/libraries/pom.xml index 163f5872ce..909be87083 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -771,6 +771,11 @@ ${hamcrest-all.version} test + + org.eclipse.paho + org.eclipse.paho.client.mqttv3 + 1.2.0 + diff --git a/mqtt/src/main/java/com/baeldung/mqtt/EngineTemperatureSensor.java b/libraries/src/main/java/com/baeldung/mqtt/EngineTemperatureSensor.java similarity index 100% rename from mqtt/src/main/java/com/baeldung/mqtt/EngineTemperatureSensor.java rename to libraries/src/main/java/com/baeldung/mqtt/EngineTemperatureSensor.java diff --git a/mqtt/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java b/libraries/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java similarity index 100% rename from mqtt/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java rename to libraries/src/test/java/com/baeldung/mqtt/EngineTemperatureSensorLiveTest.java diff --git a/mqtt/README.md b/mqtt/README.md deleted file mode 100644 index 5a388aab4c..0000000000 --- a/mqtt/README.md +++ /dev/null @@ -1,4 +0,0 @@ -### Relevant Articles: -================================ - -- [MQTT Client in Java](http://www.baeldung.com/mqtt-client) diff --git a/mqtt/pom.xml b/mqtt/pom.xml deleted file mode 100644 index 346433aa69..0000000000 --- a/mqtt/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - 4.0.0 - org.baeldung - mqtt - 0.0.1-SNAPSHOT - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.eclipse.paho - org.eclipse.paho.client.mqttv3 - 1.2.0 - - - - - From 748c94f23123391bd1372858d17471d828bd69f6 Mon Sep 17 00:00:00 2001 From: Felipe Santiago Corro Date: Sun, 29 Jul 2018 01:38:51 -0300 Subject: [PATCH 32/38] Add items to list in core-java-collections (#4841) --- .../java/com/baeldung/java/list/Flower.java | 28 ++++++++ .../listoflist/AddElementsToListUnitTest.java | 69 +++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 core-java-collections/src/main/java/com/baeldung/java/list/Flower.java create mode 100644 core-java-collections/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java diff --git a/core-java-collections/src/main/java/com/baeldung/java/list/Flower.java b/core-java-collections/src/main/java/com/baeldung/java/list/Flower.java new file mode 100644 index 0000000000..eb897ea72f --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/list/Flower.java @@ -0,0 +1,28 @@ +package com.baeldung.java.list; + +public class Flower { + + private String name; + private int petals; + + public Flower(String name, int petals) { + this.name = name; + this.petals = petals; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getPetals() { + return petals; + } + + public void setPetals(int petals) { + this.petals = petals; + } +} diff --git a/core-java-collections/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java new file mode 100644 index 0000000000..299a87026f --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.list.listoflist; + +import com.baeldung.java.list.Flower; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import java.util.*; +import static org.junit.Assert.*; + +public class AddElementsToListUnitTest { + + List flowers; + + @Before + public void init() { + this.flowers = new ArrayList<>(Arrays.asList( + new Flower("Poppy", 12), + new Flower("Anemone", 8), + new Flower("Catmint", 12))); + } + @Test + public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() { + List anotherList = new ArrayList<>(); + anotherList.addAll(flowers); + assertEquals(anotherList.size(), flowers.size()); + Assert.assertTrue(anotherList.containsAll(flowers)); + } + @Test + public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() { + List anotherList = new ArrayList<>(); + anotherList.addAll(flowers); + Flower flower = anotherList.get(0); + flower.setPetals(flowers.get(0).getPetals() * 3); + assertEquals(anotherList.size(), flowers.size()); + Assert.assertTrue(anotherList.containsAll(flowers)); + } + @Test + public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() { + List target = new ArrayList<>(); + Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0)); + assertEquals(target.size(), 4); + } + @Test + public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() { + List flowerVase = new ArrayList<>(); + flowers.stream() + .skip(1) + .forEachOrdered(flowerVase::add); + assertEquals(flowerVase.size() + 1, flowers.size()); + assertFalse(flowerVase.containsAll(flowers)); + } + @Test + public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() { + List flowerVase = new ArrayList<>(); + flowers.stream() + .filter(f -> f.getPetals() > 10) + .forEachOrdered(flowerVase::add); + assertEquals(flowerVase.size() + 1, flowers.size()); + assertFalse(flowerVase.containsAll(flowers)); + } + @Test + public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() { + List target = new ArrayList<>(); + Optional.ofNullable(flowers) + .ifPresent(target::addAll); + assertNotNull(target); + assertEquals(target.size(), 3); + } +} From 578bcb7f79bdf0410a0144f5a765eba00e14e120 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 29 Jul 2018 00:06:59 +0530 Subject: [PATCH 33/38] [BAEL-7608] - Fixed spring-5-reactive integration tests --- .../com/baeldung/functional/FormHandler.java | 3 +-- .../functional/FunctionalWebApplication.java | 25 +++++------------- .../FurtherCorsConfigsController.java | 2 +- .../controllers/RegularRestController.java | 2 +- ...Spring5URLPatternUsingRouterFunctions.java | 25 ++++++------------ .../webflux/EmployeeCreationEvent.java | 6 ++++- .../webflux/EmployeeWebSocketHandler.java | 2 +- .../ReactiveWebSocketConfiguration.java | 7 +++-- .../websocket/ReactiveWebSocketHandler.java | 2 +- ...nctionalWebApplicationIntegrationTest.java | 16 ++++++----- ...rnUsingRouterFunctionsIntegrationTest.java | 12 +++++---- .../security/SecurityIntegrationTest.java | 2 +- .../client/WebTestClientIntegrationTest.java | 2 +- .../src/test/resources/baeldung-weekly.png | Bin 0 -> 28106 bytes 14 files changed, 49 insertions(+), 57 deletions(-) create mode 100644 spring-5-reactive/src/test/resources/baeldung-weekly.png diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java index 05069735bb..c4f8c9f41f 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java @@ -34,8 +34,7 @@ public class FormHandler { private AtomicLong extractData(List dataBuffers) { AtomicLong atomicLong = new AtomicLong(0); - dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer() - .array().length)); + dataBuffers.forEach(d -> atomicLong.addAndGet(d.readableByteCount())); return atomicLong; } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java index 5a7d70d3db..4e914ab65e 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java @@ -12,13 +12,9 @@ import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; -import org.apache.catalina.Context; -import org.apache.catalina.startup.Tomcat; -import org.springframework.boot.web.embedded.tomcat.TomcatWebServer; -import org.springframework.boot.web.server.WebServer; import org.springframework.core.io.ClassPathResource; import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.http.server.reactive.ServletHttpHandlerAdapter; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; @@ -26,6 +22,8 @@ import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; import reactor.core.publisher.Flux; +import reactor.ipc.netty.NettyContext; +import reactor.ipc.netty.http.server.HttpServer; public class FunctionalWebApplication { @@ -50,24 +48,15 @@ public class FunctionalWebApplication { }); } - WebServer start() throws Exception { + NettyContext start() throws Exception { WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction()); HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler) .filter(new IndexRewriteFilter()) .build(); - Tomcat tomcat = new Tomcat(); - tomcat.setHostname("localhost"); - tomcat.setPort(9090); - Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir")); - ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler); - Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet); - rootContext.addServletMappingDecoded("/", "httpHandlerServlet"); - - TomcatWebServer server = new TomcatWebServer(tomcat); - server.start(); - return server; - + ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); + HttpServer server = HttpServer.create("localhost", 9090); + return server.newHandler(adapter).block(); } public static void main(String[] args) { diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java index b6341c9af1..4358326df8 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java @@ -8,7 +8,7 @@ import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; -@RestController +@RestController("FurtherCorsConfigsController-cors-on-global-config-and-more") @RequestMapping("/cors-on-global-config-and-more") public class FurtherCorsConfigsController { diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java index 5945cfc9f2..e57e573146 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java @@ -7,7 +7,7 @@ import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; -@RestController +@RestController("RegularRestController-cors-on-global-config") @RequestMapping("/cors-on-global-config") public class RegularRestController { diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java index 78f40be57a..0de1bcb539 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java @@ -6,19 +6,18 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler; import static org.springframework.web.reactive.function.server.ServerResponse.ok; -import org.apache.catalina.Context; -import org.apache.catalina.startup.Tomcat; -import org.springframework.boot.web.embedded.tomcat.TomcatWebServer; -import org.springframework.boot.web.server.WebServer; import org.springframework.core.io.ClassPathResource; import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.http.server.reactive.ServletHttpHandlerAdapter; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; +import reactor.ipc.netty.NettyContext; +import reactor.ipc.netty.http.server.HttpServer; + public class ExploreSpring5URLPatternUsingRouterFunctions { private RouterFunction routingFunction() { @@ -30,23 +29,15 @@ public class ExploreSpring5URLPatternUsingRouterFunctions { .and(RouterFunctions.resources("/files/{*filepaths}", new ClassPathResource("files/"))); } - WebServer start() throws Exception { + NettyContext start() throws Exception { WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction()); HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler) .filter(new IndexRewriteFilter()) .build(); - Tomcat tomcat = new Tomcat(); - tomcat.setHostname("localhost"); - tomcat.setPort(9090); - Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir")); - ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler); - Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet); - rootContext.addServletMappingDecoded("/", "httpHandlerServlet"); - - TomcatWebServer server = new TomcatWebServer(tomcat); - server.start(); - return server; + ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); + HttpServer server = HttpServer.create("localhost", 9090); + return server.newHandler(adapter).block(); } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeCreationEvent.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeCreationEvent.java index 7be088f073..7a66e1e147 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeCreationEvent.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeCreationEvent.java @@ -4,8 +4,12 @@ import lombok.AllArgsConstructor; import lombok.Data; @Data -@AllArgsConstructor public class EmployeeCreationEvent { private String employeeId; private String creationTime; + public EmployeeCreationEvent(String employeeId, String creationTime) { + super(); + this.employeeId = employeeId; + this.creationTime = creationTime; + } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketHandler.java index caa2a38b65..c696bc8215 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeWebSocketHandler.java @@ -15,7 +15,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -@Component +@Component("EmployeeWebSocketHandler") public class EmployeeWebSocketHandler implements WebSocketHandler { ObjectMapper om = new ObjectMapper(); diff --git a/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java index ef8d81d3c2..43a98d068d 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketConfiguration.java @@ -1,19 +1,22 @@ package com.baeldung.websocket; +import java.util.HashMap; +import java.util.Map; + import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; import org.springframework.web.reactive.socket.WebSocketHandler; import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter; -import java.util.HashMap; -import java.util.Map; @Configuration public class ReactiveWebSocketConfiguration { @Autowired + @Qualifier("ReactiveWebSocketHandler") private WebSocketHandler webSocketHandler; @Bean diff --git a/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java index 5adad6bf15..f85f2c0424 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/websocket/ReactiveWebSocketHandler.java @@ -14,7 +14,7 @@ import java.time.Duration; import static java.time.LocalDateTime.now; import static java.util.UUID.randomUUID; -@Component +@Component("ReactiveWebSocketHandler") public class ReactiveWebSocketHandler implements WebSocketHandler { private static final ObjectMapper json = new ObjectMapper(); diff --git a/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java index a7b951b930..e780589333 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java @@ -1,9 +1,13 @@ package com.baeldung.functional; +import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromResource; + +import java.net.InetSocketAddress; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import org.springframework.boot.web.server.WebServer; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; @@ -12,25 +16,25 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.BodyInserters; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; -import static org.springframework.web.reactive.function.BodyInserters.fromResource; +import reactor.ipc.netty.NettyContext; public class FunctionalWebApplicationIntegrationTest { private static WebTestClient client; - private static WebServer server; + private static NettyContext server; @BeforeClass public static void setup() throws Exception { server = new FunctionalWebApplication().start(); + InetSocketAddress serverAddress = server.address(); client = WebTestClient.bindToServer() - .baseUrl("http://localhost:" + server.getPort()) + .baseUrl("http://" + serverAddress.getHostName() + ":" + serverAddress.getPort()) .build(); } @AfterClass public static void destroy() { - server.stop(); + server.dispose(); } @Test diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java index 21ba11616d..c9e1c59fdc 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java @@ -1,29 +1,31 @@ package com.baeldung.reactive.urlmatch; +import java.net.InetSocketAddress; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import org.springframework.boot.web.server.WebServer; import org.springframework.test.web.reactive.server.WebTestClient; -import com.baeldung.reactive.urlmatch.ExploreSpring5URLPatternUsingRouterFunctions; +import reactor.ipc.netty.NettyContext; public class ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest { private static WebTestClient client; - private static WebServer server; + private static NettyContext server; @BeforeClass public static void setup() throws Exception { server = new ExploreSpring5URLPatternUsingRouterFunctions().start(); + InetSocketAddress serverAddress = server.address(); client = WebTestClient.bindToServer() - .baseUrl("http://localhost:" + server.getPort()) + .baseUrl("http://" + serverAddress.getHostName() + ":" + serverAddress.getPort()) .build(); } @AfterClass public static void destroy() { - server.stop(); + server.dispose(); } @Test diff --git a/spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java index a59ef57db8..341bd2a0c7 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/security/SecurityIntegrationTest.java @@ -28,7 +28,7 @@ public class SecurityIntegrationTest { @Test public void whenNoCredentials_thenRedirectToLogin() { - this.rest.get().uri("/").exchange().expectStatus().is3xxRedirection(); + this.rest.get().uri("/").exchange().expectStatus().is4xxClientError(); } @Test diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java index a1c0eecb8f..08bd883b0b 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java @@ -53,7 +53,7 @@ public class WebTestClientIntegrationTest { .uri("/resource") .exchange() .expectStatus() - .is3xxRedirection() + .isOk() .expectBody(); } diff --git a/spring-5-reactive/src/test/resources/baeldung-weekly.png b/spring-5-reactive/src/test/resources/baeldung-weekly.png new file mode 100644 index 0000000000000000000000000000000000000000..a1b7eebcabe64f27e1c4d5ec9948dd38165d331e GIT binary patch literal 28106 zcmeFZS5Q-J_%9lJL9hZMO$9-^Qlx{5(n3*sM?^qc=p6zU@B;)sKzi>Tq=uFRK|lyS zgh-8mlo079QbP8d?>}eGnK?J-;#}?7BTNQNvhuF=uIKr+hwv9#D)bj`U4%d&^lGZl zbRdwEA++!FXTfhS_4jarhqJGtD$gKP+P`dMQ9Ss~1y@yL5Adk^-?ws)qXGottfBVo ziJtGoDuwL9=99U$udqNj6L9&;=?nh6Ix}^nH5CSk35^(OS&u@W^(Iy_tS{Kz*4iaq z%ExYCE!|DtZqz}*g-`qC4)^)?Ycm15`uCF#Pn|!1`(3Z#&4^bh%c~LDAsm?aqVaH_ZON0v>+Sod6GQw&z2@508`}ry-E9EGKV6AR+x%ASWOYr!WY3 z_A9Z|kHP<^-GQ70FS+!8Uh@CpjKLVb`7EjK!{t$=FWh`=bR=}(UJQY_J#KDP#(XO) zj=OX2A%!#Rm{1tJjpY(45iB!`8&#Cg#|xvrvC=`>y1n&R)o|?|ogPoSL_2t6=4#R_rdG^R|PrqNy3eMDnX#BR>d_1OG z0rnjyFwvWWQ@$@`h#<)7I#Mp`^`9LY<%g2=PBg|k$0sC$$OI^D&QQ8s;icPJnBAf@<1-xtJQcaC+tzMd8Q=meha386^ z@bbdHJAw1@y{)@4ua(U@YV!^{aO4{ig07(_Ax@D2D7wagT$goWWt>+!ZW5=2GkCXINfRu{5wS8F2p_pMN99GG<+-AnCGP{6^ENa5=8* zlZ6rO{oI@DTE2SY0&0ly!?Qy%mle=#>4_XmZ};CVWDBe5H!U3O4<{vc5atLn`e}v* z(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-7608] - Reverted NettyContext to Embedded Tomcat example with Async = true --- .../functional/FunctionalWebApplication.java | 27 ++++++++++++++----- ...Spring5URLPatternUsingRouterFunctions.java | 27 +++++++++++++------ ...nctionalWebApplicationIntegrationTest.java | 12 +++------ ...rnUsingRouterFunctionsIntegrationTest.java | 8 +++--- 4 files changed, 47 insertions(+), 27 deletions(-) diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java index 4e914ab65e..1f40798ada 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java @@ -12,9 +12,14 @@ import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; +import org.apache.catalina.Context; +import org.apache.catalina.Wrapper; +import org.apache.catalina.startup.Tomcat; +import org.springframework.boot.web.embedded.tomcat.TomcatWebServer; +import org.springframework.boot.web.server.WebServer; import org.springframework.core.io.ClassPathResource; import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.http.server.reactive.ServletHttpHandlerAdapter; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; @@ -22,8 +27,6 @@ import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; import reactor.core.publisher.Flux; -import reactor.ipc.netty.NettyContext; -import reactor.ipc.netty.http.server.HttpServer; public class FunctionalWebApplication { @@ -48,15 +51,25 @@ public class FunctionalWebApplication { }); } - NettyContext start() throws Exception { + WebServer start() throws Exception { WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction()); HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler) .filter(new IndexRewriteFilter()) .build(); - ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); - HttpServer server = HttpServer.create("localhost", 9090); - return server.newHandler(adapter).block(); + Tomcat tomcat = new Tomcat(); + tomcat.setHostname("localhost"); + tomcat.setPort(9090); + Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir")); + ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler); + Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet); + servletWrapper.setAsyncSupported(true); + rootContext.addServletMappingDecoded("/", "httpHandlerServlet"); + + TomcatWebServer server = new TomcatWebServer(tomcat); + server.start(); + return server; + } public static void main(String[] args) { diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java index 0de1bcb539..115a057915 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java @@ -6,18 +6,20 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler; import static org.springframework.web.reactive.function.server.ServerResponse.ok; +import org.apache.catalina.Context; +import org.apache.catalina.Wrapper; +import org.apache.catalina.startup.Tomcat; +import org.springframework.boot.web.embedded.tomcat.TomcatWebServer; +import org.springframework.boot.web.server.WebServer; import org.springframework.core.io.ClassPathResource; import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.http.server.reactive.ServletHttpHandlerAdapter; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; -import reactor.ipc.netty.NettyContext; -import reactor.ipc.netty.http.server.HttpServer; - public class ExploreSpring5URLPatternUsingRouterFunctions { private RouterFunction routingFunction() { @@ -29,15 +31,24 @@ public class ExploreSpring5URLPatternUsingRouterFunctions { .and(RouterFunctions.resources("/files/{*filepaths}", new ClassPathResource("files/"))); } - NettyContext start() throws Exception { + WebServer start() throws Exception { WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction()); HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler) .filter(new IndexRewriteFilter()) .build(); - ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler); - HttpServer server = HttpServer.create("localhost", 9090); - return server.newHandler(adapter).block(); + Tomcat tomcat = new Tomcat(); + tomcat.setHostname("localhost"); + tomcat.setPort(9090); + Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir")); + ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler); + Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet); + servletWrapper.setAsyncSupported(true); + rootContext.addServletMappingDecoded("/", "httpHandlerServlet"); + + TomcatWebServer server = new TomcatWebServer(tomcat); + server.start(); + return server; } diff --git a/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java index e780589333..4dea2a05cf 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java @@ -3,11 +3,10 @@ package com.baeldung.functional; import static org.springframework.web.reactive.function.BodyInserters.fromObject; import static org.springframework.web.reactive.function.BodyInserters.fromResource; -import java.net.InetSocketAddress; - import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; +import org.springframework.boot.web.server.WebServer; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; @@ -16,25 +15,22 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.BodyInserters; -import reactor.ipc.netty.NettyContext; - public class FunctionalWebApplicationIntegrationTest { private static WebTestClient client; - private static NettyContext server; + private static WebServer server; @BeforeClass public static void setup() throws Exception { server = new FunctionalWebApplication().start(); - InetSocketAddress serverAddress = server.address(); client = WebTestClient.bindToServer() - .baseUrl("http://" + serverAddress.getHostName() + ":" + serverAddress.getPort()) + .baseUrl("http://localhost:" + server.getPort()) .build(); } @AfterClass public static void destroy() { - server.dispose(); + server.stop(); } @Test diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java index c9e1c59fdc..d735fd9f72 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java @@ -5,6 +5,7 @@ import java.net.InetSocketAddress; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; +import org.springframework.boot.web.server.WebServer; import org.springframework.test.web.reactive.server.WebTestClient; import reactor.ipc.netty.NettyContext; @@ -12,20 +13,19 @@ import reactor.ipc.netty.NettyContext; public class ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest { private static WebTestClient client; - private static NettyContext server; + private static WebServer server; @BeforeClass public static void setup() throws Exception { server = new ExploreSpring5URLPatternUsingRouterFunctions().start(); - InetSocketAddress serverAddress = server.address(); client = WebTestClient.bindToServer() - .baseUrl("http://" + serverAddress.getHostName() + ":" + serverAddress.getPort()) + .baseUrl("http://localhost:" + server.getPort()) .build(); } @AfterClass public static void destroy() { - server.dispose(); + server.stop(); } @Test From 38e7ec8065772db736169fbd8d3fe27dbadba406 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 29 Jul 2018 14:17:48 +0530 Subject: [PATCH 35/38] [BAEL-7608] - Removed unused imports --- ...eSpring5URLPatternUsingRouterFunctionsIntegrationTest.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java index d735fd9f72..91721d2cef 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest.java @@ -1,15 +1,11 @@ package com.baeldung.reactive.urlmatch; -import java.net.InetSocketAddress; - import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.boot.web.server.WebServer; import org.springframework.test.web.reactive.server.WebTestClient; -import reactor.ipc.netty.NettyContext; - public class ExploreSpring5URLPatternUsingRouterFunctionsIntegrationTest { private static WebTestClient client; From 4981b1fd0e52510e07776263802c49005fac7d8e Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 29 Jul 2018 15:03:12 +0300 Subject: [PATCH 36/38] Update pom.xml --- libraries/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/pom.xml b/libraries/pom.xml index 909be87083..02ea1d4d51 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -771,7 +771,7 @@ ${hamcrest-all.version} test - + org.eclipse.paho org.eclipse.paho.client.mqttv3 1.2.0 @@ -1024,4 +1024,4 @@ 3.0.2 - \ No newline at end of file + From ec4a0a5b941bb2c4da4c37a4a017943759490df6 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 29 Jul 2018 18:32:39 +0530 Subject: [PATCH 37/38] [BAEL-7609] - Fixed spring-boot integration tests --- .../controller/FooController.java | 5 +++-- .../org/baeldung/boot/config/WebConfig.java | 15 +++++++++++++++ .../converter/StringToEmployeeConverter.java | 16 ++++++++++++++++ .../StringToEmployeeConverterController.java | 17 +++++++++++++++++ .../HibernateSessionIntegrationTest.java | 10 ++++------ .../NoHibernateSessionIntegrationTest.java | 2 ++ .../CustomConverterIntegrationTest.java | 2 +- .../EmployeeServiceImplIntegrationTest.java | 19 ++++++++----------- 8 files changed, 66 insertions(+), 20 deletions(-) create mode 100644 spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java create mode 100644 spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java create mode 100644 spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java index c4a83cc2d9..630820ff9f 100644 --- a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java @@ -3,6 +3,7 @@ package com.baeldung.displayallbeans.controller; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @@ -14,9 +15,9 @@ public class FooController { private FooService fooService; @GetMapping(value = "/displayallbeans") - public String getHeaderAndBody(Map model) { + public ResponseEntity getHeaderAndBody(Map model) { model.put("header", fooService.getHeader()); model.put("message", fooService.getBody()); - return "displayallbeans"; + return ResponseEntity.ok("displayallbeans"); } } diff --git a/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java b/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java new file mode 100644 index 0000000000..69abeb0bdd --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java @@ -0,0 +1,15 @@ +package org.baeldung.boot.config; + +import org.baeldung.boot.converter.StringToEmployeeConverter; +import org.springframework.context.annotation.Configuration; +import org.springframework.format.FormatterRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addFormatters(FormatterRegistry registry) { + registry.addConverter(new StringToEmployeeConverter()); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java new file mode 100644 index 0000000000..6902cd84d1 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java @@ -0,0 +1,16 @@ +package org.baeldung.boot.converter; + +import org.springframework.core.convert.converter.Converter; + +import com.baeldung.toggle.Employee; + +public class StringToEmployeeConverter implements Converter { + + @Override + public Employee convert(String from) { + String[] data = from.split(","); + return new Employee( + Long.parseLong(data[0]), + Double.parseDouble(data[1])); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java b/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java new file mode 100644 index 0000000000..27bad4c387 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java @@ -0,0 +1,17 @@ +package org.baeldung.boot.converter.controller; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.toggle.Employee; + +@RestController +public class StringToEmployeeConverterController { + + @GetMapping("/string-to-employee") + public ResponseEntity getStringToEmployee(@RequestParam("employee") Employee employee) { + return ResponseEntity.ok(employee); + } +} diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java index 4658861162..baa4f70e83 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java @@ -4,17 +4,15 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; -import org.baeldung.boot.ApplicationIntegrationTest; +import org.baeldung.boot.DemoApplicationIntegrationTest; import org.baeldung.demo.model.Foo; -import org.baeldung.session.exception.repository.FooRepository; +import org.baeldung.demo.repository.FooRepository; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.TestPropertySource; import org.springframework.transaction.annotation.Transactional; @Transactional -@TestPropertySource("classpath:exception-hibernate.properties") -public class HibernateSessionIntegrationTest extends ApplicationIntegrationTest { +public class HibernateSessionIntegrationTest extends DemoApplicationIntegrationTest { @Autowired private FooRepository fooRepository; @@ -23,7 +21,7 @@ public class HibernateSessionIntegrationTest extends ApplicationIntegrationTest Foo foo = new Foo("Exception Solved"); fooRepository.save(foo); foo = null; - foo = fooRepository.get(1); + foo = fooRepository.findByName("Exception Solved"); assertThat(foo, notNullValue()); assertThat(foo.getId(), is(1)); diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java index 8de7068949..5c8d10223b 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java @@ -6,9 +6,11 @@ import org.baeldung.session.exception.repository.FooRepository; import org.hibernate.HibernateException; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.TestPropertySource; import org.springframework.transaction.annotation.Transactional; @Transactional +@TestPropertySource("classpath:exception-hibernate.properties") public class NoHibernateSessionIntegrationTest extends ApplicationIntegrationTest { @Autowired private FooRepository fooRepository; diff --git a/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java index bd1ae2c8fa..1356de6d0e 100644 --- a/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java @@ -43,7 +43,7 @@ public class CustomConverterIntegrationTest { @Test public void whenConvertingToBigDecimalUsingGenericConverter_thenSuccess() { - assertThat(conversionService.convert(Integer.valueOf(11), BigDecimal.class)).isEqualTo(BigDecimal.valueOf(11.00).setScale(2, BigDecimal.ROUND_HALF_EVEN)); + assertThat(conversionService.convert(Integer.valueOf(11), BigDecimal.class)).isEqualTo(BigDecimal.valueOf(11.00).setScale(0, BigDecimal.ROUND_HALF_EVEN)); assertThat(conversionService.convert(Double.valueOf(25.23), BigDecimal.class)).isEqualByComparingTo(BigDecimal.valueOf(Double.valueOf(25.23))); assertThat(conversionService.convert("2.32", BigDecimal.class)).isEqualTo(BigDecimal.valueOf(2.32)); } diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java index 4eec62db13..df28111a57 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java @@ -1,9 +1,11 @@ package org.baeldung.demo.boottest; -import org.baeldung.demo.boottest.Employee; -import org.baeldung.demo.boottest.EmployeeRepository; -import org.baeldung.demo.boottest.EmployeeService; -import org.baeldung.demo.boottest.EmployeeServiceImpl; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -15,11 +17,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; -import java.util.Arrays; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - @RunWith(SpringRunner.class) public class EmployeeServiceImplIntegrationTest { @@ -50,9 +47,9 @@ public class EmployeeServiceImplIntegrationTest { Mockito.when(employeeRepository.findByName(john.getName())).thenReturn(john); Mockito.when(employeeRepository.findByName(alex.getName())).thenReturn(alex); Mockito.when(employeeRepository.findByName("wrong_name")).thenReturn(null); - Mockito.when(employeeRepository.findById(john.getId()).orElse(null)).thenReturn(john); + Mockito.when(employeeRepository.findById(john.getId())).thenReturn(Optional.of(john)); Mockito.when(employeeRepository.findAll()).thenReturn(allEmployees); - Mockito.when(employeeRepository.findById(-99L).orElse(null)).thenReturn(null); + Mockito.when(employeeRepository.findById(-99L)).thenReturn(Optional.empty()); } @Test From deb27c1e3bbd7b2dc6416a70a0004a1f359a8f71 Mon Sep 17 00:00:00 2001 From: Tonnix Date: Sun, 29 Jul 2018 18:07:16 +0300 Subject: [PATCH 38/38] Added PR files for BAEL-2031 (#4844) * Added source files for BAEL-2031 * Added test files for BAEL-2031 --- ...lectionStreamsUsingCommonsEmptyIfNull.java | 19 +++++++ ...ionStreamsUsingJava8OptionalContainer.java | 21 ++++++++ ...ctionStreamsUsingNullDereferenceCheck.java | 20 +++++++ ...treamsUsingCommonsEmptyIfNullUnitTest.java | 41 ++++++++++++++ ...msUsingJava8OptionalContainerUnitTest.java | 53 +++++++++++++++++++ ...eamsUsingNullDereferenceCheckUnitTest.java | 45 ++++++++++++++++ 6 files changed, 199 insertions(+) create mode 100644 core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java create mode 100644 core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java create mode 100644 core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java create mode 100644 core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java create mode 100644 core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java create mode 100644 core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java new file mode 100644 index 0000000000..7587cc6834 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java @@ -0,0 +1,19 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Collection; +import java.util.stream.Stream; +import static org.apache.commons.collections4.CollectionUtils.emptyIfNull; + +public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull { + + /** + * This method shows how to make a null safe stream from a collection through the use of + * emptyIfNull() method from Apache Commons CollectionUtils library + * + * @param collection The collection that is to be converted into a stream + * @return The stream that has been created from the collection or an empty stream if the collection is null + */ + public Stream collectionAsStream(Collection collection) { + return emptyIfNull(collection).stream(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java new file mode 100644 index 0000000000..ae8e399d53 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java @@ -0,0 +1,21 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Collection; +import java.util.Optional; +import java.util.stream.Stream; + +public class NullSafeCollectionStreamsUsingJava8OptionalContainer { + + /** + * This method shows how to make a null safe stream from a collection through the use of + * Java SE 8’s Optional Container + * + * @param collection The collection that is to be converted into a stream + * @return The stream that has been created from the collection or an empty stream if the collection is null + */ + public Stream collectionAsStream(Collection collection) { + return Optional.ofNullable(collection) + .map(Collection::stream) + .orElseGet(Stream::empty); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java new file mode 100644 index 0000000000..63b6d34f11 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java @@ -0,0 +1,20 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Collection; +import java.util.stream.Stream; + +public class NullSafeCollectionStreamsUsingNullDereferenceCheck { + + /** + * This method shows how to make a null safe stream from a collection through the use of a check + * to prevent null dereferences + * + * @param collection The collection that is to be converted into a stream + * @return The stream that has been created from the collection or an empty stream if the collection is null + */ + public Stream collectionAsStream(Collection collection) { + return collection == null ? Stream.empty() : collection.stream(); + } + + +} diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java new file mode 100644 index 0000000000..f68df2c821 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.stream.Stream; +import org.junit.Test; +import static org.junit.Assert.*; + + +public class NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest { + + private final NullSafeCollectionStreamsUsingCommonsEmptyIfNull instance = + new NullSafeCollectionStreamsUsingCommonsEmptyIfNull(); + + @Test + public void whenCollectionIsNull_thenExpectAnEmptyStream() { + Collection collection = null; + Stream expResult = Stream.empty(); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + + } + + @Test + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { + + Collection collection = Arrays.asList("a", "b", "c"); + Stream expResult = Arrays.stream(new String[] { "a", "b", "c" }); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + private static void assertStreamEquals(Stream s1, Stream s2) { + Iterator iter1 = s1.iterator(), iter2 = s2.iterator(); + while (iter1.hasNext() && iter2.hasNext()) + assertEquals(iter1.next(), iter2.next()); + assert !iter1.hasNext() && !iter2.hasNext(); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java new file mode 100644 index 0000000000..4df3482633 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java @@ -0,0 +1,53 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.baeldung.nullsafecollectionstreams; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.stream.Stream; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Kwaje Anthony + */ +public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest { + + private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = + new NullSafeCollectionStreamsUsingJava8OptionalContainer(); + + @Test + public void whenCollectionIsNull_thenExpectAnEmptyStream() { + Collection collection = null; + Stream expResult = Stream.empty(); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + + } + + @Test + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { + + Collection collection = Arrays.asList("a", "b", "c"); + Stream expResult = Arrays.stream(new String[] { "a", "b", "c" }); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + private static void assertStreamEquals(Stream s1, Stream s2) { + Iterator iter1 = s1.iterator(), iter2 = s2.iterator(); + while (iter1.hasNext() && iter2.hasNext()) + assertEquals(iter1.next(), iter2.next()); + assert !iter1.hasNext() && !iter2.hasNext(); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java new file mode 100644 index 0000000000..ddb4dcdc12 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java @@ -0,0 +1,45 @@ + +package com.baeldung.nullsafecollectionstreams; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.stream.Stream; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Kwaje Anthony + */ +public class NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest { + + private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance = + new NullSafeCollectionStreamsUsingNullDereferenceCheck(); + + @Test + public void whenCollectionIsNull_thenExpectAnEmptyStream() { + Collection collection = null; + Stream expResult = Stream.empty(); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + + } + + @Test + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { + + Collection collection = Arrays.asList("a", "b", "c"); + Stream expResult = Arrays.stream(new String[] { "a", "b", "c" }); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + private static void assertStreamEquals(Stream s1, Stream s2) { + Iterator iter1 = s1.iterator(), iter2 = s2.iterator(); + while (iter1.hasNext() && iter2.hasNext()) + assertEquals(iter1.next(), iter2.next()); + assert !iter1.hasNext() && !iter2.hasNext(); + } + +}