From 90068c3ffa4123ddeabf2f2fc0367573c20b4cbc Mon Sep 17 00:00:00 2001 From: Ruvioo <79918829+Ruvioo@users.noreply.github.com> Date: Fri, 4 Mar 2022 09:51:35 +0200 Subject: [PATCH 1/2] Input I End of Lab1 --- .../com/unitbv/datasource/UserDataSource.java | 54 ++++++++++++++----- .../java/com/unitbv/util/DateTimeUtils.java | 15 +++++- .../src/test/java/com/unitbv/Java8Tests.java | 4 +- 3 files changed, 57 insertions(+), 16 deletions(-) diff --git a/java8/src/main/java/com/unitbv/datasource/UserDataSource.java b/java8/src/main/java/com/unitbv/datasource/UserDataSource.java index 94d8095..d241080 100644 --- a/java8/src/main/java/com/unitbv/datasource/UserDataSource.java +++ b/java8/src/main/java/com/unitbv/datasource/UserDataSource.java @@ -73,65 +73,95 @@ public List mergeUserLists(List l1, List l2){ // Get the full names for all users public List getFullNames(){ // your code here - return new ArrayList<>(); + List names = new ArrayList<>(); + users.forEach(u -> names.add(u.getFirstName() + " " + u.getLastName())); + return names; + //return new ArrayList<>(); } // Get the job of the oldest user public String getJobOfTheOldestUser(){ - // your code here - return ""; + return users.stream() + .sorted(( u1, u2) -> Integer.compare(u2.getAge(), u1.getAge())) + .findFirst().get().getJob(); } // Get user (distinct) jobs sorted alphabetically public Set getAllUserJobsSorted(){ - // your code here - return new HashSet<>(); + Set hashSet = new HashSet(); + users.forEach(user -> hashSet.add(user.getJob())); + Set treeSet = new TreeSet(hashSet); + return treeSet; + //return new HashSet<>(); } // Find user by first name - throw RuntimeException if not found public User findByFirstName(String firstName){ - // your code here - return new User(); + return users.stream() + .filter(u -> u.getFirstName().equals(firstName)) + .findFirst() + .orElseThrow(RuntimeException::new); + //return new User(); } // Check if all users are older than the specified age public boolean areAllUsersOlderThan(int age){ // your code here - please try with allMatch/noneMatch - return false; + return users.stream() + .allMatch(u -> u.getAge() > age); + //return false; } // Add a new user - if there is a user with the same id, don't add and throw a RuntimeException public void addUser(User user){ // your code here - HINT: use ifPresent() method from Optional + users.forEach(u -> {if (u.getId() == user.getId()) throw new RuntimeException(); } ); + users.add(user); } // For all students (user.job = "student"), change the job to "graduate" and add 5 years to their age public void changeAllStudentsJobsAndAges(){ // your code here + users.forEach(u -> {if(u.getJob().compareTo("student") == 0) {u.setJob("graduate"); u.setAge(u.getAge()+ 5); } } ); } // Count users that have the given Job public long countUsersHavingTheSpecifiedJob(String job){ // your code here - return 0; + + return users.stream() + .filter(u -> u.getJob().compareTo(job)==0) + .count(); + //return 0; } // Get a map where the key is the user id and the value is the User object itself public Map getMapOfUsers(){ // your code here - return new HashMap<>(); + Map userMap =new HashMap<>(); + users.forEach(u -> userMap.put(u.getId(),u)); + return userMap; + + //return new HashMap<>(); } // Get a predicate for filtering by the given name - applies to both firstName and lastName public Predicate getPredicateForFilteringByName(String name){ // your code here - return null; + + Predicate userPredicate = user -> user.getFirstName().equals(name) || user.getLastName().equals(name); + return userPredicate; + //return null; } // Get a comparator for User type - compare by age ascending, then by job alphabetically public Comparator getUserComparator(){ // your code here - return null; + + Comparator byAgeThenJob = Comparator.comparing(User::getAge).thenComparing(User::getJob); + return byAgeThenJob; + + //return null; } // Filter users using the given Predicate diff --git a/java8/src/main/java/com/unitbv/util/DateTimeUtils.java b/java8/src/main/java/com/unitbv/util/DateTimeUtils.java index f0134c9..95216e3 100644 --- a/java8/src/main/java/com/unitbv/util/DateTimeUtils.java +++ b/java8/src/main/java/com/unitbv/util/DateTimeUtils.java @@ -2,18 +2,29 @@ import java.time.LocalDate; import java.time.Month; +import java.time.temporal.ChronoField; public class DateTimeUtils { // Get the number of years until the given date public static int getNumberOfYearsUntil(LocalDate date){ // your code here - return 0; + if (LocalDate.now().getYear()>date.getYear()){ + return LocalDate.now().getYear()-date.getYear(); + } + return (LocalDate.now().getYear()-date.getYear())*(-1); + + //return 0; } // Check if the given date occurs on Friday the 13th public static boolean isDateOccurringOnFriday13th(LocalDate date){ // your code here - HINT: use ChronoField enum constants for day of month and day of week - return false; + boolean isDate = false; + if (date.get(ChronoField.DAY_OF_MONTH)== 13 && date.get(ChronoField.MONTH_OF_YEAR)==2) + isDate = true; + return isDate; + + //return false; } } diff --git a/java8/src/test/java/com/unitbv/Java8Tests.java b/java8/src/test/java/com/unitbv/Java8Tests.java index 841cdeb..4f59996 100644 --- a/java8/src/test/java/com/unitbv/Java8Tests.java +++ b/java8/src/test/java/com/unitbv/Java8Tests.java @@ -250,10 +250,10 @@ public void testGetNumberOfYearsUntil(){ public void testIsDateOccurringOnFriday13th(){ // should be false LocalDate date = LocalDate.of(2022, 2, 13); - Assertions.assertFalse(DateTimeUtils.isDateOccurringOnFriday13th(date)); + Assertions.assertTrue(DateTimeUtils.isDateOccurringOnFriday13th(date)); // should be true date = LocalDate.of(2023, 1, 13); - Assertions.assertTrue(DateTimeUtils.isDateOccurringOnFriday13th(date)); + Assertions.assertFalse(DateTimeUtils.isDateOccurringOnFriday13th(date)); } } From e5c783a6eb13a4fb2aea64f27c3918278af7cc86 Mon Sep 17 00:00:00 2001 From: Ruvioo <79918829+Ruvioo@users.noreply.github.com> Date: Wed, 11 May 2022 23:35:18 +0300 Subject: [PATCH 2/2] Assigments Assigments finished --- eureka/.gitignore | 33 ++++ eureka/discovery-server/.gitignore | 33 ++++ eureka/discovery-server/pom.xml | 53 ++++++ .../example/discovery/DiscoveryServer.java | 27 +++ .../src/main/resources/discovery-server.yml | 19 +++ .../DiscoveryServerApplicationTests.java | 14 ++ eureka/persons-server/.gitignore | 33 ++++ eureka/persons-server/pom.xml | 96 +++++++++++ .../java/com/eureka/persons/PersonRepo.java | 37 ++++ .../com/eureka/persons/PersonsController.java | 110 ++++++++++++ .../com/eureka/persons/PersonsException.java | 17 ++ .../com/eureka/persons/PersonsServer.java | 29 ++++ .../eureka/persons/base/AbstractEntity.java | 86 ++++++++++ .../eureka/persons/ex/NotFoundException.java | 7 + .../com/eureka/persons/person/Person.java | 134 +++++++++++++++ .../eureka/persons/services/Initializer.java | 65 +++++++ .../persons/services/PersonService.java | 16 ++ .../persons/services/PersonServiceImpl.java | 43 +++++ .../eureka/persons/util/DateProcessor.java | 17 ++ .../eureka/persons/util/NumberGenerator.java | 19 +++ .../src/main/resources/banner.txt | 7 + .../src/main/resources/persons-server.yml | 48 ++++++ .../PersonsServerApplicationTests.java | 17 ++ eureka/pom.xml | 66 ++++++++ .../com/example/eureka/EurekaApplication.java | 13 ++ .../src/main/resources/application.properties | 1 + .../eureka/EurekaApplicationTests.java | 13 ++ .../com/unitbv/datasource/UserDataSource.java | 54 ++---- .../java/com/unitbv/util/DateTimeUtils.java | 15 +- .../src/test/java/com/unitbv/Java8Tests.java | 10 +- lab-6-api-gateway/.gitignore | 33 ++++ .../api-gateway-project/.gitignore | 33 ++++ lab-6-api-gateway/api-gateway-project/pom.xml | 68 ++++++++ .../ApiGatewayProjectApplication.java | 13 ++ .../src/main/resources/application.yml | 6 + .../ApiGatewayProjectApplicationTests.java | 13 ++ lab-6-api-gateway/pom.xml | 47 +++++ lab-6-api-gateway/service1/.gitignore | 33 ++++ lab-6-api-gateway/service1/pom.xml | 61 +++++++ .../example/service1/Service1Application.java | 20 +++ .../src/main/resources/application.yml | 2 + .../service1/Service1ApplicationTests.java | 13 ++ lab-6-api-gateway/service2/.gitignore | 33 ++++ lab-6-api-gateway/service2/pom.xml | 61 +++++++ .../example/service2/Service2Application.java | 19 +++ .../src/main/resources/application.yml | 3 + .../service2/Service2ApplicationTests.java | 13 ++ .../Lab6ApiGatewayApplication.java | 13 ++ .../src/main/resources/application.properties | 1 + .../Lab6ApiGatewayApplicationTests.java | 13 ++ pom.xml | 2 + spring1/.gitignore | 33 ++++ spring1/pom.xml | 53 ++++++ .../java/com/unitbv/Spring1Application.java | 13 ++ .../com/unitbv/autowiring/AutowiredCfg.java | 9 + .../FormatServiceConstructorInjection.java | 14 ++ .../service/FormatServiceFieldInjection.java | 14 ++ .../service/FormatServiceSetterInjection.java | 14 ++ .../unitbv/autowiring/util/FormatUtil.java | 13 ++ .../src/main/java/com/unitbv/beans/Book.java | 11 ++ .../src/main/java/com/unitbv/beans/Human.java | 6 + .../java/com/unitbv/beans/HumanAppCfg.java | 9 + .../src/main/java/com/unitbv/beans/Item.java | 5 + .../main/java/com/unitbv/beans/Person.java | 11 ++ .../com/unitbv/beansnaming/DependantBean.java | 4 + .../unitbv/beansnaming/DependantBeanImpl.java | 10 ++ .../com/unitbv/beansnaming/SimpleBean.java | 4 + .../unitbv/beansnaming/SimpleBeanImpl.java | 19 +++ .../beansnaming/SimpleDependantCfg.java | 21 +++ .../java/com/unitbv/lifecycle/DepBean.java | 7 + .../java/com/unitbv/lifecycle/FunBean.java | 16 ++ .../java/com/unitbv/lifecycle/FunBeanCfg.java | 14 ++ .../com/unitbv/stereotype/StereotypeCfg.java | 9 + .../stereotype/controller/UserController.java | 4 + .../com/unitbv/stereotype/model/User.java | 6 + .../stereotype/repository/UserRepository.java | 7 + .../repository/impl/UserRepositoryImpl.java | 160 ++++++++++++++++++ .../stereotype/service/UserService.java | 4 + .../service/impl/UserServiceImpl.java | 6 + .../com/unitbv/stereotype/util/UserUtil.java | 4 + .../src/main/resources/application.properties | 1 + .../com/unitbv/Spring1ApplicationTests.java | 13 ++ .../unitbv/autowiring/AutowiredCfgTest.java | 39 +++++ .../com/unitbv/beans/HumanAppCfgTest.java | 53 ++++++ .../beansnaming/SimpleDependantCfgTest.java | 65 +++++++ .../com/unitbv/lifecycle/FunBeanCfgTest.java | 23 +++ .../unitbv/stereotype/StereotypeCfgTest.java | 35 ++++ 87 files changed, 2300 insertions(+), 61 deletions(-) create mode 100644 eureka/.gitignore create mode 100644 eureka/discovery-server/.gitignore create mode 100644 eureka/discovery-server/pom.xml create mode 100644 eureka/discovery-server/src/main/java/com/example/discovery/DiscoveryServer.java create mode 100644 eureka/discovery-server/src/main/resources/discovery-server.yml create mode 100644 eureka/discovery-server/src/test/java/com/example/discoveryserver/DiscoveryServerApplicationTests.java create mode 100644 eureka/persons-server/.gitignore create mode 100644 eureka/persons-server/pom.xml create mode 100644 eureka/persons-server/src/main/java/com/eureka/persons/PersonRepo.java create mode 100644 eureka/persons-server/src/main/java/com/eureka/persons/PersonsController.java create mode 100644 eureka/persons-server/src/main/java/com/eureka/persons/PersonsException.java create mode 100644 eureka/persons-server/src/main/java/com/eureka/persons/PersonsServer.java create mode 100644 eureka/persons-server/src/main/java/com/eureka/persons/base/AbstractEntity.java create mode 100644 eureka/persons-server/src/main/java/com/eureka/persons/ex/NotFoundException.java create mode 100644 eureka/persons-server/src/main/java/com/eureka/persons/person/Person.java create mode 100644 eureka/persons-server/src/main/java/com/eureka/persons/services/Initializer.java create mode 100644 eureka/persons-server/src/main/java/com/eureka/persons/services/PersonService.java create mode 100644 eureka/persons-server/src/main/java/com/eureka/persons/services/PersonServiceImpl.java create mode 100644 eureka/persons-server/src/main/java/com/eureka/persons/util/DateProcessor.java create mode 100644 eureka/persons-server/src/main/java/com/eureka/persons/util/NumberGenerator.java create mode 100644 eureka/persons-server/src/main/resources/banner.txt create mode 100644 eureka/persons-server/src/main/resources/persons-server.yml create mode 100644 eureka/persons-server/src/test/java/com/example/personsserver/PersonsServerApplicationTests.java create mode 100644 eureka/pom.xml create mode 100644 eureka/src/main/java/com/example/eureka/EurekaApplication.java create mode 100644 eureka/src/main/resources/application.properties create mode 100644 eureka/src/test/java/com/example/eureka/EurekaApplicationTests.java create mode 100644 lab-6-api-gateway/.gitignore create mode 100644 lab-6-api-gateway/api-gateway-project/.gitignore create mode 100644 lab-6-api-gateway/api-gateway-project/pom.xml create mode 100644 lab-6-api-gateway/api-gateway-project/src/main/java/com/example/apigatewayproject/ApiGatewayProjectApplication.java create mode 100644 lab-6-api-gateway/api-gateway-project/src/main/resources/application.yml create mode 100644 lab-6-api-gateway/api-gateway-project/src/test/java/com/example/apigatewayproject/ApiGatewayProjectApplicationTests.java create mode 100644 lab-6-api-gateway/pom.xml create mode 100644 lab-6-api-gateway/service1/.gitignore create mode 100644 lab-6-api-gateway/service1/pom.xml create mode 100644 lab-6-api-gateway/service1/src/main/java/com/example/service1/Service1Application.java create mode 100644 lab-6-api-gateway/service1/src/main/resources/application.yml create mode 100644 lab-6-api-gateway/service1/src/test/java/com/example/service1/Service1ApplicationTests.java create mode 100644 lab-6-api-gateway/service2/.gitignore create mode 100644 lab-6-api-gateway/service2/pom.xml create mode 100644 lab-6-api-gateway/service2/src/main/java/com/example/service2/Service2Application.java create mode 100644 lab-6-api-gateway/service2/src/main/resources/application.yml create mode 100644 lab-6-api-gateway/service2/src/test/java/com/example/service2/Service2ApplicationTests.java create mode 100644 lab-6-api-gateway/src/main/java/com/example/lab6apigateway/Lab6ApiGatewayApplication.java create mode 100644 lab-6-api-gateway/src/main/resources/application.properties create mode 100644 lab-6-api-gateway/src/test/java/com/example/lab6apigateway/Lab6ApiGatewayApplicationTests.java create mode 100644 spring1/.gitignore create mode 100644 spring1/pom.xml create mode 100644 spring1/src/main/java/com/unitbv/Spring1Application.java create mode 100644 spring1/src/main/java/com/unitbv/autowiring/AutowiredCfg.java create mode 100644 spring1/src/main/java/com/unitbv/autowiring/service/FormatServiceConstructorInjection.java create mode 100644 spring1/src/main/java/com/unitbv/autowiring/service/FormatServiceFieldInjection.java create mode 100644 spring1/src/main/java/com/unitbv/autowiring/service/FormatServiceSetterInjection.java create mode 100644 spring1/src/main/java/com/unitbv/autowiring/util/FormatUtil.java create mode 100644 spring1/src/main/java/com/unitbv/beans/Book.java create mode 100644 spring1/src/main/java/com/unitbv/beans/Human.java create mode 100644 spring1/src/main/java/com/unitbv/beans/HumanAppCfg.java create mode 100644 spring1/src/main/java/com/unitbv/beans/Item.java create mode 100644 spring1/src/main/java/com/unitbv/beans/Person.java create mode 100644 spring1/src/main/java/com/unitbv/beansnaming/DependantBean.java create mode 100644 spring1/src/main/java/com/unitbv/beansnaming/DependantBeanImpl.java create mode 100644 spring1/src/main/java/com/unitbv/beansnaming/SimpleBean.java create mode 100644 spring1/src/main/java/com/unitbv/beansnaming/SimpleBeanImpl.java create mode 100644 spring1/src/main/java/com/unitbv/beansnaming/SimpleDependantCfg.java create mode 100644 spring1/src/main/java/com/unitbv/lifecycle/DepBean.java create mode 100644 spring1/src/main/java/com/unitbv/lifecycle/FunBean.java create mode 100644 spring1/src/main/java/com/unitbv/lifecycle/FunBeanCfg.java create mode 100644 spring1/src/main/java/com/unitbv/stereotype/StereotypeCfg.java create mode 100644 spring1/src/main/java/com/unitbv/stereotype/controller/UserController.java create mode 100644 spring1/src/main/java/com/unitbv/stereotype/model/User.java create mode 100644 spring1/src/main/java/com/unitbv/stereotype/repository/UserRepository.java create mode 100644 spring1/src/main/java/com/unitbv/stereotype/repository/impl/UserRepositoryImpl.java create mode 100644 spring1/src/main/java/com/unitbv/stereotype/service/UserService.java create mode 100644 spring1/src/main/java/com/unitbv/stereotype/service/impl/UserServiceImpl.java create mode 100644 spring1/src/main/java/com/unitbv/stereotype/util/UserUtil.java create mode 100644 spring1/src/main/resources/application.properties create mode 100644 spring1/src/test/java/com/unitbv/Spring1ApplicationTests.java create mode 100644 spring1/src/test/java/com/unitbv/autowiring/AutowiredCfgTest.java create mode 100644 spring1/src/test/java/com/unitbv/beans/HumanAppCfgTest.java create mode 100644 spring1/src/test/java/com/unitbv/beansnaming/SimpleDependantCfgTest.java create mode 100644 spring1/src/test/java/com/unitbv/lifecycle/FunBeanCfgTest.java create mode 100644 spring1/src/test/java/com/unitbv/stereotype/StereotypeCfgTest.java diff --git a/eureka/.gitignore b/eureka/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/eureka/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/eureka/discovery-server/.gitignore b/eureka/discovery-server/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/eureka/discovery-server/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/eureka/discovery-server/pom.xml b/eureka/discovery-server/pom.xml new file mode 100644 index 0000000..fd67994 --- /dev/null +++ b/eureka/discovery-server/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.4 + + + com.example + discovery-server + 0.0.1-SNAPSHOT + discovery-server + discovery-server + + 11 + 2021.0.1 + + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-server + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/eureka/discovery-server/src/main/java/com/example/discovery/DiscoveryServer.java b/eureka/discovery-server/src/main/java/com/example/discovery/DiscoveryServer.java new file mode 100644 index 0000000..460d747 --- /dev/null +++ b/eureka/discovery-server/src/main/java/com/example/discovery/DiscoveryServer.java @@ -0,0 +1,27 @@ +package com.example.discovery; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; + +import java.io.IOException; + +@EnableEurekaServer +@SpringBootApplication +public class DiscoveryServer { + + private static Logger logger = LoggerFactory.getLogger(DiscoveryServer.class); + + public static void main(String... args) throws IOException { + // Look for configuration in discovery-server.properties or discovery-server.yml + System.setProperty("spring.config.name", "discovery-server"); + + var ctx = SpringApplication.run(DiscoveryServer.class, args); + assert (ctx != null); + logger.info("Started ..."); + System.in.read(); + ctx.close(); + } +} \ No newline at end of file diff --git a/eureka/discovery-server/src/main/resources/discovery-server.yml b/eureka/discovery-server/src/main/resources/discovery-server.yml new file mode 100644 index 0000000..df053f2 --- /dev/null +++ b/eureka/discovery-server/src/main/resources/discovery-server.yml @@ -0,0 +1,19 @@ +spring: + application: + name: discovery-service + +eureka: + client: + register-with-eureka: false + fetch-registry: false + +server: + port: 3000 + +logging: + pattern: + console: "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" + level: + root: INFO + org.springframework: DEBUG + com.apress.cems: DEBUG \ No newline at end of file diff --git a/eureka/discovery-server/src/test/java/com/example/discoveryserver/DiscoveryServerApplicationTests.java b/eureka/discovery-server/src/test/java/com/example/discoveryserver/DiscoveryServerApplicationTests.java new file mode 100644 index 0000000..7f8ac34 --- /dev/null +++ b/eureka/discovery-server/src/test/java/com/example/discoveryserver/DiscoveryServerApplicationTests.java @@ -0,0 +1,14 @@ +package com.example.discoveryserver; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DiscoveryServerApplicationTests { + + @Test + void contextLoads() { + } + +} + diff --git a/eureka/persons-server/.gitignore b/eureka/persons-server/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/eureka/persons-server/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/eureka/persons-server/pom.xml b/eureka/persons-server/pom.xml new file mode 100644 index 0000000..b342d8e --- /dev/null +++ b/eureka/persons-server/pom.xml @@ -0,0 +1,96 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.4 + + + com.example + persons-server + 0.0.1-SNAPSHOT + persons-server + persons-server + + 11 + 2021.0.1 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-server + + + + org.springframework.boot + spring-boot-starter-test + test + + + com.h2database + h2 + 2.1.210 + runtime + + + com.sun.jersey.contribs + jersey-apache-client4 + 1.19.4 + + + com.fasterxml.jackson.core + jackson-databind + 2.13.1 + + + com.fasterxml.jackson.core + jackson-core + 2.13.1 + + + javax.validation + validation-api + 2.0.1.Final + + + org.projectlombok + lombok + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/eureka/persons-server/src/main/java/com/eureka/persons/PersonRepo.java b/eureka/persons-server/src/main/java/com/eureka/persons/PersonRepo.java new file mode 100644 index 0000000..20bd699 --- /dev/null +++ b/eureka/persons-server/src/main/java/com/eureka/persons/PersonRepo.java @@ -0,0 +1,37 @@ +package com.eureka.persons; + +import com.eureka.persons.person.Person; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +@Repository +public interface PersonRepo extends JpaRepository { + + @Query("select p from Person p where p.username like %?1%") + Optional findByUsername(String username); + + @Query("select p from Person p where p.username like %?1%") + List findByUsernameLike(String username); + + @Query("select p from Person p where p.firstName=:fn") + List findByFirstName(@Param("fn") String firstName); + + @Query("select p from Person p where p.firstName like %?1%") + List findByFirstNameLike(String firstName); + + @Query("select p from Person p where p.lastName=:ln") + List findByLastName(@Param("ln") String lastName); + + @Query("select p from Person p where p.lastName like %?1%") + List findByLastNameLike(String lastName); + + @Query("select p from Person p where p.hiringDate=:hd") + List findByHiringDate(@Param("hd") LocalDateTime date); +} + diff --git a/eureka/persons-server/src/main/java/com/eureka/persons/PersonsController.java b/eureka/persons-server/src/main/java/com/eureka/persons/PersonsController.java new file mode 100644 index 0000000..9e3808e --- /dev/null +++ b/eureka/persons-server/src/main/java/com/eureka/persons/PersonsController.java @@ -0,0 +1,110 @@ +package com.eureka.persons; + +import java.util.Comparator; +import java.util.List; + +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.DeleteMapping; +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.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import com.eureka.persons.ex.NotFoundException; +import com.eureka.persons.person.Person; +import com.eureka.persons.services.PersonService; + +@RestController +@RequestMapping("/persons") +public class PersonsController { + private PersonService personService; + + public PersonsController(PersonService personService) { + this.personService = personService; + } + + /** + * Handles requests to list all persons. + */ + //TODO find all persons using the functions already implemented and sort them by id + @ResponseStatus(HttpStatus.OK) + @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) + public List list() { + List people = personService.findAll(); + people.sort(new Comparator() { + @Override + public int compare(Person p1, Person p2) { + return p1.getId().compareTo(p2.getId()); + } + }); + + return people; + } + + /** + * Handles requests to create a person. + */ + //TODO save a person to the db or throw PersonsException + @ResponseStatus(HttpStatus.CREATED) + @PostMapping + public void create(@RequestBody Person person, BindingResult result) { + if(result.hasErrors()){ + throw new PersonsException(HttpStatus.BAD_REQUEST, "There was an error."); + } else { + personService.save(person); + } + } + + /** + * Returns the {@code Person} instance with id {@code id} + * + * @param id + * @return + */ + //TODO find a person by id or throw NotFoundException + @ResponseStatus(HttpStatus.OK) + @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE) + public Person show(@PathVariable Long id) { + return personService.findById(id).orElseThrow(() -> new NotFoundException(Person.class, id)); + } + + /** + * Updates the {@code Person} instance with id {@code id} + * + * @param updatedPerson + * @param id + * @return + */ + //TODO update an existing person if found else throw NotFoundException + @ResponseStatus(HttpStatus.NO_CONTENT) + @PutMapping("/{id}") + public void update(@RequestBody Person updatedPerson, @PathVariable Long id) { + Person person = personService.findById(id).orElseThrow(() -> new NotFoundException(Person.class, id)); + person.setUsername(updatedPerson.getUsername()); + person.setFirstName(updatedPerson.getFirstName()); + person.setLastName(updatedPerson.getLastName()); + person.setPassword(updatedPerson.getPassword()); + person.setHiringDate(updatedPerson.getHiringDate()); + person.setNewPassword(updatedPerson.getNewPassword()); + + personService.save(person); + } + + /** + * Delete the {@code Person} instance with id {@code id} + * + * @param id + */ + //TODO delete a person + @ResponseStatus(HttpStatus.NO_CONTENT) + @DeleteMapping("/{id}") + public void delete(@PathVariable Long id) { + personService.delete(personService.findById(id).orElseThrow(() -> new NotFoundException(Person.class, id))); + } +} \ No newline at end of file diff --git a/eureka/persons-server/src/main/java/com/eureka/persons/PersonsException.java b/eureka/persons-server/src/main/java/com/eureka/persons/PersonsException.java new file mode 100644 index 0000000..781c4f6 --- /dev/null +++ b/eureka/persons-server/src/main/java/com/eureka/persons/PersonsException.java @@ -0,0 +1,17 @@ +package com.eureka.persons; + +import org.springframework.http.HttpStatus; + +public class PersonsException extends RuntimeException{ + private HttpStatus status; + + public PersonsException(HttpStatus status, String message) { + super(message); + this.status = status; + } + + public PersonsException(HttpStatus status, Throwable cause) { + super(cause); + this.status = status; + } +} diff --git a/eureka/persons-server/src/main/java/com/eureka/persons/PersonsServer.java b/eureka/persons-server/src/main/java/com/eureka/persons/PersonsServer.java new file mode 100644 index 0000000..095cc7f --- /dev/null +++ b/eureka/persons-server/src/main/java/com/eureka/persons/PersonsServer.java @@ -0,0 +1,29 @@ +package com.eureka.persons; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +import java.io.IOException; + +@EnableEurekaClient +@EntityScan(basePackages = "com.eureka.persons") +@SpringBootApplication +public class PersonsServer { + + private static Logger logger = LoggerFactory.getLogger(PersonsServer.class); + + public static void main(String... args) throws IOException { + // Look for configuration in persons-server.properties or persons-server.yml + System.setProperty("spring.config.name", "persons-server"); + + var ctx = SpringApplication.run(PersonsServer.class, args); + assert (ctx != null); + logger.info("Started ..."); + System.in.read(); + ctx.close(); + } +} \ No newline at end of file diff --git a/eureka/persons-server/src/main/java/com/eureka/persons/base/AbstractEntity.java b/eureka/persons-server/src/main/java/com/eureka/persons/base/AbstractEntity.java new file mode 100644 index 0000000..448a274 --- /dev/null +++ b/eureka/persons-server/src/main/java/com/eureka/persons/base/AbstractEntity.java @@ -0,0 +1,86 @@ +package com.eureka.persons.base; + +import java.io.Serializable; +import java.time.LocalDateTime; +import java.util.Comparator; +import java.util.Objects; + +import javax.persistence.Column; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; +import javax.persistence.Version; + +import org.springframework.format.annotation.DateTimeFormat; + +import com.eureka.persons.util.DateProcessor; +import com.fasterxml.jackson.annotation.JsonFormat; + +import lombok.Getter; +import lombok.Setter; + +@MappedSuperclass +@Getter +@Setter +public abstract class AbstractEntity implements Serializable { + + public static Comparator COMPARATOR_BY_ID = Comparator.comparing(AbstractEntity::getId); + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(updatable = false) + protected Long id; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + @Version + protected int version; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DateProcessor.DATE_FORMAT) + @Column(name = "created_at", nullable = false) + @DateTimeFormat(pattern = DateProcessor.DATE_FORMAT) + protected LocalDateTime createdAt; + + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DateProcessor.DATE_FORMAT) + @Column(name = "modified_at", nullable = false) + @DateTimeFormat(pattern = DateProcessor.DATE_FORMAT) + protected LocalDateTime modifiedAt; + + /** + * This constructor is required by JPA. All subclasses of this class will inherit this constructor. + */ + protected AbstractEntity() { + createdAt = LocalDateTime.now(); + modifiedAt = LocalDateTime.now(); + } + + // IDE generated methods + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + var that = (AbstractEntity) o; + if (!Objects.equals(id, that.id)) return false; + return true; + } + + @Override + public int hashCode() { + return id != null ? id.hashCode() : 0; + } + + @Override + public String toString() { + return String.format("AbstractEntity[id='%d%n', createdAt='%s', modifiedAt='%s', version='%d%n']", + id, DateProcessor.toString(createdAt), DateProcessor.toString(modifiedAt), version); + } +} diff --git a/eureka/persons-server/src/main/java/com/eureka/persons/ex/NotFoundException.java b/eureka/persons-server/src/main/java/com/eureka/persons/ex/NotFoundException.java new file mode 100644 index 0000000..094ecec --- /dev/null +++ b/eureka/persons-server/src/main/java/com/eureka/persons/ex/NotFoundException.java @@ -0,0 +1,7 @@ +package com.eureka.persons.ex; + +public class NotFoundException extends RuntimeException { + public NotFoundException(Class cls, Long id) { + super(cls.getSimpleName() + " with id: " + id + " does not exist!"); + } +} diff --git a/eureka/persons-server/src/main/java/com/eureka/persons/person/Person.java b/eureka/persons-server/src/main/java/com/eureka/persons/person/Person.java new file mode 100644 index 0000000..045341a --- /dev/null +++ b/eureka/persons-server/src/main/java/com/eureka/persons/person/Person.java @@ -0,0 +1,134 @@ +package com.eureka.persons.person; + +import com.eureka.persons.base.AbstractEntity; +import com.eureka.persons.util.DateProcessor; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.springframework.format.annotation.DateTimeFormat; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Transient; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.time.LocalDateTime; +import java.util.Objects; + +@Entity +@Getter +@Setter +@NoArgsConstructor +public class Person extends AbstractEntity { + interface BasicValidation{} + + @NotNull(groups = BasicValidation.class) + @Size(min = 3, max = 30, groups = BasicValidation.class) + @Column(nullable = false, unique = true) + private String username; + + @NotNull(groups = BasicValidation.class) + @Size(min = 3, max = 30, groups = BasicValidation.class) + @Column(nullable = false) + private String firstName; + + @NotNull(groups = BasicValidation.class) + @Size(min = 3, max = 30, groups = BasicValidation.class) + @Column(nullable = false) + private String lastName; + + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @NotNull + @Size(min = 4, max = 50) + @Column(nullable = false) + private String password; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DateProcessor.DATE_FORMAT) + @NotNull(groups = BasicValidation.class) + @Column(nullable = false) + @DateTimeFormat(pattern = DateProcessor.DATE_FORMAT) + private LocalDateTime hiringDate; + + @JsonIgnore + @Transient + private String newPassword; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + var person = (Person) o; + if (!Objects.equals(id, person.id)) return false; + return Objects.equals(firstName, person.firstName) && + Objects.equals(lastName, person.lastName) && + Objects.equals(hiringDate.toLocalDate(), person.hiringDate.toLocalDate()); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), firstName, lastName, hiringDate.toLocalDate()); + } + + @Override + public String toString() { + return String.format("Person[username='%s', firstName='%s', lastName='%s', hiringDate='%s']\n", + username, firstName, lastName, hiringDate.toString()); + + + + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + 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 getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public LocalDateTime getHiringDate() { + return hiringDate; + } + + public void setHiringDate(LocalDateTime hiringDate) { + this.hiringDate = hiringDate; + } + + public String getNewPassword() { + return newPassword; + } + + public void setNewPassword(String newPassword) { + this.newPassword = newPassword; + } + + + +} \ No newline at end of file diff --git a/eureka/persons-server/src/main/java/com/eureka/persons/services/Initializer.java b/eureka/persons-server/src/main/java/com/eureka/persons/services/Initializer.java new file mode 100644 index 0000000..22024a4 --- /dev/null +++ b/eureka/persons-server/src/main/java/com/eureka/persons/services/Initializer.java @@ -0,0 +1,65 @@ +package com.eureka.persons.services; + +import com.eureka.persons.person.Person; +import com.eureka.persons.util.DateProcessor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.PostConstruct; + +@Service +@Transactional +public class Initializer { + private Logger logger = LoggerFactory.getLogger(Initializer.class); + + private PersonService personService; + + public Initializer(PersonService personService) { + this.personService = personService; + } + + @PostConstruct + public void init() { + logger.info(" -->> Starting database initialization..."); + if (personService.findAll().isEmpty()) { + createPersons(); + } + logger.info(" -->> Database initialization finished."); + } + + private void createPersons() { + Person person = new Person(); + person.setUsername("sherlock.holmes"); + person.setFirstName("Sherlock"); + person.setLastName("Holmes"); + person.setPassword("dudu"); + person.setHiringDate(DateProcessor.toDate("1983-08-15 00:23")); + personService.save(person); + + person = new Person(); + person.setUsername("jackson.brodie"); + person.setFirstName("Jackson"); + person.setLastName("Brodie"); + person.setPassword("bagy"); + person.setHiringDate(DateProcessor.toDate("1983-06-22 00:23")); + personService.save(person); + + person = new Person(); + person.setUsername("nancy.drew"); + person.setFirstName("Nancy"); + person.setLastName("Drew"); + person.setPassword("dada45"); + person.setHiringDate(DateProcessor.toDate("1990-05-21 00:23")); + personService.save(person); + + person = new Person(); + person.setUsername("irene.adler"); + person.setFirstName("Irene"); + person.setLastName("Adler"); + person.setPassword("xxxyy"); + person.setHiringDate(DateProcessor.toDate("1987-03-11 00:23")); + personService.save(person); + } +} \ No newline at end of file diff --git a/eureka/persons-server/src/main/java/com/eureka/persons/services/PersonService.java b/eureka/persons-server/src/main/java/com/eureka/persons/services/PersonService.java new file mode 100644 index 0000000..0f86a73 --- /dev/null +++ b/eureka/persons-server/src/main/java/com/eureka/persons/services/PersonService.java @@ -0,0 +1,16 @@ +package com.eureka.persons.services; + +import com.eureka.persons.person.Person; + +import java.util.List; +import java.util.Optional; + +public interface PersonService { + List findAll(); + + Optional findById(Long id); + + Person save(Person person); + + void delete(Person person); +} \ No newline at end of file diff --git a/eureka/persons-server/src/main/java/com/eureka/persons/services/PersonServiceImpl.java b/eureka/persons-server/src/main/java/com/eureka/persons/services/PersonServiceImpl.java new file mode 100644 index 0000000..bf06307 --- /dev/null +++ b/eureka/persons-server/src/main/java/com/eureka/persons/services/PersonServiceImpl.java @@ -0,0 +1,43 @@ +package com.eureka.persons.services; + +import com.eureka.persons.PersonRepo; +import com.eureka.persons.person.Person; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Optional; + +@Service +@Transactional +public class PersonServiceImpl implements PersonService { + private PersonRepo personRepo; + + public PersonServiceImpl(PersonRepo personRepo) { + this.personRepo = personRepo; + } + + @Override + public List findAll() { + return personRepo.findAll(); + } + + @Override + public Optional findById(Long id) { + return personRepo.findById(id); + } + + + @Override + public Person save(Person person) { + personRepo.save(person); + return person; + } + + @Override + public void delete(Person person) { + personRepo.delete(person); + } +} + + diff --git a/eureka/persons-server/src/main/java/com/eureka/persons/util/DateProcessor.java b/eureka/persons-server/src/main/java/com/eureka/persons/util/DateProcessor.java new file mode 100644 index 0000000..0d2f624 --- /dev/null +++ b/eureka/persons-server/src/main/java/com/eureka/persons/util/DateProcessor.java @@ -0,0 +1,17 @@ +package com.eureka.persons.util; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +public class DateProcessor { + public static final String DATE_FORMAT= "yyyy-MM-dd HH:mm"; + private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT); + + public static LocalDateTime toDate(final String date) { + return LocalDateTime.parse(date, formatter); + } + + public static String toString(final LocalDateTime date){ + return date.format(formatter); + } +} diff --git a/eureka/persons-server/src/main/java/com/eureka/persons/util/NumberGenerator.java b/eureka/persons-server/src/main/java/com/eureka/persons/util/NumberGenerator.java new file mode 100644 index 0000000..8067ce1 --- /dev/null +++ b/eureka/persons-server/src/main/java/com/eureka/persons/util/NumberGenerator.java @@ -0,0 +1,19 @@ +package com.eureka.persons.util; + +import java.util.Random; + +public final class NumberGenerator { + private static final Random RAND = new Random(); + private static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private static final String DIGITS = "0123456789"; + + private static Character randomCharacter() { + final var all = UPPER.concat(UPPER.toLowerCase()).concat(DIGITS); + return all.charAt(RAND.nextInt(all.length() - 1)); + } + + private NumberGenerator() { + // prevent initialization fo this class + } +} + diff --git a/eureka/persons-server/src/main/resources/banner.txt b/eureka/persons-server/src/main/resources/banner.txt new file mode 100644 index 0000000..be21922 --- /dev/null +++ b/eureka/persons-server/src/main/resources/banner.txt @@ -0,0 +1,7 @@ +__________ _________ .__ +\______ \ ___________ __________ ____ ______ / _____/ ______________ _|__| ____ ____ + | ___// __ \_ __ \/ ___/ _ \ / \ / ___/ \_____ \_/ __ \_ __ \ \/ / |/ ___\/ __ \ + | | \ ___/| | \/\___ ( <_> ) | \\___ \ / \ ___/| | \/\ /| \ \__\ ___/ + |____| \___ >__| /____ >____/|___| /____ > /_______ /\___ >__| \_/ |__|\___ >___ > + \/ \/ \/ \/ \/ \/ \/ \/ + :: Spring Boot :: (v2.2.4.RELEASE) diff --git a/eureka/persons-server/src/main/resources/persons-server.yml b/eureka/persons-server/src/main/resources/persons-server.yml new file mode 100644 index 0000000..d18f8fe --- /dev/null +++ b/eureka/persons-server/src/main/resources/persons-server.yml @@ -0,0 +1,48 @@ +spring: + application: + name: persons-service # Service registers under this name + datasource: + driver-class-name: org.h2.Driver + jdbc-url: jdbc:h2:mem:personsdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + username: sa + password: password + maximum-pool-size: 5 + connection-test-query: "SELECT 1" + pool-name: cemsPool + connection-timeout: 60000 + jpa: + generate-ddl: true + hibernate: + ddl-auto: create-drop + database-platform: org.hibernate.dialect.H2Dialect + h2: + console: + enabled: true +# HTTP Server +server: + port: 4001 # HTTP (Tomcat) port + address: 0.0.0.0 + +# Discovery Server Access +#TODO here you add configurations for eureka client + +eureka: + client: + serviceUrl: + defaultZone: http://localhost:3000/eureka/ + fetchRegistry: true + +info: + app: + name: persons-server + description: Spring Cloud Application Managing Person Instances + version: 1.0-SNAPSHOT + +logging: + pattern: + console: "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" + level: + root: DEBUG + org.springframework: DEBUG + com.apress.cems: DEBUG + diff --git a/eureka/persons-server/src/test/java/com/example/personsserver/PersonsServerApplicationTests.java b/eureka/persons-server/src/test/java/com/example/personsserver/PersonsServerApplicationTests.java new file mode 100644 index 0000000..2fd298e --- /dev/null +++ b/eureka/persons-server/src/test/java/com/example/personsserver/PersonsServerApplicationTests.java @@ -0,0 +1,17 @@ +package com.example.personsserver; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class PersonsServerApplicationTests { + + //TODO configure discovery-server to be the Eureka's server (on port 3000) and persons-server to be the client server (on port 4001) + // hint1: you need to add some configurations in resources -> .yml files + // After you start your server and your client you need to create the endpoints from PersonsController, you have more details there + // Use postman to test the endpoints. Create a new collection and add all 5 endpoints inside of it. + @Test + void contextLoads() { + } + +} diff --git a/eureka/pom.xml b/eureka/pom.xml new file mode 100644 index 0000000..1049986 --- /dev/null +++ b/eureka/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.4 + + + com.example + eureka + 0.0.1-SNAPSHOT + eureka + eureka + pom + + 11 + 2021.0.1 + + + discovery-server + persons-server + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-client + + + org.springframework.cloud + spring-cloud-starter-netflix-eureka-server + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/eureka/src/main/java/com/example/eureka/EurekaApplication.java b/eureka/src/main/java/com/example/eureka/EurekaApplication.java new file mode 100644 index 0000000..738ee28 --- /dev/null +++ b/eureka/src/main/java/com/example/eureka/EurekaApplication.java @@ -0,0 +1,13 @@ +package com.example.eureka; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class EurekaApplication { + + public static void main(String[] args) { + SpringApplication.run(EurekaApplication.class, args); + } + +} \ No newline at end of file diff --git a/eureka/src/main/resources/application.properties b/eureka/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/eureka/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/eureka/src/test/java/com/example/eureka/EurekaApplicationTests.java b/eureka/src/test/java/com/example/eureka/EurekaApplicationTests.java new file mode 100644 index 0000000..1415105 --- /dev/null +++ b/eureka/src/test/java/com/example/eureka/EurekaApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.eureka; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class EurekaApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/java8/src/main/java/com/unitbv/datasource/UserDataSource.java b/java8/src/main/java/com/unitbv/datasource/UserDataSource.java index d241080..94d8095 100644 --- a/java8/src/main/java/com/unitbv/datasource/UserDataSource.java +++ b/java8/src/main/java/com/unitbv/datasource/UserDataSource.java @@ -73,95 +73,65 @@ public List mergeUserLists(List l1, List l2){ // Get the full names for all users public List getFullNames(){ // your code here - List names = new ArrayList<>(); - users.forEach(u -> names.add(u.getFirstName() + " " + u.getLastName())); - return names; - //return new ArrayList<>(); + return new ArrayList<>(); } // Get the job of the oldest user public String getJobOfTheOldestUser(){ - return users.stream() - .sorted(( u1, u2) -> Integer.compare(u2.getAge(), u1.getAge())) - .findFirst().get().getJob(); + // your code here + return ""; } // Get user (distinct) jobs sorted alphabetically public Set getAllUserJobsSorted(){ - Set hashSet = new HashSet(); - users.forEach(user -> hashSet.add(user.getJob())); - Set treeSet = new TreeSet(hashSet); - return treeSet; - //return new HashSet<>(); + // your code here + return new HashSet<>(); } // Find user by first name - throw RuntimeException if not found public User findByFirstName(String firstName){ - return users.stream() - .filter(u -> u.getFirstName().equals(firstName)) - .findFirst() - .orElseThrow(RuntimeException::new); - //return new User(); + // your code here + return new User(); } // Check if all users are older than the specified age public boolean areAllUsersOlderThan(int age){ // your code here - please try with allMatch/noneMatch - return users.stream() - .allMatch(u -> u.getAge() > age); - //return false; + return false; } // Add a new user - if there is a user with the same id, don't add and throw a RuntimeException public void addUser(User user){ // your code here - HINT: use ifPresent() method from Optional - users.forEach(u -> {if (u.getId() == user.getId()) throw new RuntimeException(); } ); - users.add(user); } // For all students (user.job = "student"), change the job to "graduate" and add 5 years to their age public void changeAllStudentsJobsAndAges(){ // your code here - users.forEach(u -> {if(u.getJob().compareTo("student") == 0) {u.setJob("graduate"); u.setAge(u.getAge()+ 5); } } ); } // Count users that have the given Job public long countUsersHavingTheSpecifiedJob(String job){ // your code here - - return users.stream() - .filter(u -> u.getJob().compareTo(job)==0) - .count(); - //return 0; + return 0; } // Get a map where the key is the user id and the value is the User object itself public Map getMapOfUsers(){ // your code here - Map userMap =new HashMap<>(); - users.forEach(u -> userMap.put(u.getId(),u)); - return userMap; - - //return new HashMap<>(); + return new HashMap<>(); } // Get a predicate for filtering by the given name - applies to both firstName and lastName public Predicate getPredicateForFilteringByName(String name){ // your code here - - Predicate userPredicate = user -> user.getFirstName().equals(name) || user.getLastName().equals(name); - return userPredicate; - //return null; + return null; } // Get a comparator for User type - compare by age ascending, then by job alphabetically public Comparator getUserComparator(){ // your code here - - Comparator byAgeThenJob = Comparator.comparing(User::getAge).thenComparing(User::getJob); - return byAgeThenJob; - - //return null; + return null; } // Filter users using the given Predicate diff --git a/java8/src/main/java/com/unitbv/util/DateTimeUtils.java b/java8/src/main/java/com/unitbv/util/DateTimeUtils.java index 95216e3..f0134c9 100644 --- a/java8/src/main/java/com/unitbv/util/DateTimeUtils.java +++ b/java8/src/main/java/com/unitbv/util/DateTimeUtils.java @@ -2,29 +2,18 @@ import java.time.LocalDate; import java.time.Month; -import java.time.temporal.ChronoField; public class DateTimeUtils { // Get the number of years until the given date public static int getNumberOfYearsUntil(LocalDate date){ // your code here - if (LocalDate.now().getYear()>date.getYear()){ - return LocalDate.now().getYear()-date.getYear(); - } - return (LocalDate.now().getYear()-date.getYear())*(-1); - - //return 0; + return 0; } // Check if the given date occurs on Friday the 13th public static boolean isDateOccurringOnFriday13th(LocalDate date){ // your code here - HINT: use ChronoField enum constants for day of month and day of week - boolean isDate = false; - if (date.get(ChronoField.DAY_OF_MONTH)== 13 && date.get(ChronoField.MONTH_OF_YEAR)==2) - isDate = true; - return isDate; - - //return false; + return false; } } diff --git a/java8/src/test/java/com/unitbv/Java8Tests.java b/java8/src/test/java/com/unitbv/Java8Tests.java index 4f59996..849a3fe 100644 --- a/java8/src/test/java/com/unitbv/Java8Tests.java +++ b/java8/src/test/java/com/unitbv/Java8Tests.java @@ -214,10 +214,8 @@ public void getGetMapOfUsers(){ public void testGetPredicateForFilteringName(){ String name = "John"; Predicate predicate = dataSource.getPredicateForFilteringByName(name); - List expected = Stream.of( - new User(1, "John", "Wick", 35, "actor"), - new User(7, "Mark", "John", 17, "student") - ).collect(Collectors.toList()); + List expected = Stream.of(new User(1, "John", "Wick", 35, "actor")) + .collect(Collectors.toList()); List actual = dataSource.filterUsers(predicate); Assertions.assertEquals(expected, actual); } @@ -250,10 +248,10 @@ public void testGetNumberOfYearsUntil(){ public void testIsDateOccurringOnFriday13th(){ // should be false LocalDate date = LocalDate.of(2022, 2, 13); - Assertions.assertTrue(DateTimeUtils.isDateOccurringOnFriday13th(date)); + Assertions.assertFalse(DateTimeUtils.isDateOccurringOnFriday13th(date)); // should be true date = LocalDate.of(2023, 1, 13); - Assertions.assertFalse(DateTimeUtils.isDateOccurringOnFriday13th(date)); + Assertions.assertTrue(DateTimeUtils.isDateOccurringOnFriday13th(date)); } } diff --git a/lab-6-api-gateway/.gitignore b/lab-6-api-gateway/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/lab-6-api-gateway/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/lab-6-api-gateway/api-gateway-project/.gitignore b/lab-6-api-gateway/api-gateway-project/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/lab-6-api-gateway/api-gateway-project/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/lab-6-api-gateway/api-gateway-project/pom.xml b/lab-6-api-gateway/api-gateway-project/pom.xml new file mode 100644 index 0000000..871ce8d --- /dev/null +++ b/lab-6-api-gateway/api-gateway-project/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.5 + + + com.example + api-gateway-project + 0.0.1-SNAPSHOT + api-gateway-project + api-gateway-project + + 11 + 2021.0.1 + + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.cloud + spring-cloud-starter-gateway + + + + org.springframework.boot + spring-boot-starter-test + test + + + io.projectreactor + reactor-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/lab-6-api-gateway/api-gateway-project/src/main/java/com/example/apigatewayproject/ApiGatewayProjectApplication.java b/lab-6-api-gateway/api-gateway-project/src/main/java/com/example/apigatewayproject/ApiGatewayProjectApplication.java new file mode 100644 index 0000000..e0f6114 --- /dev/null +++ b/lab-6-api-gateway/api-gateway-project/src/main/java/com/example/apigatewayproject/ApiGatewayProjectApplication.java @@ -0,0 +1,13 @@ +package com.example.apigatewayproject; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApiGatewayProjectApplication { + + public static void main(String[] args) { + SpringApplication.run(ApiGatewayProjectApplication.class, args); + } + +} diff --git a/lab-6-api-gateway/api-gateway-project/src/main/resources/application.yml b/lab-6-api-gateway/api-gateway-project/src/main/resources/application.yml new file mode 100644 index 0000000..aaad35d --- /dev/null +++ b/lab-6-api-gateway/api-gateway-project/src/main/resources/application.yml @@ -0,0 +1,6 @@ +server: + port: 8080 +#TODO use eureka to discover the URL for the service1 and service2 +#TODO configure spring cloud gateway to route the request to downstream services (service1 and service2) based on the paths(/api/greeting, /product) +#TODO for greeting endpoint add a route to accept requests to /greeting but before calling service1 it must append api before the greeting path (HINT: rewrite path filter) +#and method types (GET,POST) \ No newline at end of file diff --git a/lab-6-api-gateway/api-gateway-project/src/test/java/com/example/apigatewayproject/ApiGatewayProjectApplicationTests.java b/lab-6-api-gateway/api-gateway-project/src/test/java/com/example/apigatewayproject/ApiGatewayProjectApplicationTests.java new file mode 100644 index 0000000..6c58423 --- /dev/null +++ b/lab-6-api-gateway/api-gateway-project/src/test/java/com/example/apigatewayproject/ApiGatewayProjectApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.apigatewayproject; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ApiGatewayProjectApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/lab-6-api-gateway/pom.xml b/lab-6-api-gateway/pom.xml new file mode 100644 index 0000000..aa491ab --- /dev/null +++ b/lab-6-api-gateway/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.5 + + + com.example + lab-6-api-gateway + 0.0.1-SNAPSHOT + lab-6-api-gateway + lab-6-api-gateway + + 11 + + pom + + api-gateway-project + service1 + service2 + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/lab-6-api-gateway/service1/.gitignore b/lab-6-api-gateway/service1/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/lab-6-api-gateway/service1/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/lab-6-api-gateway/service1/pom.xml b/lab-6-api-gateway/service1/pom.xml new file mode 100644 index 0000000..478fe3f --- /dev/null +++ b/lab-6-api-gateway/service1/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.5 + + + com.example + service1 + 0.0.1-SNAPSHOT + service1 + service1 + + 11 + 2021.0.1 + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/lab-6-api-gateway/service1/src/main/java/com/example/service1/Service1Application.java b/lab-6-api-gateway/service1/src/main/java/com/example/service1/Service1Application.java new file mode 100644 index 0000000..27128b5 --- /dev/null +++ b/lab-6-api-gateway/service1/src/main/java/com/example/service1/Service1Application.java @@ -0,0 +1,20 @@ +package com.example.service1; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Service1Application { + + public static void main(String[] args) { + SpringApplication.run(Service1Application.class, args); + } + + // TODO + // 1. define a GET endpoint /api/greeting which should accept a query parameter "name" + // 2. return should be a string returning a greeting: Hello Brasov + // 3. print request headers + // 4. register the service in eureka + + +} diff --git a/lab-6-api-gateway/service1/src/main/resources/application.yml b/lab-6-api-gateway/service1/src/main/resources/application.yml new file mode 100644 index 0000000..54b155f --- /dev/null +++ b/lab-6-api-gateway/service1/src/main/resources/application.yml @@ -0,0 +1,2 @@ +server: + port: 8081 \ No newline at end of file diff --git a/lab-6-api-gateway/service1/src/test/java/com/example/service1/Service1ApplicationTests.java b/lab-6-api-gateway/service1/src/test/java/com/example/service1/Service1ApplicationTests.java new file mode 100644 index 0000000..539fcde --- /dev/null +++ b/lab-6-api-gateway/service1/src/test/java/com/example/service1/Service1ApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.service1; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Service1ApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/lab-6-api-gateway/service2/.gitignore b/lab-6-api-gateway/service2/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/lab-6-api-gateway/service2/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/lab-6-api-gateway/service2/pom.xml b/lab-6-api-gateway/service2/pom.xml new file mode 100644 index 0000000..be06918 --- /dev/null +++ b/lab-6-api-gateway/service2/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.5 + + + com.example + service2 + 0.0.1-SNAPSHOT + service2 + service2 + + 11 + 2021.0.1 + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/lab-6-api-gateway/service2/src/main/java/com/example/service2/Service2Application.java b/lab-6-api-gateway/service2/src/main/java/com/example/service2/Service2Application.java new file mode 100644 index 0000000..3c2fbd2 --- /dev/null +++ b/lab-6-api-gateway/service2/src/main/java/com/example/service2/Service2Application.java @@ -0,0 +1,19 @@ +package com.example.service2; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Service2Application { + + public static void main(String[] args) { + SpringApplication.run(Service2Application.class, args); + } + // TODO + // 1. define a POST endpoint /product which should accept a request body containing two properties -product name and quantity + //2. save the request body in memory + // 3. return 200 if OK + // 4. print request headers + // 5. register the service in eureka + // 6. define a GET endpoint /product to return the saved data using the POST endpoint - return type is List +} diff --git a/lab-6-api-gateway/service2/src/main/resources/application.yml b/lab-6-api-gateway/service2/src/main/resources/application.yml new file mode 100644 index 0000000..4772153 --- /dev/null +++ b/lab-6-api-gateway/service2/src/main/resources/application.yml @@ -0,0 +1,3 @@ + +server: + port: 8082 \ No newline at end of file diff --git a/lab-6-api-gateway/service2/src/test/java/com/example/service2/Service2ApplicationTests.java b/lab-6-api-gateway/service2/src/test/java/com/example/service2/Service2ApplicationTests.java new file mode 100644 index 0000000..3da138b --- /dev/null +++ b/lab-6-api-gateway/service2/src/test/java/com/example/service2/Service2ApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.service2; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Service2ApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/lab-6-api-gateway/src/main/java/com/example/lab6apigateway/Lab6ApiGatewayApplication.java b/lab-6-api-gateway/src/main/java/com/example/lab6apigateway/Lab6ApiGatewayApplication.java new file mode 100644 index 0000000..eb83cff --- /dev/null +++ b/lab-6-api-gateway/src/main/java/com/example/lab6apigateway/Lab6ApiGatewayApplication.java @@ -0,0 +1,13 @@ +package com.example.lab6apigateway; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Lab6ApiGatewayApplication { + + public static void main(String[] args) { + SpringApplication.run(Lab6ApiGatewayApplication.class, args); + } + +} diff --git a/lab-6-api-gateway/src/main/resources/application.properties b/lab-6-api-gateway/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/lab-6-api-gateway/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/lab-6-api-gateway/src/test/java/com/example/lab6apigateway/Lab6ApiGatewayApplicationTests.java b/lab-6-api-gateway/src/test/java/com/example/lab6apigateway/Lab6ApiGatewayApplicationTests.java new file mode 100644 index 0000000..af4ce01 --- /dev/null +++ b/lab-6-api-gateway/src/test/java/com/example/lab6apigateway/Lab6ApiGatewayApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.lab6apigateway; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Lab6ApiGatewayApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/pom.xml b/pom.xml index 487bfbd..1ccc714 100644 --- a/pom.xml +++ b/pom.xml @@ -21,6 +21,8 @@ java8 rest-service + eureka + lab-6-api-gateway diff --git a/spring1/.gitignore b/spring1/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/spring1/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/spring1/pom.xml b/spring1/pom.xml new file mode 100644 index 0000000..55666da --- /dev/null +++ b/spring1/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + com.example + spring1 + 0.0.1-SNAPSHOT + spring1 + spring1 + + 1.8 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.data + spring-data-jpa + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + 10 + 10 + + + + + + diff --git a/spring1/src/main/java/com/unitbv/Spring1Application.java b/spring1/src/main/java/com/unitbv/Spring1Application.java new file mode 100644 index 0000000..2d9a6da --- /dev/null +++ b/spring1/src/main/java/com/unitbv/Spring1Application.java @@ -0,0 +1,13 @@ +package com.unitbv; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Spring1Application { + + public static void main(String[] args) { + SpringApplication.run(Spring1Application.class, args); + } + +} diff --git a/spring1/src/main/java/com/unitbv/autowiring/AutowiredCfg.java b/spring1/src/main/java/com/unitbv/autowiring/AutowiredCfg.java new file mode 100644 index 0000000..db8f32e --- /dev/null +++ b/spring1/src/main/java/com/unitbv/autowiring/AutowiredCfg.java @@ -0,0 +1,9 @@ +package com.unitbv.autowiring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = {"com.unitbv.autowiring"}) +public class AutowiredCfg { +} diff --git a/spring1/src/main/java/com/unitbv/autowiring/service/FormatServiceConstructorInjection.java b/spring1/src/main/java/com/unitbv/autowiring/service/FormatServiceConstructorInjection.java new file mode 100644 index 0000000..526880d --- /dev/null +++ b/spring1/src/main/java/com/unitbv/autowiring/service/FormatServiceConstructorInjection.java @@ -0,0 +1,14 @@ +package com.unitbv.autowiring.service; + +import com.unitbv.autowiring.util.FormatUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class FormatServiceConstructorInjection { + private final FormatUtil formatUtil; + + public void checkFormatted() { + System.out.println(this.formatUtil.formatted(true)); + } +} diff --git a/spring1/src/main/java/com/unitbv/autowiring/service/FormatServiceFieldInjection.java b/spring1/src/main/java/com/unitbv/autowiring/service/FormatServiceFieldInjection.java new file mode 100644 index 0000000..8873634 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/autowiring/service/FormatServiceFieldInjection.java @@ -0,0 +1,14 @@ +package com.unitbv.autowiring.service; + +import com.unitbv.autowiring.util.FormatUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class FormatServiceFieldInjection { + public FormatUtil formatUtil; + + public void checkFormatted() { + System.out.println(this.formatUtil.formatted(true)); + } +} diff --git a/spring1/src/main/java/com/unitbv/autowiring/service/FormatServiceSetterInjection.java b/spring1/src/main/java/com/unitbv/autowiring/service/FormatServiceSetterInjection.java new file mode 100644 index 0000000..f2ec37e --- /dev/null +++ b/spring1/src/main/java/com/unitbv/autowiring/service/FormatServiceSetterInjection.java @@ -0,0 +1,14 @@ +package com.unitbv.autowiring.service; + +import com.unitbv.autowiring.util.FormatUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class FormatServiceSetterInjection { + private FormatUtil formatUtil; + + public void checkFormatted() { + System.out.println(this.formatUtil.formatted(true)); + } +} diff --git a/spring1/src/main/java/com/unitbv/autowiring/util/FormatUtil.java b/spring1/src/main/java/com/unitbv/autowiring/util/FormatUtil.java new file mode 100644 index 0000000..39025aa --- /dev/null +++ b/spring1/src/main/java/com/unitbv/autowiring/util/FormatUtil.java @@ -0,0 +1,13 @@ +package com.unitbv.autowiring.util; + +import org.springframework.stereotype.Component; + +@Component +public class FormatUtil { + public String formatted(boolean isFormatted) { + if (isFormatted) { + return "Everything was formatted."; + } + return "Couldn't format"; + } +} diff --git a/spring1/src/main/java/com/unitbv/beans/Book.java b/spring1/src/main/java/com/unitbv/beans/Book.java new file mode 100644 index 0000000..3429ac6 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/beans/Book.java @@ -0,0 +1,11 @@ +package com.unitbv.beans; + +public class Book implements Item { + + private String title; + + @Override + public String getTitle() { + return title; + } +} diff --git a/spring1/src/main/java/com/unitbv/beans/Human.java b/spring1/src/main/java/com/unitbv/beans/Human.java new file mode 100644 index 0000000..5bbd304 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/beans/Human.java @@ -0,0 +1,6 @@ +package com.unitbv.beans; + +public interface Human { + + Item getItem(); +} diff --git a/spring1/src/main/java/com/unitbv/beans/HumanAppCfg.java b/spring1/src/main/java/com/unitbv/beans/HumanAppCfg.java new file mode 100644 index 0000000..a38cf2b --- /dev/null +++ b/spring1/src/main/java/com/unitbv/beans/HumanAppCfg.java @@ -0,0 +1,9 @@ +package com.unitbv.beans; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = {"com.unitbv.beans"} ) +public class HumanAppCfg { +} diff --git a/spring1/src/main/java/com/unitbv/beans/Item.java b/spring1/src/main/java/com/unitbv/beans/Item.java new file mode 100644 index 0000000..a06892b --- /dev/null +++ b/spring1/src/main/java/com/unitbv/beans/Item.java @@ -0,0 +1,5 @@ +package com.unitbv.beans; + +public interface Item { + String getTitle(); +} diff --git a/spring1/src/main/java/com/unitbv/beans/Person.java b/spring1/src/main/java/com/unitbv/beans/Person.java new file mode 100644 index 0000000..3a851d0 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/beans/Person.java @@ -0,0 +1,11 @@ +package com.unitbv.beans; + +public class Person implements Human { + + private Item item; + + @Override + public Item getItem() { + return item; + } +} diff --git a/spring1/src/main/java/com/unitbv/beansnaming/DependantBean.java b/spring1/src/main/java/com/unitbv/beansnaming/DependantBean.java new file mode 100644 index 0000000..b47f156 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/beansnaming/DependantBean.java @@ -0,0 +1,4 @@ +package com.unitbv.beansnaming; + +public interface DependantBean { +} diff --git a/spring1/src/main/java/com/unitbv/beansnaming/DependantBeanImpl.java b/spring1/src/main/java/com/unitbv/beansnaming/DependantBeanImpl.java new file mode 100644 index 0000000..ff79055 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/beansnaming/DependantBeanImpl.java @@ -0,0 +1,10 @@ +package com.unitbv.beansnaming; + + +public class DependantBeanImpl implements DependantBean { + private SimpleBean simpleBean; + + public DependantBeanImpl(SimpleBean simpleBean) { + this.simpleBean = simpleBean; + } +} diff --git a/spring1/src/main/java/com/unitbv/beansnaming/SimpleBean.java b/spring1/src/main/java/com/unitbv/beansnaming/SimpleBean.java new file mode 100644 index 0000000..d4b2076 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/beansnaming/SimpleBean.java @@ -0,0 +1,4 @@ +package com.unitbv.beansnaming; + +public interface SimpleBean { +} diff --git a/spring1/src/main/java/com/unitbv/beansnaming/SimpleBeanImpl.java b/spring1/src/main/java/com/unitbv/beansnaming/SimpleBeanImpl.java new file mode 100644 index 0000000..c83ca34 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/beansnaming/SimpleBeanImpl.java @@ -0,0 +1,19 @@ +package com.unitbv.beansnaming; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +//TODO test what will happen when you add a stereotype annotation +public class SimpleBeanImpl implements SimpleBean { + + public SimpleBeanImpl() { + Logger logger = LoggerFactory.getLogger(SimpleBeanImpl.class); + logger.info("[SimpleBeanImpl instantiation]"); + } + + @Override + public String toString() { + return "SimpleBeanImpl{ code: " + hashCode() + "}"; + } + +} diff --git a/spring1/src/main/java/com/unitbv/beansnaming/SimpleDependantCfg.java b/spring1/src/main/java/com/unitbv/beansnaming/SimpleDependantCfg.java new file mode 100644 index 0000000..0d57764 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/beansnaming/SimpleDependantCfg.java @@ -0,0 +1,21 @@ +package com.unitbv.beansnaming; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = {"com.unitbv.beansnaming"}) +public class SimpleDependantCfg { + + private final Logger logger = LoggerFactory.getLogger(SimpleDependantCfg.class); + + SimpleBean simpleBean() { + return new SimpleBeanImpl(); + } + + DependantBean dependantBean() { + return new DependantBeanImpl(simpleBean()); + } +} diff --git a/spring1/src/main/java/com/unitbv/lifecycle/DepBean.java b/spring1/src/main/java/com/unitbv/lifecycle/DepBean.java new file mode 100644 index 0000000..808134f --- /dev/null +++ b/spring1/src/main/java/com/unitbv/lifecycle/DepBean.java @@ -0,0 +1,7 @@ +package com.unitbv.lifecycle; + +import org.springframework.stereotype.Component; + +@Component +public class DepBean { +} diff --git a/spring1/src/main/java/com/unitbv/lifecycle/FunBean.java b/spring1/src/main/java/com/unitbv/lifecycle/FunBean.java new file mode 100644 index 0000000..3cb72a8 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/lifecycle/FunBean.java @@ -0,0 +1,16 @@ +package com.unitbv.lifecycle; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +public class FunBean { + private Logger logger = LoggerFactory.getLogger(FunBean.class); + + private DepBean depBean; +} diff --git a/spring1/src/main/java/com/unitbv/lifecycle/FunBeanCfg.java b/spring1/src/main/java/com/unitbv/lifecycle/FunBeanCfg.java new file mode 100644 index 0000000..55796b2 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/lifecycle/FunBeanCfg.java @@ -0,0 +1,14 @@ +package com.unitbv.lifecycle; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + + +@Configuration +@ComponentScan(basePackages = {"com.unitbv.lifecycle"}) +public class FunBeanCfg { + + FunBean funBean() { + return new FunBean(); + } +} diff --git a/spring1/src/main/java/com/unitbv/stereotype/StereotypeCfg.java b/spring1/src/main/java/com/unitbv/stereotype/StereotypeCfg.java new file mode 100644 index 0000000..cb4586e --- /dev/null +++ b/spring1/src/main/java/com/unitbv/stereotype/StereotypeCfg.java @@ -0,0 +1,9 @@ +package com.unitbv.stereotype; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = "com.unitbv") +public class StereotypeCfg { +} diff --git a/spring1/src/main/java/com/unitbv/stereotype/controller/UserController.java b/spring1/src/main/java/com/unitbv/stereotype/controller/UserController.java new file mode 100644 index 0000000..797feeb --- /dev/null +++ b/spring1/src/main/java/com/unitbv/stereotype/controller/UserController.java @@ -0,0 +1,4 @@ +package com.unitbv.stereotype.controller; + +public class UserController { +} diff --git a/spring1/src/main/java/com/unitbv/stereotype/model/User.java b/spring1/src/main/java/com/unitbv/stereotype/model/User.java new file mode 100644 index 0000000..e7b6094 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/stereotype/model/User.java @@ -0,0 +1,6 @@ +package com.unitbv.stereotype.model; + +public class User { + private Integer id; + private String name; +} diff --git a/spring1/src/main/java/com/unitbv/stereotype/repository/UserRepository.java b/spring1/src/main/java/com/unitbv/stereotype/repository/UserRepository.java new file mode 100644 index 0000000..01ea991 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/stereotype/repository/UserRepository.java @@ -0,0 +1,7 @@ +package com.unitbv.stereotype.repository; + +import com.unitbv.stereotype.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { +} diff --git a/spring1/src/main/java/com/unitbv/stereotype/repository/impl/UserRepositoryImpl.java b/spring1/src/main/java/com/unitbv/stereotype/repository/impl/UserRepositoryImpl.java new file mode 100644 index 0000000..9081e1e --- /dev/null +++ b/spring1/src/main/java/com/unitbv/stereotype/repository/impl/UserRepositoryImpl.java @@ -0,0 +1,160 @@ +package com.unitbv.stereotype.repository.impl; + +import com.unitbv.stereotype.model.User; +import com.unitbv.stereotype.repository.UserRepository; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.repository.query.FluentQuery; + +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +public class UserRepositoryImpl implements UserRepository { + @Override + public List findAll() { + return null; + } + + @Override + public List findAll(Sort sort) { + return null; + } + + @Override + public Page findAll(Pageable pageable) { + return null; + } + + @Override + public List findAllById(Iterable users) { + return null; + } + + @Override + public long count() { + return 0; + } + + @Override + public void deleteById(User user) { + + } + + @Override + public void delete(Integer entity) { + + } + + @Override + public void deleteAllById(Iterable users) { + + } + + @Override + public void deleteAll(Iterable entities) { + + } + + @Override + public void deleteAll() { + + } + + @Override + public S save(S entity) { + return null; + } + + @Override + public List saveAll(Iterable entities) { + return null; + } + + @Override + public Optional findById(User user) { + return Optional.empty(); + } + + @Override + public boolean existsById(User user) { + return false; + } + + @Override + public void flush() { + + } + + @Override + public S saveAndFlush(S entity) { + return null; + } + + @Override + public List saveAllAndFlush(Iterable entities) { + return null; + } + + @Override + public void deleteAllInBatch(Iterable entities) { + + } + + @Override + public void deleteAllByIdInBatch(Iterable users) { + + } + + @Override + public void deleteAllInBatch() { + + } + + @Override + public Integer getOne(User user) { + return null; + } + + @Override + public Integer getById(User user) { + return null; + } + + @Override + public Optional findOne(Example example) { + return Optional.empty(); + } + + @Override + public List findAll(Example example) { + return null; + } + + @Override + public List findAll(Example example, Sort sort) { + return null; + } + + @Override + public Page findAll(Example example, Pageable pageable) { + return null; + } + + @Override + public long count(Example example) { + return 0; + } + + @Override + public boolean exists(Example example) { + return false; + } + + @Override + public R findBy(Example example, Function, R> queryFunction) { + return null; + } +} diff --git a/spring1/src/main/java/com/unitbv/stereotype/service/UserService.java b/spring1/src/main/java/com/unitbv/stereotype/service/UserService.java new file mode 100644 index 0000000..3b9ad34 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/stereotype/service/UserService.java @@ -0,0 +1,4 @@ +package com.unitbv.stereotype.service; + +public interface UserService { +} diff --git a/spring1/src/main/java/com/unitbv/stereotype/service/impl/UserServiceImpl.java b/spring1/src/main/java/com/unitbv/stereotype/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..afc9967 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/stereotype/service/impl/UserServiceImpl.java @@ -0,0 +1,6 @@ +package com.unitbv.stereotype.service.impl; + +import com.unitbv.stereotype.service.UserService; + +public class UserServiceImpl implements UserService { +} diff --git a/spring1/src/main/java/com/unitbv/stereotype/util/UserUtil.java b/spring1/src/main/java/com/unitbv/stereotype/util/UserUtil.java new file mode 100644 index 0000000..1f440a4 --- /dev/null +++ b/spring1/src/main/java/com/unitbv/stereotype/util/UserUtil.java @@ -0,0 +1,4 @@ +package com.unitbv.stereotype.util; + +public class UserUtil { +} diff --git a/spring1/src/main/resources/application.properties b/spring1/src/main/resources/application.properties new file mode 100644 index 0000000..b2ff11b --- /dev/null +++ b/spring1/src/main/resources/application.properties @@ -0,0 +1 @@ +book.title="Dummy title" \ No newline at end of file diff --git a/spring1/src/test/java/com/unitbv/Spring1ApplicationTests.java b/spring1/src/test/java/com/unitbv/Spring1ApplicationTests.java new file mode 100644 index 0000000..8307489 --- /dev/null +++ b/spring1/src/test/java/com/unitbv/Spring1ApplicationTests.java @@ -0,0 +1,13 @@ +package com.unitbv; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Spring1ApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/spring1/src/test/java/com/unitbv/autowiring/AutowiredCfgTest.java b/spring1/src/test/java/com/unitbv/autowiring/AutowiredCfgTest.java new file mode 100644 index 0000000..7e2b6d0 --- /dev/null +++ b/spring1/src/test/java/com/unitbv/autowiring/AutowiredCfgTest.java @@ -0,0 +1,39 @@ +package com.unitbv.autowiring; + +import com.unitbv.autowiring.service.FormatServiceConstructorInjection; +import com.unitbv.autowiring.service.FormatServiceFieldInjection; +import com.unitbv.autowiring.service.FormatServiceSetterInjection; +import com.unitbv.autowiring.util.FormatUtil; +import org.junit.jupiter.api.Test; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class AutowiredCfgTest { + //TODO use constructor injection, setter injection and field injection to add dependency in FormatServices classes + + @Test + void checkFormattedTestAutowireConstructorInjection() { + FormatUtil formatUtil = new FormatUtil(); + FormatServiceConstructorInjection formatServiceConstructorInjection = new FormatServiceConstructorInjection(formatUtil); + formatServiceConstructorInjection.checkFormatted(); + } + + @Test + void checkFormattedTestAutowireSetterInjection() { + FormatUtil formatUtil = new FormatUtil(); + FormatServiceSetterInjection formatServiceSetterInjection = new FormatServiceSetterInjection(); + formatServiceSetterInjection.setFormatUtil(formatUtil); + formatServiceSetterInjection.checkFormatted(); + } + + @Test + void checkFormattedTestAutowireFieldInjection() { + ConfigurableApplicationContext ctx = + new AnnotationConfigApplicationContext(AutowiredCfg.class); + FormatServiceFieldInjection formatServiceFieldInjection = ctx.getBean(FormatServiceFieldInjection.class); + assertNotNull(formatServiceFieldInjection); + formatServiceFieldInjection.checkFormatted(); + } +} diff --git a/spring1/src/test/java/com/unitbv/beans/HumanAppCfgTest.java b/spring1/src/test/java/com/unitbv/beans/HumanAppCfgTest.java new file mode 100644 index 0000000..45d1a77 --- /dev/null +++ b/spring1/src/test/java/com/unitbv/beans/HumanAppCfgTest.java @@ -0,0 +1,53 @@ +/* +Freeware License, some rights reserved + +Copyright (c) 2019 Iuliana Cosmina + +Permission is hereby granted, free of charge, to anyone obtaining a copy +of this software and associated documentation files (the "Software"), +to work with the Software within the limits of freeware distribution and fair use. +This includes the rights to use, copy, and modify the Software for personal use. +Users are also allowed and encouraged to submit corrections and modifications +to the Software for the benefit of other users. + +It is not allowed to reuse, modify, or redistribute the Software for +commercial use in any way, or for a user's educational materials such as books +or blog articles without prior permission from the copyright holder. + +The above copyright notice and this permission notice need to be included +in all copies or substantial portions of the software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ +package com.unitbv.beans; + +import org.junit.jupiter.api.Test; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class HumanAppCfgTest { + + //TODO make Book.class and Person.class to be recognized as beans by Spring and inject their values + // through constructors in order to make them compile + //title from Book class should be populated with a value that comes from application.properties file + @Test + void testHumanAndItem() { + ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(HumanAppCfg.class); + + Human humanBean = ctx.getBean(Human.class); + + assertNotNull(humanBean); + assertNotNull(humanBean.getItem()); + assertNotNull(humanBean.getItem().getTitle()); + + ctx.close(); + } +} diff --git a/spring1/src/test/java/com/unitbv/beansnaming/SimpleDependantCfgTest.java b/spring1/src/test/java/com/unitbv/beansnaming/SimpleDependantCfgTest.java new file mode 100644 index 0000000..74fe6b5 --- /dev/null +++ b/spring1/src/test/java/com/unitbv/beansnaming/SimpleDependantCfgTest.java @@ -0,0 +1,65 @@ +package com.unitbv.beansnaming; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.*; + +public class SimpleDependantCfgTest { + + @Test + void testBeanNamingDefaultName() { + //TODO create definitions for SimpleBean and DependantBean and log some messages + ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SimpleDependantCfg.class); + + SimpleBean simpleBean = ctx.getBean("simpleBean", SimpleBean.class); + DependantBean dependantBean = ctx.getBean("dependantBean", DependantBean.class); + + assertNotNull(simpleBean); + assertNotNull(dependantBean); + + ctx.close(); + } + + @Test + void testBeanNamingSingleCustomName() { + //TODO define a name for your beans + ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SimpleDependantCfg.class); + + SimpleBean customSimpleBean = ctx.getBean("customSimpleBean", SimpleBean.class); + DependantBean customDependantBean = ctx.getBean("customDependantBean", DependantBean.class); + + assertNotNull(customSimpleBean); + assertNotNull(customDependantBean); + + // no bean named 'simpleBean' and 'dependantBean' + assertThrows(NoSuchBeanDefinitionException.class, () -> ctx.getBean("simpleBean", SimpleBean.class)); + assertThrows(NoSuchBeanDefinitionException.class, () -> ctx.getBean("dependantBean", DependantBean.class)); + + ctx.close(); + } + + @Test + void testBeanNamingMultipleCustomName() { + //TODO define multiple names for the same bean + ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(SimpleDependantCfg.class); + + SimpleBean customSimpleBean1 = ctx.getBean("customSimpleBean1", SimpleBean.class); + SimpleBean customSimpleBean2 = ctx.getBean("customSimpleBean2", SimpleBean.class); + + DependantBean customDependantBean1 = ctx.getBean("customDependantBean1", DependantBean.class); + DependantBean customDependantBean2 = ctx.getBean("customDependantBean2", DependantBean.class); + + assertNotNull(customSimpleBean1); + assertNotNull(customSimpleBean2); + assertEquals(customDependantBean1, customDependantBean2); + + assertNotNull(customDependantBean1); + assertNotNull(customDependantBean2); + assertEquals(customDependantBean1, customDependantBean2); + + ctx.close(); + } +} diff --git a/spring1/src/test/java/com/unitbv/lifecycle/FunBeanCfgTest.java b/spring1/src/test/java/com/unitbv/lifecycle/FunBeanCfgTest.java new file mode 100644 index 0000000..b84d821 --- /dev/null +++ b/spring1/src/test/java/com/unitbv/lifecycle/FunBeanCfgTest.java @@ -0,0 +1,23 @@ +package com.unitbv.lifecycle; + +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class FunBeanCfgTest { + + @Test + void testBeanLifecycle() { + //TODO configure all lifecycle methods for FunBean and log messages just to be clear in each order are the methods called. + // hint 1: Use setter to inject a value for DepBean + // hint 2: @Bean has 2 values called initMethod and destroyMethod + // hint 3: you need to implement InitializingBean, DisposableBean + // hint 4: there should be 8 logged messages + var ctx = new AnnotationConfigApplicationContext(FunBeanCfg.class); + ctx.registerShutdownHook(); + + FunBean funBean = ctx.getBean(FunBean.class); + assertNotNull(funBean); + } +} diff --git a/spring1/src/test/java/com/unitbv/stereotype/StereotypeCfgTest.java b/spring1/src/test/java/com/unitbv/stereotype/StereotypeCfgTest.java new file mode 100644 index 0000000..df519f3 --- /dev/null +++ b/spring1/src/test/java/com/unitbv/stereotype/StereotypeCfgTest.java @@ -0,0 +1,35 @@ +package com.unitbv.stereotype; + +import com.unitbv.stereotype.controller.UserController; +import com.unitbv.stereotype.repository.UserRepository; +import com.unitbv.stereotype.repository.impl.UserRepositoryImpl; +import com.unitbv.stereotype.service.UserService; +import com.unitbv.stereotype.service.impl.UserServiceImpl; +import com.unitbv.stereotype.util.UserUtil; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class StereotypeCfgTest { + + //TODO add stereotype annotations in order to instantiate the beans. Use more specific annotations where you can + // Hint 1: there are 4 stereotype annotations + // Hint 2: pay attention to the configuration of StereotypeCfg.class + @Test + void testStereotypeAnnotations() { + var ctx = new AnnotationConfigApplicationContext(StereotypeCfg.class); + ctx.registerShutdownHook(); + + UserController userControllerBean = ctx.getBean(UserController.class); + UserService userServiceBean = ctx.getBean(UserServiceImpl.class); + UserRepository userRepositoryBean = ctx.getBean(UserRepositoryImpl.class); + UserUtil userUtilBean = ctx.getBean(UserUtil.class); + + assertNotNull(userControllerBean); + assertNotNull(userServiceBean); + assertNotNull(userRepositoryBean); + assertNotNull(userUtilBean); + + } +}