diff --git a/JUnit4-Tests/src/main/java/com/howtodoinjava/demo/App.java b/JUnit4-Tests/src/main/java/com/howtodoinjava/demo/App.java index d8250c0..accc6d6 100644 --- a/JUnit4-Tests/src/main/java/com/howtodoinjava/demo/App.java +++ b/JUnit4-Tests/src/main/java/com/howtodoinjava/demo/App.java @@ -1,13 +1,13 @@ package com.howtodoinjava.demo; -/** - * Hello world! - * - */ +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication public class App { public static void main( String[] args ) { - System.out.println( "Hello World!" ); + SpringApplication.run(App.class, args); } } diff --git a/Testing-Libraries/pom.xml b/Testing-Libraries/pom.xml index 871d979..137b54a 100644 --- a/Testing-Libraries/pom.xml +++ b/Testing-Libraries/pom.xml @@ -1,84 +1,89 @@ - - spring-boot-examples - com.howtodoinjava.demo - 1.0-SNAPSHOT - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + spring-boot-examples + com.howtodoinjava.demo + 1.0-SNAPSHOT + - 4.0.0 - Testing-Libraries - Testing-Libraries + 4.0.0 + Testing-Libraries + Testing-Libraries - - UTF-8 - 17 - 17 - + + UTF-8 + 17 + 17 + - - - org.springframework.boot - spring-boot-starter-webflux - - - com.github.tomakehurst - wiremock-jre8 - 2.33.2 - test - - - com.squareup.okhttp3 - okhttp - 4.10.0 - test - - - com.squareup.okhttp3 - mockwebserver - 4.10.0 - test - - - io.projectreactor - reactor-test - test - - - org.easymock - easymock - 4.3 - test - - - org.jmockit - jmockit - 1.49 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - - - src\test\resources\hello_testng_suite.xml - - - - - - - + + + org.springframework.boot + spring-boot-starter-webflux + + + com.github.tomakehurst + wiremock-jre8 + 2.35.0 + test + + + com.squareup.okhttp3 + okhttp + 4.10.0 + test + + + com.squareup.okhttp3 + mockwebserver + 4.10.0 + test + + + io.projectreactor + reactor-test + test + + + org.easymock + easymock + 4.3 + test + + + org.jmockit + jmockit + 1.49 + + + org.testng + testng + 7.7.0 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + + + src\test\resources\hello_testng_suite.xml + + + + + + + diff --git a/caching/pom.xml b/caching/pom.xml index 5f043ff..67e65ae 100644 --- a/caching/pom.xml +++ b/caching/pom.xml @@ -1,34 +1,38 @@ - - spring-boot-examples - com.howtodoinjava.demo - 1.0-SNAPSHOT - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + spring-boot-examples + com.howtodoinjava.demo + 1.0-SNAPSHOT + - 4.0.0 - com.howtodoinjava.app - caching - caching + 4.0.0 + com.howtodoinjava.app + caching + caching - - UTF-8 - 17 - 17 - + + UTF-8 + 17 + 17 + - - - org.springframework.boot - spring-boot-starter-cache - - - org.springframework.boot - spring-boot-starter-data-jpa - - + + + org.springframework.boot + spring-boot-starter-cache + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + diff --git a/caching/src/test/java/com/howtodoinjava/app/AppTest.java b/caching/src/test/java/com/howtodoinjava/app/AppTest.java index 365bdc4..4f8ee13 100644 --- a/caching/src/test/java/com/howtodoinjava/app/AppTest.java +++ b/caching/src/test/java/com/howtodoinjava/app/AppTest.java @@ -1,9 +1,13 @@ package com.howtodoinjava.app; -import static org.testng.AssertJUnit.assertTrue; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +@SpringBootTest public class AppTest { - public void shouldAnswerWithTrue() { - assertTrue(true); + + @Test + public void contextLoads() { + } } diff --git a/pom.xml b/pom.xml index 33c71e2..70375ea 100644 --- a/pom.xml +++ b/pom.xml @@ -1,100 +1,110 @@ - 4.0.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - com.howtodoinjava.demo - spring-boot-examples - 1.0-SNAPSHOT - - Application-Properties - Profiles - spring-boot-vuejs-jwt-auth/Spring-Boot-API - spring-boot-keycloak-auth/Spring-Boot-API - JUnit4-Tests - Testing-Libraries - Spring-Boot-Filters - springboot-graphql-main - social-connect-spring-boot-starter - spring-angular-application-example/SpringBootApplication - - spring-mvc-angular-file-upload/springboot-3-mvc-file-upload - - Retry-example - caching - spring-react-file-upload/SpringBootFileUploadApplication - - Spring-Validation - spring-boot-docker-minikube - multiple-dataSources - spring-boot-vuejs/Spring-Boot-API - spring-data-dynamodb - spring-boot-mongodb-crud - spring-boot-resilience4j - spring-boot-load-initial-data - - spring-boot-examples - https://howtodoinjava.com - pom + com.howtodoinjava.demo + spring-boot-examples + 1.0-SNAPSHOT + + Application-Properties + Profiles + spring-boot-vuejs-jwt-auth/Spring-Boot-API + JUnit4-Tests + Testing-Libraries + Spring-Boot-Filters + springboot-graphql-main + social-connect-spring-boot-starter + spring-angular-application-example/SpringBootApplication + + spring-mvc-angular-file-upload/springboot-3-mvc-file-upload + + Retry-example + caching + spring-react-file-upload/SpringBootFileUploadApplication + + Spring-Validation + spring-boot-docker-minikube + multiple-dataSources + spring-boot-vuejs/Spring-Boot-API + spring-data-dynamodb + spring-boot-mongodb-crud + spring-boot-resilience4j + spring-boot-load-initial-data + spring-boot-xml-request-response + spring-deploy-docker-image-to-aws + spring-boot-mvc-thymeleaf + spring_boot_elastic-beanstalk-aws + + spring-boot-examples + https://howtodoinjava.com + pom - - org.springframework.boot - spring-boot-starter-parent - 3.0.0 - + + org.springframework.boot + spring-boot-starter-parent + 3.0.0 + - - UTF-8 - 17 - 17 - + + UTF-8 + 17 + 17 + - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-data-jpa - - - com.h2database - h2 - - - org.projectlombok - lombok - provided - - - org.testng - testng - 7.6.1 - test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.mockito - mockito-inline - test - - + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.data + spring-data-jpa + + + jakarta.persistence + jakarta.persistence-api + + + org.keycloak + keycloak-admin-client + 20.0.0 + + + - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/search-in-keycloak-with-spring-boot/pom.xml b/search-in-keycloak-with-spring-boot/pom.xml index 9a8b4d6..4d7acc3 100644 --- a/search-in-keycloak-with-spring-boot/pom.xml +++ b/search-in-keycloak-with-spring-boot/pom.xml @@ -8,7 +8,7 @@ 3.0.6 - com.example + com.howtodoinjava search-in-keycloak-with-spring-boot 0.0.1-SNAPSHOT search-in-keycloak-with-spring-boot @@ -24,7 +24,7 @@ org.keycloak keycloak-admin-client - 19.0.1 + 21.1.1 org.projectlombok diff --git a/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/SearchInKeycloakWithSpringBootApplication.java b/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/SearchInKeycloakWithSpringBootApplication.java index d80088e..f0fb871 100644 --- a/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/SearchInKeycloakWithSpringBootApplication.java +++ b/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/SearchInKeycloakWithSpringBootApplication.java @@ -6,8 +6,7 @@ @SpringBootApplication public class SearchInKeycloakWithSpringBootApplication { - public static void main(String[] args) { - SpringApplication.run(SearchInKeycloakWithSpringBootApplication.class, args); - } - + public static void main(String[] args) { + SpringApplication.run(SearchInKeycloakWithSpringBootApplication.class, args); + } } diff --git a/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/config/Config.java b/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/config/Config.java index 815be5b..919ccbd 100644 --- a/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/config/Config.java +++ b/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/config/Config.java @@ -6,22 +6,19 @@ import org.keycloak.admin.client.KeycloakBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.stereotype.Component; @Configuration public class Config { - @Bean - public Keycloak keycloak() { - return KeycloakBuilder.builder() - .serverUrl("http://localhost:8080/") - .realm("master") - .grantType(OAuth2Constants.PASSWORD) - .username("admin") - .password("admin") - .clientId("admin-cli") - .resteasyClient(new ResteasyClientBuilder() - .connectionPoolSize(10) - .build()).build(); - } + @Bean + public Keycloak keycloak() { + return KeycloakBuilder.builder() + .serverUrl("http://localhost:8080/") + .realm("master") + .grantType(OAuth2Constants.PASSWORD) + .username("admin") + .password("admin") + .clientId("admin-cli") + .build(); + } } diff --git a/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/exception/handler/ExceptionController.java b/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/exception/handler/ExceptionController.java index 91e1e84..994de42 100644 --- a/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/exception/handler/ExceptionController.java +++ b/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/exception/handler/ExceptionController.java @@ -8,11 +8,9 @@ @ControllerAdvice public class ExceptionController { - - - @ExceptionHandler - public ResponseEntity handleUserNotFoundInKeycloakException(UserNotFoundInKeycloakException e){ - return ResponseEntity.badRequest().body(e.getMessage()); - } - + @ExceptionHandler + public ResponseEntity handleUserNotFoundInKeycloakException( + UserNotFoundInKeycloakException e) { + return ResponseEntity.badRequest().body(e.getMessage()); + } } diff --git a/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/service/KeycloakService.java b/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/service/KeycloakService.java index 83a9d3a..ef0a071 100644 --- a/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/service/KeycloakService.java +++ b/search-in-keycloak-with-spring-boot/src/main/java/com/example/searchinkeycloakwithspringboot/service/KeycloakService.java @@ -15,37 +15,44 @@ public class KeycloakService { - @Autowired - private Keycloak keycloak; - - - public UserRepresentation searchById(String id) { - UserResource userResource = keycloak.realm("master").users().get(id); - return userResource.toRepresentation(); - } - public UserRepresentation searchByEmail(String email) throws UserNotFoundInKeycloakException { - List userRepresentations = keycloak.realm("master").users().search(null, null, null, email, 0, 1); - if (userRepresentations.isEmpty()) { - throw new UserNotFoundInKeycloakException("User with email " + email + " not found"); - } - return userRepresentations.get(0); + @Autowired + private Keycloak keycloak; + + public UserRepresentation searchById(String id) { + UserResource userResource = keycloak.realm("master").users().get(id); + return userResource.toRepresentation(); + } + + public UserRepresentation searchByEmail(String email) throws UserNotFoundInKeycloakException { + List userRepresentations = keycloak.realm("master").users() + .search(null, null, null, email, 0, 1); + if (userRepresentations.isEmpty()) { + throw new UserNotFoundInKeycloakException("User with email " + email + " not found"); } - public UserRepresentation searchByUsername(String username) throws UserNotFoundInKeycloakException { - List userRepresentations = keycloak.realm("master").users().search(username, true); - if (userRepresentations.isEmpty()) { - throw new UserNotFoundInKeycloakException("User with username " + username + " not found"); - } - return userRepresentations.get(0); + return userRepresentations.get(0); + } + + public UserRepresentation searchByUsername(String username) + throws UserNotFoundInKeycloakException { + List userRepresentations = keycloak.realm("master").users() + .search(username, true); + if (userRepresentations.isEmpty()) { + throw new UserNotFoundInKeycloakException("User with username " + username + " not found"); } - public UserRepresentation searchByPhone(String phone) throws UserNotFoundInKeycloakException { - List userRepresentations = keycloak.realm("master").users().searchByAttributes("phone:" + phone); - if (userRepresentations.isEmpty()) { - throw new UserNotFoundInKeycloakException("User with phone number " + phone + " not found"); - } - return userRepresentations.get(0); - } - public Set searchByRole(String roleName) { - return keycloak.realm("master").roles().get(roleName).getRoleUserMembers() ; + return userRepresentations.get(0); + } + + public UserRepresentation searchByPhone(String phone) throws UserNotFoundInKeycloakException { + List userRepresentations = keycloak.realm("master").users() + .searchByAttributes("phone:" + phone); + if (userRepresentations.isEmpty()) { + throw new UserNotFoundInKeycloakException("User with phone number " + phone + " not found"); } + return userRepresentations.get(0); + } + + public Set searchByRole(String roleName) { + return keycloak.realm("master").roles().get(roleName).getRoleUserMembers(); + } } diff --git a/search-in-keycloak-with-spring-boot/src/test/java/com/example/searchinkeycloakwithspringboot/SearchInKeycloakWithSpringBootApplicationTests.java b/search-in-keycloak-with-spring-boot/src/test/java/com/example/searchinkeycloakwithspringboot/SearchInKeycloakWithSpringBootApplicationTests.java index 6dacd75..3fd8d90 100644 --- a/search-in-keycloak-with-spring-boot/src/test/java/com/example/searchinkeycloakwithspringboot/SearchInKeycloakWithSpringBootApplicationTests.java +++ b/search-in-keycloak-with-spring-boot/src/test/java/com/example/searchinkeycloakwithspringboot/SearchInKeycloakWithSpringBootApplicationTests.java @@ -1,13 +1,43 @@ package com.example.searchinkeycloakwithspringboot; +import java.util.List; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import org.keycloak.admin.client.Keycloak; +import org.keycloak.admin.client.resource.UserResource; +import org.keycloak.representations.idm.UserRepresentation; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SearchInKeycloakWithSpringBootApplicationTests { - @Test - void contextLoads() { - } + @Autowired + private Keycloak keycloak; + + @Test + void testSearchById() { + String id = "test-id"; + UserResource userResource = keycloak.realm("master").users().get(id); + Assertions.assertEquals(id, userResource.toRepresentation().getId()); + } + + @Test + void testSearchByEmail() { + String email = "test-email"; + List userRepresentationsList = keycloak.realm("master").users() + .searchByEmail(email, true); + Assertions.assertEquals(1, userRepresentationsList.size()); + Assertions.assertEquals(email, userRepresentationsList.get(0).getEmail()); + } + + @Test + void testSearchByUsername() { + String username = "username"; + List userRepresentationsList = keycloak.realm("master").users() + .searchByUsername(username, true); + Assertions.assertEquals(1, userRepresentationsList.size()); + Assertions.assertEquals(username, userRepresentationsList.get(0).getUsername()); + } } diff --git a/spring-angular-application-example/SpringBootApplication/pom.xml b/spring-angular-application-example/SpringBootApplication/pom.xml index 456ff12..021128d 100644 --- a/spring-angular-application-example/SpringBootApplication/pom.xml +++ b/spring-angular-application-example/SpringBootApplication/pom.xml @@ -22,10 +22,18 @@ + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + mysql mysql-connector-java - 5.1.41 + 8.0.32 diff --git a/spring-angular-application-example/SpringBootApplication/src/main/resources/application.properties b/spring-angular-application-example/SpringBootApplication/src/main/resources/application.properties index 1be2668..b2db5a9 100644 --- a/spring-angular-application-example/SpringBootApplication/src/main/resources/application.properties +++ b/spring-angular-application-example/SpringBootApplication/src/main/resources/application.properties @@ -1,14 +1,14 @@ #jpa config #JDBC connection properties -spring.datasource.driver-class-name = com.mysql.jdbc.Driver -spring.datasource.url = jdbc:mysql://localhost:3306/howtodoinjavadb -spring.datasource.username = root -spring.datasource.password = root +spring.datasource.url=jdbc:h2:file:C:/temp/test +spring.datasource.username=sa +spring.datasource.password= +spring.datasource.driverClassName=org.h2.Driver +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect #Hibernate properties -spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect spring.jpa.hibernate.ddl-auto = update spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true diff --git a/spring-aws-dynamodb-example/.gitignore b/spring-aws-dynamodb-example/.gitignore new file mode 100644 index 0000000..4ff3812 --- /dev/null +++ b/spring-aws-dynamodb-example/.gitignore @@ -0,0 +1,144 @@ +###################### +# Project Specific +###################### +/build/www/** +/src/test/javascript/coverage/ +/src/test/javascript/PhantomJS*/ + +###################### +# Node +###################### +/node/ +node_tmp/ +node_modules/ +npm-debug.log.* + +###################### +# SASS +###################### +.sass-cache/ + +###################### +# Eclipse +###################### +*.pydevproject +.project +.metadata +tmp/ +tmp/**/* +*.tmp +*.bak +*.swp +*~.nib +local.properties +.classpath +.settings/ +.loadpath +.factorypath +/src/main/resources/rebel.xml + +# External tool builders +.externalToolBuilders/** + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# PDT-specific +.buildpath + +###################### +# Intellij +###################### +.idea/ +*.iml +*.iws +*.ipr +*.ids +*.orig + +###################### +# Visual Studio Code +###################### +.vscode/ + +###################### +# Maven +###################### +/log/ +*/target/** +*/target/sonar/** +/target/** +###################### +# Gradle +###################### +.gradle/ +/build/ + +###################### +# Package Files +###################### +*.jar +*.war +*.ear +*.db + +###################### +# Windows +###################### +# Windows image file caches +Thumbs.db + +# Folder config file +Desktop.ini + +###################### +# Mac OSX +###################### +.DS_Store +.svn + +# Thumbnails +._* + +# Files that might appear on external disk +.Spotlight-V100 +.Trashes + +###################### +# Directories +###################### +/bin/ +/deploy/ + +###################### +# Logs +###################### +*.log + +###################### +# Others +###################### +*.class +*.*~ +*~ +.merge_file* + +###################### +# Gradle Wrapper +###################### +!gradle/wrapper/gradle-wrapper.jar + +###################### +# Maven Wrapper +###################### +!.mvn/wrapper/maven-wrapper.jar + +###################### +# ESLint +###################### +.eslintcache +/.idea/ + diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/.mvn/wrapper/maven-wrapper.jar b/spring-aws-dynamodb-example/.mvn/wrapper/maven-wrapper.jar similarity index 100% rename from spring-boot-keycloak-auth/Spring-Boot-API/.mvn/wrapper/maven-wrapper.jar rename to spring-aws-dynamodb-example/.mvn/wrapper/maven-wrapper.jar diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/.mvn/wrapper/maven-wrapper.properties b/spring-aws-dynamodb-example/.mvn/wrapper/maven-wrapper.properties similarity index 100% rename from spring-boot-keycloak-auth/Spring-Boot-API/.mvn/wrapper/maven-wrapper.properties rename to spring-aws-dynamodb-example/.mvn/wrapper/maven-wrapper.properties diff --git a/spring-aws-dynamodb-example/HELP.md b/spring-aws-dynamodb-example/HELP.md new file mode 100644 index 0000000..8c6dcbf --- /dev/null +++ b/spring-aws-dynamodb-example/HELP.md @@ -0,0 +1,19 @@ +# Getting Started + +### Reference Documentation + +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/3.0.6/maven-plugin/reference/html/) +* [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.0.6/maven-plugin/reference/html/#build-image) +* [Spring Web](https://docs.spring.io/spring-boot/docs/3.0.6/reference/htmlsingle/#web) + +### Guides + +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) + diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/mvnw b/spring-aws-dynamodb-example/mvnw old mode 100755 new mode 100644 similarity index 100% rename from spring-boot-keycloak-auth/Spring-Boot-API/mvnw rename to spring-aws-dynamodb-example/mvnw diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/mvnw.cmd b/spring-aws-dynamodb-example/mvnw.cmd similarity index 100% rename from spring-boot-keycloak-auth/Spring-Boot-API/mvnw.cmd rename to spring-aws-dynamodb-example/mvnw.cmd diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/pom.xml b/spring-aws-dynamodb-example/pom.xml similarity index 58% rename from spring-boot-keycloak-auth/Spring-Boot-API/pom.xml rename to spring-aws-dynamodb-example/pom.xml index 680344b..c18d0b0 100644 --- a/spring-boot-keycloak-auth/Spring-Boot-API/pom.xml +++ b/spring-aws-dynamodb-example/pom.xml @@ -1,6 +1,5 @@ - 4.0.0 @@ -8,47 +7,54 @@ com.howtodoinjava.demo 1.0-SNAPSHOT - - com.howtodoinjava - EmployeeAPI_keycloak + com.howtodoinjava.demo + spring-aws-dynamodb-example 0.0.1-SNAPSHOT - EmployeeAPI_keycloak - EmployeeRestAPI - + spring-aws-dynamodb-example + spring-aws-dynamodb-example - UTF-8 - 17 - 17 + 17 + + + + io.awspring.cloud + spring-cloud-aws-dependencies + 3.0.0 + pom + import + + + + - - org.springframework.boot - spring-boot-starter-data-jpa - org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-devtools + + - - - org.springframework.boot - spring-boot-starter-security - + - com.h2database - h2 - runtime + io.awspring.cloud + spring-cloud-aws-starter + - org.springframework.boot - spring-boot-starter-oauth2-client + io.awspring.cloud + spring-cloud-aws-starter-dynamodb org.projectlombok lombok true + org.springframework.boot spring-boot-starter-test diff --git a/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/SpringAwsDynamodbExampleApplication.java b/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/SpringAwsDynamodbExampleApplication.java new file mode 100644 index 0000000..e35b230 --- /dev/null +++ b/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/SpringAwsDynamodbExampleApplication.java @@ -0,0 +1,13 @@ +package com.howtodoinjava.demo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringAwsDynamodbExampleApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringAwsDynamodbExampleApplication.class, args); + } + +} diff --git a/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/config/DynamoDBConfiguration.java b/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/config/DynamoDBConfiguration.java new file mode 100644 index 0000000..a5aca38 --- /dev/null +++ b/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/config/DynamoDBConfiguration.java @@ -0,0 +1,42 @@ +package com.howtodoinjava.demo.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; + +import java.net.URI; + +@Configuration +public class DynamoDBConfiguration { + + @Value("${aws.dynamodb.accessKey}") + private String accessKey; + + @Value("${aws.dynamodb.secretKey}") + private String secretKey; + + @Value("${aws.dynamodb.endpoint}") + private String endpoint; + + @Bean(name = "dynamoDbClient") + public DynamoDbClient getDynamoDbClient() { + return DynamoDbClient.builder() + .endpointOverride(URI.create(endpoint)) + .region(Region.AP_SOUTH_1) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create(accessKey, secretKey))) + .build(); + } + + @Bean(name = "dynamoDbEnhancedClient") + public DynamoDbEnhancedClient getDynamoDbEnhancedClient() { + return DynamoDbEnhancedClient.builder() + .dynamoDbClient(getDynamoDbClient()) + .build(); + } +} \ No newline at end of file diff --git a/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/controller/MovieController.java b/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/controller/MovieController.java new file mode 100644 index 0000000..ef29868 --- /dev/null +++ b/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/controller/MovieController.java @@ -0,0 +1,41 @@ +package com.howtodoinjava.demo.controller; + +import com.howtodoinjava.demo.entity.MovieDetails; +import com.howtodoinjava.demo.service.DynamoDbOperationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import software.amazon.awssdk.enhanced.dynamodb.model.PageIterable; + +import java.util.List; + +@RestController +public class MovieController { + + @Autowired + private DynamoDbOperationService dbOperationService; + + @PostMapping("/movie") + public MovieDetails saveMovie(@RequestBody MovieDetails movieDetails) { + return dbOperationService.saveData(movieDetails); + } + + @PutMapping("/movie") + public MovieDetails updateMovie(@RequestBody MovieDetails movieDetails) { + return dbOperationService.updateData(movieDetails); + } + + @GetMapping("/movie/{id}") + public MovieDetails findById(@PathVariable("id") String id) { + return dbOperationService.findById(id); + } + + @DeleteMapping("/movie/{id}") + public void deleteById(@PathVariable("id") String id) { + dbOperationService.deleteById(id); + } + + @GetMapping("/movie") + public List getMovieListByGenre(@RequestParam("genre") String genre) { + return dbOperationService.scanDataByGenre(genre); + } +} diff --git a/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/entity/MovieDetails.java b/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/entity/MovieDetails.java new file mode 100644 index 0000000..75b2371 --- /dev/null +++ b/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/entity/MovieDetails.java @@ -0,0 +1,86 @@ +package com.howtodoinjava.demo.entity; + +import lombok.AllArgsConstructor; +import lombok.NoArgsConstructor; +import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; +import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; +import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; + +@NoArgsConstructor +@AllArgsConstructor +@DynamoDbBean +public class MovieDetails { + + private String id; + private String title; + private String year; + private String genre; + private String country; + private String duration; + private String language; + + + @DynamoDbPartitionKey + @DynamoDbAttribute("id") + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @DynamoDbAttribute("title") + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + @DynamoDbAttribute("release_year") + public String getYear() { + return year; + } + + public void setYear(String year) { + this.year = year; + } + + @DynamoDbAttribute("genre") + public String getGenre() { + return genre; + } + + public void setGenre(String genre) { + this.genre = genre; + } + + @DynamoDbAttribute("country") + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + @DynamoDbAttribute("duration") + public String getDuration() { + return duration; + } + + public void setDuration(String duration) { + this.duration = duration; + } + + @DynamoDbAttribute("language") + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } +} \ No newline at end of file diff --git a/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/service/DynamoDbOperationService.java b/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/service/DynamoDbOperationService.java new file mode 100644 index 0000000..dac216b --- /dev/null +++ b/spring-aws-dynamodb-example/src/main/java/com/howtodoinjava/demo/service/DynamoDbOperationService.java @@ -0,0 +1,108 @@ +package com.howtodoinjava.demo.service; + +import com.howtodoinjava.demo.entity.MovieDetails; +import io.awspring.cloud.dynamodb.DynamoDbTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; +import software.amazon.awssdk.core.pagination.sync.SdkIterable; +import software.amazon.awssdk.enhanced.dynamodb.*; +import software.amazon.awssdk.enhanced.dynamodb.model.PageIterable; +import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; +import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; +import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +public class DynamoDbOperationService { + + private DynamoDbTemplate dynamoDbTemplate; + private DynamoDbTable movieTable; + private DynamoDbClient dynamoDbClient; + private DynamoDbEnhancedClient dynamoDbEnhancedClient; + + @Autowired + public DynamoDbOperationService(@Qualifier("dynamoDbClient") DynamoDbClient dynamoDbClient, + @Qualifier("dynamoDbEnhancedClient") DynamoDbEnhancedClient dynamoDbEnhancedClient) { + + this.dynamoDbClient = dynamoDbClient; + this.dynamoDbEnhancedClient = dynamoDbEnhancedClient; + + dynamoDbTemplate = new DynamoDbTemplate(this.dynamoDbEnhancedClient); + movieTable = DynamoDbEnhancedClient.builder().dynamoDbClient(this.dynamoDbClient).build().table("movie_details", + TableSchema.fromBean(MovieDetails.class)); + + } + + public MovieDetails saveData(MovieDetails movieDetails) { + return dynamoDbTemplate.save(movieDetails); + } + + public MovieDetails updateData(MovieDetails movieDetails) { + return dynamoDbTemplate.update(movieDetails); + } + + public void deleteByObject(MovieDetails movieDetails) { + dynamoDbTemplate.delete(movieDetails); + } + + public void deleteById(String id) { + Key key = Key.builder().partitionValue(id).build(); + dynamoDbTemplate.delete(key, MovieDetails.class); + } + + public MovieDetails findById(String hashKey) { + + Key key = Key.builder().partitionValue(hashKey).build(); + + return dynamoDbTemplate.load(key, MovieDetails.class); + } + + public List scanDataByGenre(String genre) { + Map expressionValues = new HashMap<>(); + expressionValues.put(":val1", AttributeValue.fromS(genre)); + + Expression filterExpression = Expression.builder() + .expression("genre = :val1") + .expressionValues(expressionValues) + .build(); + + ScanEnhancedRequest scanEnhancedRequest = ScanEnhancedRequest.builder() + .filterExpression(filterExpression).build(); + + PageIterable returnedList = dynamoDbTemplate.scan(scanEnhancedRequest, MovieDetails.class); + + return returnedList.items().stream().collect(Collectors.toList()); + } + + public PageIterable queryData(String partitionKey, String genre) { + + Map expressionValues = new HashMap<>(); + expressionValues.put(":value", AttributeValue.fromS(genre)); + + Expression filterExpression = Expression.builder() + .expression("genre = :val1") + .expressionValues(expressionValues) + .build(); + + QueryConditional queryConditional = QueryConditional + .keyEqualTo( + Key.builder() + .partitionValue(partitionKey) + .build()); + + QueryEnhancedRequest queryRequest = QueryEnhancedRequest.builder() + .queryConditional(queryConditional) + .filterExpression(filterExpression) + .build(); + + return dynamoDbTemplate.query(queryRequest,MovieDetails.class); + } + +} diff --git a/spring-aws-dynamodb-example/src/main/resources/application.properties b/spring-aws-dynamodb-example/src/main/resources/application.properties new file mode 100644 index 0000000..0df23f0 --- /dev/null +++ b/spring-aws-dynamodb-example/src/main/resources/application.properties @@ -0,0 +1,3 @@ +aws.dynamodb.accessKey=accessKey +aws.dynamodb.secretKey=secretKey +aws.dynamodb.endpoint=http://localhost:8000 diff --git a/spring-aws-dynamodb-example/src/test/java/com/howtodoinjava/demo/SpringAwsDynamodbExampleApplicationTests.java b/spring-aws-dynamodb-example/src/test/java/com/howtodoinjava/demo/SpringAwsDynamodbExampleApplicationTests.java new file mode 100644 index 0000000..1bcd100 --- /dev/null +++ b/spring-aws-dynamodb-example/src/test/java/com/howtodoinjava/demo/SpringAwsDynamodbExampleApplicationTests.java @@ -0,0 +1,111 @@ +package com.howtodoinjava.demo; + +import com.howtodoinjava.demo.entity.MovieDetails; +import com.howtodoinjava.demo.service.DynamoDbOperationService; +import io.awspring.cloud.dynamodb.DynamoDbTemplate; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.lang.Nullable; +import org.springframework.util.StringUtils; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.enhanced.dynamodb.*; +import software.amazon.awssdk.enhanced.dynamodb.model.PageIterable; +import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; +import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; +import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.*; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@SpringBootTest +class SpringAwsDynamodbExampleApplicationTests { + + @Autowired + private DynamoDbOperationService dbOperationService; + + @Test + void testCrud() { + MovieDetails movieDetails = new MovieDetails("MOV001", "Avengers", null, "Action", "US", "175", "English"); + MovieDetails savedMovie = dbOperationService.saveData(movieDetails); + + Assertions.assertEquals(movieDetails.getId(), savedMovie.getId()); + + savedMovie.setTitle("Avengers Endgame"); + MovieDetails updatedMovie = dbOperationService.updateData(movieDetails); + + Assertions.assertEquals(movieDetails.getId(), updatedMovie.getId()); + Assertions.assertEquals(savedMovie.getTitle(), updatedMovie.getTitle()); + + dbOperationService.deleteByObject(updatedMovie); + + MovieDetails fetchedDetails = dbOperationService.findById(movieDetails.getId()); + + Assertions.assertNull(fetchedDetails); + } + + @Test + void testScan() throws InterruptedException { + + MovieDetails actionMovie = new MovieDetails("MOV001", "Avengers", null, + "Action", "US", "175", "English"); + dbOperationService.saveData(actionMovie); + + MovieDetails ThrillerMovie = new MovieDetails("MOV002", "James Bond", null, + "Thriller", "US", "167", "English"); + dbOperationService.saveData(ThrillerMovie); + + + List fetchedDataList = dbOperationService.scanDataByGenre("Thriller"); + Long countResult = fetchedDataList.stream().count(); + + Assertions.assertEquals(1, countResult); + + List fetchedActionDataList = dbOperationService.scanDataByGenre("Action"); + Long countActionResult = fetchedActionDataList.stream().count(); + + Assertions.assertEquals(1, countActionResult); + + // cleanUp(dynamoDbTable, actionMovie.getId()); + dbOperationService.deleteByObject(actionMovie); + dbOperationService.deleteByObject(ThrillerMovie); + + } + + private static void describeAndCreateTable(DynamoDbClient dynamoDbClient, @Nullable String tablePrefix) { + ArrayList attributeDefinitions = new ArrayList<>(); + attributeDefinitions.add(AttributeDefinition.builder().attributeName("id").attributeType("S").build()); + + ArrayList tableKeySchema = new ArrayList<>(); + tableKeySchema.add(KeySchemaElement.builder().attributeName("id").keyType(KeyType.HASH).build()); + + String tableName = StringUtils.hasText(tablePrefix) ? tablePrefix.concat("movie_details") : "movie_details"; + CreateTableRequest createTableRequest = CreateTableRequest.builder().tableName(tableName) + .provisionedThroughput(ProvisionedThroughput.builder().readCapacityUnits((long) 1) + .writeCapacityUnits((long) 1).build()) + .attributeDefinitions(attributeDefinitions).keySchema(tableKeySchema).build(); + + try { + dynamoDbClient.createTable(createTableRequest); + } + catch (ResourceInUseException e) { + // table already exists, do nothing + } + } + + public static void cleanUp(DynamoDbTable dynamoDbTable, String uuid) { + dynamoDbTable.deleteItem(Key.builder().partitionValue(uuid).build()); + } + +} diff --git a/spring-boot-keycloak-auth/README.md b/spring-boot-keycloak-auth/README.md deleted file mode 100644 index 57ea039..0000000 --- a/spring-boot-keycloak-auth/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Related Tutorials - -1. [Vue.js Application with Spring Boot](https://howtodoinjava.com/spring-boot/vuejs-app-with-spring-boot/) \ No newline at end of file diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/EmployeeRestApiApplication.java b/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/EmployeeRestApiApplication.java deleted file mode 100644 index 171af43..0000000 --- a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/EmployeeRestApiApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.howtodoinjava.app; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class EmployeeRestApiApplication { - - public static void main(String[] args) { - SpringApplication.run(EmployeeRestApiApplication.class, args); - } - -} diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/config/SecurityConfig.java b/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/config/SecurityConfig.java deleted file mode 100644 index 6004052..0000000 --- a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/config/SecurityConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.howtodoinjava.app.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.web.SecurityFilterChain; - -@Configuration -@EnableWebSecurity -public class SecurityConfig { - - @Bean - public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { - httpSecurity.authorizeHttpRequests() - .requestMatchers("/public").permitAll() - .anyRequest().authenticated() - .and() - .oauth2Login(); - return httpSecurity.build(); - } -} diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/entity/Employee.java b/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/entity/Employee.java deleted file mode 100644 index 1b2730a..0000000 --- a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/entity/Employee.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.howtodoinjava.app.entity; - -import jakarta.persistence.*; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -@Entity -@Getter -@Setter -@AllArgsConstructor -@NoArgsConstructor -public class Employee { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - private String name; - - private String phone; - - private String email; - - private String position; - - - @Column(length = 1000) - private String bio; - -} diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/repository/EmployeeRepository.java b/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/repository/EmployeeRepository.java deleted file mode 100644 index 89e8af1..0000000 --- a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/repository/EmployeeRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.howtodoinjava.app.repository; - -import com.howtodoinjava.app.entity.Employee; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface EmployeeRepository extends JpaRepository { - - -} - diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/service/EmployeeService.java b/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/service/EmployeeService.java deleted file mode 100644 index 9a1eefe..0000000 --- a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/service/EmployeeService.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.howtodoinjava.app.service; - -import com.howtodoinjava.app.entity.Employee; -import com.howtodoinjava.app.repository.EmployeeRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Optional; - -@Service -public class EmployeeService { - - @Autowired - private EmployeeRepository employeeRepository; - - public List getAllEmployees() { - return employeeRepository.findAll(); - } - - public Optional getEmployeeById(Long id) { - return employeeRepository.findById(id); - } - - public Employee addEmployee(Employee employee) { - return employeeRepository.save(employee); - } - - public Optional updateEmployee(Long id, Employee employee) { - Optional existingEmployee = employeeRepository.findById(id); - if (existingEmployee.isPresent()) { - Employee updatedEmployee = existingEmployee.get(); - updatedEmployee.setName(employee.getName()); - updatedEmployee.setPhone(employee.getPhone()); - updatedEmployee.setEmail(employee.getEmail()); - updatedEmployee.setPosition(employee.getPosition()); - updatedEmployee.setBio(employee.getBio()); - employeeRepository.save(updatedEmployee); - } - return existingEmployee; - } - - public void deleteEmployee(Long id) { - employeeRepository.deleteById(id); - } -} - diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/web/EmployeeController.java b/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/web/EmployeeController.java deleted file mode 100644 index a1988d4..0000000 --- a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/web/EmployeeController.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.howtodoinjava.app.web; - -import com.howtodoinjava.app.entity.Employee; -import com.howtodoinjava.app.service.EmployeeService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.net.URI; -import java.util.List; -import java.util.Optional; - -@RestController -@RequestMapping("/api/employees") -@CrossOrigin -public class EmployeeController { - - @Autowired - private EmployeeService employeeService; - - @GetMapping - public List getAllEmployees() { - return employeeService.getAllEmployees(); - } - - @GetMapping("/{id}") - public ResponseEntity getEmployeeById(@PathVariable Long id) { - Optional employee = employeeService.getEmployeeById(id); - return employee.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); - } - - @PostMapping - public ResponseEntity addEmployee(@RequestBody Employee employee) { - Employee savedEmployee = employeeService.addEmployee(employee); - return ResponseEntity.created(URI.create("/api/employees/" + savedEmployee.getId())).body(savedEmployee); - } - - @PutMapping("/{id}") - public ResponseEntity updateEmployee(@PathVariable Long id, - @RequestBody Employee employee) { - Optional existingEmployee = employeeService.updateEmployee(id, - employee); - return existingEmployee.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); - } - - @DeleteMapping("/{id}") - public ResponseEntity deleteEmployee(@PathVariable Long id) { - employeeService.deleteEmployee(id); - return ResponseEntity.noContent().build(); - } -} - diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/web/HomeController.java b/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/web/HomeController.java deleted file mode 100644 index 7b131d5..0000000 --- a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/web/HomeController.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.howtodoinjava.app.web; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class HomeController { - - - @GetMapping("/public") - public String publicResource(){ - return "public Resource "; - } - @GetMapping("/protected") - public String protectedResource(){ - return "protected Resource "; - } -} diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/resources/application.properties b/spring-boot-keycloak-auth/Spring-Boot-API/src/main/resources/application.properties deleted file mode 100644 index bae6335..0000000 --- a/spring-boot-keycloak-auth/Spring-Boot-API/src/main/resources/application.properties +++ /dev/null @@ -1,9 +0,0 @@ -server.port=9090 - - -spring.security.oauth2.client.registration.keycloak.client-id=EmployeeRestAPI -spring.security.oauth2.client.registration.keycloak.client-secret=OGYlvRiJw11MAB9i7Tr1Pcc09OoGLi8Y -spring.security.oauth2.client.registration.keycloak.scope=openid -spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code -spring.security.oauth2.client.registration..keycloak.redirect-uri= -spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8080/auth/realms/howtodoinjava \ No newline at end of file diff --git a/spring-boot-load-initial-data/pom.xml b/spring-boot-load-initial-data/pom.xml index 1d8b777..bbd7591 100644 --- a/spring-boot-load-initial-data/pom.xml +++ b/spring-boot-load-initial-data/pom.xml @@ -28,6 +28,10 @@ org.springframework.boot spring-boot-starter-test + + com.h2database + h2 + diff --git a/spring-boot-load-initial-data/src/main/resources/application.properties b/spring-boot-load-initial-data/src/main/resources/application.properties index 3c413ba..2126d20 100644 --- a/spring-boot-load-initial-data/src/main/resources/application.properties +++ b/spring-boot-load-initial-data/src/main/resources/application.properties @@ -8,8 +8,8 @@ spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true -logging.level.org.hibernate.SQL=DEBUG -logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE +#logging.level.org.hibernate.SQL=DEBUG +#logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE #spring.jpa.hibernate.ddl-auto=none #spring.sql.init.schema-locations=classpath:sql/schema.sql diff --git a/spring-boot-mongodb-crud/src/test/java/com/howtodoinjava/app/service/impl/MongoRepositoryServiceImplTest.java b/spring-boot-mongodb-crud/src/test/java/com/howtodoinjava/app/service/impl/MongoRepositoryServiceImplTest.java index 9db0bdf..6c5fb0d 100644 --- a/spring-boot-mongodb-crud/src/test/java/com/howtodoinjava/app/service/impl/MongoRepositoryServiceImplTest.java +++ b/spring-boot-mongodb-crud/src/test/java/com/howtodoinjava/app/service/impl/MongoRepositoryServiceImplTest.java @@ -2,14 +2,17 @@ import com.howtodoinjava.app.model.Item; import com.howtodoinjava.app.service.MongoRepositoryService; -import org.junit.jupiter.api.*; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.testng.Assert; - -import java.util.List; @SpringBootTest +@Disabled class MongoRepositoryServiceImplTest { @Autowired @@ -50,10 +53,10 @@ void tearDown() { void testAddItem() { Item savedItem = mongoRepositoryService.add(itemBiscuit); - Assert.assertEquals(itemBiscuit.getId(), savedItem.getId()); - Assert.assertEquals(itemBiscuit.getName(), savedItem.getName()); - Assert.assertEquals(itemBiscuit.getQuantity(), savedItem.getQuantity()); - Assert.assertEquals(itemBiscuit.getCategory(), savedItem.getCategory()); + Assertions.assertEquals(itemBiscuit.getId(), savedItem.getId()); + Assertions.assertEquals(itemBiscuit.getName(), savedItem.getName()); + Assertions.assertEquals(itemBiscuit.getQuantity(), savedItem.getQuantity()); + Assertions.assertEquals(itemBiscuit.getCategory(), savedItem.getCategory()); mongoRepositoryService.delete(savedItem.getId()); } @@ -65,7 +68,7 @@ void testUpdateItem() { itemToUpdate.setId(savedItem.getId()); Item updatedItem = mongoRepositoryService.update(itemToUpdate); - Assert.assertEquals(updatedItem.getQuantity(), itemToUpdate.getQuantity()); + Assertions.assertEquals(updatedItem.getQuantity(), itemToUpdate.getQuantity()); mongoRepositoryService.delete(updatedItem.getId()); } @@ -77,7 +80,7 @@ void testGetAllItems() { List items = mongoRepositoryService.getAll(); - Assert.assertTrue(items.size() > 0); + Assertions.assertTrue(items.size() > 0); mongoRepositoryService.delete(savedItemBiscuit.getId()); mongoRepositoryService.delete(savedItemCrackers.getId()); @@ -89,7 +92,7 @@ void testGetAllItemsWithPagination() { Item savedItemCrackers = mongoRepositoryService.add(itemCrackers); List items = mongoRepositoryService.getAll(1, 2); - Assert.assertTrue(items.size() == 2); + Assertions.assertTrue(items.size() == 2); mongoRepositoryService.delete(savedItemBiscuit.getId()); mongoRepositoryService.delete(savedItemCrackers.getId()); @@ -101,7 +104,7 @@ void testGetItemById() { Item fetchedItem = mongoRepositoryService.getById(savedItem.getId()); - Assert.assertEquals(fetchedItem.getName(), savedItem.getName()); + Assertions.assertEquals(fetchedItem.getName(), savedItem.getName()); mongoRepositoryService.delete(fetchedItem.getId()); } @@ -113,8 +116,8 @@ void testFindItemByName() { Item itemFound = mongoRepositoryService.findByName(itemBiscuit.getName()); - Assert.assertEquals(itemBiscuit.getName(), itemFound.getName()); - Assert.assertEquals(itemBiscuit.getId(), itemFound.getId()); + Assertions.assertEquals(itemBiscuit.getName(), itemFound.getName()); + Assertions.assertEquals(itemBiscuit.getId(), itemFound.getId()); mongoRepositoryService.delete(savedItemBiscuit.getId()); mongoRepositoryService.delete(savedItemCrackers.getId()); @@ -128,12 +131,12 @@ void testFindAllByCategory() { List items = mongoRepositoryService.findAllByCategory(searchCategory); - Assert.assertTrue(items.size() == 2); + Assertions.assertTrue(items.size() == 2); Item item = items.get(0); - Assert.assertNotNull(item.getName()); - Assert.assertNotNull(item.getQuantity()); - Assert.assertNull(item.getCategory()); + Assertions.assertNotNull(item.getName()); + Assertions.assertNotNull(item.getQuantity()); + Assertions.assertNull(item.getCategory()); mongoRepositoryService.delete(savedItemBiscuit.getId()); mongoRepositoryService.delete(savedItemCrackers.getId()); @@ -145,7 +148,7 @@ void testFindItemByQuantityBetween() { Item savedItemCrackers = mongoRepositoryService.add(itemCrackers); List items = mongoRepositoryService.findAllByQuantityBetween(1, 5); - Assert.assertTrue(items.size() == 1); + Assertions.assertTrue(items.size() == 1); mongoRepositoryService.delete(savedItemBiscuit.getId()); mongoRepositoryService.delete(savedItemCrackers.getId()); @@ -156,6 +159,6 @@ void testDeleteItem() { Item savedItem = mongoRepositoryService.add(itemBiscuit); boolean response = mongoRepositoryService.delete(savedItem.getId()); - Assert.assertEquals(response, true); + Assertions.assertEquals(response, true); } } \ No newline at end of file diff --git a/spring-boot-mongodb-crud/src/test/java/com/howtodoinjava/app/service/impl/MongoTemplateServiceImplTest.java b/spring-boot-mongodb-crud/src/test/java/com/howtodoinjava/app/service/impl/MongoTemplateServiceImplTest.java index db1f2b2..c9e3e49 100644 --- a/spring-boot-mongodb-crud/src/test/java/com/howtodoinjava/app/service/impl/MongoTemplateServiceImplTest.java +++ b/spring-boot-mongodb-crud/src/test/java/com/howtodoinjava/app/service/impl/MongoTemplateServiceImplTest.java @@ -5,195 +5,194 @@ import org.junit.jupiter.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.testng.Assert; import java.util.List; @SpringBootTest +@Disabled class MongoTemplateServiceImplTest { - @Autowired - MongoTemplateService mongoTemplateService; + @Autowired + MongoTemplateService mongoTemplateService; - Integer pageNumber = 1; - Integer pageSize = 5; - Item itemSpices = null; - Item itemSnacks = null; - Item itemToUpdate = null; - String searchCategory = "spices"; + Integer pageNumber = 1; + Integer pageSize = 5; + Item itemSpices = null; + Item itemSnacks = null; + Item itemToUpdate = null; + String searchCategory = "spices"; - @BeforeEach - void setUp() { - itemSpices = new Item(); - itemSpices.setName("Dried Red Chilli"); - itemSpices.setQuantity(3); - itemSpices.setCategory("spices"); + @BeforeEach + void setUp() { + itemSpices = new Item(); + itemSpices.setName("Dried Red Chilli"); + itemSpices.setQuantity(3); + itemSpices.setCategory("spices"); - itemToUpdate = new Item(); - itemToUpdate.setQuantity(1); - itemToUpdate.setCategory("spices"); - itemToUpdate.setName("Dried Red Chilli"); + itemToUpdate = new Item(); + itemToUpdate.setQuantity(1); + itemToUpdate.setCategory("spices"); + itemToUpdate.setName("Dried Red Chilli"); - itemSnacks = new Item(); - itemSnacks.setName("Cheese Crackers"); - itemSnacks.setQuantity(8); - itemSnacks.setCategory("snacks"); + itemSnacks = new Item(); + itemSnacks.setName("Cheese Crackers"); + itemSnacks.setQuantity(8); + itemSnacks.setCategory("snacks"); - } + } - @AfterEach - void tearDown() { - itemSpices = null; - itemToUpdate = null; - itemSnacks = null; - } + @AfterEach + void tearDown() { + itemSpices = null; + itemToUpdate = null; + itemSnacks = null; + } - @Test - void testAddItem() { + @Test + void testAddItem() { - Item savedItem = mongoTemplateService.add(itemSpices); + Item savedItem = mongoTemplateService.add(itemSpices); - Assert.assertEquals(savedItem.getId(), itemSpices.getId()); - Assert.assertEquals(savedItem.getName(), itemSpices.getName()); - Assert.assertEquals(savedItem.getQuantity(), itemSpices.getQuantity()); - Assert.assertEquals(savedItem.getCategory(), itemSpices.getCategory()); + Assertions.assertEquals(savedItem.getId(), itemSpices.getId()); + Assertions.assertEquals(savedItem.getName(), itemSpices.getName()); + Assertions.assertEquals(savedItem.getQuantity(), itemSpices.getQuantity()); + Assertions.assertEquals(savedItem.getCategory(), itemSpices.getCategory()); - mongoTemplateService.delete(savedItem.getId()); - } + mongoTemplateService.delete(savedItem.getId()); + } - @Test - void testUpdateItem() { - Item savedItem = mongoTemplateService.add(itemSpices); + @Test + void testUpdateItem() { + Item savedItem = mongoTemplateService.add(itemSpices); - itemToUpdate.setId(savedItem.getId()); - Item updatedItem = mongoTemplateService.update(itemToUpdate); + itemToUpdate.setId(savedItem.getId()); + Item updatedItem = mongoTemplateService.update(itemToUpdate); - Assert.assertEquals(updatedItem.getQuantity(), - itemToUpdate.getQuantity()); + Assertions.assertEquals(updatedItem.getQuantity(), + itemToUpdate.getQuantity()); - mongoTemplateService.delete(updatedItem.getId()); - } + mongoTemplateService.delete(updatedItem.getId()); + } - @Test - void testGetAllItems() { - Item savedItemSpices = mongoTemplateService.add(itemSpices); - Item savedItemSnacks = mongoTemplateService.add(itemSnacks); + @Test + void testGetAllItems() { + Item savedItemSpices = mongoTemplateService.add(itemSpices); + Item savedItemSnacks = mongoTemplateService.add(itemSnacks); - List items = mongoTemplateService.getAll(); - Assert.assertTrue(items.size() == 2); + List items = mongoTemplateService.getAll(); + Assertions.assertTrue(items.size() == 2); - mongoTemplateService.delete(savedItemSpices.getId()); - mongoTemplateService.delete(savedItemSnacks.getId()); + mongoTemplateService.delete(savedItemSpices.getId()); + mongoTemplateService.delete(savedItemSnacks.getId()); - } + } - @Test - void testGetItemById() { - Item savedItem = mongoTemplateService.add(itemSpices); + @Test + void testGetItemById() { + Item savedItem = mongoTemplateService.add(itemSpices); - Item item = mongoTemplateService.getById(savedItem.getId()); + Item item = mongoTemplateService.getById(savedItem.getId()); - Assert.assertEquals(item.getName(), item.getName()); + Assertions.assertEquals(item.getName(), item.getName()); - mongoTemplateService.delete(savedItem.getId()); + mongoTemplateService.delete(savedItem.getId()); - } + } - @Test - void testSearchItemWithName() { + @Test + void testSearchItemWithName() { - Item savedItemSpices = mongoTemplateService.add(itemSpices); - Item savedItemSnacks = mongoTemplateService.add(itemSnacks); + Item savedItemSpices = mongoTemplateService.add(itemSpices); + Item savedItemSnacks = mongoTemplateService.add(itemSnacks); + List items = mongoTemplateService.search("Dried Red " + + "Chilli", null, + null, null); - List items = mongoTemplateService.search("Dried Red " + - "Chilli", null, - null, null); + Assertions.assertTrue(items.size() > 0); - Assert.assertTrue(items.size() > 0); + mongoTemplateService.delete(savedItemSpices.getId()); + mongoTemplateService.delete(savedItemSnacks.getId()); + } - mongoTemplateService.delete(savedItemSpices.getId()); - mongoTemplateService.delete(savedItemSnacks.getId()); - } + @Test + void testSearchItemWithQuantity() { + Item savedItemSpices = mongoTemplateService.add(itemSpices); + Item savedItemSnacks = mongoTemplateService.add(itemSnacks); - @Test - void testSearchItemWithQuantity() { - Item savedItemSpices = mongoTemplateService.add(itemSpices); - Item savedItemSnacks = mongoTemplateService.add(itemSnacks); + List items = mongoTemplateService.search(null, 1, + 5, null); - List items = mongoTemplateService.search(null, 1, - 5, null); + Assertions.assertTrue(items.size() > 0); - Assert.assertTrue(items.size() > 0); + mongoTemplateService.delete(savedItemSpices.getId()); + mongoTemplateService.delete(savedItemSnacks.getId()); - mongoTemplateService.delete(savedItemSpices.getId()); - mongoTemplateService.delete(savedItemSnacks.getId()); + } - } + @Test + void testSearchItemWithCategory() { + Item savedItemSpices = mongoTemplateService.add(itemSpices); + Item savedItemSnacks = mongoTemplateService.add(itemSnacks); - @Test - void testSearchItemWithCategory() { - Item savedItemSpices = mongoTemplateService.add(itemSpices); - Item savedItemSnacks = mongoTemplateService.add(itemSnacks); + List items = mongoTemplateService.search(null, null, + null, searchCategory); - List items = mongoTemplateService.search(null, null, - null, searchCategory); + Assertions.assertTrue(items.size() > 0); - Assert.assertTrue(items.size() > 0); + mongoTemplateService.delete(savedItemSpices.getId()); + mongoTemplateService.delete(savedItemSnacks.getId()); - mongoTemplateService.delete(savedItemSpices.getId()); - mongoTemplateService.delete(savedItemSnacks.getId()); + } - } + @Test + void testSearchItemWithAll() { + Item savedItemSpices = mongoTemplateService.add(itemSpices); + Item savedItemSnacks = mongoTemplateService.add(itemSnacks); - @Test - void testSearchItemWithAll() { - Item savedItemSpices = mongoTemplateService.add(itemSpices); - Item savedItemSnacks = mongoTemplateService.add(itemSnacks); + List items = mongoTemplateService.search("Dried Red " + + "Chilli", 1, + 5, searchCategory); - List items = mongoTemplateService.search("Dried Red " + - "Chilli", 1, - 5, searchCategory); + Assertions.assertTrue(items.size() > 0); - Assert.assertTrue(items.size() > 0); + mongoTemplateService.delete(savedItemSpices.getId()); + mongoTemplateService.delete(savedItemSnacks.getId()); - mongoTemplateService.delete(savedItemSpices.getId()); - mongoTemplateService.delete(savedItemSnacks.getId()); + } - } + @Test + void testFindAllWithPagination() { + Item savedItemSpices = mongoTemplateService.add(itemSpices); + Item savedItemSnacks = mongoTemplateService.add(itemSnacks); - @Test - void testFindAllWithPagination() { - Item savedItemSpices = mongoTemplateService.add(itemSpices); - Item savedItemSnacks = mongoTemplateService.add(itemSnacks); + List items = mongoTemplateService.getAll(pageNumber, pageSize); - List items = mongoTemplateService.getAll(pageNumber, pageSize); + Assertions.assertTrue(items.size() > 0); - Assert.assertTrue(items.size() > 0); + mongoTemplateService.delete(savedItemSpices.getId()); + mongoTemplateService.delete(savedItemSnacks.getId()); - mongoTemplateService.delete(savedItemSpices.getId()); - mongoTemplateService.delete(savedItemSnacks.getId()); + } - } + @Test + void testDeleteItemById() { + Item savedItemSpices = mongoTemplateService.add(itemSpices); - @Test - void testDeleteItemById() { - Item savedItemSpices = mongoTemplateService.add(itemSpices); + boolean result = mongoTemplateService.delete(savedItemSpices.getId()); - boolean result = mongoTemplateService.delete(savedItemSpices.getId()); + Assertions.assertEquals(result, true); - Assert.assertEquals(result, true); + } - } + @Test + void testDeleteItem() { + Item savedItemSpices = mongoTemplateService.add(itemSpices); - @Test - void testDeleteItem() { - Item savedItemSpices = mongoTemplateService.add(itemSpices); + boolean result = mongoTemplateService.delete(savedItemSpices); - boolean result = mongoTemplateService.delete(savedItemSpices); + Assertions.assertEquals(result, true); - Assert.assertEquals(result, true); - - } + } } \ No newline at end of file diff --git a/spring-boot-mvc-thymeleaf/pom.xml b/spring-boot-mvc-thymeleaf/pom.xml new file mode 100644 index 0000000..5de9860 --- /dev/null +++ b/spring-boot-mvc-thymeleaf/pom.xml @@ -0,0 +1,39 @@ + + 4.0.0 + + com.howtodoinjava.demo + spring-boot-examples + 1.0-SNAPSHOT + + + spring-boot-mvc-thymeleaf + jar + spring-boot-mvc-thymeleaf + https://howtodoinjava.com + + + UTF-8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-devtools + + + diff --git a/spring-boot-mvc-thymeleaf/src/main/java/com/howtodoinjava/demo/config/WebMvcConfig.java b/spring-boot-mvc-thymeleaf/src/main/java/com/howtodoinjava/demo/config/WebMvcConfig.java new file mode 100644 index 0000000..929b3a3 --- /dev/null +++ b/spring-boot-mvc-thymeleaf/src/main/java/com/howtodoinjava/demo/config/WebMvcConfig.java @@ -0,0 +1,33 @@ +package com.howtodoinjava.demo.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +/*@EnableWebMvc +@Configuration +@ComponentScan(basePackages = { "com.howtodoinjava.demo.web" })*/ +public class WebMvcConfig /*implements WebMvcConfigurer*/ { + + /*@Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("index"); + } + + @Bean + public ViewResolver viewResolver() { + InternalResourceViewResolver bean = new InternalResourceViewResolver(); + + bean.setViewClass(JstlView.class); + bean.setPrefix("classpath:/templates/"); + bean.setSuffix(".html"); + + return bean; + }*/ +} diff --git a/spring-boot-mvc-thymeleaf/src/main/java/com/howtodoinjava/demo/dao/ItemRepository.java b/spring-boot-mvc-thymeleaf/src/main/java/com/howtodoinjava/demo/dao/ItemRepository.java new file mode 100644 index 0000000..d17afe2 --- /dev/null +++ b/spring-boot-mvc-thymeleaf/src/main/java/com/howtodoinjava/demo/dao/ItemRepository.java @@ -0,0 +1,9 @@ +package com.howtodoinjava.demo.dao; + +import com.howtodoinjava.demo.dao.model.Item; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ItemRepository extends CrudRepository { +} diff --git a/spring-boot-mvc-thymeleaf/src/main/java/com/howtodoinjava/demo/dao/model/Item.java b/spring-boot-mvc-thymeleaf/src/main/java/com/howtodoinjava/demo/dao/model/Item.java new file mode 100644 index 0000000..b26b5b2 --- /dev/null +++ b/spring-boot-mvc-thymeleaf/src/main/java/com/howtodoinjava/demo/dao/model/Item.java @@ -0,0 +1,18 @@ +package com.howtodoinjava.demo.dao.model; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@Entity +public class Item { + + @Id + long id; + String name; +} diff --git a/spring-boot-mvc-thymeleaf/src/main/java/com/howtodoinjava/demo/web/ItemController.java b/spring-boot-mvc-thymeleaf/src/main/java/com/howtodoinjava/demo/web/ItemController.java new file mode 100644 index 0000000..3fe4bec --- /dev/null +++ b/spring-boot-mvc-thymeleaf/src/main/java/com/howtodoinjava/demo/web/ItemController.java @@ -0,0 +1,38 @@ +package com.howtodoinjava.demo.web; + +import com.howtodoinjava.demo.dao.ItemRepository; +import com.howtodoinjava.demo.dao.model.Item; +import java.util.List; +import java.util.Optional; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Controller +@RequestMapping("/items") +public class ItemController { + + @Autowired + ItemRepository itemRepository; + + @GetMapping + String getAll(Model model) { + List items = (List) itemRepository.findAll(); + model.addAttribute("items", items); + return "items"; + } + + @GetMapping("/{id}") + String get(@PathVariable("id") long id, Model model) { + Optional item = itemRepository.findById(id); + if (item.isPresent()) { + model.addAttribute("item", item); + } + return "item-detail"; + } +} diff --git a/spring-boot-mvc-thymeleaf/src/main/resources/application.properties b/spring-boot-mvc-thymeleaf/src/main/resources/application.properties new file mode 100644 index 0000000..702c99e --- /dev/null +++ b/spring-boot-mvc-thymeleaf/src/main/resources/application.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + +spring.thymeleaf.prefix=classpath:/templates/ +spring.thymeleaf.suffix=.html +spring.thymeleaf.cache=false diff --git a/spring-boot-mvc-thymeleaf/src/main/resources/templates/index.html b/spring-boot-mvc-thymeleaf/src/main/resources/templates/index.html new file mode 100644 index 0000000..aa61dbd --- /dev/null +++ b/spring-boot-mvc-thymeleaf/src/main/resources/templates/index.html @@ -0,0 +1,17 @@ + + + + + +

Home

+

Show Items

+ + \ No newline at end of file diff --git a/spring-boot-mvc-thymeleaf/src/main/resources/templates/items.html b/spring-boot-mvc-thymeleaf/src/main/resources/templates/items.html new file mode 100644 index 0000000..79eccfb --- /dev/null +++ b/spring-boot-mvc-thymeleaf/src/main/resources/templates/items.html @@ -0,0 +1,35 @@ + + + + + +

Items List

+ + + + + + + +
Item IdItem Name
+ +
+ + \ No newline at end of file diff --git a/spring-data-dynamodb/src/test/java/com/howtodoinjava/demo/AppTests.java b/spring-boot-mvc-thymeleaf/src/test/java/com/howtodoinjava/demo/AppTest.java similarity index 73% rename from spring-data-dynamodb/src/test/java/com/howtodoinjava/demo/AppTests.java rename to spring-boot-mvc-thymeleaf/src/test/java/com/howtodoinjava/demo/AppTest.java index b2bdcc3..07e4c89 100644 --- a/spring-data-dynamodb/src/test/java/com/howtodoinjava/demo/AppTests.java +++ b/spring-boot-mvc-thymeleaf/src/test/java/com/howtodoinjava/demo/AppTest.java @@ -4,10 +4,10 @@ import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest -class AppTests { +public class AppTest { @Test - void contextLoads() throws Exception { - } + public void contextLoads() { + } } diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/.gitignore b/spring-boot-resilience4j/.gitignore similarity index 100% rename from spring-boot-keycloak-auth/Spring-Boot-API/.gitignore rename to spring-boot-resilience4j/.gitignore diff --git a/spring_boot_elastic-beanstalk-aws/.mvn/wrapper/maven-wrapper.jar b/spring-boot-resilience4j/.mvn/wrapper/maven-wrapper.jar similarity index 100% rename from spring_boot_elastic-beanstalk-aws/.mvn/wrapper/maven-wrapper.jar rename to spring-boot-resilience4j/.mvn/wrapper/maven-wrapper.jar diff --git a/spring_boot_elastic-beanstalk-aws/.mvn/wrapper/maven-wrapper.properties b/spring-boot-resilience4j/.mvn/wrapper/maven-wrapper.properties similarity index 100% rename from spring_boot_elastic-beanstalk-aws/.mvn/wrapper/maven-wrapper.properties rename to spring-boot-resilience4j/.mvn/wrapper/maven-wrapper.properties diff --git a/spring_boot_elastic-beanstalk-aws/mvnw b/spring-boot-resilience4j/mvnw old mode 100755 new mode 100644 similarity index 100% rename from spring_boot_elastic-beanstalk-aws/mvnw rename to spring-boot-resilience4j/mvnw diff --git a/spring_boot_elastic-beanstalk-aws/mvnw.cmd b/spring-boot-resilience4j/mvnw.cmd similarity index 100% rename from spring_boot_elastic-beanstalk-aws/mvnw.cmd rename to spring-boot-resilience4j/mvnw.cmd diff --git a/spring-boot-resilience4j/pom.xml b/spring-boot-resilience4j/pom.xml index 2061c8e..92432d7 100644 --- a/spring-boot-resilience4j/pom.xml +++ b/spring-boot-resilience4j/pom.xml @@ -1,26 +1,106 @@ + + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - com.howtodoinjava.demo - spring-boot-examples - 1.0-SNAPSHOT + org.springframework.boot + spring-boot-starter-parent + 3.0.0 + - - spring-boot-resilience4j - jar - - spring-boot-resilience4j - https://howtodoinjava.com - + com.howtodoinjava + resilience4j + 0.0.1-SNAPSHOT + resilience4j + Demo project for Spring Boot with Resilience4j - UTF-8 17 + 2022.0.1 - - + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-aop + + + io.github.resilience4j + resilience4j-spring-boot3 + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + provided + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + diff --git a/spring-boot-resilience4j/src/main/java/com/howtodoinjava/demo/App.java b/spring-boot-resilience4j/src/main/java/com/howtodoinjava/demo/App.java deleted file mode 100644 index d8250c0..0000000 --- a/spring-boot-resilience4j/src/main/java/com/howtodoinjava/demo/App.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.howtodoinjava.demo; - -/** - * Hello world! - * - */ -public class App -{ - public static void main( String[] args ) - { - System.out.println( "Hello World!" ); - } -} diff --git a/spring-boot-resilience4j/src/main/java/com/howtodoinjava/resilience4j/Resilience4jApplication.java b/spring-boot-resilience4j/src/main/java/com/howtodoinjava/resilience4j/Resilience4jApplication.java new file mode 100644 index 0000000..7d6be4f --- /dev/null +++ b/spring-boot-resilience4j/src/main/java/com/howtodoinjava/resilience4j/Resilience4jApplication.java @@ -0,0 +1,13 @@ +package com.howtodoinjava.resilience4j; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Resilience4jApplication { + + public static void main(String[] args) { + SpringApplication.run(Resilience4jApplication.class, args); + } + +} diff --git a/spring-boot-resilience4j/src/main/java/com/howtodoinjava/resilience4j/controller/StudentController.java b/spring-boot-resilience4j/src/main/java/com/howtodoinjava/resilience4j/controller/StudentController.java new file mode 100644 index 0000000..2e7091e --- /dev/null +++ b/spring-boot-resilience4j/src/main/java/com/howtodoinjava/resilience4j/controller/StudentController.java @@ -0,0 +1,55 @@ +package com.howtodoinjava.resilience4j.controller; + +import io.github.resilience4j.ratelimiter.RequestNotPermitted; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import io.github.resilience4j.bulkhead.annotation.Bulkhead; +import io.github.resilience4j.ratelimiter.annotation.RateLimiter; + +@RestController +public class StudentController { + + @GetMapping(value = "/student/{id}") + @RateLimiter(name = "rateLimitingAPI", fallbackMethod = "rateLimitingFallback") + public ResponseEntity getStudentById(@PathVariable int id) { + + return ResponseEntity.ok("Details requested for " + id); + } + + @GetMapping(value = "/course/{id}") + @Bulkhead(name = "courseBulkheadApi", fallbackMethod = "bulkheadFallback") + public ResponseEntity getCourse(@PathVariable int id) { + System.out.println("In course details for: " + id); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Returning course details for: " + id); + return ResponseEntity.ok("Course" + id); + } + + public ResponseEntity bulkheadFallback(int id, + io.github.resilience4j.bulkhead.BulkheadFullException ex) { + System.out.println("Bulkhead applied no further calls are accepted"); + + return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) + .body("Too many request - No further calls are accepted"); + } + + + public ResponseEntity rateLimitingFallback(int id, RequestNotPermitted ex) { + + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.set("Retry-After", "60s"); // retry after one second + + return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) + .headers(responseHeaders) // send retry header + .body("Too Many Requests - Retry After 1 Minute"); + } +} diff --git a/spring-boot-resilience4j/src/main/java/com/howtodoinjava/resilience4j/dto/Student.java b/spring-boot-resilience4j/src/main/java/com/howtodoinjava/resilience4j/dto/Student.java new file mode 100644 index 0000000..a10ae99 --- /dev/null +++ b/spring-boot-resilience4j/src/main/java/com/howtodoinjava/resilience4j/dto/Student.java @@ -0,0 +1,14 @@ +package com.howtodoinjava.resilience4j.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class Student { + + private int id; + private String name; +} diff --git a/spring-boot-resilience4j/src/main/resources/application.properties b/spring-boot-resilience4j/src/main/resources/application.properties new file mode 100644 index 0000000..a2ede69 --- /dev/null +++ b/spring-boot-resilience4j/src/main/resources/application.properties @@ -0,0 +1,21 @@ +management.endpoints.web.exposure.include=* +#management.endpoint.health.show-details=always + +#management.health.circuitbreakers.enabled=true +#management.health.ratelimiters.enabled=true +#resilience4j.circuitbreaker.configs.default.registerHealthIndicator=true +#resilience4j.ratelimiter.configs.instances.registerHealthIndicator=true + +# 5 concurrent calls allowed +resilience4j.bulkhead.instances.courseBulkheadApi.maxConcurrentCalls=5 +# Wait for 10ms before failing in case of limit breach +resilience4j.bulkhead.instances.courseBulkheadApi.maxWaitDuration=10ms + +# Time window of 60 seconds +resilience4j.ratelimiter.instances.studentRateLimiterApi.limitRefreshPeriod=60s +# 5 calls allowed +resilience4j.ratelimiter.instances.studentRateLimiterApi.limitForPeriod=5 +# Fail immediately without any delay +resilience4j.ratelimiter.instances.studentRateLimiterApi.timeoutDuration=0s +resilience4j.ratelimiter.instances.studentRateLimiterApi.registerHealthIndicator=true +resilience4j.ratelimiter.instances.studentRateLimiterApi.eventConsumerBufferSize=10 diff --git a/spring-boot-resilience4j/src/test/java/com/howtodoinjava/demo/AppTest.java b/spring-boot-resilience4j/src/test/java/com/howtodoinjava/demo/AppTest.java deleted file mode 100644 index d9608ca..0000000 --- a/spring-boot-resilience4j/src/test/java/com/howtodoinjava/demo/AppTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.howtodoinjava.demo; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} diff --git a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/test/java/com/howtodoinjava/app/EmployeeRestApiApplicationTests.java b/spring-boot-resilience4j/src/test/java/com/howtodoinjava/resilience4j/Resilience4jApplicationTests.java similarity index 51% rename from spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/test/java/com/howtodoinjava/app/EmployeeRestApiApplicationTests.java rename to spring-boot-resilience4j/src/test/java/com/howtodoinjava/resilience4j/Resilience4jApplicationTests.java index 732ee04..576852e 100644 --- a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/test/java/com/howtodoinjava/app/EmployeeRestApiApplicationTests.java +++ b/spring-boot-resilience4j/src/test/java/com/howtodoinjava/resilience4j/Resilience4jApplicationTests.java @@ -1,13 +1,13 @@ -package com.howtodoinjava.app; +package com.howtodoinjava.resilience4j; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest -class EmployeeRestApiApplicationTests { +class Resilience4jApplicationTests { - @Test - void contextLoads() { - } + @Test + void contextLoads() { + } } diff --git a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/EmployeeRestApiApplication.java b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/EmployeeRestApiApplication.java index ecee85a..6382a25 100644 --- a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/EmployeeRestApiApplication.java +++ b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/EmployeeRestApiApplication.java @@ -26,7 +26,7 @@ public static void main(String[] args) { @Override public void run(String... args) throws Exception { - employeeRepository.save(new Employee("hamza" , "0435645431" , "hamza.nassour13@gmail.com" , "SDE2")); - userRepository.save(new User("hamza", "nassour" ,"hamza.nassour13@gmail.com" ,"hamza123" , Role.ADMIN)); + employeeRepository.save(new Employee("hamza" , "0435645431" , "hamza.nassour13@gmail.com" , "SDE2")); + userRepository.save(new User("hamza", "nassour" ,"hamza.nassour13@gmail.com" ,"hamza123" , Role.ADMIN)); } } diff --git a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/entity/Employee.java b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/entity/Employee.java index 7344fd7..6b5e70f 100644 --- a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/entity/Employee.java +++ b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/entity/Employee.java @@ -20,17 +20,13 @@ public class Employee { private String phone; private String email; private String position; - @Column(length = 1000) private String bio; - - public Employee(String name, String phone, String email, String position) { this.name = name; this.phone = phone; this.email = email; this.position = position; } - } diff --git a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/config/SecurityConfig.java b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/config/SecurityConfig.java index fdb3964..eec14f8 100644 --- a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/config/SecurityConfig.java +++ b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/config/SecurityConfig.java @@ -1,6 +1,5 @@ package com.howtodoinjava.app.security.config; - import com.howtodoinjava.app.security.filter.JwtTokenFilter; import com.howtodoinjava.app.security.repo.UserRepository; import jakarta.servlet.http.HttpServletResponse; @@ -24,20 +23,24 @@ import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; - @EnableWebSecurity @Configuration -@RequiredArgsConstructor public class SecurityConfig { private final JwtTokenFilter jwtAuthenticationFilter; - private final UserDetailsService userDetailsService ; - - + private final UserDetailsService userDetailsService; + private final DaoAuthenticationProvider daoAuthenticationProvider; + + public SecurityConfig(JwtTokenFilter jwtAuthenticationFilter, + UserDetailsService userDetailsService, + DaoAuthenticationProvider daoAuthenticationProvider) { + this.jwtAuthenticationFilter = jwtAuthenticationFilter; + this.userDetailsService = userDetailsService; + this.daoAuthenticationProvider = daoAuthenticationProvider; + } @Bean public AuthenticationProvider authenticationProvider() { - DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setUserDetailsService(userDetailsService); daoAuthenticationProvider.setPasswordEncoder(passwordEncoder()); return daoAuthenticationProvider; @@ -58,23 +61,29 @@ AuthenticationManager authenticationManager( public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { httpSecurity.headers().frameOptions().disable(); - httpSecurity.csrf().disable(); - httpSecurity - .authorizeHttpRequests() - .requestMatchers("/api/auth/**").permitAll() - .anyRequest().authenticated() - .and() - .sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.STATELESS) - .and() - .exceptionHandling() - .authenticationEntryPoint(((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))) - .and() - .authenticationProvider(authenticationProvider()) - .addFilterBefore(jwtAuthenticationFilter , UsernamePasswordAuthenticationFilter.class); + httpSecurity.cors().and().csrf().disable(); + //@formatter:off + httpSecurity + .authorizeHttpRequests() + .requestMatchers("/api/auth/**").permitAll() + .anyRequest().authenticated() + .and() + .sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .exceptionHandling() + .authenticationEntryPoint( + (request, response, authException) + -> response.sendError( + HttpServletResponse.SC_UNAUTHORIZED, + authException.getLocalizedMessage() + ) + ) + .and() + .authenticationProvider(authenticationProvider()) + .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); + //@formatter:on return httpSecurity.build(); - } - } diff --git a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/entity/User.java b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/entity/User.java index e63a5ee..999eebc 100644 --- a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/entity/User.java +++ b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/entity/User.java @@ -27,7 +27,6 @@ public class User implements UserDetails { private String lastName; private String username; private String password; - @Enumerated(EnumType.STRING) private Role role; diff --git a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/filter/JwtTokenFilter.java b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/filter/JwtTokenFilter.java index 6e1661b..09bb56a 100644 --- a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/filter/JwtTokenFilter.java +++ b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/filter/JwtTokenFilter.java @@ -25,8 +25,7 @@ public class JwtTokenFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, - FilterChain filterChain) - throws ServletException, IOException { + FilterChain filterChain) throws ServletException, IOException { // Get the JWT token from the Authorization header String token = jwtTokenProvider.resolveToken(request); diff --git a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/service/CustomUserDetailsService.java b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/service/CustomUserDetailsService.java index 1679a44..b073c9d 100644 --- a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/service/CustomUserDetailsService.java +++ b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/service/CustomUserDetailsService.java @@ -9,19 +9,19 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; @Configuration -public class CustomUserDetailsService implements UserDetailsService { +public class CustomUserDetailsService implements UserDetailsService { - @Autowired - private UserRepository userRepository; + @Autowired + private UserRepository userRepository; - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - try { - return userRepository.findByUsername(username) - .orElseThrow(() -> new Exception("user Not found ")); - } catch (Exception e) { - throw new RuntimeException(e); - } + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + try { + return userRepository.findByUsername(username) + .orElseThrow(() -> new Exception("user Not found ")); + } catch (Exception e) { + throw new RuntimeException(e); } + } } \ No newline at end of file diff --git a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/utils/JwtTokenProvider.java b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/utils/JwtTokenProvider.java index 63cb2f7..24433ea 100644 --- a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/utils/JwtTokenProvider.java +++ b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/security/utils/JwtTokenProvider.java @@ -17,57 +17,56 @@ @Slf4j public class JwtTokenProvider { - Key key = Keys.secretKeyFor(SignatureAlgorithm.HS512); + Key key = Keys.secretKeyFor(SignatureAlgorithm.HS512); - public String createToken(Authentication authentication) { - UserDetails userDetails = (UserDetails) authentication.getPrincipal(); - Date now = new Date(); - Date expiryDate = new Date(now.getTime() + 3600000); - - return Jwts.builder() - .setSubject(userDetails.getUsername()) - .setIssuedAt(new Date()) - .setExpiration(expiryDate) - .signWith(SignatureAlgorithm.HS512, key) - .compact(); - } + public String createToken(Authentication authentication) { + UserDetails userDetails = (UserDetails) authentication.getPrincipal(); + Date now = new Date(); + Date expiryDate = new Date(now.getTime() + 3600000); + return Jwts.builder() + .setSubject(userDetails.getUsername()) + .setIssuedAt(new Date()) + .setExpiration(expiryDate) + .signWith(SignatureAlgorithm.HS512, key) + .compact(); + } - public String resolveToken(HttpServletRequest request) { - String bearerToken = request.getHeader("Authorization"); - if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { - return bearerToken.substring(7); - } - return null; + public String resolveToken(HttpServletRequest request) { + String bearerToken = request.getHeader("Authorization"); + if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { + return bearerToken.substring(7); } + return null; + } - public boolean validateToken(String token) { - // Check if the token is valid and not expired - try { - Jwts.parser().setSigningKey(key).parseClaimsJws(token); - return true; - } catch (MalformedJwtException ex) { - log.error("Invalid JWT token"); - } catch (ExpiredJwtException ex) { - log.error("Expired JWT token"); - } catch (UnsupportedJwtException ex) { - log.error("Unsupported JWT token"); - } catch (IllegalArgumentException ex) { - log.error("JWT claims string is empty"); - }catch (SignatureException e){ - log.error("there is an error with the signature of you token "); - } - return false; + public boolean validateToken(String token) { + // Check if the token is valid and not expired + try { + Jwts.parser().setSigningKey(key).parseClaimsJws(token); + return true; + } catch (MalformedJwtException ex) { + log.error("Invalid JWT token"); + } catch (ExpiredJwtException ex) { + log.error("Expired JWT token"); + } catch (UnsupportedJwtException ex) { + log.error("Unsupported JWT token"); + } catch (IllegalArgumentException ex) { + log.error("JWT claims string is empty"); + } catch (SignatureException e) { + log.error("there is an error with the signature of you token "); } + return false; + } - public String getUsername(String token) { - // Extract the username from the JWT token - return Jwts.parser() - .setSigningKey(key) - .parseClaimsJws(token) - .getBody() - .getSubject(); - } + public String getUsername(String token) { + // Extract the username from the JWT token + return Jwts.parser() + .setSigningKey(key) + .parseClaimsJws(token) + .getBody() + .getSubject(); + } } \ No newline at end of file diff --git a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/service/EmployeeService.java b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/service/EmployeeService.java index 9a1eefe..2a7480c 100644 --- a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/service/EmployeeService.java +++ b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/service/EmployeeService.java @@ -27,8 +27,10 @@ public Employee addEmployee(Employee employee) { } public Optional updateEmployee(Long id, Employee employee) { + Optional existingEmployee = employeeRepository.findById(id); if (existingEmployee.isPresent()) { + Employee updatedEmployee = existingEmployee.get(); updatedEmployee.setName(employee.getName()); updatedEmployee.setPhone(employee.getPhone()); diff --git a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/web/AuthController.java b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/web/AuthController.java index 47045b5..73078f7 100644 --- a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/web/AuthController.java +++ b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/java/com/howtodoinjava/app/web/AuthController.java @@ -30,7 +30,6 @@ public ResponseEntity authenticateUser( authenticationRequest.getPassword()) ); - SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = jwtTokenProvider.createToken(authentication); return ResponseEntity.ok(new AuthenticationResponse(jwt)); diff --git a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/resources/application.properties b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/resources/application.properties index 21ef0c8..da366a1 100644 --- a/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/resources/application.properties +++ b/spring-boot-vuejs-jwt-auth/Spring-Boot-API/src/main/resources/application.properties @@ -7,5 +7,4 @@ spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.h2.console.enabled=true - spring.main.allow-circular-references=true diff --git a/spring-boot-xml-request-response/README.md b/spring-boot-xml-request-response/README.md new file mode 100644 index 0000000..9e99cbc --- /dev/null +++ b/spring-boot-xml-request-response/README.md @@ -0,0 +1,3 @@ +# Related Tutorials + +1. [Spring Boot REST – Handling XML Request and Response](https://howtodoinjava.com/spring-boot/xml-request-response-body/) \ No newline at end of file diff --git a/spring-boot-xml-request-response/pom.xml b/spring-boot-xml-request-response/pom.xml new file mode 100644 index 0000000..4178ebd --- /dev/null +++ b/spring-boot-xml-request-response/pom.xml @@ -0,0 +1,31 @@ + + 4.0.0 + + com.howtodoinjava.demo + spring-boot-examples + 1.0-SNAPSHOT + + + spring-boot-xml-request-response + jar + + spring-boot-xml-request-response + https://howtodoinjava.com + + + UTF-8 + + + + + + org.glassfish.jaxb + jaxb-runtime + + + diff --git a/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/App.java b/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/App.java new file mode 100644 index 0000000..c8b0a9e --- /dev/null +++ b/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/App.java @@ -0,0 +1,20 @@ +package com.howtodoinjava.demo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.http.MediaType; +import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@SpringBootApplication +public class App implements WebMvcConfigurer { + + public static void main(String[] args) { + SpringApplication.run(App.class, args); + } + + @Override + public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { + configurer.defaultContentType(MediaType.APPLICATION_XML); + } +} diff --git a/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/model/Item.java b/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/model/Item.java new file mode 100644 index 0000000..f185228 --- /dev/null +++ b/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/model/Item.java @@ -0,0 +1,20 @@ +package com.howtodoinjava.demo.model; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlRootElement; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +/*@JacksonXmlRootElement(localName = "item")*/ +@XmlRootElement(name = "item") +@XmlAccessorType(XmlAccessType.FIELD) +public class Item { + + private Long id; + private String name; +} diff --git a/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/model/Items.java b/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/model/Items.java new file mode 100644 index 0000000..dcde671 --- /dev/null +++ b/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/model/Items.java @@ -0,0 +1,24 @@ +package com.howtodoinjava.demo.model; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import java.util.List; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +/*@JacksonXmlRootElement(localName = "items")*/ +@XmlRootElement(name = "items") +@XmlAccessorType(XmlAccessType.FIELD) +public class Items { + + /*@JacksonXmlElementWrapper(useWrapping = false) + @JacksonXmlProperty(localName = "item")*/ + @XmlElement(name = "item") + List items; +} diff --git a/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/model/Record.java b/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/model/Record.java new file mode 100644 index 0000000..212f13c --- /dev/null +++ b/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/model/Record.java @@ -0,0 +1,28 @@ +package com.howtodoinjava.demo.model; + +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlElementWrapper; +import jakarta.xml.bind.annotation.XmlRootElement; +import java.util.List; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +/*@JacksonXmlRootElement(localName = "record")*/ +@XmlRootElement(name = "record") +@XmlAccessorType(XmlAccessType.FIELD) +public class Record { + + private Long id; + + /* @JacksonXmlElementWrapper(localName = "items") + @JacksonXmlProperty(localName = "item")*/ + @XmlElementWrapper(name = "items") + @XmlElement(name = "item") + List items; +} diff --git a/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/web/ItemController.java b/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/web/ItemController.java new file mode 100644 index 0000000..6057154 --- /dev/null +++ b/spring-boot-xml-request-response/src/main/java/com/howtodoinjava/demo/web/ItemController.java @@ -0,0 +1,39 @@ +package com.howtodoinjava.demo.web; + +import com.howtodoinjava.demo.model.Item; +import com.howtodoinjava.demo.model.Items; +import com.howtodoinjava.demo.model.Record; +import java.util.List; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/items") +public class ItemController { + + @GetMapping + public Items getItems(){ + return new Items(List.of(new Item(1L, "Item1"), new Item(2L, "Item2"))); + } + + @GetMapping("/record") + public Record getItemsAsRecord(){ + return new Record(1L, List.of(new Item(1L, "Item1"), new Item(2L, "Item2"))); + } + + @GetMapping("/{id}") + public Item getItemById(@PathVariable("id") Long id){ + return new Item(id, "temp-item"); + } + + @PostMapping + public Item createItem(@RequestBody Item item){ + return item; + } +} diff --git a/spring-boot-xml-request-response/src/test/java/com/howtodoinjava/demo/AppTest.java b/spring-boot-xml-request-response/src/test/java/com/howtodoinjava/demo/AppTest.java new file mode 100644 index 0000000..5990bae --- /dev/null +++ b/spring-boot-xml-request-response/src/test/java/com/howtodoinjava/demo/AppTest.java @@ -0,0 +1,10 @@ +package com.howtodoinjava.demo; + +import org.junit.jupiter.api.Test; + +public class AppTest +{ + @Test + void loadsContext(){ + } +} diff --git a/spring-data-dynamodb/pom.xml b/spring-data-dynamodb/pom.xml index 43176ab..67119ab 100644 --- a/spring-data-dynamodb/pom.xml +++ b/spring-data-dynamodb/pom.xml @@ -29,10 +29,14 @@ org.springframework.boot spring-boot-starter-web
+ + org.springframework.boot + spring-boot-starter-data-jpa + com.amazonaws aws-java-sdk-dynamodb - 1.12.423 + 1.12.429 io.github.boostchicken @@ -50,11 +54,6 @@ lombok true - - org.springframework.boot - spring-boot-starter-test - test - diff --git a/spring-deploy-docker-image-to-aws/README.md b/spring-deploy-docker-image-to-aws/README.md index a444760..df0178d 100644 --- a/spring-deploy-docker-image-to-aws/README.md +++ b/spring-deploy-docker-image-to-aws/README.md @@ -1,8 +1,21 @@ # Deploy a Spring Boot App on AWS ECS Cluster - 1. Create a Dockerfile for your Spring Boot application that specifies the base image, dependencies, and application code. - 2. Build a Docker image of your Spring Boot application using the Docker CLI. - 3. Tag the Docker image with the name of your ECR repository and push the Docker image to your ECR repository using the AWS CLI. - 4. Create an ECS task definition that defines the Docker container for your Spring Boot application, including the Docker image name and the required CPU and memory resources. +* Create a Dockerfile for the Spring Boot application that specifies the base image, dependencies, and application code. +* Build a Docker image of the Spring Boot application using the Docker CLI. + +``` +docker build -t my-application . +``` - 5. Create an ECS service that runs your ECS task definition, specifying the desired number of tasks and the load balancer configuration for distributing traffic to the tasks. - 6. Test your Spring Boot application by accessing the application deployed on the ECS service. \ No newline at end of file +* Tag the Docker image with the name of the ECR repository and push the Docker image to ECR repository using the AWS CLI. + +``` +aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 644805545910.dkr.ecr.us-east-1.amazonaws.com + +docker tag my-application:latest 644805545910.dkr.ecr.us-east-1.amazonaws.com/howtodoinjava:latest + +docker push 644805545910.dkr.ecr.us-east-1.amazonaws.com/howtodoinjava:latest +``` + +* Create an ECS task definition that defines the Docker container for your Spring Boot application, including the Docker image name and the required CPU and memory resources. +* Create an ECS service that runs your ECS task definition, specifying the desired number of tasks and the load balancer configuration for distributing traffic to the tasks. +* Test your Spring Boot application by accessing the application deployed on the ECS service. \ No newline at end of file diff --git a/spring-deploy-docker-image-to-aws/pom.xml b/spring-deploy-docker-image-to-aws/pom.xml index 447e909..029cbb8 100644 --- a/spring-deploy-docker-image-to-aws/pom.xml +++ b/spring-deploy-docker-image-to-aws/pom.xml @@ -1,40 +1,19 @@ - - 4.0.0 - - spring-boot-examples - com.howtodoinjava.demo - 1.0-SNAPSHOT - - com.example - AWSDockerDeploy - 0.0.1-SNAPSHOT - AWSDockerDeploy - AWSDockerDeploy - - 1.8 - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - + + 4.0.0 + + spring-boot-examples + com.howtodoinjava.demo + 1.0-SNAPSHOT + + com.example + AWSDockerDeploy + 0.0.1-SNAPSHOT + AWSDockerDeploy + AWSDockerDeploy + + 17 + diff --git a/spring-deploy-docker-image-to-aws/src/main/java/com/example/awsdockerdeploy/api/HomeController.java b/spring-deploy-docker-image-to-aws/src/main/java/com/example/awsdockerdeploy/api/HomeController.java index 9a358b5..b6a4edf 100644 --- a/spring-deploy-docker-image-to-aws/src/main/java/com/example/awsdockerdeploy/api/HomeController.java +++ b/spring-deploy-docker-image-to-aws/src/main/java/com/example/awsdockerdeploy/api/HomeController.java @@ -5,9 +5,10 @@ @RestController public class HomeController { - @GetMapping("/home") - public String hello(){ - return "Project running successfully " ; - } + + @GetMapping("/home") + public String hello() { + return "Project running successfully "; + } } diff --git a/spring-react-file-upload/SpringBootFileUploadApplication/pom.xml b/spring-react-file-upload/SpringBootFileUploadApplication/pom.xml index 0aff75f..680af3d 100644 --- a/spring-react-file-upload/SpringBootFileUploadApplication/pom.xml +++ b/spring-react-file-upload/SpringBootFileUploadApplication/pom.xml @@ -9,6 +9,7 @@ 2.7.5 + war com.rest.demo SpringBootFileUploadApplication 0.0.1-SNAPSHOT @@ -40,7 +41,7 @@ mysql mysql-connector-java - 5.1.41 + 8.0.32 @@ -51,6 +52,4 @@ - - war diff --git a/spring_boot_elastic-beanstalk-aws/.elasticbeanstalk/config.yml b/spring_boot_elastic-beanstalk-aws/.elasticbeanstalk/config.yml new file mode 100644 index 0000000..8032eb5 --- /dev/null +++ b/spring_boot_elastic-beanstalk-aws/.elasticbeanstalk/config.yml @@ -0,0 +1,24 @@ +branch-defaults: + default: + environment: spring-boot-app-qa-env + group_suffix: null +deploy: + artifact: target/spring_boot_elastic-beanstalk-aws.jar +global: + application_name: spring_boot_elastic-beanstalk-aws + branch: null + default_ec2_keyname: eb-howtodoinjava + default_platform: Corretto 17 running on 64bit Amazon Linux 2 + default_region: us-east-1 + include_git_submodules: true + instance_profile: null + platform_name: null + platform_version: null + profile: eb-cli + repository: null + sc: null + workspace_type: Application +option_settings: + aws:autoscaling:asg: + MinSize: '2' + MaxSize: '4' diff --git a/spring_boot_elastic-beanstalk-aws/.gitignore b/spring_boot_elastic-beanstalk-aws/.gitignore index e2aa7a6..549e00a 100644 --- a/spring_boot_elastic-beanstalk-aws/.gitignore +++ b/spring_boot_elastic-beanstalk-aws/.gitignore @@ -31,8 +31,3 @@ build/ ### VS Code ### .vscode/ - -# Elastic Beanstalk Files -.elasticbeanstalk/* -!.elasticbeanstalk/*.cfg.yml -!.elasticbeanstalk/*.global.yml diff --git a/spring_boot_elastic-beanstalk-aws/pom.xml b/spring_boot_elastic-beanstalk-aws/pom.xml index 40d56e8..e4aed46 100644 --- a/spring_boot_elastic-beanstalk-aws/pom.xml +++ b/spring_boot_elastic-beanstalk-aws/pom.xml @@ -1,63 +1,64 @@ - - 4.0.0 - + + 4.0.0 + + spring-boot-examples + com.howtodoinjava.demo + 1.0-SNAPSHOT + + com.example + spring_boot_elastic-beanstalk-aws + 0.0.1-SNAPSHOT + spring_boot_elastic-beanstalk-aws + spring_boot_elastic-beanstalk-aws + + 17 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.postgresql + postgresql + runtime + + + com.h2database + h2 + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.springframework.boot - spring-boot-starter-parent - 3.0.6 - - - com.example - spring_boot_elastic-beanstalk-aws - 0.0.1-SNAPSHOT - spring_boot_elastic-beanstalk-aws - spring_boot_elastic-beanstalk-aws - - 17 - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-web - - - - org.postgresql - postgresql - runtime - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.projectlombok - lombok - - - - - - - + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + diff --git a/spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/SpringBootElasticBeanstalkAwsApplication.java b/spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/SpringBootElasticBeanstalkAwsApplication.java deleted file mode 100644 index 2d40d2d..0000000 --- a/spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/SpringBootElasticBeanstalkAwsApplication.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.example.spring_boot_elasticbeanstalkaws; - -import com.example.spring_boot_elasticbeanstalkaws.entity.Employee; -import com.example.spring_boot_elasticbeanstalkaws.repo.EmployeeRepo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class SpringBootElasticBeanstalkAwsApplication implements CommandLineRunner { - - @Autowired - private EmployeeRepo employeeRepo ; - - public static void main(String[] args) { - SpringApplication.run(SpringBootElasticBeanstalkAwsApplication.class, args); - } - - @Override - public void run(String... args) throws Exception { - - for (int i =0 ; i<10 ; i++){ - employeeRepo.save(new Employee(null , "employee"+i , "java Developer")) ; - } - - } -} diff --git a/spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/service/EmployeeService.java b/spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/service/EmployeeService.java deleted file mode 100644 index 2211b25..0000000 --- a/spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/service/EmployeeService.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.example.spring_boot_elasticbeanstalkaws.service; - -import com.example.spring_boot_elasticbeanstalkaws.entity.Employee; -import com.example.spring_boot_elasticbeanstalkaws.repo.EmployeeRepo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.List; - - -@Service -public class EmployeeService { - @Autowired - private EmployeeRepo employeeRepository; - - public List getAllEmployees() { - return employeeRepository.findAll(); - } -} diff --git a/spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/web/EmployeeController.java b/spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/web/EmployeeController.java deleted file mode 100644 index 51b3023..0000000 --- a/spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/web/EmployeeController.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.example.spring_boot_elasticbeanstalkaws.web; - -import com.example.spring_boot_elasticbeanstalkaws.entity.Employee; -import com.example.spring_boot_elasticbeanstalkaws.service.EmployeeService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.List; - -@RestController -public class EmployeeController { - - @Autowired - private EmployeeService employeeService ; - - @GetMapping("/employees") - public ResponseEntity> getAllEmployees(){ - - return ResponseEntity.ok().body( employeeService.getAllEmployees()); - } -} diff --git a/spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/SpringBootElasticBeanstalkAwsApplication.java b/spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/SpringBootElasticBeanstalkAwsApplication.java new file mode 100644 index 0000000..3db84aa --- /dev/null +++ b/spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/SpringBootElasticBeanstalkAwsApplication.java @@ -0,0 +1,28 @@ +package com.howtodoinjava.app; + +import com.howtodoinjava.app.entity.Employee; +import com.howtodoinjava.app.repo.EmployeeRepo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootElasticBeanstalkAwsApplication implements CommandLineRunner { + + @Autowired + private EmployeeRepo employeeRepo; + + public static void main(String[] args) { + SpringApplication.run(SpringBootElasticBeanstalkAwsApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + + for (int i = 0; i < 10; i++) { + employeeRepo.save(new Employee(null, "employee" + i, "java Developer")); + } + + } +} diff --git a/spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/entity/Employee.java b/spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/entity/Employee.java similarity index 89% rename from spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/entity/Employee.java rename to spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/entity/Employee.java index fa68348..3075e7a 100644 --- a/spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/entity/Employee.java +++ b/spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/entity/Employee.java @@ -1,4 +1,4 @@ -package com.example.spring_boot_elasticbeanstalkaws.entity; +package com.howtodoinjava.app.entity; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/repo/EmployeeRepo.java b/spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/repo/EmployeeRepo.java similarity index 61% rename from spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/repo/EmployeeRepo.java rename to spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/repo/EmployeeRepo.java index 8fff616..d0aac5c 100644 --- a/spring_boot_elastic-beanstalk-aws/src/main/java/com/example/spring_boot_elasticbeanstalkaws/repo/EmployeeRepo.java +++ b/spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/repo/EmployeeRepo.java @@ -1,6 +1,6 @@ -package com.example.spring_boot_elasticbeanstalkaws.repo; +package com.howtodoinjava.app.repo; -import com.example.spring_boot_elasticbeanstalkaws.entity.Employee; +import com.howtodoinjava.app.entity.Employee; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; diff --git a/spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/service/EmployeeService.java b/spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/service/EmployeeService.java new file mode 100644 index 0000000..29a432d --- /dev/null +++ b/spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/service/EmployeeService.java @@ -0,0 +1,19 @@ +package com.howtodoinjava.app.service; + +import com.howtodoinjava.app.entity.Employee; +import com.howtodoinjava.app.repo.EmployeeRepo; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + + +@Service +public class EmployeeService { + + @Autowired + private EmployeeRepo employeeRepository; + + public List getAllEmployees() { + return employeeRepository.findAll(); + } +} diff --git a/spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/web/EmployeeController.java b/spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/web/EmployeeController.java new file mode 100644 index 0000000..409316a --- /dev/null +++ b/spring_boot_elastic-beanstalk-aws/src/main/java/com/howtodoinjava/app/web/EmployeeController.java @@ -0,0 +1,22 @@ +package com.howtodoinjava.app.web; + +import com.howtodoinjava.app.entity.Employee; +import com.howtodoinjava.app.service.EmployeeService; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class EmployeeController { + + @Autowired + private EmployeeService employeeService; + + @GetMapping("/employees") + public ResponseEntity> getAllEmployees() { + + return ResponseEntity.ok().body(employeeService.getAllEmployees()); + } +} diff --git a/spring_boot_elastic-beanstalk-aws/src/main/resources/application-dev.properties b/spring_boot_elastic-beanstalk-aws/src/main/resources/application-dev.properties new file mode 100644 index 0000000..fa97eef --- /dev/null +++ b/spring_boot_elastic-beanstalk-aws/src/main/resources/application-dev.properties @@ -0,0 +1,5 @@ +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/spring_boot_elastic-beanstalk-aws/src/main/resources/application-prod.properties b/spring_boot_elastic-beanstalk-aws/src/main/resources/application-prod.properties new file mode 100644 index 0000000..7e11d81 --- /dev/null +++ b/spring_boot_elastic-beanstalk-aws/src/main/resources/application-prod.properties @@ -0,0 +1,6 @@ +spring.datasource.url=jdbc:postgresql://database-1.cyajlbwfvrqi.us-east-1.rds.amazonaws.com:5432/howtodoinjava +spring.datasource.username=postgres +spring.datasource.password=Hnas2018 +spring.datasource.driver-class-name=org.postgresql.Driver +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.hibernate.ddl-auto=create \ No newline at end of file diff --git a/spring_boot_elastic-beanstalk-aws/src/main/resources/application.properties b/spring_boot_elastic-beanstalk-aws/src/main/resources/application.properties index 7e11d81..257b306 100644 --- a/spring_boot_elastic-beanstalk-aws/src/main/resources/application.properties +++ b/spring_boot_elastic-beanstalk-aws/src/main/resources/application.properties @@ -1,6 +1 @@ -spring.datasource.url=jdbc:postgresql://database-1.cyajlbwfvrqi.us-east-1.rds.amazonaws.com:5432/howtodoinjava -spring.datasource.username=postgres -spring.datasource.password=Hnas2018 -spring.datasource.driver-class-name=org.postgresql.Driver -spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect -spring.jpa.hibernate.ddl-auto=create \ No newline at end of file +spring.profiles.active=dev \ No newline at end of file diff --git a/spring_boot_elastic-beanstalk-aws/src/test/java/com/example/spring_boot_elasticbeanstalkaws/SpringBootElasticBeanstalkAwsApplicationTests.java b/spring_boot_elastic-beanstalk-aws/src/test/java/com/example/spring_boot_elasticbeanstalkaws/SpringBootElasticBeanstalkAwsApplicationTests.java deleted file mode 100644 index 3ffe2d6..0000000 --- a/spring_boot_elastic-beanstalk-aws/src/test/java/com/example/spring_boot_elasticbeanstalkaws/SpringBootElasticBeanstalkAwsApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.example.spring_boot_elasticbeanstalkaws; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class SpringBootElasticBeanstalkAwsApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/spring-boot-keycloak-auth/Spring-Boot-API/src/test/java/com/howtodoinjava/app/EmployeeRestApiApplicationTests.java b/spring_boot_elastic-beanstalk-aws/src/test/java/com/howtodoinjava/app/SpringBootElasticBeanstalkAwsApplicationTests.java similarity index 63% rename from spring-boot-keycloak-auth/Spring-Boot-API/src/test/java/com/howtodoinjava/app/EmployeeRestApiApplicationTests.java rename to spring_boot_elastic-beanstalk-aws/src/test/java/com/howtodoinjava/app/SpringBootElasticBeanstalkAwsApplicationTests.java index 732ee04..e1dd25c 100644 --- a/spring-boot-keycloak-auth/Spring-Boot-API/src/test/java/com/howtodoinjava/app/EmployeeRestApiApplicationTests.java +++ b/spring_boot_elastic-beanstalk-aws/src/test/java/com/howtodoinjava/app/SpringBootElasticBeanstalkAwsApplicationTests.java @@ -1,13 +1,14 @@ package com.howtodoinjava.app; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest -class EmployeeRestApiApplicationTests { +class SpringBootElasticBeanstalkAwsApplicationTests { + @Disabled @Test void contextLoads() { } - }