From 31ddc6a45dc01d066b0000fd616084ba4a33a374 Mon Sep 17 00:00:00 2001 From: mobin Date: Sat, 15 Jan 2022 16:37:28 +0530 Subject: [PATCH 01/43] Move arrive and wait after thread sleep and detailed logging --- .../baeldung/concurrent/phaser/LongRunningAction.java | 9 +++++++-- .../com/baeldung/concurrent/phaser/PhaserUnitTest.java | 7 +++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java index dd1487b5cb..c022c02085 100644 --- a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java +++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java @@ -16,12 +16,17 @@ class LongRunningAction implements Runnable { public void run() { System.out.println("This is phase " + ph.getPhase()); System.out.println("Thread " + threadName + " before long running action"); - ph.arriveAndAwaitAdvance(); + try { - Thread.sleep(20); + Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } + + System.out.println("Thread " + threadName + " action completed and waiting for others"); + ph.arriveAndAwaitAdvance(); + System.out.println("Thread " + threadName + " proceeding in phase " + ph.getPhase()); + ph.arriveAndDeregister(); } } \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java index a7b56e1151..88c18b5149 100644 --- a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java +++ b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java @@ -26,13 +26,20 @@ public class PhaserUnitTest { executorService.submit(new LongRunningAction("thread-3", ph)); //then + System.out.println("Thread " + Thread.currentThread().getName() + " waiting for others"); ph.arriveAndAwaitAdvance(); + System.out.println("Thread " + Thread.currentThread().getName() + " proceeding in phase " + ph.getPhase()); + assertEquals(1, ph.getPhase()); //and executorService.submit(new LongRunningAction("thread-4", ph)); executorService.submit(new LongRunningAction("thread-5", ph)); + + System.out.println("Thread " + Thread.currentThread().getName() + " waiting for others"); ph.arriveAndAwaitAdvance(); + System.out.println("Thread " + Thread.currentThread().getName() + " proceeding in phase " + ph.getPhase()); + assertEquals(2, ph.getPhase()); From ad893be8ac4d6fea0f1e2799cad6b3c8c3ba40c1 Mon Sep 17 00:00:00 2001 From: palani-a Date: Sun, 30 Jan 2022 22:12:18 +0530 Subject: [PATCH 02/43] Implementation for Simple Hexagonal Architecture --- .../ConferenceApplication.java | 15 ++ .../controllers/SessionController.java | 54 ++++++++ .../controllers/SpeakerController.java | 57 ++++++++ .../simplehexagonal/domain/Session.java | 58 ++++++++ .../simplehexagonal/domain/Speaker.java | 90 ++++++++++++ .../domain/repository/SessionRepository.java | 17 +++ .../domain/repository/SpeakerRepository.java | 17 +++ .../domain/services/SessionService.java | 19 +++ .../domain/services/SessionServiceImpl.java | 40 ++++++ .../domain/services/SpeakerService.java | 19 +++ .../domain/services/SpeakerServiceImpl.java | 39 ++++++ .../config/BeanConfiguration.java | 30 ++++ .../repositories/SessionEntity.java | 99 ++++++++++++++ .../repositories/SessionJpaRepository.java | 9 ++ .../repositories/SessionRepositoryImpl.java | 42 ++++++ .../repositories/SpeakerEntity.java | 129 ++++++++++++++++++ .../repositories/SpeakerJpaRepository.java | 9 ++ .../repositories/SpeakerRepositoryImpl.java | 42 ++++++ .../resources/simple-hexagonal.properties | 8 ++ .../services/SessionServiceUnitTest.java | 74 ++++++++++ .../services/SpeakerServiceUnitTest.java | 74 ++++++++++ 21 files changed, 941 insertions(+) create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java create mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java create mode 100644 ddd/src/main/resources/simple-hexagonal.properties create mode 100644 ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java create mode 100644 ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java b/ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java new file mode 100644 index 0000000000..106b013ab6 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.simplehexagonal; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication(scanBasePackages = "com.baeldung.simplehexagonal") +@PropertySource(value = { "classpath:simple-hexagonal.properties" }) +public class ConferenceApplication { + + public static void main(String[] args) { + SpringApplication.run(ConferenceApplication.class, args); + } + +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java b/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java new file mode 100644 index 0000000000..5cc3880851 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java @@ -0,0 +1,54 @@ +package com.baeldung.simplehexagonal.application.controllers; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +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.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.simplehexagonal.domain.Session; +import com.baeldung.simplehexagonal.domain.services.SessionService; + +@RestController +@RequestMapping("/api/v1/sessions") +public class SessionController { + + private SessionService sessionService; + + @Autowired + public SessionController(SessionService sessionService) { + this.sessionService = sessionService; + } + + @GetMapping + public List findAll() { + return sessionService.findAll(); + } + + @GetMapping + @RequestMapping("{id}") + public Session get(@PathVariable Long id) { + return sessionService.get(id); + } + + @PostMapping + public Session create(@RequestBody final Session session) { + return sessionService.create(session); + } + + @RequestMapping(value = "{id}", method = RequestMethod.DELETE) + public void delete(@PathVariable Long id) { + sessionService.delete(id); + } + + @RequestMapping(value = "{id}", method = RequestMethod.PUT) + public Session update(@PathVariable Long id, @RequestBody Session session) { + return sessionService.update(id, session); + } + +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java b/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java new file mode 100644 index 0000000000..bea5370da7 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java @@ -0,0 +1,57 @@ +package com.baeldung.simplehexagonal.application.controllers; + +import java.util.List; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +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.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.simplehexagonal.domain.Speaker; +import com.baeldung.simplehexagonal.domain.services.SpeakerService; + +@RestController +@RequestMapping("/api/v1/speakers") +public class SpeakerController { + + private SpeakerService speakerService; + + @Autowired + public SpeakerController(SpeakerService speakerService) { + this.speakerService = speakerService; + } + + @GetMapping + public List findAll() { + return speakerService.findAll(); + } + + @GetMapping + @RequestMapping("{id}") + public Speaker get(@PathVariable Long id) { + return speakerService.get(id); + } + + @PostMapping + public Speaker create(@RequestBody final Speaker speaker) { + return speakerService.save(speaker); + } + + @RequestMapping(value = "{id}", method = RequestMethod.DELETE) + public void delete(@PathVariable Long id) { + speakerService.delete(id); + } + + @RequestMapping(value = "{id}", method = RequestMethod.PUT) + public Speaker update(@PathVariable Long id, @RequestBody Speaker speaker) { + Speaker currentSpeaker = speakerService.get(id); + BeanUtils.copyProperties(speaker, currentSpeaker, "speaker_id"); + return speakerService.save(currentSpeaker); + } + +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java new file mode 100644 index 0000000000..93c88b1461 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java @@ -0,0 +1,58 @@ +package com.baeldung.simplehexagonal.domain; + +import java.util.List; + +public class Session { + + private Long sessionId; + + private String sessionName; + private String sessionDescription; + private Integer sessionLength; + + private List speakers; + + public Session() { + } + + public Long getSessionId() { + return sessionId; + } + + public void setSessionId(Long sessionId) { + this.sessionId = sessionId; + } + + public String getSessionName() { + return sessionName; + } + + public void setSessionName(String sessionName) { + this.sessionName = sessionName; + } + + public String getSessionDescription() { + return sessionDescription; + } + + public void setSessionDescription(String sessionDescription) { + this.sessionDescription = sessionDescription; + } + + public Integer getSessionLength() { + return sessionLength; + } + + public void setSessionLength(Integer sessionLength) { + this.sessionLength = sessionLength; + } + + public List getSpeakers() { + return speakers; + } + + public void setSpeakers(List speakers) { + this.speakers = speakers; + } + +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java new file mode 100644 index 0000000000..078c7d38f7 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java @@ -0,0 +1,90 @@ +package com.baeldung.simplehexagonal.domain; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +public class Speaker { + + private Long speakerId; + + private String firstName; + private String lastName; + private String title; + private String company; + private String speakerBio; + + private byte[] speakerPhoto; + + @JsonIgnore + private List sessions; + + public Speaker() { + + } + + public Long getSpeakerId() { + return speakerId; + } + + public void setSpeakerId(Long speakerId) { + this.speakerId = speakerId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String getSpeakerBio() { + return speakerBio; + } + + public void setSpeakerBio(String speakerBio) { + this.speakerBio = speakerBio; + } + + public byte[] getSpeakerPhoto() { + return speakerPhoto; + } + + public void setSpeakerPhoto(byte[] speakerPhoto) { + this.speakerPhoto = speakerPhoto; + } + + public List getSessions() { + return sessions; + } + + public void setSessions(List sessions) { + this.sessions = sessions; + } + +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java new file mode 100644 index 0000000000..7011506ffb --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.simplehexagonal.domain.repository; + +import java.util.List; + +import com.baeldung.simplehexagonal.domain.Session; + +public interface SessionRepository { + + List findAll(); + + Session findById(Long id); + + Session save(Session session); + + void deleteById(Long id); + +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java new file mode 100644 index 0000000000..a12863f85f --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.simplehexagonal.domain.repository; + +import java.util.List; + +import com.baeldung.simplehexagonal.domain.Speaker; + +public interface SpeakerRepository { + + List findAll(); + + Speaker findById(Long id); + + Speaker save(Speaker Speaker); + + void deleteById(Long id); + +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java new file mode 100644 index 0000000000..eff942672e --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java @@ -0,0 +1,19 @@ +package com.baeldung.simplehexagonal.domain.services; + +import java.util.List; + +import com.baeldung.simplehexagonal.domain.Session; + +public interface SessionService { + + List findAll(); + + Session get(Long id); + + Session create(Session session); + + void delete(Long id); + + Session update(Long id, Session session); + +} \ No newline at end of file diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java new file mode 100644 index 0000000000..abf8ea1f86 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java @@ -0,0 +1,40 @@ +package com.baeldung.simplehexagonal.domain.services; + +import java.util.List; + +import org.springframework.beans.BeanUtils; + +import com.baeldung.simplehexagonal.domain.Session; +import com.baeldung.simplehexagonal.domain.repository.SessionRepository; + +public class SessionServiceImpl implements SessionService { + + private SessionRepository sessionRepository; + + public SessionServiceImpl(SessionRepository sessionRepository) { + this.sessionRepository = sessionRepository; + } + + public List findAll() { + return sessionRepository.findAll(); + } + + public Session get(Long id) { + return sessionRepository.findById(id); + } + + public Session create(Session session) { + return sessionRepository.save(session); + } + + public void delete(Long id) { + sessionRepository.deleteById(id); + } + + public Session update(Long id, Session session) { + Session currentSession = sessionRepository.findById(id); + BeanUtils.copyProperties(session, currentSession, "session_id"); + return sessionRepository.save(currentSession); + } + +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java new file mode 100644 index 0000000000..041fb24fe1 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java @@ -0,0 +1,19 @@ +package com.baeldung.simplehexagonal.domain.services; + +import java.util.List; + +import com.baeldung.simplehexagonal.domain.Speaker; + +public interface SpeakerService { + + List findAll(); + + Speaker get(Long id); + + Speaker save(Speaker speaker); + + void delete(Long id); + + Speaker update(Long id, Speaker speaker); + +} \ No newline at end of file diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java new file mode 100644 index 0000000000..cf01259983 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java @@ -0,0 +1,39 @@ +package com.baeldung.simplehexagonal.domain.services; + +import java.util.List; + +import org.springframework.beans.BeanUtils; + +import com.baeldung.simplehexagonal.domain.Speaker; +import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository; + +public class SpeakerServiceImpl implements SpeakerService { + + private SpeakerRepository speakerRepository; + + public SpeakerServiceImpl(SpeakerRepository speakerRepository) { + this.speakerRepository = speakerRepository; + } + + public List findAll() { + return speakerRepository.findAll(); + } + + public Speaker get(Long id) { + return speakerRepository.findById(id); + } + + public Speaker save(Speaker speaker) { + return speakerRepository.save(speaker); + } + + public void delete(Long id) { + speakerRepository.deleteById(id); + } + + public Speaker update(Long id, Speaker speaker) { + Speaker currentSpeaker = speakerRepository.findById(id); + BeanUtils.copyProperties(speaker, currentSpeaker, "speaker_id"); + return speakerRepository.save(currentSpeaker); + } +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java new file mode 100644 index 0000000000..c1875354d9 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java @@ -0,0 +1,30 @@ +package com.baeldung.simplehexagonal.infrastructure.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +import com.baeldung.simplehexagonal.ConferenceApplication; +import com.baeldung.simplehexagonal.domain.repository.SessionRepository; +import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository; +import com.baeldung.simplehexagonal.domain.services.SessionService; +import com.baeldung.simplehexagonal.domain.services.SessionServiceImpl; +import com.baeldung.simplehexagonal.domain.services.SpeakerService; +import com.baeldung.simplehexagonal.domain.services.SpeakerServiceImpl; + +@Configuration +@ComponentScan(basePackageClasses = ConferenceApplication.class) +@EnableJpaRepositories(basePackages = "com.baeldung.simplehexagonal") +public class BeanConfiguration { + + @Bean + SessionService sessionService(SessionRepository sessionRepository) { + return new SessionServiceImpl(sessionRepository); + } + + @Bean + SpeakerService speakerService(SpeakerRepository speakerRepository) { + return new SpeakerServiceImpl(speakerRepository); + } +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java new file mode 100644 index 0000000000..b9d9c765da --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java @@ -0,0 +1,99 @@ +package com.baeldung.simplehexagonal.infrastructure.repositories; + +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; + +import com.baeldung.simplehexagonal.domain.Session; +import com.baeldung.simplehexagonal.domain.Speaker; + +@Entity(name = "sessions") +public class SessionEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long session_id; + + private String session_name; + private String session_description; + private Integer session_length; + + @ManyToMany + @JoinTable(name = "session_speakers", joinColumns = @JoinColumn(name = "session_id"), inverseJoinColumns = @JoinColumn(name = "speaker_id")) + private List speakerEntities; + + public SessionEntity() { + } + + public SessionEntity(Session session) { + this.setSession_id(session.getSessionId()); + this.setSession_name(session.getSessionName()); + this.setSession_description(session.getSessionDescription()); + this.setSession_length(session.getSessionLength()); + List speakerEntities = session.getSpeakers() + .stream() + .map(it -> new SpeakerEntity(it)) + .toList(); + this.speakerEntities = speakerEntities; + } + + public Session toSession() { + Session session = new Session(); + session.setSessionId(session_id); + session.setSessionName(session_name); + session.setSessionDescription(session_description); + session.setSessionLength(session_length); + List speakers = speakerEntities.stream() + .map(it -> it.toSpeaker()) + .toList(); + session.setSpeakers(speakers); + return session; + } + + public Long getSession_id() { + return session_id; + } + + public void setSession_id(Long session_id) { + this.session_id = session_id; + } + + public String getSession_name() { + return session_name; + } + + public void setSession_name(String session_name) { + this.session_name = session_name; + } + + public String getSession_description() { + return session_description; + } + + public void setSession_description(String session_description) { + this.session_description = session_description; + } + + public Integer getSession_length() { + return session_length; + } + + public void setSession_length(Integer session_length) { + this.session_length = session_length; + } + + public List getSpeakerEntities() { + return speakerEntities; + } + + public void setSpeakerEntities(List speakerEntities) { + this.speakerEntities = speakerEntities; + } + +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java new file mode 100644 index 0000000000..83cc944dd6 --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.simplehexagonal.infrastructure.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SessionJpaRepository extends JpaRepository { + +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java new file mode 100644 index 0000000000..3af9021fff --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java @@ -0,0 +1,42 @@ +package com.baeldung.simplehexagonal.infrastructure.repositories; + +import java.util.List; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.baeldung.simplehexagonal.domain.Session; +import com.baeldung.simplehexagonal.domain.repository.SessionRepository; + +@Component +public class SessionRepositoryImpl implements SessionRepository { + + @Autowired + private SessionJpaRepository sessionJpaRepository; + + @Override + public List findAll() { + return sessionJpaRepository.findAll() + .stream() + .map(SessionEntity::toSession) + .collect(Collectors.toList()); + } + + @Override + public Session findById(Long id) { + SessionEntity sessionEntity = sessionJpaRepository.getById(id); + return sessionEntity.toSession(); + } + + @Override + public Session save(Session session) { + return sessionJpaRepository.saveAndFlush(new SessionEntity(session)) + .toSession(); + } + + public void deleteById(Long id) { + sessionJpaRepository.deleteById(id); + } + +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java new file mode 100644 index 0000000000..8937ac578f --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java @@ -0,0 +1,129 @@ +package com.baeldung.simplehexagonal.infrastructure.repositories; + +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.ManyToMany; + +import org.hibernate.annotations.Type; + +import com.baeldung.simplehexagonal.domain.Speaker; +import com.fasterxml.jackson.annotation.JsonIgnore; + +@Entity(name = "speakers") +public class SpeakerEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long speaker_id; + + private String first_name; + private String last_name; + private String title; + private String company; + private String speaker_bio; + + @Lob + @Type(type = "org.hibernate.type.BinaryType") + private byte[] speaker_photo; + + @JsonIgnore + @ManyToMany(mappedBy = "speakerEntities", fetch = FetchType.LAZY) + private List sessionEntities; + + public SpeakerEntity() { + + } + + public SpeakerEntity(Speaker speaker) { + this.setSpeaker_id(speaker.getSpeakerId()); + this.setFirst_name(speaker.getFirstName()); + this.setLast_name(speaker.getLastName()); + this.setTitle(speaker.getTitle()); + this.setCompany(speaker.getCompany()); + this.setSpeaker_bio(speaker.getSpeakerBio()); + this.setSpeaker_photo(speaker.getSpeakerPhoto()); + } + + public Speaker toSpeaker() { + Speaker speaker = new Speaker(); + speaker.setSpeakerId(speaker_id); + speaker.setFirstName(first_name); + speaker.setLastName(last_name); + speaker.setTitle(title); + speaker.setCompany(company); + speaker.setSpeakerBio(speaker_bio); + speaker.setSpeakerPhoto(speaker_photo); + return speaker; + } + + public Long getSpeaker_id() { + return speaker_id; + } + + public void setSpeaker_id(Long speaker_id) { + this.speaker_id = speaker_id; + } + + public String getFirst_name() { + return first_name; + } + + public void setFirst_name(String first_name) { + this.first_name = first_name; + } + + public String getLast_name() { + return last_name; + } + + public void setLast_name(String last_name) { + this.last_name = last_name; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String getSpeaker_bio() { + return speaker_bio; + } + + public void setSpeaker_bio(String speaker_bio) { + this.speaker_bio = speaker_bio; + } + + public byte[] getSpeaker_photo() { + return speaker_photo; + } + + public void setSpeaker_photo(byte[] speaker_photo) { + this.speaker_photo = speaker_photo; + } + + public List getSessionEntities() { + return sessionEntities; + } + + public void setSessionEntities(List sessionEntities) { + this.sessionEntities = sessionEntities; + } + +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java new file mode 100644 index 0000000000..9bbce066fb --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.simplehexagonal.infrastructure.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SpeakerJpaRepository extends JpaRepository { + +} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java new file mode 100644 index 0000000000..294bd0a1ff --- /dev/null +++ b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java @@ -0,0 +1,42 @@ +package com.baeldung.simplehexagonal.infrastructure.repositories; + +import java.util.List; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.baeldung.simplehexagonal.domain.Speaker; +import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository; + +@Component +public class SpeakerRepositoryImpl implements SpeakerRepository { + + @Autowired + private SpeakerJpaRepository speakerJpaRepository; + + @Override + public List findAll() { + return speakerJpaRepository.findAll() + .stream() + .map(SpeakerEntity::toSpeaker) + .collect(Collectors.toList()); + } + + @Override + public Speaker findById(Long id) { + SpeakerEntity speakerEntity = speakerJpaRepository.getById(id); + return speakerEntity.toSpeaker(); + } + + @Override + public Speaker save(Speaker speaker) { + return speakerJpaRepository.saveAndFlush(new SpeakerEntity(speaker)) + .toSpeaker(); + } + + public void deleteById(Long id) { + speakerJpaRepository.deleteById(id); + } + +} diff --git a/ddd/src/main/resources/simple-hexagonal.properties b/ddd/src/main/resources/simple-hexagonal.properties new file mode 100644 index 0000000000..6277d15543 --- /dev/null +++ b/ddd/src/main/resources/simple-hexagonal.properties @@ -0,0 +1,8 @@ +spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration +spring.datasource.url=jdbc:postgresql://localhost:5432/postgres +spring.datasource.username=postgres +spring.datasource.password=admin +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.hibernate.ddl-auto=none +spring.jpa.show-sql=true +spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false \ No newline at end of file diff --git a/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java b/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java new file mode 100644 index 0000000000..3fdc34e402 --- /dev/null +++ b/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java @@ -0,0 +1,74 @@ +package com.baeldung.simplehexagonal.domain.services; + +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.util.Assert.notNull; + +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import com.baeldung.simplehexagonal.domain.Session; +import com.baeldung.simplehexagonal.domain.repository.SessionRepository; +import com.baeldung.simplehexagonal.domain.services.SessionServiceImpl; + +public class SessionServiceUnitTest { + + private SessionServiceImpl sessionService; + + private SessionRepository sessionRepository; + + Session session; + + @BeforeEach + void setUp() { + sessionRepository = mock(SessionRepository.class); + sessionService = new SessionServiceImpl(sessionRepository); + + session = new Session(); + session.setSessionId(1L); + session.setSessionName("Introduction to Hexagonal Architecture"); + session.setSessionDescription("A quick and practical eample of Hexagonal Architecture"); + session.setSessionLength(30); + + when(sessionRepository.save(Mockito.any())).thenReturn(session); + when(sessionRepository.findById(1L)).thenReturn(session); + } + + @Test + void testFindAll() { + List list = sessionService.findAll(); + notNull(list, "should not return null"); + } + + @Test + void testGet() { + Session mySession = sessionService.get(1L); + notNull(mySession, "should not return null"); + } + + @Test + void testCreate() { + session = sessionService.create(new Session()); + notNull(session.getSessionId(), "Id should be populated"); + } + + @Test + void testDelete() { + try { + sessionService.delete(1L); + } catch (Exception e) { + fail("Should not throw error"); + } + } + + @Test + void testUpdate() { + Session updatedSession = sessionService.update(1L, new Session()); + notNull(updatedSession, "Id should be populated"); + } + +} diff --git a/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java b/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java new file mode 100644 index 0000000000..5fd3f9dcab --- /dev/null +++ b/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java @@ -0,0 +1,74 @@ +package com.baeldung.simplehexagonal.domain.services; + +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.util.Assert.notNull; + +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import com.baeldung.simplehexagonal.domain.Speaker; +import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository; +import com.baeldung.simplehexagonal.domain.services.SpeakerServiceImpl; + +public class SpeakerServiceUnitTest { + + private SpeakerServiceImpl speakerService; + + private SpeakerRepository speakerRepository; + + Speaker speaker; + + @BeforeEach + void setUp() { + speakerRepository = mock(SpeakerRepository.class); + speakerService = new SpeakerServiceImpl(speakerRepository); + + speaker = new Speaker(); + speaker.setSpeakerId(1L); + speaker.setTitle("Mr"); + speaker.setFirstName("Palani"); + speaker.setLastName("Arun"); + + when(speakerRepository.save(Mockito.any())).thenReturn(speaker); + when(speakerRepository.findById(1L)).thenReturn(speaker); + } + + @Test + void testFindAll() { + List list = speakerService.findAll(); + notNull(list, "should not return null"); + } + + @Test + void testGet() { + Speaker mySpeaker = speakerService.get(1L); + notNull(mySpeaker, "should not return null"); + } + + @Test + void testCreate() { + speaker = speakerService.save(new Speaker()); + notNull(speaker.getSpeakerId(), "Id should be populated"); + } + + @Test + void testDelete() { + try { + speakerService.delete(1L); + } catch (Exception e) { + fail("Should not throw error"); + } + } + + @Test + void testUpdate() { + Speaker updatedSpeaker = speakerService.update(1L, new Speaker()); + notNull(updatedSpeaker, "Id should be populated"); + } + +} From 295bf661f31b0f6450a183472c9cda812e6c47c6 Mon Sep 17 00:00:00 2001 From: sharifi Date: Mon, 31 Jan 2022 10:48:53 +0330 Subject: [PATCH 03/43] BAEL-5300: add required dependency --- spring-cloud/spring-cloud-openfeign/pom.xml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/spring-cloud/spring-cloud-openfeign/pom.xml b/spring-cloud/spring-cloud-openfeign/pom.xml index 3e59f512db..480663eb1c 100644 --- a/spring-cloud/spring-cloud-openfeign/pom.xml +++ b/spring-cloud/spring-cloud-openfeign/pom.xml @@ -48,7 +48,15 @@ io.github.openfeign.form feign-form-spring - + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.security + spring-security-oauth2-client + org.springframework.boot spring-boot-starter-test From d1ef70e63dde6b85494d455d5d40c520361a336b Mon Sep 17 00:00:00 2001 From: sharifi Date: Mon, 31 Jan 2022 10:49:16 +0330 Subject: [PATCH 04/43] BAEL-5300: add oauth2 client info --- .../src/main/resources/application.properties | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/spring-cloud/spring-cloud-openfeign/src/main/resources/application.properties b/spring-cloud/spring-cloud-openfeign/src/main/resources/application.properties index 41bbbde2c3..7188b74c9b 100644 --- a/spring-cloud/spring-cloud-openfeign/src/main/resources/application.properties +++ b/spring-cloud/spring-cloud-openfeign/src/main/resources/application.properties @@ -1,3 +1,10 @@ +server.port=8085 +spring.main.allow-bean-definition-overriding=true spring.application.name= openfeign logging.level.com.baeldung.cloud.openfeign.client: DEBUG feign.hystrix.enabled=true + +spring.security.oauth2.client.registration.keycloak.authorization-grant-type=client_credentials +spring.security.oauth2.client.registration.keycloak.client-id=payment-app +spring.security.oauth2.client.registration.keycloak.client-secret=863e9de4-33d4-4471-b35e-f8d2434385bb +spring.security.oauth2.client.provider.keycloak.token-uri=http://localhost:8083/auth/realms/master/protocol/openid-connect/token From e459737a66622ae0242e7d4b8f356ad46acefe18 Mon Sep 17 00:00:00 2001 From: sharifi Date: Mon, 31 Jan 2022 10:49:51 +0330 Subject: [PATCH 05/43] BAEL-5300: add payment resources code --- .../cloud/openfeign/client/PaymentClient.java | 16 +++++++++++++ .../controller/PaymentController.java | 24 +++++++++++++++++++ .../cloud/openfeign/model/Payment.java | 23 ++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/PaymentClient.java create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/PaymentController.java create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Payment.java diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/PaymentClient.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/PaymentClient.java new file mode 100644 index 0000000000..91932fb7d8 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/PaymentClient.java @@ -0,0 +1,16 @@ +package com.baeldung.cloud.openfeign.client; + +import com.baeldung.cloud.openfeign.model.Payment; +import com.baeldung.cloud.openfeign.oauthfeign.OAuthFeignConfig; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import java.util.List; + +@FeignClient(name = "payment-client", url = "http://localhost:8081/resource-server-jwt", configuration = OAuthFeignConfig.class) +public interface PaymentClient { + + @RequestMapping(value = "/payments", method = RequestMethod.GET) + List getPayments(); +} diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/PaymentController.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/PaymentController.java new file mode 100644 index 0000000000..97c9437ce1 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/PaymentController.java @@ -0,0 +1,24 @@ +package com.baeldung.cloud.openfeign.controller; + +import com.baeldung.cloud.openfeign.client.PaymentClient; +import com.baeldung.cloud.openfeign.model.Payment; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +public class PaymentController { + + private final PaymentClient paymentClient; + + public PaymentController(PaymentClient paymentClient) { + this.paymentClient = paymentClient; + } + + @GetMapping("/payments") + public List getPayments() { + List payments = paymentClient.getPayments(); + return payments; + } +} diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Payment.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Payment.java new file mode 100644 index 0000000000..c6d45bedbd --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Payment.java @@ -0,0 +1,23 @@ +package com.baeldung.cloud.openfeign.model; + +public class Payment { + + private String id; + private double amount; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public double getAmount() { + return amount; + } + + public void setAmount(double amount) { + this.amount = amount; + } +} From 10dd6acd33f6bd2db32ef22387f18e0f21fa9f39 Mon Sep 17 00:00:00 2001 From: sharifi Date: Mon, 31 Jan 2022 10:50:19 +0330 Subject: [PATCH 06/43] BAEL-5300: add openfeign config --- .../OAuthClientCredentialsFeignManager.java | 85 +++++++++++++++++++ .../oauthfeign/OAuthFeignConfig.java | 46 ++++++++++ 2 files changed, 131 insertions(+) create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthClientCredentialsFeignManager.java create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthFeignConfig.java diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthClientCredentialsFeignManager.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthClientCredentialsFeignManager.java new file mode 100644 index 0000000000..5e958a93de --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthClientCredentialsFeignManager.java @@ -0,0 +1,85 @@ +package com.baeldung.cloud.openfeign.oauthfeign; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager; +import org.springframework.security.oauth2.client.registration.ClientRegistration; + +import java.util.Collection; +import java.util.Collections; + +import static java.util.Objects.isNull; + +public class OAuthClientCredentialsFeignManager { + + private static final Logger logger = LoggerFactory.getLogger(OAuthClientCredentialsFeignManager.class); + + private final OAuth2AuthorizedClientManager manager; + private final Authentication principal; + private final ClientRegistration clientRegistration; + + public OAuthClientCredentialsFeignManager(OAuth2AuthorizedClientManager manager, ClientRegistration clientRegistration) { + this.manager = manager; + this.clientRegistration = clientRegistration; + this.principal = createPrincipal(); + } + + private Authentication createPrincipal() { + return new Authentication() { + @Override + public Collection getAuthorities() { + return Collections.emptySet(); + } + + @Override + public Object getCredentials() { + return null; + } + + @Override + public Object getDetails() { + return null; + } + + @Override + public Object getPrincipal() { + return this; + } + + @Override + public boolean isAuthenticated() { + return false; + } + + @Override + public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { + } + + @Override + public String getName() { + return clientRegistration.getClientId(); + } + }; + } + + public String getAccessToken() { + try { + OAuth2AuthorizeRequest oAuth2AuthorizeRequest = OAuth2AuthorizeRequest + .withClientRegistrationId(clientRegistration.getRegistrationId()) + .principal(principal) + .build(); + OAuth2AuthorizedClient client = manager.authorize(oAuth2AuthorizeRequest); + if (isNull(client)) { + throw new IllegalStateException("client credentials flow on " + clientRegistration.getRegistrationId() + " failed, client is null"); + } + return client.getAccessToken().getTokenValue(); + } catch (Exception exp) { + logger.error("client credentials error " + exp.getMessage()); + } + return null; + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthFeignConfig.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthFeignConfig.java new file mode 100644 index 0000000000..70ca45d86e --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuthFeignConfig.java @@ -0,0 +1,46 @@ +package com.baeldung.cloud.openfeign.oauthfeign; + +import feign.RequestInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.client.*; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; + +@Configuration +public class OAuthFeignConfig { + + public static final String CLIENT_REGISTRATION_ID = "keycloak"; + + private final OAuth2AuthorizedClientService oAuth2AuthorizedClientService; + private final ClientRegistrationRepository clientRegistrationRepository; + + public OAuthFeignConfig(OAuth2AuthorizedClientService oAuth2AuthorizedClientService, + ClientRegistrationRepository clientRegistrationRepository) { + this.oAuth2AuthorizedClientService = oAuth2AuthorizedClientService; + this.clientRegistrationRepository = clientRegistrationRepository; + } + + @Bean + public RequestInterceptor requestInterceptor() { + ClientRegistration clientRegistration = clientRegistrationRepository.findByRegistrationId(CLIENT_REGISTRATION_ID); + OAuthClientCredentialsFeignManager clientCredentialsFeignManager = + new OAuthClientCredentialsFeignManager(authorizedClientManager(), clientRegistration); + return requestTemplate -> { + requestTemplate.header("Authorization", "Bearer " + clientCredentialsFeignManager.getAccessToken()); + }; + } + + @Bean + OAuth2AuthorizedClientManager authorizedClientManager() { + OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() + .clientCredentials() + .build(); + + AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager = + new AuthorizedClientServiceOAuth2AuthorizedClientManager(clientRegistrationRepository, oAuth2AuthorizedClientService); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + return authorizedClientManager; + } + +} \ No newline at end of file From 1a70e89e1edb6244aae122148cedba9d132bcbca Mon Sep 17 00:00:00 2001 From: sharifi Date: Mon, 31 Jan 2022 10:50:37 +0330 Subject: [PATCH 07/43] BAEL-5300: add security config --- .../OAuth2WebSecurityConfigurerAdapter.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java diff --git a/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java new file mode 100644 index 0000000000..af60c3849b --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java @@ -0,0 +1,19 @@ +package com.baeldung.cloud.openfeign.oauthfeign; + +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 +public class OAuth2WebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .csrf() + .disable() + .oauth2Client(); + http + .authorizeRequests().anyRequest().permitAll(); + } +} From 6c2d5a66d92e5ed2c5d36310dad3ce2d72f9d0d8 Mon Sep 17 00:00:00 2001 From: sharifi Date: Mon, 31 Jan 2022 10:50:50 +0330 Subject: [PATCH 08/43] BAEL-5300: add test class --- .../openfeign/PaymentClientUnitTest.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java new file mode 100644 index 0000000000..3e53ba0d97 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.cloud.openfeign; + +import com.baeldung.cloud.openfeign.client.PaymentClient; +import com.baeldung.cloud.openfeign.model.Payment; +import com.baeldung.cloud.openfeign.model.Post; +import com.baeldung.cloud.openfeign.service.JSONPlaceHolderService; +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 java.util.List; + +import static org.junit.Assert.assertFalse; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class PaymentClientUnitTest { + + @Autowired + private PaymentClient paymentClient; + + @Test + public void whenGetPayment_thenListPayments() { + + List payments = paymentClient.getPayments(); + + assertFalse(payments.isEmpty()); + } + +} From ff2fe54750cd024c36cd5fe8282378ff2edef830 Mon Sep 17 00:00:00 2001 From: sharifi Date: Mon, 31 Jan 2022 10:53:06 +0330 Subject: [PATCH 09/43] BAEL-5300: improve test class --- .../com/baeldung/cloud/openfeign/PaymentClientUnitTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java index 3e53ba0d97..0372728515 100644 --- a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java +++ b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/PaymentClientUnitTest.java @@ -2,8 +2,6 @@ package com.baeldung.cloud.openfeign; import com.baeldung.cloud.openfeign.client.PaymentClient; import com.baeldung.cloud.openfeign.model.Payment; -import com.baeldung.cloud.openfeign.model.Post; -import com.baeldung.cloud.openfeign.service.JSONPlaceHolderService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; From d2332a5c1096d0fcfd0c853c59cc58f5389ad4a5 Mon Sep 17 00:00:00 2001 From: Mayank Agarwal Date: Sat, 5 Feb 2022 11:52:40 +0530 Subject: [PATCH 10/43] BAEL-5351: Added empty map initialization methods in Java --- .../map/initialize/EmptyMapInitializer.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java new file mode 100644 index 0000000000..bef6fa5374 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java @@ -0,0 +1,49 @@ +package com.baeldung.map.initialize; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.NavigableMap; +import java.util.TreeMap; + +public class EmptyMapInitializer { + + public static Map articleMap; + static { + articleMap = new HashMap<>(); + } + + public static Map createEmptyMap() { + return Collections.emptyMap(); + } + + public void createMapUsingConstructors() { + Map hashMap = new HashMap(); + Map linkedHashMap = new LinkedHashMap(); + Map treeMap = new TreeMap(); + } + + public Map createEmptyMapUsingMapsObject() { + Map emptyMap = Maps.newHashMap(); + return emptyMap; + } + + public Map createGenericEmptyMapUsingMapsObject() { + return Maps.newHashMap(); + } + + public static Map createMapUsingGuava() { + Map emptyMapUsingGuava = + Maps.newHashMap(ImmutableMap.of()); + return emptyMapUsingGuava; + } + + public NavigableMap createEmptyNavigableMap() { + NavigableMap navigableMap = Collections.emptyNavigableMap(); + return navigableMap; + } + +} From 2e8381fbd7be33938bf2b0f4c14aee8bd232524e Mon Sep 17 00:00:00 2001 From: Mayank Agarwal Date: Sat, 5 Feb 2022 11:53:37 +0530 Subject: [PATCH 11/43] BAEL-5351: Added unit tests for empty map methods --- .../initialize/EmptyMapInitializerTest.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java new file mode 100644 index 0000000000..07605cdd45 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java @@ -0,0 +1,30 @@ +package com.baeldung.map.initialize; + +import java.util.Map; +import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class EmptyMapInitializerTest { + + @Test(expected=UnsupportedOperationException.class) + public void givenEmptyMap_whenAddingEntries_throwsException() { + Map map = EmptyMapInitializer.createEmptyMap(); + map.put("key", "value"); + } + + @Test + public void checkStaticMap_isEmpty() { + assertTrue(EmptyMapInitializer.articleMap.isEmpty()); + } + + @Test + public void emptyMapCreated_usingGuava() { + Map emptyMapUsingGuava = EmptyMapInitializer.createMapUsingGuava(); + assertTrue(emptyMapUsingGuava.isEmpty()); + emptyMapUsingGuava.put("key", "value"); + assertFalse(emptyMapUsingGuava.isEmpty()); + } + +} From 7f88e21e92cb60ff14efc637f14cee0ca06c4ea1 Mon Sep 17 00:00:00 2001 From: Mayank Agarwal Date: Sat, 5 Feb 2022 11:56:54 +0530 Subject: [PATCH 12/43] BAEKL-5351: Added method for empty sorted map --- .../com/baeldung/map/initialize/EmptyMapInitializer.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java index bef6fa5374..06185a0f93 100644 --- a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java @@ -7,6 +7,7 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.NavigableMap; +import java.util.SortedMap; import java.util.TreeMap; public class EmptyMapInitializer { @@ -41,6 +42,11 @@ public class EmptyMapInitializer { return emptyMapUsingGuava; } + public SortedMap createEmptySortedMap() { + SortedMap sortedMap = Collections.emptySortedMap(); + return sortedMap; + } + public NavigableMap createEmptyNavigableMap() { NavigableMap navigableMap = Collections.emptyNavigableMap(); return navigableMap; From 54f43a311a223c7e529ad372a2bd4fa9d891d99a Mon Sep 17 00:00:00 2001 From: Mayank Agarwal Date: Sat, 5 Feb 2022 12:03:34 +0530 Subject: [PATCH 13/43] BAEL-5351: Resolved PMD violations by renaming file --- ...MapInitializerTest.java => EmptyMapInitializerUnitTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/{EmptyMapInitializerTest.java => EmptyMapInitializerUnitTest.java} (95%) diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java similarity index 95% rename from core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java rename to core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java index 07605cdd45..82225a46ec 100644 --- a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerTest.java +++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -public class EmptyMapInitializerTest { +public class EmptyMapInitializerUnitTest { @Test(expected=UnsupportedOperationException.class) public void givenEmptyMap_whenAddingEntries_throwsException() { From b35d0ea7c4481c5663487bd9e12a3a7eba0eb3ce Mon Sep 17 00:00:00 2001 From: Mayank Agarwal Date: Tue, 8 Feb 2022 00:40:07 +0530 Subject: [PATCH 14/43] BAEL-5351: Unit Tests name as per BBD convention --- .../map/initialize/EmptyMapInitializerUnitTest.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java index 82225a46ec..b40ffed94b 100644 --- a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java +++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java @@ -15,13 +15,14 @@ public class EmptyMapInitializerUnitTest { } @Test - public void checkStaticMap_isEmpty() { + public void givenEmptyMap_whenChecked_returnsTrue() { assertTrue(EmptyMapInitializer.articleMap.isEmpty()); } @Test - public void emptyMapCreated_usingGuava() { - Map emptyMapUsingGuava = EmptyMapInitializer.createMapUsingGuava(); + public void givenEmptyMap_whenCreatedUsingGuava_returnsEmptyOrNot() { + Map emptyMapUsingGuava = + EmptyMapInitializer.createMapUsingGuava(); assertTrue(emptyMapUsingGuava.isEmpty()); emptyMapUsingGuava.put("key", "value"); assertFalse(emptyMapUsingGuava.isEmpty()); From 3dd2802e2db7ad12994e16e79aa2a4ca2dadc202 Mon Sep 17 00:00:00 2001 From: palani-a Date: Wed, 9 Feb 2022 00:15:13 +0530 Subject: [PATCH 15/43] BAEL-5348: Invert a Map in Java + tests --- .../map/invert/InvertHashMapExample.java | 59 ++++++++++++++++++ .../map/invert/InvertHashMapExampleTest.java | 60 +++++++++++++++++++ 2 files changed, 119 insertions(+) create mode 100644 java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java create mode 100644 java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java b/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java new file mode 100644 index 0000000000..a203fd17c4 --- /dev/null +++ b/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java @@ -0,0 +1,59 @@ +package com.baeldung.map.invert; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +public class InvertHashMapExample { + + public static void main(String[] args) { + + Map map = new HashMap<>(); + map.put("first", 1); + map.put("second", 2); + System.out.println(map); + + invertMapUsingForLoop(map); + invertMapUsingStreams(map); + invertMapUsingMapper(map); + + map.put("two", 2); + invertMapUsingGroupingBy(map); + } + + public static Map invertMapUsingForLoop(Map map) { + Map inversedMap = new HashMap(); + for (Entry entry : map.entrySet()) { + inversedMap.put(entry.getValue(), entry.getKey()); + } + System.out.println(inversedMap); + return inversedMap; + } + + public static Map invertMapUsingStreams(Map map) { + Map inversedMap = map.entrySet() + .stream() + .collect(Collectors.toMap(Entry::getValue, Entry::getKey)); + System.out.println(inversedMap); + return inversedMap; + } + + public static Map invertMapUsingMapper(Map sourceMap) { + Map inversedMap = sourceMap.entrySet() + .stream() + .collect(Collectors.toMap(Entry::getValue, Entry::getKey, (oldValue, newValue) -> oldValue)); + System.out.println(inversedMap); + return inversedMap; + } + + public static Map> invertMapUsingGroupingBy(Map map) { + Map> inversedMap = map.entrySet() + .stream() + .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList()))); + System.out.println(inversedMap); + return inversedMap; + } + +} diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java new file mode 100644 index 0000000000..aecfbfe675 --- /dev/null +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java @@ -0,0 +1,60 @@ +package com.baeldung.map.invert; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class InvertHashMapExampleTest { + + Map sourceMap; + + @BeforeAll + void setup() { + sourceMap = new HashMap<>(); + sourceMap.put("Sunday", 0); + sourceMap.put("Monday", 1); + } + + @Test + void test1_invertMapUsingForLoop() { + Map inversedMap = InvertHashMapExample.invertMapUsingForLoop(sourceMap); + assertNotNull(inversedMap); + assertEquals(inversedMap.size(), 2); + assertEquals("Monday", inversedMap.get(1)); + } + + @Test + void test2_invertMapUsingStreams() { + Map inversedMap = InvertHashMapExample.invertMapUsingStreams(sourceMap); + assertNotNull(inversedMap); + assertEquals(inversedMap.size(), 2); + assertEquals("Monday", inversedMap.get(1)); + } + + @Test + void test3_invertMapUsingMapper() { + Map inversedMap = InvertHashMapExample.invertMapUsingMapper(sourceMap); + assertNotNull(inversedMap); + assertEquals(inversedMap.size(), 2); + assertEquals("Monday", inversedMap.get(1)); + } + + @Test + void test4_invertMapUsingGroupingBy() { + sourceMap.put("monday", 1); + Map> inversedMap = InvertHashMapExample.invertMapUsingGroupingBy(sourceMap); + assertNotNull(inversedMap); + assertEquals(inversedMap.size(), 2); + assertTrue(inversedMap.get(1) instanceof List); + } + +} From 5da21d6bba964c02f0a3936149ff5b0674f5282f Mon Sep 17 00:00:00 2001 From: Palaniappan Arunachalam Date: Wed, 9 Feb 2022 13:21:48 +0530 Subject: [PATCH 16/43] Revert "Implementation for Simple Hexagonal Architecture" This reverts commit ad893be8ac4d6fea0f1e2799cad6b3c8c3ba40c1. --- .../ConferenceApplication.java | 15 -- .../controllers/SessionController.java | 54 -------- .../controllers/SpeakerController.java | 57 -------- .../simplehexagonal/domain/Session.java | 58 -------- .../simplehexagonal/domain/Speaker.java | 90 ------------ .../domain/repository/SessionRepository.java | 17 --- .../domain/repository/SpeakerRepository.java | 17 --- .../domain/services/SessionService.java | 19 --- .../domain/services/SessionServiceImpl.java | 40 ------ .../domain/services/SpeakerService.java | 19 --- .../domain/services/SpeakerServiceImpl.java | 39 ------ .../config/BeanConfiguration.java | 30 ---- .../repositories/SessionEntity.java | 99 -------------- .../repositories/SessionJpaRepository.java | 9 -- .../repositories/SessionRepositoryImpl.java | 42 ------ .../repositories/SpeakerEntity.java | 129 ------------------ .../repositories/SpeakerJpaRepository.java | 9 -- .../repositories/SpeakerRepositoryImpl.java | 42 ------ .../resources/simple-hexagonal.properties | 8 -- .../services/SessionServiceUnitTest.java | 74 ---------- .../services/SpeakerServiceUnitTest.java | 74 ---------- 21 files changed, 941 deletions(-) delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java delete mode 100644 ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java delete mode 100644 ddd/src/main/resources/simple-hexagonal.properties delete mode 100644 ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java delete mode 100644 ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java b/ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java deleted file mode 100644 index 106b013ab6..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/ConferenceApplication.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.simplehexagonal; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.PropertySource; - -@SpringBootApplication(scanBasePackages = "com.baeldung.simplehexagonal") -@PropertySource(value = { "classpath:simple-hexagonal.properties" }) -public class ConferenceApplication { - - public static void main(String[] args) { - SpringApplication.run(ConferenceApplication.class, args); - } - -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java b/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java deleted file mode 100644 index 5cc3880851..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SessionController.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.simplehexagonal.application.controllers; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -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.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import com.baeldung.simplehexagonal.domain.Session; -import com.baeldung.simplehexagonal.domain.services.SessionService; - -@RestController -@RequestMapping("/api/v1/sessions") -public class SessionController { - - private SessionService sessionService; - - @Autowired - public SessionController(SessionService sessionService) { - this.sessionService = sessionService; - } - - @GetMapping - public List findAll() { - return sessionService.findAll(); - } - - @GetMapping - @RequestMapping("{id}") - public Session get(@PathVariable Long id) { - return sessionService.get(id); - } - - @PostMapping - public Session create(@RequestBody final Session session) { - return sessionService.create(session); - } - - @RequestMapping(value = "{id}", method = RequestMethod.DELETE) - public void delete(@PathVariable Long id) { - sessionService.delete(id); - } - - @RequestMapping(value = "{id}", method = RequestMethod.PUT) - public Session update(@PathVariable Long id, @RequestBody Session session) { - return sessionService.update(id, session); - } - -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java b/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java deleted file mode 100644 index bea5370da7..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/application/controllers/SpeakerController.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.simplehexagonal.application.controllers; - -import java.util.List; - -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.annotation.Autowired; -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.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import com.baeldung.simplehexagonal.domain.Speaker; -import com.baeldung.simplehexagonal.domain.services.SpeakerService; - -@RestController -@RequestMapping("/api/v1/speakers") -public class SpeakerController { - - private SpeakerService speakerService; - - @Autowired - public SpeakerController(SpeakerService speakerService) { - this.speakerService = speakerService; - } - - @GetMapping - public List findAll() { - return speakerService.findAll(); - } - - @GetMapping - @RequestMapping("{id}") - public Speaker get(@PathVariable Long id) { - return speakerService.get(id); - } - - @PostMapping - public Speaker create(@RequestBody final Speaker speaker) { - return speakerService.save(speaker); - } - - @RequestMapping(value = "{id}", method = RequestMethod.DELETE) - public void delete(@PathVariable Long id) { - speakerService.delete(id); - } - - @RequestMapping(value = "{id}", method = RequestMethod.PUT) - public Speaker update(@PathVariable Long id, @RequestBody Speaker speaker) { - Speaker currentSpeaker = speakerService.get(id); - BeanUtils.copyProperties(speaker, currentSpeaker, "speaker_id"); - return speakerService.save(currentSpeaker); - } - -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java deleted file mode 100644 index 93c88b1461..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Session.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.simplehexagonal.domain; - -import java.util.List; - -public class Session { - - private Long sessionId; - - private String sessionName; - private String sessionDescription; - private Integer sessionLength; - - private List speakers; - - public Session() { - } - - public Long getSessionId() { - return sessionId; - } - - public void setSessionId(Long sessionId) { - this.sessionId = sessionId; - } - - public String getSessionName() { - return sessionName; - } - - public void setSessionName(String sessionName) { - this.sessionName = sessionName; - } - - public String getSessionDescription() { - return sessionDescription; - } - - public void setSessionDescription(String sessionDescription) { - this.sessionDescription = sessionDescription; - } - - public Integer getSessionLength() { - return sessionLength; - } - - public void setSessionLength(Integer sessionLength) { - this.sessionLength = sessionLength; - } - - public List getSpeakers() { - return speakers; - } - - public void setSpeakers(List speakers) { - this.speakers = speakers; - } - -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java deleted file mode 100644 index 078c7d38f7..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/Speaker.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.baeldung.simplehexagonal.domain; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -public class Speaker { - - private Long speakerId; - - private String firstName; - private String lastName; - private String title; - private String company; - private String speakerBio; - - private byte[] speakerPhoto; - - @JsonIgnore - private List sessions; - - public Speaker() { - - } - - public Long getSpeakerId() { - return speakerId; - } - - public void setSpeakerId(Long speakerId) { - this.speakerId = speakerId; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getCompany() { - return company; - } - - public void setCompany(String company) { - this.company = company; - } - - public String getSpeakerBio() { - return speakerBio; - } - - public void setSpeakerBio(String speakerBio) { - this.speakerBio = speakerBio; - } - - public byte[] getSpeakerPhoto() { - return speakerPhoto; - } - - public void setSpeakerPhoto(byte[] speakerPhoto) { - this.speakerPhoto = speakerPhoto; - } - - public List getSessions() { - return sessions; - } - - public void setSessions(List sessions) { - this.sessions = sessions; - } - -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java deleted file mode 100644 index 7011506ffb..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SessionRepository.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.simplehexagonal.domain.repository; - -import java.util.List; - -import com.baeldung.simplehexagonal.domain.Session; - -public interface SessionRepository { - - List findAll(); - - Session findById(Long id); - - Session save(Session session); - - void deleteById(Long id); - -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java deleted file mode 100644 index a12863f85f..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/repository/SpeakerRepository.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.simplehexagonal.domain.repository; - -import java.util.List; - -import com.baeldung.simplehexagonal.domain.Speaker; - -public interface SpeakerRepository { - - List findAll(); - - Speaker findById(Long id); - - Speaker save(Speaker Speaker); - - void deleteById(Long id); - -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java deleted file mode 100644 index eff942672e..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionService.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.simplehexagonal.domain.services; - -import java.util.List; - -import com.baeldung.simplehexagonal.domain.Session; - -public interface SessionService { - - List findAll(); - - Session get(Long id); - - Session create(Session session); - - void delete(Long id); - - Session update(Long id, Session session); - -} \ No newline at end of file diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java deleted file mode 100644 index abf8ea1f86..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SessionServiceImpl.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.simplehexagonal.domain.services; - -import java.util.List; - -import org.springframework.beans.BeanUtils; - -import com.baeldung.simplehexagonal.domain.Session; -import com.baeldung.simplehexagonal.domain.repository.SessionRepository; - -public class SessionServiceImpl implements SessionService { - - private SessionRepository sessionRepository; - - public SessionServiceImpl(SessionRepository sessionRepository) { - this.sessionRepository = sessionRepository; - } - - public List findAll() { - return sessionRepository.findAll(); - } - - public Session get(Long id) { - return sessionRepository.findById(id); - } - - public Session create(Session session) { - return sessionRepository.save(session); - } - - public void delete(Long id) { - sessionRepository.deleteById(id); - } - - public Session update(Long id, Session session) { - Session currentSession = sessionRepository.findById(id); - BeanUtils.copyProperties(session, currentSession, "session_id"); - return sessionRepository.save(currentSession); - } - -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java deleted file mode 100644 index 041fb24fe1..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerService.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.simplehexagonal.domain.services; - -import java.util.List; - -import com.baeldung.simplehexagonal.domain.Speaker; - -public interface SpeakerService { - - List findAll(); - - Speaker get(Long id); - - Speaker save(Speaker speaker); - - void delete(Long id); - - Speaker update(Long id, Speaker speaker); - -} \ No newline at end of file diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java deleted file mode 100644 index cf01259983..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceImpl.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.simplehexagonal.domain.services; - -import java.util.List; - -import org.springframework.beans.BeanUtils; - -import com.baeldung.simplehexagonal.domain.Speaker; -import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository; - -public class SpeakerServiceImpl implements SpeakerService { - - private SpeakerRepository speakerRepository; - - public SpeakerServiceImpl(SpeakerRepository speakerRepository) { - this.speakerRepository = speakerRepository; - } - - public List findAll() { - return speakerRepository.findAll(); - } - - public Speaker get(Long id) { - return speakerRepository.findById(id); - } - - public Speaker save(Speaker speaker) { - return speakerRepository.save(speaker); - } - - public void delete(Long id) { - speakerRepository.deleteById(id); - } - - public Speaker update(Long id, Speaker speaker) { - Speaker currentSpeaker = speakerRepository.findById(id); - BeanUtils.copyProperties(speaker, currentSpeaker, "speaker_id"); - return speakerRepository.save(currentSpeaker); - } -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java deleted file mode 100644 index c1875354d9..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/config/BeanConfiguration.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.simplehexagonal.infrastructure.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -import com.baeldung.simplehexagonal.ConferenceApplication; -import com.baeldung.simplehexagonal.domain.repository.SessionRepository; -import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository; -import com.baeldung.simplehexagonal.domain.services.SessionService; -import com.baeldung.simplehexagonal.domain.services.SessionServiceImpl; -import com.baeldung.simplehexagonal.domain.services.SpeakerService; -import com.baeldung.simplehexagonal.domain.services.SpeakerServiceImpl; - -@Configuration -@ComponentScan(basePackageClasses = ConferenceApplication.class) -@EnableJpaRepositories(basePackages = "com.baeldung.simplehexagonal") -public class BeanConfiguration { - - @Bean - SessionService sessionService(SessionRepository sessionRepository) { - return new SessionServiceImpl(sessionRepository); - } - - @Bean - SpeakerService speakerService(SpeakerRepository speakerRepository) { - return new SpeakerServiceImpl(speakerRepository); - } -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java deleted file mode 100644 index b9d9c765da..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionEntity.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.baeldung.simplehexagonal.infrastructure.repositories; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; - -import com.baeldung.simplehexagonal.domain.Session; -import com.baeldung.simplehexagonal.domain.Speaker; - -@Entity(name = "sessions") -public class SessionEntity { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long session_id; - - private String session_name; - private String session_description; - private Integer session_length; - - @ManyToMany - @JoinTable(name = "session_speakers", joinColumns = @JoinColumn(name = "session_id"), inverseJoinColumns = @JoinColumn(name = "speaker_id")) - private List speakerEntities; - - public SessionEntity() { - } - - public SessionEntity(Session session) { - this.setSession_id(session.getSessionId()); - this.setSession_name(session.getSessionName()); - this.setSession_description(session.getSessionDescription()); - this.setSession_length(session.getSessionLength()); - List speakerEntities = session.getSpeakers() - .stream() - .map(it -> new SpeakerEntity(it)) - .toList(); - this.speakerEntities = speakerEntities; - } - - public Session toSession() { - Session session = new Session(); - session.setSessionId(session_id); - session.setSessionName(session_name); - session.setSessionDescription(session_description); - session.setSessionLength(session_length); - List speakers = speakerEntities.stream() - .map(it -> it.toSpeaker()) - .toList(); - session.setSpeakers(speakers); - return session; - } - - public Long getSession_id() { - return session_id; - } - - public void setSession_id(Long session_id) { - this.session_id = session_id; - } - - public String getSession_name() { - return session_name; - } - - public void setSession_name(String session_name) { - this.session_name = session_name; - } - - public String getSession_description() { - return session_description; - } - - public void setSession_description(String session_description) { - this.session_description = session_description; - } - - public Integer getSession_length() { - return session_length; - } - - public void setSession_length(Integer session_length) { - this.session_length = session_length; - } - - public List getSpeakerEntities() { - return speakerEntities; - } - - public void setSpeakerEntities(List speakerEntities) { - this.speakerEntities = speakerEntities; - } - -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java deleted file mode 100644 index 83cc944dd6..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionJpaRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.simplehexagonal.infrastructure.repositories; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface SessionJpaRepository extends JpaRepository { - -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java deleted file mode 100644 index 3af9021fff..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SessionRepositoryImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.simplehexagonal.infrastructure.repositories; - -import java.util.List; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.baeldung.simplehexagonal.domain.Session; -import com.baeldung.simplehexagonal.domain.repository.SessionRepository; - -@Component -public class SessionRepositoryImpl implements SessionRepository { - - @Autowired - private SessionJpaRepository sessionJpaRepository; - - @Override - public List findAll() { - return sessionJpaRepository.findAll() - .stream() - .map(SessionEntity::toSession) - .collect(Collectors.toList()); - } - - @Override - public Session findById(Long id) { - SessionEntity sessionEntity = sessionJpaRepository.getById(id); - return sessionEntity.toSession(); - } - - @Override - public Session save(Session session) { - return sessionJpaRepository.saveAndFlush(new SessionEntity(session)) - .toSession(); - } - - public void deleteById(Long id) { - sessionJpaRepository.deleteById(id); - } - -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java deleted file mode 100644 index 8937ac578f..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerEntity.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.baeldung.simplehexagonal.infrastructure.repositories; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Lob; -import javax.persistence.ManyToMany; - -import org.hibernate.annotations.Type; - -import com.baeldung.simplehexagonal.domain.Speaker; -import com.fasterxml.jackson.annotation.JsonIgnore; - -@Entity(name = "speakers") -public class SpeakerEntity { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long speaker_id; - - private String first_name; - private String last_name; - private String title; - private String company; - private String speaker_bio; - - @Lob - @Type(type = "org.hibernate.type.BinaryType") - private byte[] speaker_photo; - - @JsonIgnore - @ManyToMany(mappedBy = "speakerEntities", fetch = FetchType.LAZY) - private List sessionEntities; - - public SpeakerEntity() { - - } - - public SpeakerEntity(Speaker speaker) { - this.setSpeaker_id(speaker.getSpeakerId()); - this.setFirst_name(speaker.getFirstName()); - this.setLast_name(speaker.getLastName()); - this.setTitle(speaker.getTitle()); - this.setCompany(speaker.getCompany()); - this.setSpeaker_bio(speaker.getSpeakerBio()); - this.setSpeaker_photo(speaker.getSpeakerPhoto()); - } - - public Speaker toSpeaker() { - Speaker speaker = new Speaker(); - speaker.setSpeakerId(speaker_id); - speaker.setFirstName(first_name); - speaker.setLastName(last_name); - speaker.setTitle(title); - speaker.setCompany(company); - speaker.setSpeakerBio(speaker_bio); - speaker.setSpeakerPhoto(speaker_photo); - return speaker; - } - - public Long getSpeaker_id() { - return speaker_id; - } - - public void setSpeaker_id(Long speaker_id) { - this.speaker_id = speaker_id; - } - - public String getFirst_name() { - return first_name; - } - - public void setFirst_name(String first_name) { - this.first_name = first_name; - } - - public String getLast_name() { - return last_name; - } - - public void setLast_name(String last_name) { - this.last_name = last_name; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getCompany() { - return company; - } - - public void setCompany(String company) { - this.company = company; - } - - public String getSpeaker_bio() { - return speaker_bio; - } - - public void setSpeaker_bio(String speaker_bio) { - this.speaker_bio = speaker_bio; - } - - public byte[] getSpeaker_photo() { - return speaker_photo; - } - - public void setSpeaker_photo(byte[] speaker_photo) { - this.speaker_photo = speaker_photo; - } - - public List getSessionEntities() { - return sessionEntities; - } - - public void setSessionEntities(List sessionEntities) { - this.sessionEntities = sessionEntities; - } - -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java deleted file mode 100644 index 9bbce066fb..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerJpaRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.simplehexagonal.infrastructure.repositories; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface SpeakerJpaRepository extends JpaRepository { - -} diff --git a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java b/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java deleted file mode 100644 index 294bd0a1ff..0000000000 --- a/ddd/src/main/java/com/baeldung/simplehexagonal/infrastructure/repositories/SpeakerRepositoryImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.simplehexagonal.infrastructure.repositories; - -import java.util.List; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.baeldung.simplehexagonal.domain.Speaker; -import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository; - -@Component -public class SpeakerRepositoryImpl implements SpeakerRepository { - - @Autowired - private SpeakerJpaRepository speakerJpaRepository; - - @Override - public List findAll() { - return speakerJpaRepository.findAll() - .stream() - .map(SpeakerEntity::toSpeaker) - .collect(Collectors.toList()); - } - - @Override - public Speaker findById(Long id) { - SpeakerEntity speakerEntity = speakerJpaRepository.getById(id); - return speakerEntity.toSpeaker(); - } - - @Override - public Speaker save(Speaker speaker) { - return speakerJpaRepository.saveAndFlush(new SpeakerEntity(speaker)) - .toSpeaker(); - } - - public void deleteById(Long id) { - speakerJpaRepository.deleteById(id); - } - -} diff --git a/ddd/src/main/resources/simple-hexagonal.properties b/ddd/src/main/resources/simple-hexagonal.properties deleted file mode 100644 index 6277d15543..0000000000 --- a/ddd/src/main/resources/simple-hexagonal.properties +++ /dev/null @@ -1,8 +0,0 @@ -spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration -spring.datasource.url=jdbc:postgresql://localhost:5432/postgres -spring.datasource.username=postgres -spring.datasource.password=admin -spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect -spring.jpa.hibernate.ddl-auto=none -spring.jpa.show-sql=true -spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false \ No newline at end of file diff --git a/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java b/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java deleted file mode 100644 index 3fdc34e402..0000000000 --- a/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SessionServiceUnitTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.simplehexagonal.domain.services; - -import static org.junit.jupiter.api.Assertions.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.springframework.util.Assert.notNull; - -import java.util.List; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import com.baeldung.simplehexagonal.domain.Session; -import com.baeldung.simplehexagonal.domain.repository.SessionRepository; -import com.baeldung.simplehexagonal.domain.services.SessionServiceImpl; - -public class SessionServiceUnitTest { - - private SessionServiceImpl sessionService; - - private SessionRepository sessionRepository; - - Session session; - - @BeforeEach - void setUp() { - sessionRepository = mock(SessionRepository.class); - sessionService = new SessionServiceImpl(sessionRepository); - - session = new Session(); - session.setSessionId(1L); - session.setSessionName("Introduction to Hexagonal Architecture"); - session.setSessionDescription("A quick and practical eample of Hexagonal Architecture"); - session.setSessionLength(30); - - when(sessionRepository.save(Mockito.any())).thenReturn(session); - when(sessionRepository.findById(1L)).thenReturn(session); - } - - @Test - void testFindAll() { - List list = sessionService.findAll(); - notNull(list, "should not return null"); - } - - @Test - void testGet() { - Session mySession = sessionService.get(1L); - notNull(mySession, "should not return null"); - } - - @Test - void testCreate() { - session = sessionService.create(new Session()); - notNull(session.getSessionId(), "Id should be populated"); - } - - @Test - void testDelete() { - try { - sessionService.delete(1L); - } catch (Exception e) { - fail("Should not throw error"); - } - } - - @Test - void testUpdate() { - Session updatedSession = sessionService.update(1L, new Session()); - notNull(updatedSession, "Id should be populated"); - } - -} diff --git a/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java b/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java deleted file mode 100644 index 5fd3f9dcab..0000000000 --- a/ddd/src/test/java/com/baeldung/simplehexagonal/domain/services/SpeakerServiceUnitTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.simplehexagonal.domain.services; - -import static org.junit.jupiter.api.Assertions.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.springframework.util.Assert.notNull; - -import java.util.List; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import com.baeldung.simplehexagonal.domain.Speaker; -import com.baeldung.simplehexagonal.domain.repository.SpeakerRepository; -import com.baeldung.simplehexagonal.domain.services.SpeakerServiceImpl; - -public class SpeakerServiceUnitTest { - - private SpeakerServiceImpl speakerService; - - private SpeakerRepository speakerRepository; - - Speaker speaker; - - @BeforeEach - void setUp() { - speakerRepository = mock(SpeakerRepository.class); - speakerService = new SpeakerServiceImpl(speakerRepository); - - speaker = new Speaker(); - speaker.setSpeakerId(1L); - speaker.setTitle("Mr"); - speaker.setFirstName("Palani"); - speaker.setLastName("Arun"); - - when(speakerRepository.save(Mockito.any())).thenReturn(speaker); - when(speakerRepository.findById(1L)).thenReturn(speaker); - } - - @Test - void testFindAll() { - List list = speakerService.findAll(); - notNull(list, "should not return null"); - } - - @Test - void testGet() { - Speaker mySpeaker = speakerService.get(1L); - notNull(mySpeaker, "should not return null"); - } - - @Test - void testCreate() { - speaker = speakerService.save(new Speaker()); - notNull(speaker.getSpeakerId(), "Id should be populated"); - } - - @Test - void testDelete() { - try { - speakerService.delete(1L); - } catch (Exception e) { - fail("Should not throw error"); - } - } - - @Test - void testUpdate() { - Speaker updatedSpeaker = speakerService.update(1L, new Speaker()); - notNull(updatedSpeaker, "Id should be populated"); - } - -} From e4c615b52200ef94ce51669b9e443b6b33f4c1ae Mon Sep 17 00:00:00 2001 From: Palaniappan Arunachalam Date: Wed, 9 Feb 2022 13:26:47 +0530 Subject: [PATCH 17/43] Revert "BAEL-5348: Invert a Map in Java + tests" This reverts commit 3dd2802e2db7ad12994e16e79aa2a4ca2dadc202. --- .../map/invert/InvertHashMapExample.java | 59 ------------------ .../map/invert/InvertHashMapExampleTest.java | 60 ------------------- 2 files changed, 119 deletions(-) delete mode 100644 java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java delete mode 100644 java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java b/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java deleted file mode 100644 index a203fd17c4..0000000000 --- a/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.map.invert; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; - -public class InvertHashMapExample { - - public static void main(String[] args) { - - Map map = new HashMap<>(); - map.put("first", 1); - map.put("second", 2); - System.out.println(map); - - invertMapUsingForLoop(map); - invertMapUsingStreams(map); - invertMapUsingMapper(map); - - map.put("two", 2); - invertMapUsingGroupingBy(map); - } - - public static Map invertMapUsingForLoop(Map map) { - Map inversedMap = new HashMap(); - for (Entry entry : map.entrySet()) { - inversedMap.put(entry.getValue(), entry.getKey()); - } - System.out.println(inversedMap); - return inversedMap; - } - - public static Map invertMapUsingStreams(Map map) { - Map inversedMap = map.entrySet() - .stream() - .collect(Collectors.toMap(Entry::getValue, Entry::getKey)); - System.out.println(inversedMap); - return inversedMap; - } - - public static Map invertMapUsingMapper(Map sourceMap) { - Map inversedMap = sourceMap.entrySet() - .stream() - .collect(Collectors.toMap(Entry::getValue, Entry::getKey, (oldValue, newValue) -> oldValue)); - System.out.println(inversedMap); - return inversedMap; - } - - public static Map> invertMapUsingGroupingBy(Map map) { - Map> inversedMap = map.entrySet() - .stream() - .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList()))); - System.out.println(inversedMap); - return inversedMap; - } - -} diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java deleted file mode 100644 index aecfbfe675..0000000000 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapExampleTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.map.invert; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -public class InvertHashMapExampleTest { - - Map sourceMap; - - @BeforeAll - void setup() { - sourceMap = new HashMap<>(); - sourceMap.put("Sunday", 0); - sourceMap.put("Monday", 1); - } - - @Test - void test1_invertMapUsingForLoop() { - Map inversedMap = InvertHashMapExample.invertMapUsingForLoop(sourceMap); - assertNotNull(inversedMap); - assertEquals(inversedMap.size(), 2); - assertEquals("Monday", inversedMap.get(1)); - } - - @Test - void test2_invertMapUsingStreams() { - Map inversedMap = InvertHashMapExample.invertMapUsingStreams(sourceMap); - assertNotNull(inversedMap); - assertEquals(inversedMap.size(), 2); - assertEquals("Monday", inversedMap.get(1)); - } - - @Test - void test3_invertMapUsingMapper() { - Map inversedMap = InvertHashMapExample.invertMapUsingMapper(sourceMap); - assertNotNull(inversedMap); - assertEquals(inversedMap.size(), 2); - assertEquals("Monday", inversedMap.get(1)); - } - - @Test - void test4_invertMapUsingGroupingBy() { - sourceMap.put("monday", 1); - Map> inversedMap = InvertHashMapExample.invertMapUsingGroupingBy(sourceMap); - assertNotNull(inversedMap); - assertEquals(inversedMap.size(), 2); - assertTrue(inversedMap.get(1) instanceof List); - } - -} From 4b1630dc3faee93d6821dc73b2c6f7704f39419e Mon Sep 17 00:00:00 2001 From: Palaniappan Arunachalam Date: Wed, 9 Feb 2022 22:13:21 +0530 Subject: [PATCH 18/43] BAEL-5348: How to invert a Hashmap + tests --- .../map/invert/InvertHashMapExample.java | 59 ++++++++++++++++++ .../map/invert/InvertHashMapUnitTest.java | 60 +++++++++++++++++++ 2 files changed, 119 insertions(+) create mode 100644 java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java create mode 100644 java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java b/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java new file mode 100644 index 0000000000..a203fd17c4 --- /dev/null +++ b/java-collections-maps-3/src/main/java/com/baeldung/map/invert/InvertHashMapExample.java @@ -0,0 +1,59 @@ +package com.baeldung.map.invert; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +public class InvertHashMapExample { + + public static void main(String[] args) { + + Map map = new HashMap<>(); + map.put("first", 1); + map.put("second", 2); + System.out.println(map); + + invertMapUsingForLoop(map); + invertMapUsingStreams(map); + invertMapUsingMapper(map); + + map.put("two", 2); + invertMapUsingGroupingBy(map); + } + + public static Map invertMapUsingForLoop(Map map) { + Map inversedMap = new HashMap(); + for (Entry entry : map.entrySet()) { + inversedMap.put(entry.getValue(), entry.getKey()); + } + System.out.println(inversedMap); + return inversedMap; + } + + public static Map invertMapUsingStreams(Map map) { + Map inversedMap = map.entrySet() + .stream() + .collect(Collectors.toMap(Entry::getValue, Entry::getKey)); + System.out.println(inversedMap); + return inversedMap; + } + + public static Map invertMapUsingMapper(Map sourceMap) { + Map inversedMap = sourceMap.entrySet() + .stream() + .collect(Collectors.toMap(Entry::getValue, Entry::getKey, (oldValue, newValue) -> oldValue)); + System.out.println(inversedMap); + return inversedMap; + } + + public static Map> invertMapUsingGroupingBy(Map map) { + Map> inversedMap = map.entrySet() + .stream() + .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList()))); + System.out.println(inversedMap); + return inversedMap; + } + +} diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java new file mode 100644 index 0000000000..5759cc76d6 --- /dev/null +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.map.invert; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class InvertHashMapUnitTest { + + Map sourceMap; + + @BeforeAll + void setup() { + sourceMap = new HashMap<>(); + sourceMap.put("Sunday", 0); + sourceMap.put("Monday", 1); + } + + @Test + void test1_invertMapUsingForLoop() { + Map inversedMap = InvertHashMapExample.invertMapUsingForLoop(sourceMap); + assertNotNull(inversedMap); + assertEquals(inversedMap.size(), 2); + assertEquals("Monday", inversedMap.get(1)); + } + + @Test + void test2_invertMapUsingStreams() { + Map inversedMap = InvertHashMapExample.invertMapUsingStreams(sourceMap); + assertNotNull(inversedMap); + assertEquals(inversedMap.size(), 2); + assertEquals("Monday", inversedMap.get(1)); + } + + @Test + void test3_invertMapUsingMapper() { + Map inversedMap = InvertHashMapExample.invertMapUsingMapper(sourceMap); + assertNotNull(inversedMap); + assertEquals(inversedMap.size(), 2); + assertEquals("Monday", inversedMap.get(1)); + } + + @Test + void test4_invertMapUsingGroupingBy() { + sourceMap.put("monday", 1); + Map> inversedMap = InvertHashMapExample.invertMapUsingGroupingBy(sourceMap); + assertNotNull(inversedMap); + assertEquals(inversedMap.size(), 2); + assertTrue(inversedMap.get(1) instanceof List); + } + +} From 13b769cd370c372a9e125ab268ec86e58b035f6f Mon Sep 17 00:00:00 2001 From: Abhinav Pandey Date: Sun, 13 Feb 2022 14:31:17 +0530 Subject: [PATCH 19/43] BAEL-5340 - Spring security configuring ant matchers --- .../AntMatchersExampleApplication.java | 13 +++++++ .../config/SecurityConfiguration.java | 39 +++++++++++++++++++ .../controllers/CustomerController.java | 15 +++++++ .../controllers/ProductController.java | 21 ++++++++++ .../baeldung/antmatchers/dtos/Customer.java | 39 +++++++++++++++++++ .../baeldung/antmatchers/dtos/Product.java | 39 +++++++++++++++++++ .../controllers/CustomerControllerTest.java | 38 ++++++++++++++++++ .../controllers/ProductControllerTest.java | 25 ++++++++++++ 8 files changed, 229 insertions(+) create mode 100644 spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/AntMatchersExampleApplication.java create mode 100644 spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/config/SecurityConfiguration.java create mode 100644 spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/CustomerController.java create mode 100644 spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/ProductController.java create mode 100644 spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Customer.java create mode 100644 spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Product.java create mode 100644 spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/CustomerControllerTest.java create mode 100644 spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/ProductControllerTest.java diff --git a/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/AntMatchersExampleApplication.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/AntMatchersExampleApplication.java new file mode 100644 index 0000000000..0a7828eff4 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/AntMatchersExampleApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.antmatchers; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AntMatchersExampleApplication { + + public static void main(String[] args) { + SpringApplication.run(AntMatchersExampleApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/config/SecurityConfiguration.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/config/SecurityConfiguration.java new file mode 100644 index 0000000000..43e8c73bf0 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/config/SecurityConfiguration.java @@ -0,0 +1,39 @@ +package com.baeldung.antmatchers.config; + +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.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfiguration extends WebSecurityConfigurerAdapter { + + @Override + public void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("admin").password(passwordEncoder().encode("password")).roles("USER", "ADMIN") + .and() + .withUser("user").password(passwordEncoder().encode("password")).roles("USER"); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/products/**").permitAll() + .and() + .authorizeRequests() + .antMatchers("/customers/**").hasRole("ADMIN") + .anyRequest().authenticated() + .and() + .httpBasic(); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/CustomerController.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/CustomerController.java new file mode 100644 index 0000000000..a031449797 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/CustomerController.java @@ -0,0 +1,15 @@ +package com.baeldung.antmatchers.controllers; + +import com.baeldung.antmatchers.dtos.Customer; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CustomerController { + + @GetMapping("/customers/{id}") + public Customer getCustomerById(@PathVariable("id") String id) { + return new Customer("Customer 1", "Address 1", "Phone 1"); + } +} diff --git a/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/ProductController.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/ProductController.java new file mode 100644 index 0000000000..2968f3c025 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/controllers/ProductController.java @@ -0,0 +1,21 @@ +package com.baeldung.antmatchers.controllers; + +import com.baeldung.antmatchers.dtos.Product; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@RestController +public class ProductController { + + @GetMapping("/products") + public List getProducts() { + return new ArrayList<>(Arrays.asList( + new Product("Product 1", "Description 1", 1.0), + new Product("Product 2", "Description 2", 2.0) + )); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Customer.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Customer.java new file mode 100644 index 0000000000..64bd95b095 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Customer.java @@ -0,0 +1,39 @@ +package com.baeldung.antmatchers.dtos; + +import java.io.Serializable; + +public class Customer implements Serializable { + private String name; + private String address; + private String phone; + + public Customer(String name, String address, String phone) { + this.name = name; + this.address = address; + this.phone = phone; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } +} diff --git a/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Product.java b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Product.java new file mode 100644 index 0000000000..84073ee8c0 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/main/java/com/baeldung/antmatchers/dtos/Product.java @@ -0,0 +1,39 @@ +package com.baeldung.antmatchers.dtos; + +import java.io.Serializable; + +public class Product implements Serializable { + private String name; + private String description; + private double price; + + public Product(String name, String description, double price) { + this.name = name; + this.description = description; + this.price = price; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/CustomerControllerTest.java b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/CustomerControllerTest.java new file mode 100644 index 0000000000..de13dc0aea --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/CustomerControllerTest.java @@ -0,0 +1,38 @@ +package com.baeldung.antmatchers.controllers; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@WebMvcTest(value = CustomerController.class) +class CustomerControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + void getCustomerByIdUnauthorized() throws Exception { + mockMvc.perform(get("/customers/1")).andExpect(status().isUnauthorized()); + } + + @Test + void getCustomerByIdForbidden() throws Exception { + mockMvc.perform(get("/customers/1").with(user("user").roles("USER"))) + .andExpect(status().isForbidden()); + } + + @Test + void getCustomerByIdOk() throws Exception { + mockMvc.perform(get("/customers/1").with(user("admin").roles("ADMIN"))) + .andExpect(status().isOk()); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/ProductControllerTest.java b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/ProductControllerTest.java new file mode 100644 index 0000000000..370e5f1597 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/test/java/com/baeldung/antmatchers/controllers/ProductControllerTest.java @@ -0,0 +1,25 @@ +package com.baeldung.antmatchers.controllers; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@WebMvcTest(value = ProductController.class) +class ProductControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + void getProducts() throws Exception { + mockMvc.perform(get("/products")) + .andExpect(status().isOk()); + } +} \ No newline at end of file From 7995f7d7c52963a557bca75e210842299464b89a Mon Sep 17 00:00:00 2001 From: Mayank Agarwal Date: Sun, 13 Feb 2022 16:43:59 +0530 Subject: [PATCH 20/43] BAEL-5351: Moved to core-java-collections-4 --- .../com/baeldung/maps}/initialize/EmptyMapInitializer.java | 5 +++-- .../maps}/initialize/EmptyMapInitializerUnitTest.java | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) rename core-java-modules/{core-java-collections-maps-2/src/main/java/com/baeldung/map => core-java-collections-4/src/main/java/com/baeldung/maps}/initialize/EmptyMapInitializer.java (91%) rename core-java-modules/{core-java-collections-maps-2/src/test/java/com/baeldung/map => core-java-collections-4/src/test/java/com/baeldung/maps}/initialize/EmptyMapInitializerUnitTest.java (95%) diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/maps/initialize/EmptyMapInitializer.java similarity index 91% rename from core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java rename to core-java-modules/core-java-collections-4/src/main/java/com/baeldung/maps/initialize/EmptyMapInitializer.java index 06185a0f93..3dc644f1af 100644 --- a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/EmptyMapInitializer.java +++ b/core-java-modules/core-java-collections-4/src/main/java/com/baeldung/maps/initialize/EmptyMapInitializer.java @@ -1,4 +1,4 @@ -package com.baeldung.map.initialize; +package com.baeldung.maps.initialize; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; @@ -33,7 +33,8 @@ public class EmptyMapInitializer { } public Map createGenericEmptyMapUsingMapsObject() { - return Maps.newHashMap(); + Map genericEmptyMap = Maps.newHashMap(); + return genericEmptyMap; } public static Map createMapUsingGuava() { diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java b/core-java-modules/core-java-collections-4/src/test/java/com/baeldung/maps/initialize/EmptyMapInitializerUnitTest.java similarity index 95% rename from core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java rename to core-java-modules/core-java-collections-4/src/test/java/com/baeldung/maps/initialize/EmptyMapInitializerUnitTest.java index b40ffed94b..cc25205ba7 100644 --- a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/EmptyMapInitializerUnitTest.java +++ b/core-java-modules/core-java-collections-4/src/test/java/com/baeldung/maps/initialize/EmptyMapInitializerUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.map.initialize; +package com.baeldung.maps.initialize; import java.util.Map; import org.junit.Test; From e5f1f8a3b6937c3dd4154a3d7669ac7ea2b8fe89 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Mon, 14 Feb 2022 21:15:53 +0000 Subject: [PATCH 21/43] [JAVA-9910] Update Cargo plugin to latest version --- .../spring-rest-testing/pom.xml | 46 ++++++++++--------- .../baeldung/cargo/CargoPluginLiveTest.java | 13 ++++++ 2 files changed, 38 insertions(+), 21 deletions(-) create mode 100644 spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/cargo/CargoPluginLiveTest.java diff --git a/spring-web-modules/spring-rest-testing/pom.xml b/spring-web-modules/spring-rest-testing/pom.xml index 1390898bf9..67b3115a6f 100644 --- a/spring-web-modules/spring-rest-testing/pom.xml +++ b/spring-web-modules/spring-rest-testing/pom.xml @@ -64,11 +64,6 @@ org.springframework.data spring-data-commons - - - org.springframework.boot - spring-boot-starter-tomcat - org.apache.httpcomponents @@ -154,17 +149,9 @@ org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} + cargo-maven3-plugin + ${cargo-maven3-plugin.version} - true - - jetty8x - embedded - - - - 8082 @@ -194,15 +181,32 @@ - live + cargo-integration + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + + + org.codehaus.cargo - cargo-maven2-plugin - - false - + cargo-maven3-plugin start-server @@ -232,7 +236,7 @@ 3.25.0-GA - 1.6.1 + 1.9.9 1.1.3 diff --git a/spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/cargo/CargoPluginLiveTest.java b/spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/cargo/CargoPluginLiveTest.java new file mode 100644 index 0000000000..8d6dd6a823 --- /dev/null +++ b/spring-web-modules/spring-rest-testing/src/test/java/com/baeldung/cargo/CargoPluginLiveTest.java @@ -0,0 +1,13 @@ +package com.baeldung.cargo; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CargoPluginLiveTest { + + @Test + void givenCargoProfile_expectTestRuns() { + assertTrue(true); + } +} From a4a03c47900136dcdc4aa7cc494175e847fb982f Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 15 Feb 2022 13:31:37 +0200 Subject: [PATCH 22/43] move remaining files for instrumentation article --- core-java-modules/core-java-jar/pom.xml | 105 +--------------- core-java-modules/core-java-jvm/pom.xml | 114 ++++++++++++++++++ .../src/main/resources/META-INF/MANIFEST.MF | 5 + 3 files changed, 120 insertions(+), 104 deletions(-) create mode 100644 core-java-modules/core-java-jvm/src/main/resources/META-INF/MANIFEST.MF diff --git a/core-java-modules/core-java-jar/pom.xml b/core-java-modules/core-java-jar/pom.xml index da107c745f..714a370287 100644 --- a/core-java-modules/core-java-jar/pom.xml +++ b/core-java-modules/core-java-jar/pom.xml @@ -259,110 +259,7 @@ - - - buildAgentLoader - - - - org.apache.maven.plugins - maven-jar-plugin - - - package - - jar - - - agentLoader - target/classes - - - true - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - com/baeldung/instrumentation/application/AgentLoader.class - com/baeldung/instrumentation/application/Launcher.class - - - - - - - - - - buildApplication - - - - org.apache.maven.plugins - maven-jar-plugin - - - package - - jar - - - application - target/classes - - - true - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - com/baeldung/instrumentation/application/MyAtm.class - com/baeldung/instrumentation/application/MyAtmApplication.class - com/baeldung/instrumentation/application/Launcher.class - - - - - - - - - - buildAgent - - - - org.apache.maven.plugins - maven-jar-plugin - - - package - - jar - - - agent - target/classes - - - true - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - com/baeldung/instrumentation/agent/AtmTransformer.class - com/baeldung/instrumentation/agent/MyInstrumentationAgent.class - - - - - - - - + diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml index c47765e43d..216e408114 100644 --- a/core-java-modules/core-java-jvm/pom.xml +++ b/core-java-modules/core-java-jvm/pom.xml @@ -57,6 +57,11 @@ jol-core ${jol-core.version} + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + @@ -66,5 +71,114 @@ 8.0.1 6.5.0 + + + + buildAgentLoader + + + + org.apache.maven.plugins + maven-jar-plugin + + + package + + jar + + + agentLoader + target/classes + + + true +com.baeldung.instrumentation.application.Launcher + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + com/baeldung/instrumentation/application/AgentLoader.class + com/baeldung/instrumentation/application/Launcher.class + + + + + + + + + + buildApplication + + + + org.apache.maven.plugins + maven-jar-plugin + + + package + + jar + + + application + target/classes + + + true + com.baeldung.instrumentation.application.Launcher + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + com/baeldung/instrumentation/application/MyAtm.class + com/baeldung/instrumentation/application/MyAtmApplication.class + com/baeldung/instrumentation/application/Launcher.class + + + + + + + + + + buildAgent + + + + org.apache.maven.plugins + maven-jar-plugin + + + package + + jar + + + agent + target/classes + + + true +com.baeldung.instrumentation.application.Launcher + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + com/baeldung/instrumentation/agent/AtmTransformer.class + com/baeldung/instrumentation/agent/MyInstrumentationAgent.class + + + + + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-jvm/src/main/resources/META-INF/MANIFEST.MF b/core-java-modules/core-java-jvm/src/main/resources/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..d16a93ec83 --- /dev/null +++ b/core-java-modules/core-java-jvm/src/main/resources/META-INF/MANIFEST.MF @@ -0,0 +1,5 @@ +Agent-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent +Can-Redefine-Classes: true +Can-Retransform-Classes: true +Premain-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent +Main-Class: com.baeldung.instrumentation.application.Launcher \ No newline at end of file From 9dc5d75a160071c025bc48745f2e473cb0ce97d7 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 15 Feb 2022 13:39:08 +0200 Subject: [PATCH 23/43] formatting, additional details on how to run the app --- core-java-modules/core-java-jvm/README.md | 10 ++++++++++ core-java-modules/core-java-jvm/pom.xml | 6 +++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/core-java-modules/core-java-jvm/README.md b/core-java-modules/core-java-jvm/README.md index 431cf021c8..e9266dea3b 100644 --- a/core-java-modules/core-java-jvm/README.md +++ b/core-java-modules/core-java-jvm/README.md @@ -15,3 +15,13 @@ This module contains articles about working with the Java Virtual Machine (JVM). - [What Causes java.lang.OutOfMemoryError: unable to create new native thread](https://www.baeldung.com/java-outofmemoryerror-unable-to-create-new-native-thread) - [View Bytecode of a Class File in Java](https://www.baeldung.com/java-class-view-bytecode) - More articles: [[next -->]](/core-java-modules/core-java-jvm-2) + + +To run the code for the Instrumentation: https://www.baeldung.com/java-instrumentation article: +1- build the module +2- run the module 3 times to build the 3 jars: + mvn install -PbuildAgentLoader + mvn install -PbuildApplication + mvn install -PbuildAgent +3- update the commands in the article with the exact names of the jars generated in the target folder +4- update the path in the AgentLoader class with the path of the agent on your system \ No newline at end of file diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml index 216e408114..e4c0f949c2 100644 --- a/core-java-modules/core-java-jvm/pom.xml +++ b/core-java-modules/core-java-jvm/pom.xml @@ -57,7 +57,7 @@ jol-core ${jol-core.version} - + org.slf4j log4j-over-slf4j ${org.slf4j.version} @@ -92,7 +92,7 @@ true -com.baeldung.instrumentation.application.Launcher + com.baeldung.instrumentation.application.Launcher ${project.build.outputDirectory}/META-INF/MANIFEST.MF @@ -163,7 +163,7 @@ true -com.baeldung.instrumentation.application.Launcher + com.baeldung.instrumentation.application.Launcher ${project.build.outputDirectory}/META-INF/MANIFEST.MF From 9e4da20259db43a742eaa2648f2afa3030ce2cb0 Mon Sep 17 00:00:00 2001 From: Asjad J <97493880+Asjad-J@users.noreply.github.com> Date: Tue, 15 Feb 2022 21:36:09 +0500 Subject: [PATCH 24/43] Updated README.md Linked back to: https://www.baeldung.com/spring-no-converter-with-preset --- spring-boot-modules/spring-boot-data-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-data-2/README.md b/spring-boot-modules/spring-boot-data-2/README.md index 875ee502b4..b99356492b 100644 --- a/spring-boot-modules/spring-boot-data-2/README.md +++ b/spring-boot-modules/spring-boot-data-2/README.md @@ -1,5 +1,6 @@ ### Relevant Articles: +- [HttpMessageNotWritableException: No Converter for [class …] With Preset Content-Type](https://www.baeldung.com/spring-no-converter-with-preset) - [Spring Boot: Customize the Jackson ObjectMapper](https://www.baeldung.com/spring-boot-customize-jackson-objectmapper) - [“HttpMessageNotWritableException: No converter found for return value of type”](https://www.baeldung.com/spring-no-converter-found) - [Creating a Read-Only Repository with Spring Data](https://www.baeldung.com/spring-data-read-only-repository) From b73253cfbcf7c98ad74a87c9221fe08f8a4e0886 Mon Sep 17 00:00:00 2001 From: Asjad J <97493880+Asjad-J@users.noreply.github.com> Date: Tue, 15 Feb 2022 21:38:49 +0500 Subject: [PATCH 25/43] Updated README.md Linked back to: https://www.baeldung.com/spring-boot-configure-multiple-datasources --- persistence-modules/spring-data-jdbc/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jdbc/README.md b/persistence-modules/spring-data-jdbc/README.md index 0e54d0ba88..b9ff9417a9 100644 --- a/persistence-modules/spring-data-jdbc/README.md +++ b/persistence-modules/spring-data-jdbc/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: +- [Configure and Use Multiple DataSources in Spring Boot](https://www.baeldung.com/spring-boot-configure-multiple-datasources) - [Introduction to Spring Data JDBC](https://www.baeldung.com/spring-data-jdbc-intro) From 5538a7686f0977e98364b19b5aadfed8dbb9db89 Mon Sep 17 00:00:00 2001 From: Palaniappan Arunachalam Date: Tue, 15 Feb 2022 23:30:00 +0530 Subject: [PATCH 26/43] BAEL-5348: Fixed tests based on review comments --- .../map/invert/InvertHashMapUnitTest.java | 36 ++++++++++++------- 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java index 5759cc76d6..6870cdef23 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/invert/InvertHashMapUnitTest.java @@ -1,5 +1,6 @@ package com.baeldung.map.invert; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -8,7 +9,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; @@ -17,44 +18,55 @@ public class InvertHashMapUnitTest { Map sourceMap; - @BeforeAll + @BeforeEach void setup() { sourceMap = new HashMap<>(); sourceMap.put("Sunday", 0); sourceMap.put("Monday", 1); + sourceMap.put("Tuesday", 2); + sourceMap.put("Wednesday", 3); + sourceMap.put("Thursday", 4); + sourceMap.put("Friday", 5); + sourceMap.put("Saturday", 6); } @Test - void test1_invertMapUsingForLoop() { + void givenSourceMap_whenUsingForLoop_returnsInvertedMap() { Map inversedMap = InvertHashMapExample.invertMapUsingForLoop(sourceMap); + assertNotNull(inversedMap); - assertEquals(inversedMap.size(), 2); + assertEquals(sourceMap.size(), inversedMap.size()); assertEquals("Monday", inversedMap.get(1)); } @Test - void test2_invertMapUsingStreams() { + void givenSourceMap_whenUsingStreams_returnsInvertedMap() { Map inversedMap = InvertHashMapExample.invertMapUsingStreams(sourceMap); + assertNotNull(inversedMap); - assertEquals(inversedMap.size(), 2); + assertEquals(sourceMap.size(), inversedMap.size()); assertEquals("Monday", inversedMap.get(1)); } @Test - void test3_invertMapUsingMapper() { + void givenSourceMap_whenUsingMapper_returnsInvertedMap() { Map inversedMap = InvertHashMapExample.invertMapUsingMapper(sourceMap); + assertNotNull(inversedMap); - assertEquals(inversedMap.size(), 2); + assertEquals(sourceMap.size(), inversedMap.size()); assertEquals("Monday", inversedMap.get(1)); } @Test - void test4_invertMapUsingGroupingBy() { - sourceMap.put("monday", 1); + void givenSourceMapWithDuplicateValues_whenUsingGroupBy_returnsInvertedMap() { + sourceMap.put("MONDAY", 1); Map> inversedMap = InvertHashMapExample.invertMapUsingGroupingBy(sourceMap); + assertNotNull(inversedMap); - assertEquals(inversedMap.size(), 2); - assertTrue(inversedMap.get(1) instanceof List); + assertNotEquals(sourceMap.size(), inversedMap.size()); // duplicate keys are merged now + assertEquals(2, inversedMap.get(1).size()); + assertTrue(inversedMap.get(1).contains("Monday")); + assertTrue(inversedMap.get(1).contains("MONDAY")); } } From 864b139aa4961c64f0aee37250616d44b608b557 Mon Sep 17 00:00:00 2001 From: vunamtien Date: Wed, 16 Feb 2022 03:19:44 +0700 Subject: [PATCH 27/43] BAEL-5332-convert-byte-array-and-uuid (#11822) Co-authored-by: tienvn4 --- .../java/com/baeldung/uuid/UuidHelper.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/uuid/UuidHelper.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/uuid/UuidHelper.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/uuid/UuidHelper.java new file mode 100644 index 0000000000..5807262094 --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/uuid/UuidHelper.java @@ -0,0 +1,33 @@ +package com.baeldung.uuid; + +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.UUID; + +public class UuidHelper { + + public static byte[] convertUUIDToBytes(UUID uuid) { + ByteBuffer bb = ByteBuffer.wrap(new byte[16]); + bb.putLong(uuid.getMostSignificantBits()); + bb.putLong(uuid.getLeastSignificantBits()); + return bb.array(); + } + + public static UUID convertBytesToUUID(byte[] bytes) { + ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); + long high = byteBuffer.getLong(); + long low = byteBuffer.getLong(); + return new UUID(high, low); + } + + public static void main(String[] args) { + UUID uuid = UUID.randomUUID(); + System.out.println("Original UUID: " + uuid); + + byte[] bytes = convertUUIDToBytes(uuid); + System.out.println("Converted byte array: " + Arrays.toString(bytes)); + + UUID uuidNew = convertBytesToUUID(bytes); + System.out.println("Converted UUID: " + uuidNew); + } +} From 7966e98d90671a4580fe0378a2fa441d830a7b38 Mon Sep 17 00:00:00 2001 From: polomos Date: Tue, 15 Feb 2022 22:14:36 +0100 Subject: [PATCH 28/43] BAEL-4388 Test reading keyStore without trustAnchor (#11785) --- .../truststore/TrustStoreUnitTest.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 core-java-modules/core-java-security-3/src/test/java/com/baeldung/truststore/TrustStoreUnitTest.java diff --git a/core-java-modules/core-java-security-3/src/test/java/com/baeldung/truststore/TrustStoreUnitTest.java b/core-java-modules/core-java-security-3/src/test/java/com/baeldung/truststore/TrustStoreUnitTest.java new file mode 100644 index 0000000000..2c3d4c8959 --- /dev/null +++ b/core-java-modules/core-java-security-3/src/test/java/com/baeldung/truststore/TrustStoreUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.truststore; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.PKIXParameters; + +public class TrustStoreUnitTest { + + @Test + public void whenOpeningTrustStore_thenExceptionIsThrown() throws Exception { + KeyStore keyStore = getKeyStore(); + InvalidAlgorithmParameterException invalidAlgorithmParameterException = + Assertions.assertThrows(InvalidAlgorithmParameterException.class, () -> new PKIXParameters(keyStore)); + Assertions.assertEquals("the trustAnchors parameter must be non-empty", invalidAlgorithmParameterException.getMessage()); + } + + private KeyStore getKeyStore() throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException { + KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); + ks.load(null, "changeIt".toCharArray()); + return ks; + } +} \ No newline at end of file From 16b843dcb60f724ccb09a0cfe818d0fe020ab1c1 Mon Sep 17 00:00:00 2001 From: kpentaris Date: Wed, 16 Feb 2022 08:17:56 +0200 Subject: [PATCH 29/43] BAEL-4513 Gradle source vs target compatibility (#11762) * Add example code for Gradle sourceCompatibility vs targetCompatibility * Fix code format --- .../build.gradle | 12 ++++++++++++ .../java/com/baeldung/helloworld/HelloWorldApp.java | 9 +++++++++ gradle/settings.gradle | 1 + 3 files changed, 22 insertions(+) create mode 100644 gradle/gradle-source-vs-target-compatibility/build.gradle create mode 100644 gradle/gradle-source-vs-target-compatibility/src/main/java/com/baeldung/helloworld/HelloWorldApp.java diff --git a/gradle/gradle-source-vs-target-compatibility/build.gradle b/gradle/gradle-source-vs-target-compatibility/build.gradle new file mode 100644 index 0000000000..8cc50c15c6 --- /dev/null +++ b/gradle/gradle-source-vs-target-compatibility/build.gradle @@ -0,0 +1,12 @@ +plugins { + id 'java' +} + +description = 'gradle-source-vs-target-compatibility' + +group 'com.baeldung' + +java { + sourceCompatibility = "1.6" + targetCompatibility = "1.8" +} diff --git a/gradle/gradle-source-vs-target-compatibility/src/main/java/com/baeldung/helloworld/HelloWorldApp.java b/gradle/gradle-source-vs-target-compatibility/src/main/java/com/baeldung/helloworld/HelloWorldApp.java new file mode 100644 index 0000000000..a951a72dd6 --- /dev/null +++ b/gradle/gradle-source-vs-target-compatibility/src/main/java/com/baeldung/helloworld/HelloWorldApp.java @@ -0,0 +1,9 @@ +package com.baeldung.helloworld; + +public class HelloWorldApp { + + public static void main(String[] args) { + System.out.println("Hello World!"); + } + +} diff --git a/gradle/settings.gradle b/gradle/settings.gradle index 59300f9281..d1eb10f4d2 100644 --- a/gradle/settings.gradle +++ b/gradle/settings.gradle @@ -6,5 +6,6 @@ include 'greeter' include 'gradletaskdemo' include 'junit5' include 'gradle-employee-app' +include 'gradle-source-vs-target-compatibility' println 'This will be executed during the initialization phase.' From a7765c6a1966566e0cc5d1745990f6a56402db46 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Wed, 16 Feb 2022 13:42:23 +0100 Subject: [PATCH 30/43] JAVA-9880: Temporarily disable spring-boot-swagger module as it fails the builds --- spring-boot-modules/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 4925530a35..f872a6f8d5 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -69,7 +69,7 @@ spring-boot-runtime-2 spring-boot-security spring-boot-springdoc - spring-boot-swagger + spring-boot-swagger-jwt spring-boot-swagger-keycloak spring-boot-testing From cd70006bb6bccea7a9ce529cef35c8e46de65940 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Thu, 17 Feb 2022 08:29:23 +0000 Subject: [PATCH 31/43] [JAVA-9986] Fix ThreadStamped unit test --- .../StampedAccount.java | 32 +++++++++++++------ .../ThreadStampedAccountUnitTest.java | 29 +++++++++++++---- 2 files changed, 45 insertions(+), 16 deletions(-) diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java index 415b24738a..69aed0b979 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/atomicstampedreference/StampedAccount.java @@ -1,25 +1,22 @@ package com.baeldung.atomicstampedreference; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicStampedReference; public class StampedAccount { - private AtomicInteger stamp = new AtomicInteger(0); - private AtomicStampedReference account = new AtomicStampedReference<>(0, 0); - - public int getBalance() { - return account.getReference(); - } - - public int getStamp() { - return account.getStamp(); - } + private final AtomicInteger stamp = new AtomicInteger(0); + private final AtomicStampedReference account = new AtomicStampedReference<>(0, 0); public boolean deposit(int funds) { int[] stamps = new int[1]; int current = this.account.get(stamps); int newStamp = this.stamp.incrementAndGet(); + + // Thread is paused here to allow other threads to update the stamp and amount (for testing only) + sleep(); + return this.account.compareAndSet(current, current + funds, stamps[0], newStamp); } @@ -29,4 +26,19 @@ public class StampedAccount { int newStamp = this.stamp.incrementAndGet(); return this.account.compareAndSet(current, current - funds, stamps[0], newStamp); } + + public int getBalance() { + return account.getReference(); + } + + public int getStamp() { + return account.getStamp(); + } + + private static void sleep() { + try { + TimeUnit.SECONDS.sleep(1); + } catch (InterruptedException ignored) { + } + } } diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java index ce83355073..2840c25cf6 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/atomicstampedreference/ThreadStampedAccountUnitTest.java @@ -1,21 +1,38 @@ package com.baeldung.atomicstampedreference; -import org.junit.Assert; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + public class ThreadStampedAccountUnitTest { @Test public void givenMultiThread_whenStampedAccount_thenSetBalance() throws InterruptedException { StampedAccount account = new StampedAccount(); + Thread t = new Thread(() -> { - while (!account.withdrawal(100)) + while (!account.deposit(100)) { Thread.yield(); + } }); t.start(); - Assert.assertTrue(account.deposit(100)); - t.join(1_000); - Assert.assertFalse(t.isAlive()); - Assert.assertSame(0, account.getBalance()); + + Thread t2 = new Thread(() -> { + while (!account.withdrawal(100)) { + Thread.yield(); + } + }); + t2.start(); + + t.join(10_000); + t2.join(10_000); + + assertFalse(t.isAlive()); + assertFalse(t2.isAlive()); + + assertEquals(0, account.getBalance()); + assertTrue(account.getStamp() > 0); } } From c747712a0ea8512fbd3a19c46700b30ae8acd85f Mon Sep 17 00:00:00 2001 From: Parikshit Murria Date: Thu, 17 Feb 2022 16:30:42 -0700 Subject: [PATCH 32/43] Update swaggerDirectory to target folder --- .../generated/swagger-ui/swagger.json | 57 ------------------- .../spring-boot-swagger/pom.xml | 2 +- 2 files changed, 1 insertion(+), 58 deletions(-) delete mode 100644 spring-boot-modules/spring-boot-swagger/generated/swagger-ui/swagger.json diff --git a/spring-boot-modules/spring-boot-swagger/generated/swagger-ui/swagger.json b/spring-boot-modules/spring-boot-swagger/generated/swagger-ui/swagger.json deleted file mode 100644 index 4ebe165384..0000000000 --- a/spring-boot-modules/spring-boot-swagger/generated/swagger-ui/swagger.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "swagger" : "2.0", - "info" : { - "description" : "This is a Baeldung Document Enum Sample Code", - "version" : "v1", - "title" : "Baeldung - Document Enum", - "contact" : { - "name" : "Parikshit Murria", - "email" : "pmurria@baeldung.com" - }, - "license" : { - "name" : "Apache 2.0", - "url" : "https://www.apache.org/licenses/LICENSE-2.0.html" - } - }, - "host" : "baeldung.com", - "basePath" : "/api", - "schemes" : [ "http", "https" ], - "paths" : { - "/hire" : { - "post" : { - "summary" : "This method is used to hire employee with a specific role", - "description" : "", - "operationId" : "hireEmployee", - "produces" : [ "application/json" ], - "parameters" : [ { - "in" : "body", - "name" : "body", - "description" : "role", - "required" : true, - "schema" : { - "$ref" : "#/definitions/Employee" - } - } ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "type" : "string" - } - } - } - } - } - }, - "definitions" : { - "Employee" : { - "type" : "object", - "properties" : { - "role" : { - "type" : "string", - "enum" : [ "Engineer", "Clerk", "Driver", "Janitor" ] - } - } - } - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-swagger/pom.xml b/spring-boot-modules/spring-boot-swagger/pom.xml index 2c0e52b671..b6ed50534e 100644 --- a/spring-boot-modules/spring-boot-swagger/pom.xml +++ b/spring-boot-modules/spring-boot-swagger/pom.xml @@ -63,7 +63,7 @@ Apache 2.0 - generated/swagger-ui + ${basedir}/target/swagger-ui From 8b161f8f55da099068ad24abc242125da938fb9f Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Fri, 18 Feb 2022 09:30:42 +0100 Subject: [PATCH 33/43] JAVA-9880: Activate spring-boot-swagger module --- spring-boot-modules/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index f872a6f8d5..4925530a35 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -69,7 +69,7 @@ spring-boot-runtime-2 spring-boot-security spring-boot-springdoc - + spring-boot-swagger spring-boot-swagger-jwt spring-boot-swagger-keycloak spring-boot-testing From 13a7a1d7eb7ea1ef6ca67a2b3c1962c9402bd37d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20G=C5=82=C3=B3wka?= Date: Sat, 19 Feb 2022 05:19:07 +0100 Subject: [PATCH 34/43] BAEL-4234: example of JNI registerNatives() method (#11745) * BAEL-4234: example of JNI registerNatives() method * fixed formatting in the cpp file * removed camelcase in test package name --- ...ldung_jni_RegisterNativesHelloWorldJNI.cpp | 21 ++++++++++++++ ...aeldung_jni_RegisterNativesHelloWorldJNI.h | 29 +++++++++++++++++++ .../src/main/cpp/generateNativeLibMac.sh | 3 +- .../jni/RegisterNativesHelloWorldJNI.java | 18 ++++++++++++ .../JNIRegisterNativesManualTest.java | 26 +++++++++++++++++ 5 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.cpp create mode 100644 java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.h mode change 100644 => 100755 java-native/src/main/cpp/generateNativeLibMac.sh create mode 100644 java-native/src/main/java/com/baeldung/jni/RegisterNativesHelloWorldJNI.java create mode 100644 java-native/src/test/java/com/baeldung/jni/registernatives/JNIRegisterNativesManualTest.java diff --git a/java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.cpp b/java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.cpp new file mode 100644 index 0000000000..37adb35333 --- /dev/null +++ b/java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.cpp @@ -0,0 +1,21 @@ +#include "com_baeldung_jni_RegisterNativesHelloWorldJNI.h" +#include + + +JNIEXPORT jstring JNICALL hello (JNIEnv* env, jobject thisObject) { + std::string hello = "Hello from registered native C++ !!"; + std::cout << hello << std::endl; + return env->NewStringUTF(hello.c_str()); +} + +static JNINativeMethod methods[] = { + {"sayHello", "()Ljava/lang/String;", (void*) &hello }, +}; + + +JNIEXPORT void JNICALL Java_com_baeldung_jni_RegisterNativesHelloWorldJNI_register (JNIEnv* env, jobject thsObject) { + jclass clazz = env->FindClass("com/baeldung/jni/RegisterNativesHelloWorldJNI"); + + (env)->RegisterNatives(clazz, methods, sizeof(methods)/sizeof(methods[0])); +} + diff --git a/java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.h b/java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.h new file mode 100644 index 0000000000..bcca780208 --- /dev/null +++ b/java-native/src/main/cpp/com_baeldung_jni_RegisterNativesHelloWorldJNI.h @@ -0,0 +1,29 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class com_baeldung_jni_RegisterNativesHelloWorldJNI */ + +#ifndef _Included_com_baeldung_jni_RegisterNativesHelloWorldJNI +#define _Included_com_baeldung_jni_RegisterNativesHelloWorldJNI +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: com_baeldung_jni_RegisterNativesHelloWorldJNI + * Method: sayHello + * Signature: ()Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_com_baeldung_jni_RegisterNativesHelloWorldJNI_sayHello + (JNIEnv *, jobject); + +/* + * Class: com_baeldung_jni_RegisterNativesHelloWorldJNI + * Method: register + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_com_baeldung_jni_RegisterNativesHelloWorldJNI_register + (JNIEnv *, jobject); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/java-native/src/main/cpp/generateNativeLibMac.sh b/java-native/src/main/cpp/generateNativeLibMac.sh old mode 100644 new mode 100755 index d11dcc7c01..834a07acc8 --- a/java-native/src/main/cpp/generateNativeLibMac.sh +++ b/java-native/src/main/cpp/generateNativeLibMac.sh @@ -3,4 +3,5 @@ g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_HelloWorldJNI.cpp -o com_baeldung_jni_HelloWorldJNI.o g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_ExampleParametersJNI.cpp -o com_baeldung_jni_ExampleParametersJNI.o g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_ExampleObjectsJNI.cpp -o com_baeldung_jni_ExampleObjectsJNI.o -g++ -dynamiclib -o ../../../native/macos/libnative.dylib com_baeldung_jni_HelloWorldJNI.o com_baeldung_jni_ExampleParametersJNI.o com_baeldung_jni_ExampleObjectsJNI.o -lc \ No newline at end of file +g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_RegisterNativesHelloWorldJNI.cpp -o com_baeldung_jni_RegisterNativesHelloWorldJNI.o +g++ -dynamiclib -o ../../../native/macos/libnative.dylib com_baeldung_jni_HelloWorldJNI.o com_baeldung_jni_ExampleParametersJNI.o com_baeldung_jni_ExampleObjectsJNI.o com_baeldung_jni_RegisterNativesHelloWorldJNI.o -lc \ No newline at end of file diff --git a/java-native/src/main/java/com/baeldung/jni/RegisterNativesHelloWorldJNI.java b/java-native/src/main/java/com/baeldung/jni/RegisterNativesHelloWorldJNI.java new file mode 100644 index 0000000000..c5461aafef --- /dev/null +++ b/java-native/src/main/java/com/baeldung/jni/RegisterNativesHelloWorldJNI.java @@ -0,0 +1,18 @@ +package com.baeldung.jni; + +public class RegisterNativesHelloWorldJNI { + + static { + System.loadLibrary("native"); + } + + public static void main(String[] args) { + RegisterNativesHelloWorldJNI helloWorldJNI = new RegisterNativesHelloWorldJNI(); + helloWorldJNI.register(); + helloWorldJNI.sayHello(); + } + + public native String sayHello(); + + public native void register(); +} diff --git a/java-native/src/test/java/com/baeldung/jni/registernatives/JNIRegisterNativesManualTest.java b/java-native/src/test/java/com/baeldung/jni/registernatives/JNIRegisterNativesManualTest.java new file mode 100644 index 0000000000..96e15bd822 --- /dev/null +++ b/java-native/src/test/java/com/baeldung/jni/registernatives/JNIRegisterNativesManualTest.java @@ -0,0 +1,26 @@ +package com.baeldung.jni.registernatives; + +import com.baeldung.jni.RegisterNativesHelloWorldJNI; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class JNIRegisterNativesManualTest { + @Before + public void setup() { + System.loadLibrary("native"); + } + + @Test + public void whenRegisteredNativeHelloWorld_thenOutputIsAsExpected() { + RegisterNativesHelloWorldJNI helloWorld = new RegisterNativesHelloWorldJNI(); + helloWorld.register(); + + String helloFromNative = helloWorld.sayHello(); + + assertNotNull(helloFromNative); + assertTrue(helloFromNative.equals("Hello from registered native C++ !!")); + } +} From d28a3e642a7099aa850295194fa506b23314b048 Mon Sep 17 00:00:00 2001 From: Vikas Rajput Date: Sat, 19 Feb 2022 17:06:34 +0530 Subject: [PATCH 35/43] Bael 4788: Completed Article - Hibernate addScalar() method (#11783) * BAEL-4788: Added ScalarDemo Class for Hibernate addScalar Method article * BAEL-4788: Added unit tests in the article * BAEL-4788: removed redundant code Co-authored-by: Vikas Ramsingh Rajput --- .../scalarmethod/HibernateScalarExample.java | 47 +++++++++++ .../HibernateScalarExampleUnitTest.java | 83 +++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExample.java create mode 100644 persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExampleUnitTest.java diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExample.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExample.java new file mode 100644 index 0000000000..69aaaae19d --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExample.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.scalarmethod; + +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.type.StandardBasicTypes; + +public class HibernateScalarExample { + + private Session session; + + public HibernateScalarExample(Session session) { + this.session = session; + } + + public List fetchColumnWithNativeQuery() { + return session.createNativeQuery("SELECT * FROM Student student") + .list(); + } + + public List fetchColumnWithScalar() { + return session.createNativeQuery("SELECT * FROM Student student") + .addScalar("studentId", StandardBasicTypes.LONG) + .addScalar("name", StandardBasicTypes.STRING) + .addScalar("age", StandardBasicTypes.INTEGER) + .list(); + } + + public List fetchLimitedColumnWithScalar() { + return session.createNativeQuery("SELECT * FROM Student student") + .addScalar("name", StandardBasicTypes.STRING) + .list(); + } + + public List fetchColumnWithOverloadedScalar() { + return session.createNativeQuery("SELECT * FROM Student student") + .addScalar("name", StandardBasicTypes.STRING) + .addScalar("age") + .list(); + } + + public Integer fetchAvgAgeWithScalar() { + return (Integer) session.createNativeQuery("SELECT AVG(age) as avgAge FROM Student student") + .addScalar("avgAge") + .uniqueResult(); + } +} diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExampleUnitTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExampleUnitTest.java new file mode 100644 index 0000000000..ca01c5cb84 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/scalarmethod/HibernateScalarExampleUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.hibernate.scalarmethod; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.List; +import java.util.Random; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.pojo.Student; + +public class HibernateScalarExampleUnitTest { + + private static Session session; + private static Transaction transaction; + private static final int DATA_SIZE = 50000; + private static HibernateScalarExample scalarExample; + + @BeforeClass + public static void setUp() throws IOException { + session = HibernateUtil.getSessionFactory().openSession(); + transaction = session.beginTransaction(); + scalarExample = new HibernateScalarExample(session); + session.createNativeQuery("delete from Student").executeUpdate(); + for (int i = 0; i < DATA_SIZE; i++) { + Student student = new Student("John-" + i, generateRandomAge(5, 24)); + session.persist(student); + } + transaction.commit(); + transaction = session.beginTransaction(); + } + + @AfterClass + public static void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenNativeQuery_whenNoScalarUsed_ThenFetchAll() { + List list = scalarExample.fetchColumnWithNativeQuery(); + assertEquals(DATA_SIZE, list.size()); + } + + @Test + public void givenNativeQuery_whenScalarUsed_ThenFetchAll() { + List list = scalarExample.fetchColumnWithScalar(); + assertEquals(DATA_SIZE, list.size()); + } + + @Test + public void givenNativeQuery_whenScalarUsed_ThenFetchLimitedColumns() { + List list = scalarExample.fetchLimitedColumnWithScalar(); + for (String colValue : list) { + assertTrue(colValue.startsWith("John")); + } + } + + @Test + public void givenNativeQuery_whenScalarUsedForSingleResult_ThenSingleValueReturned() { + List list = scalarExample.fetchColumnWithOverloadedScalar(); + for (Object[] colArray : list) { + assertEquals(2, colArray.length); + } + } + + @Test + public void whenScalarUsedForAvgAge_ThenSingleValueReturned() { + Integer avgAge = scalarExample.fetchAvgAgeWithScalar(); + assertEquals(true, (avgAge >= 5 && avgAge <= 24)); + } + + private static int generateRandomAge(int min, int max) { + return new Random().nextInt(max - min + 1) + min; + } +} From f3b59f5316f44dc81543b293ca9b79012c9d7fc6 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Sat, 19 Feb 2022 19:41:44 +0000 Subject: [PATCH 36/43] [JAVA-10080] Add plugin for filtering xls resources --- apache-poi/pom.xml | 18 ++++++++++++++++++ .../cellstyle/CellStyleBorderHandlerTest.xlsx | Bin 0 -> 7500 bytes .../cellstyle/CellBorderHandlerUnitTest.java | 2 +- 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 apache-poi/src/main/resources/cellstyle/CellStyleBorderHandlerTest.xlsx diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml index 1a0f77b025..546eedec5b 100644 --- a/apache-poi/pom.xml +++ b/apache-poi/pom.xml @@ -32,9 +32,27 @@ + + + + org.apache.maven.plugins + maven-resources-plugin + ${maven.resources.plugin.version} + + UTF-8 + + xlsx + xls + + + + + + 5.2.0 1.0.6 + 3.2.0 \ No newline at end of file diff --git a/apache-poi/src/main/resources/cellstyle/CellStyleBorderHandlerTest.xlsx b/apache-poi/src/main/resources/cellstyle/CellStyleBorderHandlerTest.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..29f128211b6b9587a1fa5b7bc6e4401883d05a04 GIT binary patch literal 7500 zcmbt(1yCH@*7e{L2<|p$a0?bJ!QI^*1|5RC43OXi*Fl0qaCaXd1PLwyf&~p02oUV! z-TT+OFI4^Y-FLs~>FKKOsk8d5eQNE!*HKkKK*R?C0H_ZqH2~!YAq4~u0O*1T0I&db z051m)Pq2%x6V`#CC<}(+LzgWWl=4xE6S-k{@h+G{0sxMtbN0)A&F_7V`a_hWo9V6?M zbh&gZ5Nj3O>6}vQrcZj5yQL$06VOEAFHF_(@;S3->6ZVP8Lgzch;F*JXi&c5c7AfY zsc-~7jV#nB$RP$)wpUk;OOZpucS1|vxv$!zQ-%D5eVh&_`je&TIWew{w&Txd+xfzz zF21EN+2FPPC3`-4QTE21@?r1eV1C;#sGGpv5TcA?{wYRz_X3SZjYrCloD(8IwYA!V0^Tlf@RFcN!BWJbB)9y}R{E z)iQOp=^91#w~$7<%Au*D007q1007>fA$0>;Ia+c2@yqph!}?v{0KCM9f5!q@FT}kz_W`tG=h6l#6-aJt6wtsyoPOek7>lyBV>zDU$Yq)k}s~Q5DxX zLIsvl^`(4{t>%3RfCx$G$e`=f@fS4iS9^W$1P2Aag-WqC`IT-83Xs;JMOd?49D-Cq z%}BLuDZ%Nw3!MnWPTdjmR5_UE`GBH?2OIhPP)nHr3DeOSz6m|N;)k7j&lYKL=eOPto6 zu21JIRW&1!!BJ+MJ9b6WB?$_FQ9VaILLHcxk<4Z#j$G3U-?Mf2shP@x5_UjQ?VEFD z%jZdRJQ~uT6=zDTWYa7xCnO|@Fu}=!1g0oS<1b-5a8W3)fM`s(bT0iavBe+^oMovb za#;TYZ5;sO97_W;Yu04Kl-Igs2^4Wp_9FalT2RAc859PNlaqZ)HE7AMe~5{FV8>Hs z+$rpTx_&lXRjiVeEqdi$XpHup*i(&Xie&ZXc*bPa|M2E&*g#>}-M z^;A8d`f%$Pzc#{@y-@Nj%73v(VwhYIxyp9*GuM-uBJ4Rv(ga%z^!CP&&*Q)vnO2_l zS09Oz3`W-8S!As z3X}kYkn0s5Qp4OPDTVfs8M6!`-qNAFt?%EU(h$CAO0S+gdhR+p!JGQ}68ARICK;MWcmzT+*1ib?7fj7(O%?4K}vC z&xcLH$M28>*M;+{abaMVu`T%1MDhjBw+Zc1QIKz?Zzvg#aR2iZ6x+a-`1lk?bhRv& zYXE$AxFzG8pOU^&v2ku65#ZTq`(u}RnwpamkbGb29DWCo5Gb$w$T~KHy?HiXe_&c6 z%K0wKssbL*QUdcXJq`FHXIY$95|cphI2!wmcGeO@SenjKxE8?D83uiA$8I@FF(FSv zp)UL0vr&O8CgFaVlz!>-QkG3UcE^=hrlr){GoSt={Y@O7xJZ4tlZBo`Omp)P?KkTgw=j)Wwh8www=Z!N!bBa_YWZW`~WFNveYQ3XvDhi+bzF z<~$_bxvgrxx%-%d-hk9HLI`q*Ga>E3X1}7Jv?M3S1o_XLk9LD@FpY)hho4B^Ix_J( z5LEIt5w3}5(ixO*o%#?F2)rAjOuCuL20A>&n=eo|sA*_z)M%c~1&mLR9ioS922hc= z3gXGkyvgsROfJ$-{|u2BJ=y@+E(Y-wKpMsygBaTi4udbeP>k;lDv#)MO;@p6uOr-a z_s)`YlIdR-jk_w@AtLbX>{`0z@Y8>}Vd_jB$0YYTNEb*NPbhkaa%=}hwzq3^3w9t8 zk~r-&2HSP=0_8(=-%XQ&d52MajjU5*Ld9rB{3nK91Z(M@!%Y*98XV#`maTDTNf5uj z`uS!DLpcCOqnyx+J>RK7~Nxt{flV<{K3TqB46pZed2&TRN;Nwec~3r_kj&P7)Mx6lPChB+hay&gbzWP) z9_lR6!uX5BWz=~Zt=TTi*#kSjQ6P7hL(vC2ipG@kKU=%&PKk(H$c3x1x% zT3%Q~7-A3+m^4)F!7J`Hc8Sj2S5%gol7xS;J*=595@86|=c)g`wrQwYsC4*?Tpi+ILc8C% zZSmahRyt4n(Bp}51>G8dMp&y(X?=%J+vkhLS6Mv7oab~o1u)%(vyZF4XXzusz0j41 z%F6wr_`-h3(w1NgRTr?cD~Fl0^WRO;P*o*+1ZwPCmUWSGIR&O3-q1I%unL2nT#2B| zsQZk9XbXWRO?i%E9UUB$U}?unGfSeO0U3v@+W0KE#U0_NZ1)F0qin{|N!+ZXQQ2~G zk7KmolH*yPs_L?JPoCnb=|53BK!Y$THPi_Df9g>!^v13^>IgHc-v-E<({CjPvA_vB zN1YiAfn)Zc+%`>12_3NvI?20NYA+>8gE42w&iT>><0)25lAGtYCr*B%boe=Jh9s>9 zQz^}?QJIb}Ocj*7t7xH6$Gizbt60IvfIG!7F_%RyCW-8d+vWJ3FDw9xw&DXql@VTav+EIMlY4q>!4jYxf$CQFBte^Swipy{zxL}7S&;lV*8 zy($QOZZejh{^_Y!x*r5om^>9Up zl5`^K!+4Y5{TJYq3RK0BkP$}fvhF}QegtOb(13Q?QGZS?I``3IF}84fse6L!))(UK1YIr^5`X0q@R z_)M8bH2CyuSjMDp%x`7|E_qj%b%72az*lGEqfw8-6TkUJAoU?M6v%*wR^i`$ge%C( z%FUJIkIUb#JfTTTv6-CMZ%hVG{RQY8l+pDXGAmovS+tfZD`Q9?4a6Eta=Kdn7qPE% zZHJ{anZ&Hqu5L$rR=zaV(#T9mmk1WV##V#p)oCfYV7mRa^}4p8UsrqkgF0`)839Je zs*|#OR~l|NZgiEByn=nEJ29y-#F9Z3bNaGSRi8Vm%7-dL8eyajs24WHnDI6tBEu)F zp;JnNAna?k#tks9(O6PqfORrcou^30{zvAS%cydi?YL`j^A8i`4gr!Axt<2@vT8UT z?laH^tIpb9l`uUOnh{fq<*%&?Mb+k>O>Q-`>%~Hah|T?C{|cTF<^vhBXVHn;8{o+M z1tdCx#nfJXB(M8i7mQ#BegaqK?dDQ6Q3#C6-$Y>FGCrGtF(Eka;vdawUn_gIE_M= z^34t>vPBrpKq9>hcnW3#UZ{pNVgf+JO5d!(L)O4ay0;Jt=4(CZO2~XFVas8wS0%F> z>{)!T5raVahx2KgCi+Uko@E;4qLI4@q)ily%w$@x!J{$GwqrsLOr6;nWnY)SfH4ijYd#2szSv%BIf@!shOm3mX*| zvcgSK-p47fQdw5pY-u6o@pa9y`IQ%FI2Bb*HjeX@qTC%s4b%i4gl*)kjGsH_mq~>d z_0(uI2%pS%C3_9RJK-S78ZlbECHnFO?PZ7vkECrd5y%rhy1%9 z!7g1E91#Hk4srkh^UnqE>gMfW<@$HE=)0a{+@b*X9gA9L9a^Z>aHMLo11(fjE4lF* z)U6eZTEKL;Cf@5lLLhUC; zZ-*5tnhj+Rk8%=vrrqTeKWZ^2S;qUC7G7J6vW$vV4`N!tg3&BVTF5LKFS2#4$+Qc$ zVivj4k_>lgcqeA;tG?K!RLUa~^paiO^|Pq6FJH0hOeQH8c}z+kHd6u^OtQvH0i|y$ zH%4vJapi>!E9bK-XowI)#L@{r_^>D=nb8yH#4gCZQ|V%LBnj_s?_*Qx=#Pj5z+H6KdTUHWq9`n-~SwVQdQ;dLmcbWhB{uGHJ&101tiY|5yKzZfkg3G`FBW0 z=g5{g?VP+?vs9PJsTdX$oVK;N4SOQq= z`{B5bFy6_U`^NY!fwP+Aq1a%}qy(MdN=%Zx3bSCsd?)mhn{fW!*BoBGrje>p_!zh&a?%8p+1%AB%wBB{O zd#IgGsi zBm9{kaA`O9mEkK26(SxE!o#m!?8^i0M3GvJyYppQT6JaR+QkL^q8{J23mRwLwiM7;lUi zdM_uoR28l@xVRNNo{k-n!&KxIXpnD0(axIr=TBJJ$i>Sz8;%^FOn!ohbc%yaLX6ir zZ-??jWIUIk-QmcTy;`p|%Gy>+R-`)ivte5I^wpD%G&cKW?fR2PB$QXt&#Q(dg^q%e9Y z8&e;o`d?<4fdtse&C1EmMAO^Z%GK!aigiWOh*KXBTPhH#rothCy{s%UQHpAWPkjn2 zmorw46ZocJc-2#p(x1_ttdNYB?Ayvl3$1jbyZr(>4e1fHC@V@K5Piyn!3kX))MoIBam6XnA9@i!((_fG z@d&qBvp_i{PR3Jpq)_P~Kq;q*9Ea7#qfKPqTg&i`X-q%s!4vyQxj9@F|wqxS%=VtO(9 zE~HL4R&xFu@M92L$e3t{^n_}Gs;p7TO54m#9LC0uH(JsYNzrQm1Suc8)3O;vX%1rO; zez08M+aXl~Gfpo(Yxk~C_gDiF$-+!|iTzP&@``fTxcdu(QNCbSgEGSEaK}1(zCBpyaPVvoBKZH?4|#a-AD@4)JMtLdu{;0Q=u;0e^#Jfsy!yu= zkIjX@K)lfa|Hx{1jPSS}{|liM{XY=?o96s6#N(FoF9=zTKbZR0M%6!RFdrj5uI2wi zdV%!^(tlUkKOX*Zy8UbTbG$!?|0l`!G0Nji2mCk8*N5f(5A&Xwt25Zuie19W!NC=1 z4R!&_xY%0Cy8=D9x!Acl*|{FS#AEUP_d5U*2>+Ps|3S(hV?CC*zp& Date: Mon, 21 Feb 2022 13:12:24 -0300 Subject: [PATCH 37/43] Bael 5259 (#11832) * [BAEL-4849] Article code * [BAEL-4968] Article code * [BAEL-4968] Article code * [BAEL-4968] Article code * [BAEL-4968] Remove extra comments * [BAEL-5259] simple test case * [BAEL-5259] DSL-based rewrite * [BAEL-5259] Code formatting * [BAEL-5259] Test case naming --- spring-cloud/spring-cloud-gateway/pom.xml | 16 +++ .../rewrite/URLRewriteGatewayApplication.java | 25 ++++ .../rewrite/routes/DynamicRewriteRoute.java | 43 +++++++ .../WebFilterGatewayApplication.java | 2 +- .../main/resources/application-nosecurity.yml | 8 ++ .../resources/application-url-rewrite.yml | 11 ++ .../URLRewriteGatewayApplicationLiveTest.java | 109 ++++++++++++++++++ 7 files changed, 213 insertions(+), 1 deletion(-) create mode 100644 spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplication.java create mode 100644 spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/routes/DynamicRewriteRoute.java create mode 100644 spring-cloud/spring-cloud-gateway/src/main/resources/application-nosecurity.yml create mode 100644 spring-cloud/spring-cloud-gateway/src/main/resources/application-url-rewrite.yml create mode 100644 spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplicationLiveTest.java diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml index dcad2b7da6..a352bbd4e4 100644 --- a/spring-cloud/spring-cloud-gateway/pom.xml +++ b/spring-cloud/spring-cloud-gateway/pom.xml @@ -177,5 +177,21 @@ + + + gateway-url-rewrite + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.springcloudgateway.rewrite.URLRewriteGatewayApplication + -Dspring.profiles.active=url-rewrite + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplication.java new file mode 100644 index 0000000000..46541b4826 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplication.java @@ -0,0 +1,25 @@ +/** + * + */ +package com.baeldung.springcloudgateway.rewrite; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.cloud.gateway.filter.GatewayFilter; + +import reactor.core.publisher.Mono; + +/** + * @author Baeldung + * + */ +@SpringBootApplication +public class URLRewriteGatewayApplication { + + public static void main(String[] args) { + new SpringApplicationBuilder(URLRewriteGatewayApplication.class) + .profiles("url-rewrite") + .run(args); + } + +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/routes/DynamicRewriteRoute.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/routes/DynamicRewriteRoute.java new file mode 100644 index 0000000000..29d40d7021 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/rewrite/routes/DynamicRewriteRoute.java @@ -0,0 +1,43 @@ +package com.baeldung.springcloudgateway.rewrite.routes; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.http.server.reactive.ServerHttpRequest; + +import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR; +import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl; + +import java.util.Random; + +@Configuration +@Profile("url-rewrite") +public class DynamicRewriteRoute { + + @Value("${rewrite.backend.uri}") + private String backendUri; + private static Random rnd = new Random(); + + @Bean + public RouteLocator dynamicZipCodeRoute(RouteLocatorBuilder builder) { + return builder.routes() + .route("dynamicRewrite", r -> + r.path("/v2/zip/**") + .filters(f -> f.filter((exchange, chain) -> { + ServerHttpRequest req = exchange.getRequest(); + addOriginalRequestUrl(exchange, req.getURI()); + String path = req.getURI().getRawPath(); + String newPath = path.replaceAll( + "/v2/zip/(?.*)", + "/api/zip/${zipcode}-" + String.format("%03d", rnd.nextInt(1000))); + ServerHttpRequest request = req.mutate().path(newPath).build(); + exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI()); + return chain.filter(exchange.mutate().request(request).build()); + })) + .uri(backendUri)) + .build(); + } +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java index 852e5cadba..9e212cc4bf 100644 --- a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java @@ -8,7 +8,7 @@ public class WebFilterGatewayApplication { public static void main(String[] args) { new SpringApplicationBuilder(WebFilterGatewayApplication.class) - .profiles("webfilters") + .profiles("url-rewrite") .run(args); } diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application-nosecurity.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application-nosecurity.yml new file mode 100644 index 0000000000..40a52ded0f --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application-nosecurity.yml @@ -0,0 +1,8 @@ +# Enable this profile to disable security +spring: + autoconfigure: + exclude: + - org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration + - org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration + - org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration + - org.springframework.boot.actuate.autoconfigure.security.reactive.ReactiveManagementWebSecurityAutoConfiguration \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application-url-rewrite.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application-url-rewrite.yml new file mode 100644 index 0000000000..b2656151db --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application-url-rewrite.yml @@ -0,0 +1,11 @@ +spring: + cloud: + gateway: + routes: + - id: rewrite_v1 + uri: ${rewrite.backend.uri:http://example.com} + predicates: + - Path=/v1/customer/** + filters: + - RewritePath=/v1/customer/(?.*),/api/$\{segment} + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplicationLiveTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplicationLiveTest.java new file mode 100644 index 0000000000..41fe37045c --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/rewrite/URLRewriteGatewayApplicationLiveTest.java @@ -0,0 +1,109 @@ +package com.baeldung.springcloudgateway.rewrite; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.OutputStream; +import java.net.InetSocketAddress; + +import org.junit.AfterClass; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.reactive.server.WebTestClient; + +import com.sun.net.httpserver.HttpServer; + +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles({ "nosecurity", "url-rewrite" }) +class URLRewriteGatewayApplicationLiveTest { + + // NOTE for Eclipse users: By default, Eclipse will complain about com.sun.** classes. + // To solve this issue, follow instructions available at the : + // https://stackoverflow.com/questions/13155734/eclipse-cant-recognize-com-sun-net-httpserver-httpserver-package + private static HttpServer mockServer; + private static Logger log = LoggerFactory.getLogger(URLRewriteGatewayApplicationLiveTest.class); + + // Create a running HttpServer that echoes back the request URL. + private static HttpServer startTestServer() { + + try { + log.info("[I26] Starting mock server"); + mockServer = HttpServer.create(); + mockServer.bind(new InetSocketAddress(0), 0); + mockServer.createContext("/api", (xchg) -> { + String uri = xchg.getRequestURI() + .toString(); + log.info("[I23] Backend called: uri={}", uri); + xchg.getResponseHeaders() + .add("Content-Type", "text/plain"); + xchg.sendResponseHeaders(200, 0); + OutputStream os = xchg.getResponseBody(); + os.write(uri.getBytes()); + os.flush(); + os.close(); + }); + + mockServer.start(); + InetSocketAddress localAddr = mockServer.getAddress(); + log.info("[I36] mock server started: local address={}", localAddr); + + return mockServer; + } catch (Exception ex) { + throw new RuntimeException(ex); + } + + } + + // TIP: https://www.baeldung.com/spring-dynamicpropertysource + @DynamicPropertySource + static void registerBackendServer(DynamicPropertyRegistry registry) { + registry.add("rewrite.backend.uri", () -> { + HttpServer s = startTestServer(); + return "http://localhost:" + s.getAddress().getPort(); + }); + } + + @AfterClass + public static void stopMockBackend() throws Exception { + log.info("[I40] Shutdown mock http server"); + mockServer.stop(5); + } + + @LocalServerPort + private int localPort; + + @Test + void testWhenApiCall_thenRewriteSuccess(@Autowired WebTestClient webClient) { + webClient.get() + .uri("http://localhost:" + localPort + "/v1/customer/customer1") + .exchange() + .expectBody() + .consumeWith((result) -> { + String body = new String(result.getResponseBody()); + log.info("[I99] body={}", body); + assertEquals("/api/customer1", body); + }); + } + + @Test + void testWhenDslCall_thenRewriteSuccess(@Autowired WebTestClient webClient) { + webClient.get() + .uri("http://localhost:" + localPort + "/v2/zip/123456") + .exchange() + .expectBody() + .consumeWith((result) -> { + String body = new String(result.getResponseBody()); + log.info("[I99] body={}", body); + assertTrue(body.matches("/api/zip/123456-\\d{3}")); + }); + } + +} From 082d48e291d1799eb84c3cfc431147e71712bd71 Mon Sep 17 00:00:00 2001 From: vunamtien Date: Tue, 22 Feb 2022 00:35:48 +0700 Subject: [PATCH 38/43] BAEL-5379-create-simple-rock-paper-scissors-game (#11846) Co-authored-by: tienvn4 --- .../baeldung/game/RockPaperScissorsGame.java | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/game/RockPaperScissorsGame.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/game/RockPaperScissorsGame.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/game/RockPaperScissorsGame.java new file mode 100644 index 0000000000..fc9299f12d --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/game/RockPaperScissorsGame.java @@ -0,0 +1,66 @@ +package com.baeldung.game; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import java.util.Scanner; + +class RockPaperScissorsGame { + + private static Map movesMap = new HashMap() {{ + put(0, "rock"); + put(1, "paper"); + put(2, "scissors"); + }}; + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + int wins = 0; + int losses = 0; + + System.out.println("Welcome to Rock-Paper-Scissors! Please enter \"rock\", \"paper\", \"scissors\", or \"quit\" to exit."); + + while (true) { + System.out.println("-------------------------"); + System.out.print("Enter your move: "); + String playerMove = scanner.nextLine(); + + if (playerMove.equals("quit")) { + System.out.println("You won " + wins + " times and lost " + losses + " times."); + System.out.println("Thanks for playing! See you again."); + break; + } + + if (!movesMap.containsValue(playerMove)) { + System.out.println("Your move isn't valid!"); + continue; + } + + String computerMove = getComputerMove(); + + if (playerMove.equals(computerMove)) { + System.out.println("It's a tie!"); + } else if (isPlayerWin(playerMove, computerMove)) { + System.out.println("You won!"); + wins++; + } else { + System.out.println("You lost!"); + losses++; + } + } + } + + private static boolean isPlayerWin(String playerMove, String computerMove) { + return playerMove.equals("rock") && computerMove.equals("scissors") + || (playerMove.equals("scissors") && computerMove.equals("paper")) + || (playerMove.equals("paper") && computerMove.equals("rock")); + } + + private static String getComputerMove() { + Random random = new Random(); + int randomNumber = random.nextInt(3); + String computerMove = movesMap.get(randomNumber); + System.out.println("Computer move: " + computerMove); + return computerMove; + } +} \ No newline at end of file From 5ee332c6061ab0fb2e99b2aa7ceb418450d181cb Mon Sep 17 00:00:00 2001 From: Eugene Kovko <37694937+eukovko@users.noreply.github.com> Date: Tue, 22 Feb 2022 02:05:08 +0100 Subject: [PATCH 39/43] BAEL-5349 Example for the difference between map and hashmap (#11827) * example for the difference between map and hashmap * unit tests for the example * rename unit tests Co-authored-by: eugene.kovko --- .../java/com/baeldung/mapandhashmap/Main.java | 25 +++++++ .../mapandhashmap/printer/HashMapPrinter.java | 13 ++++ .../mapandhashmap/printer/MapPrinter.java | 13 ++++ .../mapandhashmap/printer/MapReporter.java | 19 +++++ .../printer/HashMapPrinterUnitTest.java | 56 ++++++++++++++ .../printer/MapPrinterUnitTest.java | 71 ++++++++++++++++++ .../printer/MapReporterUnitTest.java | 74 +++++++++++++++++++ 7 files changed, 271 insertions(+) create mode 100644 core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/Main.java create mode 100644 core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/HashMapPrinter.java create mode 100644 core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapPrinter.java create mode 100644 core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapReporter.java create mode 100644 core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/HashMapPrinterUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapPrinterUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapReporterUnitTest.java diff --git a/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/Main.java b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/Main.java new file mode 100644 index 0000000000..1024399a98 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/Main.java @@ -0,0 +1,25 @@ +package com.baeldung.mapandhashmap; + +import com.baeldung.mapandhashmap.printer.HashMapPrinter; +import com.baeldung.mapandhashmap.printer.MapPrinter; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +public class Main { + public static void main(String[] args) { + Map map = new HashMap<>(); + HashMap hashMap = new HashMap<>(); + TreeMap treeMap = new TreeMap<>(); + + HashMapPrinter hashMapPrinter = new HashMapPrinter(); + hashMapPrinter.printMap(hashMap); +// hashMapPrinter.printMap(treeMap); Compile time error +// hashMapPrinter.printMap(map); Compile time error + + MapPrinter mapPrinter = new MapPrinter(); + mapPrinter.printMap(hashMap); + mapPrinter.printMap(treeMap); + mapPrinter.printMap(map); + } +} diff --git a/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/HashMapPrinter.java b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/HashMapPrinter.java new file mode 100644 index 0000000000..53c78bfc55 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/HashMapPrinter.java @@ -0,0 +1,13 @@ +package com.baeldung.mapandhashmap.printer; + +import java.util.HashMap; +import java.util.Map.Entry; + +public class HashMapPrinter { + + public void printMap(final HashMap map) { + for (final Entry entry : map.entrySet()) { + System.out.println(entry.getKey() + " " + entry.getValue()); + } + } +} diff --git a/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapPrinter.java b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapPrinter.java new file mode 100644 index 0000000000..e5c0ab49cd --- /dev/null +++ b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapPrinter.java @@ -0,0 +1,13 @@ +package com.baeldung.mapandhashmap.printer; + +import java.util.Map; +import java.util.Map.Entry; + +public class MapPrinter { + + public void printMap(final Map map) { + for (final Entry entry : map.entrySet()) { + System.out.println(entry.getKey() + " " + entry.getValue()); + } + } +} diff --git a/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapReporter.java b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapReporter.java new file mode 100644 index 0000000000..fd7347c2d1 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-4/src/main/java/com/baeldung/mapandhashmap/printer/MapReporter.java @@ -0,0 +1,19 @@ +package com.baeldung.mapandhashmap.printer; + +import java.util.Map; +import java.util.Map.Entry; + +public class MapReporter { + + private final Map map; + + public MapReporter(final Map map) { + this.map = map; + } + + public void printMap() { + for (final Entry entry : this.map.entrySet()) { + System.out.println(entry.getKey() + " " + entry.getValue()); + } + } +} diff --git a/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/HashMapPrinterUnitTest.java b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/HashMapPrinterUnitTest.java new file mode 100644 index 0000000000..e1147f6e00 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/HashMapPrinterUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.mapandhashmap.printer; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.HashMap; +import java.util.LinkedHashMap; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class HashMapPrinterUnitTest { + + private final HashMapPrinter mapPrinter = new HashMapPrinter(); + private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); + + @BeforeEach + public void setUp() { + System.setOut(new PrintStream(outputStreamCaptor)); + } + + @Test + @DisplayName("Test hash map printer with HashMap") + void testPrintHashMap() { + // given + String key = "HashMap"; + String value = "Main default implementation for the Map interface"; + String expected = key + " " + value; + HashMap map = new HashMap<>(); + map.put(key, value); + // when + mapPrinter.printMap(map); + // then + String actual = outputStreamCaptor.toString().trim(); + assertThat(actual).isEqualTo(expected); + + } + + @Test + @DisplayName("Test hash map printer with LinkedHash") + void testPrintLinkedHashMap() { + // given + String key = "LinkedHashMap"; + String value = "Use this implementation if you need keep the order of elements"; + String expected = key + " " + value; + LinkedHashMap map = new LinkedHashMap<>(); + map.put(key, value); + // when + mapPrinter.printMap(map); + // then + String actual = outputStreamCaptor.toString().trim(); + assertThat(actual).isEqualTo(expected); + + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapPrinterUnitTest.java b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapPrinterUnitTest.java new file mode 100644 index 0000000000..8c45758bdf --- /dev/null +++ b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapPrinterUnitTest.java @@ -0,0 +1,71 @@ +package com.baeldung.mapandhashmap.printer; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.TreeMap; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class MapPrinterUnitTest { + + private final MapPrinter mapPrinter = new MapPrinter(); + private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); + + @BeforeEach + public void setUp() { + System.setOut(new PrintStream(outputStreamCaptor)); + } + + @Test + @DisplayName("Test printer with TreeMap") + void testPrintTreeMap() { + // given + String key = "TreeMap"; + String value = "Used when sorting is needed"; + String expected = key + " " + value; + TreeMap map = new TreeMap<>(); + map.put(key, value); + // when + mapPrinter.printMap(map); + // then + String actual = outputStreamCaptor.toString().trim(); + assertThat(actual).isEqualTo(expected); + } + + @Test + @DisplayName("Test printer with HashMap") + void testPrintHashMap() { + // given + String key = "HashMap"; + String value = "Main default implementation for the Map interface"; + String expected = key + " " + value; + HashMap map = new HashMap<>(); + map.put(key, value); + // when + mapPrinter.printMap(map); + // then + String actual = outputStreamCaptor.toString().trim(); + assertThat(actual).isEqualTo(expected); + } + + @Test + @DisplayName("Test printer with LinkedHash") + void testPrintLinkedHashMap() { + // given + String key = "LinkedHashMap"; + String value = "Use this implementation if you need keep the order of elements"; + String expected = key + " " + value; + LinkedHashMap map = new LinkedHashMap<>(); + map.put(key, value); + // when + mapPrinter.printMap(map); + // then + String actual = outputStreamCaptor.toString().trim(); + assertThat(actual).isEqualTo(expected); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapReporterUnitTest.java b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapReporterUnitTest.java new file mode 100644 index 0000000000..8f858a75c4 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-4/src/test/java/com/baeldung/mapandhashmap/printer/MapReporterUnitTest.java @@ -0,0 +1,74 @@ +package com.baeldung.mapandhashmap.printer; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.TreeMap; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class MapReporterUnitTest { + + private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); + + @BeforeEach + public void setUp() { + System.setOut(new PrintStream(outputStreamCaptor)); + } + + @Test + @DisplayName("Test reporter with TreeMap") + void testPrintTreeMap() { + // given + String key = "TreeMap"; + String value = "Used when sorting is needed"; + String expected = key + " " + value; + TreeMap map = new TreeMap<>(); + map.put(key, value); + // when + MapReporter mapReporter = new MapReporter(map); + mapReporter.printMap(); + // then + String actual = outputStreamCaptor.toString().trim(); + assertThat(actual).isEqualTo(expected); + } + + @Test + @DisplayName("Test reporter with HashMap") + void testPrintHashMap() { + // given + String key = "HashMap"; + String value = "Main default implementation for the Map interface"; + String expected = key + " " + value; + HashMap map = new HashMap<>(); + map.put(key, value); + // when + MapReporter mapReporter = new MapReporter(map); + mapReporter.printMap(); + // then + String actual = outputStreamCaptor.toString().trim(); + assertThat(actual).isEqualTo(expected); + } + + @Test + @DisplayName("Test reporter with LinkedHash") + void testPrintLinkedHashMap() { + // given + String key = "LinkedHashMap"; + String value = "Use this implementation if you need keep the order of elements"; + String expected = key + " " + value; + LinkedHashMap map = new LinkedHashMap<>(); + map.put(key, value); + // when + MapReporter mapReporter = new MapReporter(map); + mapReporter.printMap(); + // then + String actual = outputStreamCaptor.toString().trim(); + assertThat(actual).isEqualTo(expected); + } + +} \ No newline at end of file From 26a0093154832f9162df2baabd884d43aabb8884 Mon Sep 17 00:00:00 2001 From: alemoles Date: Mon, 21 Feb 2022 22:13:41 -0500 Subject: [PATCH 40/43] BAEL-5391 - Java Error "Missing return statement" (#5) (#11845) * BAEL-5391 - Java Error "Missing return statement" (#5) * BAEL-5391 - Java Error "Missing return statement" --- .../MissingReturnStatement.java | 41 +++++++++++++++++++ .../MissingReturnStatementUnitTest.java | 38 +++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatement.java create mode 100644 core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatementUnitTest.java diff --git a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatement.java b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatement.java new file mode 100644 index 0000000000..d76ae76a0e --- /dev/null +++ b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatement.java @@ -0,0 +1,41 @@ +package com.baeldung.exception.missingreturnstatement; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class MissingReturnStatement { + public static void main(String[] args) { + int a = -12; + int result = pow(a); + System.out.println(result); + Map dictionary = createDictionary(); + dictionary.forEach((s, integer) -> System.out.println(s + " " + integer)); + } + + public static int pow(int number) { + int pow = number * number; + return pow; + } + + public static String checkNumber(int number) { + if (number == 0) { + return "It's equals to zero"; + } + + for (int i = 0; i < number; i++) { + if (i > 100) { + return "It's a big number"; + } + } + return "It's a negative number"; + } + + public static Map createDictionary() { + List words = Arrays.asList("Hello", "World"); + return words.stream() + .collect(Collectors.toMap(s -> s, s -> 1)); + } + +} diff --git a/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatementUnitTest.java b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatementUnitTest.java new file mode 100644 index 0000000000..97a050a3f0 --- /dev/null +++ b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/missingreturnstatement/MissingReturnStatementUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.exception.missingreturnstatement; + +import static org.junit.Assert.assertEquals; + +import java.util.Map; + +import org.junit.Test; + +public class MissingReturnStatementUnitTest { + + @Test + public void givenANumber_thenReturnItsPow() { + int number = 10; + int pow = MissingReturnStatement.pow(number); + assertEquals(100, pow); + } + + @Test + public void givenABigNumber_thenReturnItsType() { + int number = 200; + String type = MissingReturnStatement.checkNumber(number); + assertEquals("It's a big number", type); + } + + @Test + public void givenANegativeNumber_thenReturnItsType() { + int number = -10; + String type = MissingReturnStatement.checkNumber(number); + assertEquals("It's a negative number", type); + } + + @Test + public void getStringDictionary_thenPrintValues() { + Map dictionary = MissingReturnStatement.createDictionary(); + assertEquals(2, dictionary.size()); + dictionary.forEach((s, integer) -> System.out.println(s + " - " + integer)); + } +} \ No newline at end of file From c8231b7c60ee610934afd4f91dcf5d5c17c6f5ee Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Tue, 22 Feb 2022 10:19:48 +0100 Subject: [PATCH 41/43] BAEL-4316 Sample apps to showcase how to add files from outside docker context (#11606) * BAEL-4316 Sample apps to showcase how to add files from outside docker context * BAEL-4316 update README content * BAEL-4316 change example * BAEL-4316 update docker file * BAEL-4316 revert the README changes * BAEL-4316 change directory structure * BAEL-4316 deleted old files Co-authored-by: Swapan Pramanick --- .../projects/config/Dockerfile | 2 ++ .../projects/config/nginx.conf | 8 ++++++++ .../projects/sample-site/docker/Dockerfile | 3 +++ .../projects/sample-site/docker/Dockerfile-from-base | 2 ++ .../projects/sample-site/docker/Dockerfile-script | 3 +++ .../projects/sample-site/docker/build-docker.sh | 6 ++++++ .../projects/sample-site/html/index.html | 10 ++++++++++ 7 files changed, 34 insertions(+) create mode 100644 docker/docker-include-outside-build-context/projects/config/Dockerfile create mode 100644 docker/docker-include-outside-build-context/projects/config/nginx.conf create mode 100644 docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile create mode 100644 docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-from-base create mode 100644 docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-script create mode 100755 docker/docker-include-outside-build-context/projects/sample-site/docker/build-docker.sh create mode 100644 docker/docker-include-outside-build-context/projects/sample-site/html/index.html diff --git a/docker/docker-include-outside-build-context/projects/config/Dockerfile b/docker/docker-include-outside-build-context/projects/config/Dockerfile new file mode 100644 index 0000000000..754f9f9be3 --- /dev/null +++ b/docker/docker-include-outside-build-context/projects/config/Dockerfile @@ -0,0 +1,2 @@ +FROM nginx:latest +COPY nginx.conf /etc/nginx/nginx.conf diff --git a/docker/docker-include-outside-build-context/projects/config/nginx.conf b/docker/docker-include-outside-build-context/projects/config/nginx.conf new file mode 100644 index 0000000000..944da2f112 --- /dev/null +++ b/docker/docker-include-outside-build-context/projects/config/nginx.conf @@ -0,0 +1,8 @@ +events {} + +http { + server { + listen 80; + index index.html; + } +} diff --git a/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile b/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile new file mode 100644 index 0000000000..bda0bbe257 --- /dev/null +++ b/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile @@ -0,0 +1,3 @@ +FROM nginx:latest +COPY sample-site/html/* /etc/nginx/html/ +COPY config/nginx.conf /etc/nginx/nginx.conf diff --git a/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-from-base b/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-from-base new file mode 100644 index 0000000000..1b72414bc0 --- /dev/null +++ b/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-from-base @@ -0,0 +1,2 @@ +FROM sample-site-base:latest +COPY html/* /etc/nginx/html/ diff --git a/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-script b/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-script new file mode 100644 index 0000000000..572028f19f --- /dev/null +++ b/docker/docker-include-outside-build-context/projects/sample-site/docker/Dockerfile-script @@ -0,0 +1,3 @@ +FROM nginx:latest +COPY html/* /etc/nginx/html/ +COPY config/nginx.conf /etc/nginx/nginx.conf diff --git a/docker/docker-include-outside-build-context/projects/sample-site/docker/build-docker.sh b/docker/docker-include-outside-build-context/projects/sample-site/docker/build-docker.sh new file mode 100755 index 0000000000..e84687b7b7 --- /dev/null +++ b/docker/docker-include-outside-build-context/projects/sample-site/docker/build-docker.sh @@ -0,0 +1,6 @@ +mkdir tmp-context +cp -R ../html tmp-context/ +cp -R ../../config tmp-context/ +cp Dockerfile-script tmp-context/Dockerfile +docker build -t sample-site:latest tmp-context +rm -rf tmp-context diff --git a/docker/docker-include-outside-build-context/projects/sample-site/html/index.html b/docker/docker-include-outside-build-context/projects/sample-site/html/index.html new file mode 100644 index 0000000000..85f287fad7 --- /dev/null +++ b/docker/docker-include-outside-build-context/projects/sample-site/html/index.html @@ -0,0 +1,10 @@ + + + + + Sample Site + + +

Welcome to the first page of the site

+ + From 74b2b2e910eaf521494d377dd55f3b3699ffc76c Mon Sep 17 00:00:00 2001 From: Muhammad Abdullah Azam Khan Date: Tue, 22 Feb 2022 13:28:27 +0400 Subject: [PATCH 42/43] Bael 5303 graphqlvs rest (#11715) * GraphQL and REST Comparison * Updating README * Reformatting code --- spring-boot-modules/pom.xml | 1 + .../README.md | 7 ++ .../spring-boot-libraries-comparison/pom.xml | 46 +++++++ .../GraphqlVsRestApplication.java | 19 +++ .../configuration/GraphqlConfiguration.java | 35 ++++++ .../controller/OrderController.java | 25 ++++ .../controller/ProductController.java | 38 ++++++ .../baeldung/graphqlvsrest/entity/Order.java | 58 +++++++++ .../graphqlvsrest/entity/Product.java | 115 ++++++++++++++++++ .../graphqlvsrest/model/ProductModel.java | 92 ++++++++++++++ .../repository/OrderRepository.java | 11 ++ .../repository/ProductRepository.java | 14 +++ .../repository/impl/OrderRepositoryImpl.java | 36 ++++++ .../impl/ProductRepositoryImpl.java | 74 +++++++++++ .../graphqlvsrest/resolver/Mutation.java | 22 ++++ .../resolver/ProductResolver.java | 18 +++ .../graphqlvsrest/resolver/Query.java | 27 ++++ .../src/main/resources/application.properties | 0 .../main/resources/graphql/schema.graphqls | 57 +++++++++ 19 files changed, 695 insertions(+) create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/README.md create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/pom.xml create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/GraphqlVsRestApplication.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/configuration/GraphqlConfiguration.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/OrderController.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/ProductController.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Order.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Product.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/model/ProductModel.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/OrderRepository.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/ProductRepository.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/OrderRepositoryImpl.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/ProductRepositoryImpl.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Mutation.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/ProductResolver.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Query.java create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/application.properties create mode 100644 spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/graphql/schema.graphqls diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 4925530a35..c1a96a0604 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -51,6 +51,7 @@ spring-boot-libraries spring-boot-libraries-2 + spring-boot-libraries-comparison spring-boot-logging-log4j2 spring-boot-multiple-datasources spring-boot-mvc diff --git a/spring-boot-modules/spring-boot-libraries-comparison/README.md b/spring-boot-modules/spring-boot-libraries-comparison/README.md new file mode 100644 index 0000000000..3efdac2a4c --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/README.md @@ -0,0 +1,7 @@ +## Spring Boot Libraries + +This module contains articles about various Spring Boot libraries Comparison + +### Relevant Articles: + +- [GraphQL vs REST](https://www.baeldung.com/graphql-vs-rest/) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-libraries-comparison/pom.xml b/spring-boot-modules/spring-boot-libraries-comparison/pom.xml new file mode 100644 index 0000000000..59d0e75be3 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + spring-boot-libraries-comparison + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.data + spring-data-jpa + + + com.graphql-java + graphql-spring-boot-starter + ${graphql-spring-boot-starter.version} + + + com.graphql-java + graphql-java-tools + ${graphql-java-tools.version} + + + com.graphql-java + graphiql-spring-boot-starter + ${graphql-spring-boot-starter.version} + + + + + + 5.0.2 + 5.2.4 + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/GraphqlVsRestApplication.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/GraphqlVsRestApplication.java new file mode 100644 index 0000000000..29a3ef1e0f --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/GraphqlVsRestApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.graphqlvsrest; + +import com.baeldung.graphqlvsrest.configuration.GraphqlConfiguration; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.context.annotation.Import; + +@SpringBootApplication +@Import(GraphqlConfiguration.class) +@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class}) +public class GraphqlVsRestApplication { + + public static void main(String[] args) { + SpringApplication.run(GraphqlVsRestApplication.class, args); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/configuration/GraphqlConfiguration.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/configuration/GraphqlConfiguration.java new file mode 100644 index 0000000000..c100a03143 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/configuration/GraphqlConfiguration.java @@ -0,0 +1,35 @@ +package com.baeldung.graphqlvsrest.configuration; + +import com.baeldung.graphqlvsrest.repository.OrderRepository; +import com.baeldung.graphqlvsrest.resolver.Mutation; +import com.baeldung.graphqlvsrest.resolver.ProductResolver; +import com.baeldung.graphqlvsrest.resolver.Query; +import com.baeldung.graphqlvsrest.repository.ProductRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class GraphqlConfiguration { + + @Autowired + ProductRepository productRepository; + + @Autowired + OrderRepository orderRepository; + + @Bean + public Query query() { + return new Query(productRepository); + } + + @Bean + public ProductResolver productResolver(){ + return new ProductResolver(orderRepository); + } + + @Bean + public Mutation mutation() { + return new Mutation(productRepository); + } +} diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/OrderController.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/OrderController.java new file mode 100644 index 0000000000..14f0468bbd --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/OrderController.java @@ -0,0 +1,25 @@ +package com.baeldung.graphqlvsrest.controller; + +import com.baeldung.graphqlvsrest.entity.Order; +import com.baeldung.graphqlvsrest.entity.Product; +import com.baeldung.graphqlvsrest.model.ProductModel; +import com.baeldung.graphqlvsrest.repository.OrderRepository; +import com.baeldung.graphqlvsrest.repository.ProductRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("order") +public class OrderController { + + @Autowired + OrderRepository orderRepository; + + @GetMapping() + public List getOrders(@RequestParam("product-id") Integer productId){ + return orderRepository.getOrdersByProduct(productId); + } +} diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/ProductController.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/ProductController.java new file mode 100644 index 0000000000..2fdee8765a --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/controller/ProductController.java @@ -0,0 +1,38 @@ +package com.baeldung.graphqlvsrest.controller; + +import com.baeldung.graphqlvsrest.entity.Product; +import com.baeldung.graphqlvsrest.model.ProductModel; +import com.baeldung.graphqlvsrest.repository.ProductRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("product") +public class ProductController { + + @Autowired + ProductRepository productRepository; + + @GetMapping + public List getProducts(Pageable pageable){ + return productRepository.getProducts(pageable.getPageSize(), pageable.getPageNumber()); + } + + @GetMapping("/{product-id}") + public Product getProducts(@PathVariable("product-id") Integer productId){ + return productRepository.getProduct(productId); + } + + @PostMapping + public Product save(@RequestBody ProductModel productModel){ + return productRepository.save(productModel); + } + + @PutMapping("/{product-id}") + public Product update(@PathVariable("product-id") Integer productId, @RequestBody ProductModel productModel){ + return productRepository.update(productId, productModel); + } +} diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Order.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Order.java new file mode 100644 index 0000000000..89606e9897 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Order.java @@ -0,0 +1,58 @@ +package com.baeldung.graphqlvsrest.entity; + +public class Order { + private Integer id; + private Integer product_id; + private String customer_uuid; + private String status; + private String address; + private String creation_date; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getProduct_id() { + return product_id; + } + + public void setProduct_id(Integer product_id) { + this.product_id = product_id; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCustomer_uuid() { + return customer_uuid; + } + + public void setCustomer_uuid(String customer_uuid) { + this.customer_uuid = customer_uuid; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getCreation_date() { + return creation_date; + } + + public void setCreation_date(String creation_date) { + this.creation_date = creation_date; + } +} diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Product.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Product.java new file mode 100644 index 0000000000..2da9244c92 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/entity/Product.java @@ -0,0 +1,115 @@ +package com.baeldung.graphqlvsrest.entity; + +import com.baeldung.graphqlvsrest.model.ProductModel; + +import java.util.List; + +public class Product { + private Integer id; + private String name; + private String description; + private String status; + private String currency; + private Double price; + private List image_url; + private List video_url; + private Integer stock; + private Float average_rating; + + public Product(Integer id, ProductModel productModel) { + this.id = id; + this.name = productModel.getName(); + this.description = productModel.getDescription(); + this.currency = productModel.getCurrency(); + this.price = productModel.getPrice(); + this.stock = productModel.getStock(); + this.image_url = productModel.getImage_url(); + this.video_url = productModel.getVideo_url(); + this.average_rating = 0F; + this.status = productModel.getStatus(); + } + + public Product(){ + + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCurrency() { + return currency; + } + + public void setCurrency(String currency) { + this.currency = currency; + } + + public Double getPrice() { + return price; + } + + public void setPrice(Double price) { + this.price = price; + } + + public List getImage_url() { + return image_url; + } + + public void setImage_url(List image_url) { + this.image_url = image_url; + } + + public List getVideo_url() { + return video_url; + } + + public void setVideo_url(List video_url) { + this.video_url = video_url; + } + + public Integer getStock() { + return stock; + } + + public void setStock(Integer stock) { + this.stock = stock; + } + + public Float getAverage_rating() { + return average_rating; + } + + public void setAverage_rating(Float average_rating) { + this.average_rating = average_rating; + } +} diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/model/ProductModel.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/model/ProductModel.java new file mode 100644 index 0000000000..db7a3ba54e --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/model/ProductModel.java @@ -0,0 +1,92 @@ +package com.baeldung.graphqlvsrest.model; + +import java.util.List; + +public class ProductModel { + private String name; + private String description; + private String status; + private String currency; + private Double price; + private List image_url; + private List video_url; + private Integer stock; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCurrency() { + return currency; + } + + public void setCurrency(String currency) { + this.currency = currency; + } + + public Double getPrice() { + return price; + } + + public void setPrice(Double price) { + this.price = price; + } + + public List getImage_url() { + return image_url; + } + + public void setImage_url(List image_url) { + this.image_url = image_url; + } + + public List getVideo_url() { + return video_url; + } + + public void setVideo_url(List video_url) { + this.video_url = video_url; + } + + public Integer getStock() { + return stock; + } + + public void setStock(Integer stock) { + this.stock = stock; + } + + @Override + public String toString() { + return "ProductModel{" + + "name='" + name + '\'' + + ", description='" + description + '\'' + + ", status='" + status + '\'' + + ", currency='" + currency + '\'' + + ", price=" + price + + ", image_url=" + image_url + + ", video_url=" + video_url + + ", stock=" + stock + + '}'; + } +} diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/OrderRepository.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/OrderRepository.java new file mode 100644 index 0000000000..92cc288426 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/OrderRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.graphqlvsrest.repository; + +import com.baeldung.graphqlvsrest.entity.Order; +import com.baeldung.graphqlvsrest.entity.Product; +import com.baeldung.graphqlvsrest.model.ProductModel; + +import java.util.List; + +public interface OrderRepository { + List getOrdersByProduct(Integer productId); +} diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/ProductRepository.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/ProductRepository.java new file mode 100644 index 0000000000..c0fb12327f --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/ProductRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.graphqlvsrest.repository; + +import com.baeldung.graphqlvsrest.entity.Product; +import com.baeldung.graphqlvsrest.model.ProductModel; + +import java.util.List; + +public interface ProductRepository { + List getProducts(Integer pageSize, Integer pageNumber); + Product getProduct(Integer id); + Product save(ProductModel productModel); + Product update(Integer productId, ProductModel productModel); + +} diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/OrderRepositoryImpl.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/OrderRepositoryImpl.java new file mode 100644 index 0000000000..e4f316c865 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/OrderRepositoryImpl.java @@ -0,0 +1,36 @@ +package com.baeldung.graphqlvsrest.repository.impl; + +import com.baeldung.graphqlvsrest.entity.Order; +import com.baeldung.graphqlvsrest.repository.OrderRepository; +import org.springframework.stereotype.Repository; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Repository +public class OrderRepositoryImpl implements OrderRepository { + + private static List orderList = new ArrayList<>(); + + public OrderRepositoryImpl() { + for (int i = 1; i <= 100; i++){ + Order order = new Order(); + order.setId(i); + order.setProduct_id(i%10); + order.setAddress(UUID.randomUUID().toString()); + order.setCustomer_uuid(UUID.randomUUID().toString()); + order.setCreation_date(new Date(System.currentTimeMillis()).toString()); + order.setStatus("Delivered"); + orderList.add(order); + } + } + + + @Override + public List getOrdersByProduct(Integer productId) { + return orderList.stream().filter(order -> order.getProduct_id().equals(productId)).collect(Collectors.toList()); + } +} diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/ProductRepositoryImpl.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/ProductRepositoryImpl.java new file mode 100644 index 0000000000..845472faea --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/repository/impl/ProductRepositoryImpl.java @@ -0,0 +1,74 @@ +package com.baeldung.graphqlvsrest.repository.impl; + +import com.baeldung.graphqlvsrest.entity.Product; +import com.baeldung.graphqlvsrest.model.ProductModel; +import com.baeldung.graphqlvsrest.repository.ProductRepository; +import org.springframework.stereotype.Repository; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +@Repository +public class ProductRepositoryImpl implements ProductRepository { + + private static List productList = new ArrayList<>(); + + public ProductRepositoryImpl() { + for (int i = 1; i <= 10; i++){ + Product product = new Product(); + product.setId(i); + product.setName(String.format("Product %d", i)); + product.setDescription(String.format("Product %d description", i)); + product.setCurrency(String.format("Product %d currency", i)); + product.setPrice(Double.valueOf(i^2)); + product.setStock(10); + product.setAverage_rating(0F); + product.setImage_url(Arrays.asList(String.format("www.baeldung.com/imageurl/%d", i))); + product.setVideo_url(Arrays.asList(String.format("www.baeldung.com/videourl/%d", i))); + productList.add(product); + } + } + + @Override + public List getProducts(Integer pageSize, Integer pageNumber) { + return productList.stream().skip(pageSize*pageNumber).limit(pageSize).collect(Collectors.toList()); + } + + @Override + public Product getProduct(Integer id) { + return productList.stream().filter(product -> product.getId().equals(id)).findFirst().orElse(null); + } + + @Override + public Product save(ProductModel productModel) { + Product product = new Product(productList.size()+1, productModel); + productList.add(product); + return product; + } + + @Override + public Product update(Integer productId, ProductModel productModel) { + Product product = getProduct(productId); + if (product != null){ + update(product, productModel); + } + return product; + } + + private void update(Product product, ProductModel productModel){ + if (productModel != null) { + System.out.println(productModel.toString()); + Optional.ofNullable(productModel.getName()).ifPresent(product::setName); + Optional.ofNullable(productModel.getDescription()).ifPresent(product::setDescription); + Optional.ofNullable(productModel.getCurrency()).ifPresent(product::setCurrency); + Optional.ofNullable(productModel.getImage_url()).ifPresent(product::setImage_url); + Optional.ofNullable(productModel.getStock()).ifPresent(product::setStock); + Optional.ofNullable(productModel.getStatus()).ifPresent(product::setStatus); + Optional.ofNullable(productModel.getVideo_url()).ifPresent(product::setVideo_url); + Optional.ofNullable(productModel.getPrice()).ifPresent(product::setPrice); + } + } +} diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Mutation.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Mutation.java new file mode 100644 index 0000000000..3d643f97e6 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Mutation.java @@ -0,0 +1,22 @@ +package com.baeldung.graphqlvsrest.resolver; + +import com.baeldung.graphqlvsrest.entity.Product; +import com.baeldung.graphqlvsrest.model.ProductModel; +import com.baeldung.graphqlvsrest.repository.ProductRepository; +import com.coxautodev.graphql.tools.GraphQLMutationResolver; + +public class Mutation implements GraphQLMutationResolver { + + private ProductRepository productRepository; + public Mutation(ProductRepository productRepository){ + this.productRepository = productRepository; + } + + public Product saveProduct(ProductModel productModel) { + return productRepository.save(productModel); + } + + public Product updateProduct(Integer productId, ProductModel productModel) { + return productRepository.update(productId, productModel); + } +} diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/ProductResolver.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/ProductResolver.java new file mode 100644 index 0000000000..f20b8d5920 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/ProductResolver.java @@ -0,0 +1,18 @@ +package com.baeldung.graphqlvsrest.resolver; + +import com.baeldung.graphqlvsrest.entity.Order; +import com.baeldung.graphqlvsrest.entity.Product; +import com.baeldung.graphqlvsrest.repository.OrderRepository; +import com.coxautodev.graphql.tools.GraphQLResolver; + +import java.util.List; + +public class ProductResolver implements GraphQLResolver { + private OrderRepository orderRepository; + public ProductResolver(OrderRepository orderRepository){ + this.orderRepository = orderRepository; + } + public List getOrders(Product product){ + return orderRepository.getOrdersByProduct(product.getId()); + } +} diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Query.java b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Query.java new file mode 100644 index 0000000000..0d218261b2 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/java/com/baeldung/graphqlvsrest/resolver/Query.java @@ -0,0 +1,27 @@ +package com.baeldung.graphqlvsrest.resolver; + +import com.baeldung.graphqlvsrest.entity.Order; +import com.baeldung.graphqlvsrest.entity.Product; +import com.baeldung.graphqlvsrest.repository.OrderRepository; +import com.baeldung.graphqlvsrest.repository.ProductRepository; +import com.coxautodev.graphql.tools.GraphQLQueryResolver; + +import java.util.List; + +public class Query implements GraphQLQueryResolver { + + private ProductRepository productRepository; + public Query(ProductRepository productRepository){ + this.productRepository = productRepository; + } + + public List getProducts(int pageSize, int pageNumber) { + return productRepository.getProducts(pageSize, pageNumber); + } + + public Product getProduct(int id) { + return productRepository.getProduct(id); + } + + +} diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/application.properties b/spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/graphql/schema.graphqls b/spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/graphql/schema.graphqls new file mode 100644 index 0000000000..2709510d72 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-comparison/src/main/resources/graphql/schema.graphqls @@ -0,0 +1,57 @@ +type Product { + id: ID + name: String! + description: String + status: String + currency: String! + price: Float + image_url: [String] + video_url: [String] + stock: Int + average_rating: Float + orders:[Order] +} + +type Order{ + id:ID + product_id:Int + customer_uuid:String + address:String + status:String + creation_date:String +} + +input ProductModel { + name: String! + description: String + status: String + currency: String! + price: Float + image_url: [String] + video_url: [String] + stock: Int +} + +input ProductUpdateModel { + name: String + description: String + status: String + currency: String + price: Float + image_url: [String] + video_url: [String] + stock: Int +} + + +# The Root Query for the application +type Query { + products(size: Int, page: Int): [Product]! + product(id: Int): Product! +} + +# The Root Mutation for the application +type Mutation { + saveProduct(product: ProductModel) : Product! + updateProduct(id: Int, product: ProductUpdateModel) : Product! +} From 920d09bcea946477049a5592cd24f0423835d56d Mon Sep 17 00:00:00 2001 From: kwoyke Date: Tue, 22 Feb 2022 14:27:58 +0100 Subject: [PATCH 43/43] JAVA-9960: Upgrade parent-spring-5 to 5.3.16 (#11848) --- parent-spring-5/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 175e8d58f9..b2d581c9c1 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -24,7 +24,7 @@ - 5.3.13 + 5.3.16 5.6.0 1.5.10.RELEASE