├── 01-hello-world-rest-api ├── pom.xml ├── readme.md └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── in28minutes │ │ │ └── rest │ │ │ └── webservices │ │ │ └── restfulwebservices │ │ │ ├── HelloWorldBean.java │ │ │ ├── HelloWorldController.java │ │ │ └── RestfulWebServicesApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── in28minutes │ └── rest │ └── webservices │ └── restfulwebservices │ └── RestfulWebServicesApplicationTests.java ├── 02-todo-web-application-h2 ├── Dockerfile ├── pom.xml ├── readme.md └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── in28minutes │ │ │ └── springboot │ │ │ └── web │ │ │ ├── EnvironmentConfigurationLogger.java │ │ │ ├── SpringBootFirstWebApplication.java │ │ │ ├── controller │ │ │ ├── ErrorController.java │ │ │ ├── LogoutController.java │ │ │ ├── TodoController.java │ │ │ └── WelcomeController.java │ │ │ ├── model │ │ │ └── Todo.java │ │ │ ├── security │ │ │ └── SecurityConfiguration.java │ │ │ └── service │ │ │ └── TodoRepository.java │ ├── resources │ │ ├── application.properties │ │ └── data.sql │ └── webapp │ │ └── WEB-INF │ │ └── jsp │ │ ├── common │ │ ├── footer.jspf │ │ ├── header.jspf │ │ └── navigation.jspf │ │ ├── error.jsp │ │ ├── list-todos.jsp │ │ ├── todo.jsp │ │ └── welcome.jsp │ └── test │ └── java │ └── com │ └── in28minutes │ └── springboot │ └── web │ └── SpringBootFirstWebApplicationTests.java ├── 03-todo-web-application-mysql ├── pom.xml ├── readme.md └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── in28minutes │ │ │ └── springboot │ │ │ └── web │ │ │ ├── EnvironmentConfigurationLogger.java │ │ │ ├── SpringBootFirstWebApplication.java │ │ │ ├── controller │ │ │ ├── ErrorController.java │ │ │ ├── LogoutController.java │ │ │ ├── TodoController.java │ │ │ └── WelcomeController.java │ │ │ ├── model │ │ │ └── Todo.java │ │ │ ├── security │ │ │ └── SecurityConfiguration.java │ │ │ └── service │ │ │ ├── TodoRepository.java │ │ │ └── TodoService.java │ ├── resources │ │ └── application.properties │ └── webapp │ │ └── WEB-INF │ │ └── jsp │ │ ├── common │ │ ├── footer.jspf │ │ ├── header.jspf │ │ └── navigation.jspf │ │ ├── error.jsp │ │ ├── list-todos.jsp │ │ ├── todo.jsp │ │ └── welcome.jsp │ └── test │ ├── java │ └── com │ │ └── in28minutes │ │ └── springboot │ │ └── web │ │ └── SpringBootFirstWebApplicationTests.java │ └── resources │ └── application.properties ├── 04-spring-boot-react-full-stack-h2 ├── frontend │ └── todo-app │ │ ├── Dockerfile │ │ ├── build │ │ ├── .azure │ │ │ └── config │ │ ├── asset-manifest.json │ │ ├── favicon.ico │ │ ├── index.html │ │ ├── manifest.json │ │ ├── precache-manifest.761a421da099d8debfc4c14fcfc2a75b.js │ │ ├── service-worker.js │ │ └── static │ │ │ ├── css │ │ │ ├── main.e593cbc2.chunk.css │ │ │ └── main.e593cbc2.chunk.css.map │ │ │ └── js │ │ │ ├── 2.3f64e426.chunk.js │ │ │ ├── 2.3f64e426.chunk.js.map │ │ │ ├── main.dec38524.chunk.js │ │ │ ├── main.dec38524.chunk.js.map │ │ │ ├── runtime~main.c5541365.js │ │ │ └── runtime~main.c5541365.js.map │ │ ├── package-lock.json │ │ ├── package.json │ │ ├── public │ │ ├── favicon.ico │ │ ├── index.html │ │ └── manifest.json │ │ └── src │ │ ├── App.css │ │ ├── App.js │ │ ├── App.test.js │ │ ├── Constants.js │ │ ├── api │ │ └── todo │ │ │ ├── HelloWorldService.js │ │ │ └── TodoDataService.js │ │ ├── bootstrap.css │ │ ├── components │ │ ├── counter │ │ │ ├── Counter.css │ │ │ └── Counter.jsx │ │ ├── learning-examples │ │ │ ├── FirstComponent.jsx │ │ │ ├── SecondComponent.jsx │ │ │ └── ThirdComponent.jsx │ │ └── todo │ │ │ ├── AuthenticatedRoute.jsx │ │ │ ├── AuthenticationService.js │ │ │ ├── ErrorComponent.jsx │ │ │ ├── FooterComponent.jsx │ │ │ ├── HeaderComponent.jsx │ │ │ ├── ListTodosComponent.jsx │ │ │ ├── LoginComponent.jsx │ │ │ ├── LogoutComponent.jsx │ │ │ ├── TodoApp.jsx │ │ │ ├── TodoComponent.jsx │ │ │ └── WelcomeComponent.jsx │ │ ├── index.css │ │ ├── index.js │ │ ├── logo.svg │ │ ├── serviceWorker.js │ │ └── web.config └── restful-web-services │ ├── pom.xml │ ├── react_00_architecture.png │ ├── readme.md │ └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── in28minutes │ │ │ └── rest │ │ │ ├── basic │ │ │ └── auth │ │ │ │ ├── AuthenticationBean.java │ │ │ │ ├── BasicAuthenticationController.java │ │ │ │ └── SpringSecurityConfigurationBasicAuth.java │ │ │ └── webservices │ │ │ └── restfulwebservices │ │ │ ├── RestfulWebServicesApplication.java │ │ │ ├── helloworld │ │ │ ├── HelloWorldBean.java │ │ │ └── HelloWorldController.java │ │ │ ├── jwt │ │ │ ├── JWTWebSecurityConfig.java │ │ │ ├── JwtInMemoryUserDetailsService.java │ │ │ ├── JwtTokenAuthorizationOncePerRequestFilter.java │ │ │ ├── JwtTokenUtil.java │ │ │ ├── JwtUnAuthorizedResponseAuthenticationEntryPoint.java │ │ │ ├── JwtUserDetails.java │ │ │ ├── JwtUserDetailsService.java │ │ │ ├── User.java │ │ │ ├── UserRepository.java │ │ │ └── resource │ │ │ │ ├── AuthenticationException.java │ │ │ │ ├── JwtAuthenticationRestController.java │ │ │ │ ├── JwtTokenRequest.java │ │ │ │ └── JwtTokenResponse.java │ │ │ └── todo │ │ │ ├── Todo.java │ │ │ ├── TodoJpaRepository.java │ │ │ └── TodoJpaResource.java │ └── resources │ │ ├── application.properties │ │ └── data.sql │ └── test │ └── java │ └── com │ └── in28minutes │ └── rest │ └── webservices │ └── restfulwebservices │ └── RestfulWebServicesApplicationTests.java ├── 05-todo-rest-api-h2-containerized ├── Dockerfile ├── pom.xml ├── readme.md └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── in28minutes │ │ │ └── rest │ │ │ └── webservices │ │ │ └── restfulwebservices │ │ │ ├── RestfulWebServicesApplication.java │ │ │ ├── helloworld │ │ │ ├── HelloWorldBean.java │ │ │ └── HelloWorldController.java │ │ │ └── todo │ │ │ ├── Todo.java │ │ │ ├── TodoJpaRepository.java │ │ │ └── TodoJpaResource.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── in28minutes │ └── rest │ └── webservices │ └── restfulwebservices │ └── RestfulWebServicesApplicationTests.java ├── 06-todo-rest-api-mysql-containerized ├── .ebextensions │ └── sg-extensions.config ├── Dockerfile ├── docker-compose.yaml ├── pom.xml ├── readme.md └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── in28minutes │ │ │ └── rest │ │ │ └── webservices │ │ │ └── restfulwebservices │ │ │ ├── RestfulWebServicesApplication.java │ │ │ ├── helloworld │ │ │ ├── HelloWorldBean.java │ │ │ └── HelloWorldController.java │ │ │ └── todo │ │ │ ├── Todo.java │ │ │ ├── TodoJpaRepository.java │ │ │ └── TodoJpaResource.java │ └── resources │ │ └── application.properties │ └── test │ ├── java │ └── com │ │ └── in28minutes │ │ └── rest │ │ └── webservices │ │ └── restfulwebservices │ │ └── RestfulWebServicesApplicationTests.java │ └── resources │ └── application.properties ├── 07-hello-world-rest-api ├── pom.xml ├── readme.md └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── in28minutes │ │ │ └── rest │ │ │ └── webservices │ │ │ └── restfulwebservices │ │ │ ├── HelloWorldBean.java │ │ │ ├── HelloWorldController.java │ │ │ ├── InstanceInformationService.java │ │ │ └── RestfulWebServicesApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── in28minutes │ └── rest │ └── webservices │ └── restfulwebservices │ └── RestfulWebServicesApplicationTests.java └── README.md /01-hello-world-rest-api/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 4.0.0 7 | com.in28minutes.rest.webservices 8 | 01-hello-world-rest-api 9 | 0.0.1-SNAPSHOT 10 | jar 11 | Demo project for Spring Boot 12 | hello-world-rest-api 13 | 14 | org.springframework.boot 15 | spring-boot-starter-parent 16 | 2.1.7.RELEASE 17 | 18 | 19 | 20 | 21 | UTF-8 22 | UTF-8 23 | 1.8 24 | 3.1.1 25 | 26 | ${project.build.directory}/${project.build.finalName}.jar 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-devtools 36 | runtime 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-test 41 | test 42 | 43 | 44 | 45 | hello-world-rest-api 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-maven-plugin 50 | 51 | 56 | 57 | 58 | 59 | 60 | spring-snapshots 61 | Spring Snapshots 62 | https://repo.spring.io/snapshot 63 | 64 | true 65 | 66 | 67 | 68 | spring-milestones 69 | Spring Milestones 70 | https://repo.spring.io/milestone 71 | 72 | false 73 | 74 | 75 | 76 | 77 | 78 | spring-snapshots 79 | Spring Snapshots 80 | https://repo.spring.io/snapshot 81 | 82 | true 83 | 84 | 85 | 86 | spring-milestones 87 | Spring Milestones 88 | https://repo.spring.io/milestone 89 | 90 | false 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /01-hello-world-rest-api/readme.md: -------------------------------------------------------------------------------- 1 | # Hello World Rest API 2 | 3 | ### Running the Application 4 | 5 | Run com.in28minutes.rest.webservices.restfulwebservices.RestfulWebServicesApplication as a Java Application. 6 | 7 | - http://localhost:8080/hello-world 8 | 9 | ```txt 10 | Hello World 11 | ``` 12 | 13 | - http://localhost:8080/hello-world-bean 14 | 15 | ```json 16 | {"message":"Hello World"} 17 | ``` 18 | 19 | - http://localhost:8080/hello-world/path-variable/in28minutes 20 | 21 | ```json 22 | {"message":"Hello World, in28minutes"} 23 | ``` 24 | 25 | ### Plugin configuration 26 | 27 | ``` 28 | 29 | com.microsoft.azure 30 | azure-webapp-maven-plugin 31 | 1.7.0 32 | 33 | ``` 34 | 35 | ### Azure CLI 36 | 37 | - https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest 38 | 39 | ### Final Plugin Configuration 40 | ``` 41 | 42 | com.microsoft.azure 43 | azure-webapp-maven-plugin 44 | 1.7.0 45 | 46 | V2 47 | hello-world-rest-api-rg 48 | hello-world-rest-api-in28minutes 49 | B1 50 | westeurope 51 | 52 | 53 | JAVA_OPTS 54 | -Dserver.port=80 55 | 56 | 57 | 58 | linux 59 | java11 60 | java11 61 | 62 | 63 | 64 | 65 | ${project.basedir}/target 66 | 67 | *.jar 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | ``` 76 | ### Logging Configuration 77 | 78 | ``` 79 | -Dlogging.level.org.springframework=DEBUG 80 | ``` -------------------------------------------------------------------------------- /01-hello-world-rest-api/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/HelloWorldBean.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | public class HelloWorldBean { 4 | 5 | private String message; 6 | 7 | public HelloWorldBean(String message) { 8 | this.message = message; 9 | } 10 | 11 | public String getMessage() { 12 | return message; 13 | } 14 | 15 | public void setMessage(String message) { 16 | this.message = message; 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | return String.format("HelloWorldBean [message=%s]", message); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /01-hello-world-rest-api/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/HelloWorldController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.PathVariable; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @RestController 8 | public class HelloWorldController { 9 | 10 | @GetMapping(path = "/hello-world") 11 | public String helloWorld() { 12 | return "Hello World"; 13 | } 14 | 15 | @GetMapping(path = "/hello-world-bean") 16 | public HelloWorldBean helloWorldBean() { 17 | // throw new RuntimeException("Some Error has Happened! Contact Support at 18 | // ***-***"); 19 | return new HelloWorldBean("Hello World"); 20 | } 21 | 22 | /// hello-world/path-variable/in28minutes 23 | @GetMapping(path = "/hello-world/path-variable/{name}") 24 | public HelloWorldBean helloWorldPathVariable(@PathVariable String name) { 25 | return new HelloWorldBean(String.format("Hello World, %s", name)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /01-hello-world-rest-api/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/RestfulWebServicesApplication.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class RestfulWebServicesApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(RestfulWebServicesApplication.class, args); 11 | } 12 | } -------------------------------------------------------------------------------- /01-hello-world-rest-api/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | logging.level.org.springframework = debug 2 | -------------------------------------------------------------------------------- /01-hello-world-rest-api/src/test/java/com/in28minutes/rest/webservices/restfulwebservices/RestfulWebServicesApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class RestfulWebServicesApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /02-todo-web-application-h2/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM tomcat:8.0.51-jre8-alpine 2 | EXPOSE 8080 3 | RUN rm -rf /usr/local/tomcat/webapps/* 4 | COPY target/*.war /usr/local/tomcat/webapps/ROOT.war 5 | CMD ["catalina.sh","run"] -------------------------------------------------------------------------------- /02-todo-web-application-h2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 4.0.0 7 | com.in28minutes.springboot.web 8 | 02-todo-web-application-h2 9 | 0.0.1-SNAPSHOT 10 | war 11 | todo-web-application-h2 12 | Demo project for Spring Boot 13 | 14 | org.springframework.boot 15 | spring-boot-starter-parent 16 | 2.1.7.RELEASE 17 | 18 | 19 | 20 | 21 | UTF-8 22 | UTF-8 23 | 1.8 24 | 3.1.1 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-data-jpa 34 | 35 | 36 | com.h2database 37 | h2 38 | runtime 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-security 43 | 44 | 45 | javax.servlet 46 | jstl 47 | 48 | 49 | org.webjars 50 | bootstrap 51 | 3.3.6 52 | 53 | 54 | org.webjars 55 | bootstrap-datepicker 56 | 1.0.1 57 | 58 | 59 | org.webjars 60 | jquery 61 | 1.9.1 62 | 63 | 64 | org.apache.tomcat.embed 65 | tomcat-embed-jasper 66 | provided 67 | 68 | 69 | org.springframework.boot 70 | spring-boot-starter-tomcat 71 | provided 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-devtools 76 | runtime 77 | 78 | 79 | org.springframework.boot 80 | spring-boot-starter-test 81 | test 82 | 83 | 84 | 85 | todo-web-application-h2 86 | 87 | 88 | org.springframework.boot 89 | spring-boot-maven-plugin 90 | 91 | 92 | 97 | 98 | 99 | 100 | spring-milestones 101 | Spring Milestones 102 | https://repo.spring.io/milestones 103 | 104 | 105 | 106 | 107 | spring-milestones 108 | Spring Milestones 109 | https://repo.spring.io/milestones 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /02-todo-web-application-h2/readme.md: -------------------------------------------------------------------------------- 1 | # Todo Web Application using Spring Boot and H2 In memory database 2 | 3 | Run com.in28minutes.springboot.web.SpringBootFirstWebApplication as a Java Application. 4 | 5 | Runs on default port of Spring Boot - 8080 6 | 7 | ## Can be run as a Jar or a WAR 8 | 9 | `mvn clean install` generate a war which can deployed to your favorite web server. 10 | 11 | ## Web Application 12 | 13 | - http://localhost:8080/login with in28minutes/dummy as credentials 14 | - You can add, delete and update your todos 15 | - Spring Security is used to secure the application 16 | - `com.in28minutes.springboot.web.security.SecurityConfiguration` contains the in memory security credential configuration. 17 | 18 | ## H2 Console 19 | 20 | - http://localhost:8080/h2-console 21 | - Use `jdbc:h2:mem:testdb` as JDBC URL 22 | 23 | 24 | ## Plugin Initial Configuration 25 | ``` 26 | 27 | com.microsoft.azure 28 | azure-webapp-maven-plugin 29 | 1.7.0 30 | 31 | 32 | ``` 33 | 34 | ## Plugin Final Configuration 35 | ``` 36 | 37 | com.microsoft.azure 38 | azure-webapp-maven-plugin 39 | 1.7.0 40 | 41 | V2 42 | todo-web-application-h2-rg 43 | todo-web-application-h2-in28minutes 44 | B1 45 | westeurope 46 | 47 | windows 48 | 11 49 | tomcat 9.0 50 | 51 | 52 | 53 | 54 | ${project.basedir}/target 55 | 56 | *.war 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | ``` -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/java/com/in28minutes/springboot/web/EnvironmentConfigurationLogger.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web; 2 | 3 | import java.util.Arrays; 4 | import java.util.stream.StreamSupport; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.context.event.ContextRefreshedEvent; 9 | import org.springframework.context.event.EventListener; 10 | import org.springframework.core.env.AbstractEnvironment; 11 | import org.springframework.core.env.EnumerablePropertySource; 12 | import org.springframework.core.env.Environment; 13 | import org.springframework.core.env.MutablePropertySources; 14 | import org.springframework.stereotype.Component; 15 | 16 | @Component 17 | public class EnvironmentConfigurationLogger { 18 | 19 | private static final Logger LOGGER = LoggerFactory.getLogger(EnvironmentConfigurationLogger.class); 20 | 21 | @SuppressWarnings("rawtypes") 22 | @EventListener 23 | public void handleContextRefresh(ContextRefreshedEvent event) { 24 | final Environment environment = event.getApplicationContext().getEnvironment(); 25 | LOGGER.debug("====== Environment and configuration ======"); 26 | LOGGER.debug("Active profiles: {}", Arrays.toString(environment.getActiveProfiles())); 27 | final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources(); 28 | StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource) 29 | .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct() 30 | .forEach(prop -> LOGGER.debug("{}", prop));// environment.getProperty(prop) 31 | LOGGER.debug("==========================================="); 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/java/com/in28minutes/springboot/web/SpringBootFirstWebApplication.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 7 | import org.springframework.context.annotation.ComponentScan; 8 | 9 | @SpringBootApplication 10 | @ComponentScan("com.in28minutes.springboot.web") 11 | public class SpringBootFirstWebApplication extends SpringBootServletInitializer { 12 | 13 | @Override 14 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 15 | return application.sources(SpringBootFirstWebApplication.class); 16 | } 17 | 18 | public static void main(String[] args) { 19 | SpringApplication.run(SpringBootFirstWebApplication.class, args); 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/java/com/in28minutes/springboot/web/controller/ErrorController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.controller; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.web.bind.annotation.ExceptionHandler; 7 | import org.springframework.web.servlet.ModelAndView; 8 | 9 | @Controller("error") 10 | public class ErrorController { 11 | 12 | @ExceptionHandler(Exception.class) 13 | public ModelAndView handleException 14 | (HttpServletRequest request, Exception ex){ 15 | ModelAndView mv = new ModelAndView(); 16 | 17 | mv.addObject("exception", ex.getLocalizedMessage()); 18 | mv.addObject("url", request.getRequestURL()); 19 | 20 | mv.setViewName("error"); 21 | return mv; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/java/com/in28minutes/springboot/web/controller/LogoutController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.controller; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import javax.servlet.http.HttpServletResponse; 5 | 6 | import org.springframework.security.core.Authentication; 7 | import org.springframework.security.core.context.SecurityContextHolder; 8 | import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RequestMethod; 12 | 13 | @Controller 14 | public class LogoutController { 15 | 16 | @RequestMapping(value = "/logout", method = RequestMethod.GET) 17 | public String logout(HttpServletRequest request, 18 | HttpServletResponse response) { 19 | 20 | Authentication authentication = SecurityContextHolder.getContext() 21 | .getAuthentication(); 22 | 23 | if (authentication != null) { 24 | new SecurityContextLogoutHandler().logout(request, response, 25 | authentication); 26 | } 27 | 28 | return "redirect:/"; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/java/com/in28minutes/springboot/web/controller/TodoController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.controller; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | 6 | import javax.validation.Valid; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.propertyeditors.CustomDateEditor; 10 | import org.springframework.security.core.context.SecurityContextHolder; 11 | import org.springframework.security.core.userdetails.UserDetails; 12 | import org.springframework.stereotype.Controller; 13 | import org.springframework.ui.ModelMap; 14 | import org.springframework.validation.BindingResult; 15 | import org.springframework.web.bind.WebDataBinder; 16 | import org.springframework.web.bind.annotation.InitBinder; 17 | import org.springframework.web.bind.annotation.RequestMapping; 18 | import org.springframework.web.bind.annotation.RequestMethod; 19 | import org.springframework.web.bind.annotation.RequestParam; 20 | 21 | import com.in28minutes.springboot.web.model.Todo; 22 | import com.in28minutes.springboot.web.service.TodoRepository; 23 | 24 | @Controller 25 | public class TodoController { 26 | 27 | @Autowired 28 | TodoRepository repository; 29 | 30 | @InitBinder 31 | public void initBinder(WebDataBinder binder) { 32 | // Date - dd/MM/yyyy 33 | SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); 34 | binder.registerCustomEditor(Date.class, new CustomDateEditor( 35 | dateFormat, false)); 36 | } 37 | 38 | @RequestMapping(value = "/list-todos", method = RequestMethod.GET) 39 | public String showTodos(ModelMap model) { 40 | String name = getLoggedInUserName(model); 41 | model.put("todos", repository.findByUser(name)); 42 | //model.put("todos", service.retrieveTodos(name)); 43 | return "list-todos"; 44 | } 45 | 46 | private String getLoggedInUserName(ModelMap model) { 47 | Object principal = SecurityContextHolder.getContext() 48 | .getAuthentication().getPrincipal(); 49 | 50 | if (principal instanceof UserDetails) { 51 | return ((UserDetails) principal).getUsername(); 52 | } 53 | 54 | return principal.toString(); 55 | } 56 | 57 | @RequestMapping(value = "/add-todo", method = RequestMethod.GET) 58 | public String showAddTodoPage(ModelMap model) { 59 | model.addAttribute("todo", new Todo(0, getLoggedInUserName(model), 60 | "Default Desc", new Date(), false)); 61 | return "todo"; 62 | } 63 | 64 | @RequestMapping(value = "/delete-todo", method = RequestMethod.GET) 65 | public String deleteTodo(@RequestParam int id) { 66 | 67 | //if(id==1) 68 | //throw new RuntimeException("Something went wrong"); 69 | repository.deleteById(id); 70 | //service.deleteTodo(id); 71 | return "redirect:/list-todos"; 72 | } 73 | 74 | @RequestMapping(value = "/update-todo", method = RequestMethod.GET) 75 | public String showUpdateTodoPage(@RequestParam int id, ModelMap model) { 76 | Todo todo = repository.findById(id).get(); 77 | //Todo todo = service.retrieveTodo(id); 78 | model.put("todo", todo); 79 | return "todo"; 80 | } 81 | 82 | @RequestMapping(value = "/update-todo", method = RequestMethod.POST) 83 | public String updateTodo(ModelMap model, @Valid Todo todo, 84 | BindingResult result) { 85 | 86 | if (result.hasErrors()) { 87 | return "todo"; 88 | } 89 | 90 | todo.setUser(getLoggedInUserName(model)); 91 | 92 | repository.save(todo); 93 | //service.updateTodo(todo); 94 | 95 | return "redirect:/list-todos"; 96 | } 97 | 98 | @RequestMapping(value = "/add-todo", method = RequestMethod.POST) 99 | public String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) { 100 | 101 | if (result.hasErrors()) { 102 | return "todo"; 103 | } 104 | 105 | todo.setUser(getLoggedInUserName(model)); 106 | repository.save(todo); 107 | /*service.addTodo(getLoggedInUserName(model), todo.getDesc(), todo.getTargetDate(), 108 | false);*/ 109 | return "redirect:/list-todos"; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/java/com/in28minutes/springboot/web/controller/WelcomeController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.controller; 2 | 3 | import org.springframework.security.core.context.SecurityContextHolder; 4 | import org.springframework.security.core.userdetails.UserDetails; 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.ui.ModelMap; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RequestMethod; 9 | 10 | @Controller 11 | public class WelcomeController { 12 | 13 | @RequestMapping(value = "/", method = RequestMethod.GET) 14 | public String showWelcomePage(ModelMap model) { 15 | model.put("name", getLoggedinUserName()); 16 | return "welcome"; 17 | } 18 | 19 | private String getLoggedinUserName() { 20 | Object principal = SecurityContextHolder.getContext() 21 | .getAuthentication().getPrincipal(); 22 | 23 | if (principal instanceof UserDetails) { 24 | return ((UserDetails) principal).getUsername(); 25 | } 26 | 27 | return principal.toString(); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/java/com/in28minutes/springboot/web/model/Todo.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.model; 2 | 3 | import java.util.Date; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.Id; 8 | import javax.validation.constraints.Size; 9 | 10 | @Entity 11 | public class Todo { 12 | 13 | @Id 14 | @GeneratedValue 15 | private int id; 16 | 17 | private String user; 18 | 19 | @Size(min=10, message="Enter at least 10 Characters...") 20 | private String desc; 21 | 22 | private Date targetDate; 23 | private boolean isDone; 24 | 25 | public Todo() { 26 | super(); 27 | } 28 | 29 | public Todo(int id, String user, String desc, Date targetDate, 30 | boolean isDone) { 31 | super(); 32 | this.id = id; 33 | this.user = user; 34 | this.desc = desc; 35 | this.targetDate = targetDate; 36 | this.isDone = isDone; 37 | } 38 | 39 | public int getId() { 40 | return id; 41 | } 42 | 43 | public void setId(int id) { 44 | this.id = id; 45 | } 46 | 47 | public String getUser() { 48 | return user; 49 | } 50 | 51 | public void setUser(String user) { 52 | this.user = user; 53 | } 54 | 55 | public String getDesc() { 56 | return desc; 57 | } 58 | 59 | public void setDesc(String desc) { 60 | this.desc = desc; 61 | } 62 | 63 | public Date getTargetDate() { 64 | return targetDate; 65 | } 66 | 67 | public void setTargetDate(Date targetDate) { 68 | this.targetDate = targetDate; 69 | } 70 | 71 | public boolean isDone() { 72 | return isDone; 73 | } 74 | 75 | public void setDone(boolean isDone) { 76 | this.isDone = isDone; 77 | } 78 | 79 | @Override 80 | public int hashCode() { 81 | final int prime = 31; 82 | int result = 1; 83 | result = prime * result + id; 84 | return result; 85 | } 86 | 87 | @Override 88 | public boolean equals(Object obj) { 89 | if (this == obj) { 90 | return true; 91 | } 92 | if (obj == null) { 93 | return false; 94 | } 95 | if (getClass() != obj.getClass()) { 96 | return false; 97 | } 98 | Todo other = (Todo) obj; 99 | if (id != other.id) { 100 | return false; 101 | } 102 | return true; 103 | } 104 | 105 | @Override 106 | public String toString() { 107 | return String.format( 108 | "Todo [id=%s, user=%s, desc=%s, targetDate=%s, isDone=%s]", id, 109 | user, desc, targetDate, isDone); 110 | } 111 | 112 | } -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/java/com/in28minutes/springboot/web/security/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.security; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 7 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 8 | 9 | @Configuration 10 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter{ 11 | //Create User - in28Minutes/dummy 12 | @Autowired 13 | public void configureGlobalSecurity(AuthenticationManagerBuilder auth) 14 | throws Exception { 15 | auth.inMemoryAuthentication().withUser("in28minutes").password("{noop}dummy") 16 | .roles("USER", "ADMIN"); 17 | } 18 | 19 | @Override 20 | protected void configure(HttpSecurity http) throws Exception { 21 | http.authorizeRequests().antMatchers("/login", "/h2-console/**").permitAll() 22 | .antMatchers("/", "/*todo*/**").access("hasRole('USER')").and() 23 | .formLogin(); 24 | 25 | http.csrf().disable(); 26 | http.headers().frameOptions().disable(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/java/com/in28minutes/springboot/web/service/TodoRepository.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.service; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | 7 | import com.in28minutes.springboot.web.model.Todo; 8 | 9 | public interface TodoRepository extends JpaRepository { 10 | List findByUser(String user); 11 | } -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.mvc.view.prefix=/WEB-INF/jsp/ 2 | spring.mvc.view.suffix=.jsp 3 | logging.level.org.springframework.web=INFO 4 | 5 | spring.jpa.show-sql=true 6 | spring.h2.console.enabled=true 7 | spring.h2.console.settings.web-allow-others=true -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | insert into TODO 2 | values(10001, 'Learn Spring Boot', false, sysdate(), 'in28minutes'); 3 | insert into TODO 4 | values(10002, 'Learn Angular JS', false, sysdate(), 'in28minutes'); 5 | insert into TODO 6 | values(10003, 'Learn to Dance', false, sysdate(), 'in28minutes'); 7 | -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/webapp/WEB-INF/jsp/common/footer.jspf: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/webapp/WEB-INF/jsp/common/header.jspf: -------------------------------------------------------------------------------- 1 | <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 2 | <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> 3 | <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> 4 | 5 | 6 | 7 | 8 | First Web Application 9 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/webapp/WEB-INF/jsp/common/navigation.jspf: -------------------------------------------------------------------------------- 1 | 2 | 16 | -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/webapp/WEB-INF/jsp/error.jsp: -------------------------------------------------------------------------------- 1 | <%@ include file="common/header.jspf"%> 2 | <%@ include file="common/navigation.jspf"%> 3 |
4 | An exception occurred! Please contact Support! 5 |
6 | <%@ include file="common/footer.jspf"%> -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/webapp/WEB-INF/jsp/list-todos.jsp: -------------------------------------------------------------------------------- 1 | <%@ include file="common/header.jspf" %> 2 | <%@ include file="common/navigation.jspf" %> 3 | 4 |
5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 24 | 26 | 27 | 28 | 29 |
Your todos are
DescriptionTarget DateIs it Done?
${todo.desc}${todo.done}UpdateDelete
30 |
31 | Add a Todo 32 |
33 |
34 | <%@ include file="common/footer.jspf" %> -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/webapp/WEB-INF/jsp/todo.jsp: -------------------------------------------------------------------------------- 1 | <%@ include file="common/header.jspf" %> 2 | <%@ include file="common/navigation.jspf" %> 3 |
4 | 5 | 6 |
7 | Description 8 | 10 | 11 |
12 | 13 |
14 | Target Date 15 | 17 | 18 |
19 | 20 | 21 |
22 |
23 | <%@ include file="common/footer.jspf" %> -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/main/webapp/WEB-INF/jsp/welcome.jsp: -------------------------------------------------------------------------------- 1 | <%@ include file="common/header.jspf"%> 2 | <%@ include file="common/navigation.jspf"%> 3 |
4 | Welcome ${name}!! Click here to manage your 5 | todo's. 6 |
7 | <%@ include file="common/footer.jspf"%> -------------------------------------------------------------------------------- /02-todo-web-application-h2/src/test/java/com/in28minutes/springboot/web/SpringBootFirstWebApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringBootFirstWebApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 4.0.0 7 | com.in28minutes.springboot.web 8 | 03-todo-web-application-mysql 9 | 0.0.1-SNAPSHOT 10 | war 11 | todo-web-application-mysql 12 | Demo project for Spring Boot 13 | 14 | org.springframework.boot 15 | spring-boot-starter-parent 16 | 2.1.7.RELEASE 17 | 18 | 19 | 20 | 21 | UTF-8 22 | UTF-8 23 | 1.8 24 | 3.1.1 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-web 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-actuator 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-starter-data-jpa 38 | 39 | 40 | com.h2database 41 | h2 42 | test 43 | 44 | 45 | mysql 46 | mysql-connector-java 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-security 51 | 52 | 53 | javax.servlet 54 | jstl 55 | 56 | 57 | org.webjars 58 | bootstrap 59 | 3.3.6 60 | 61 | 62 | org.webjars 63 | bootstrap-datepicker 64 | 1.0.1 65 | 66 | 67 | org.webjars 68 | jquery 69 | 1.9.1 70 | 71 | 72 | org.apache.tomcat.embed 73 | tomcat-embed-jasper 74 | provided 75 | 76 | 77 | org.springframework.boot 78 | spring-boot-starter-tomcat 79 | provided 80 | 81 | 82 | org.springframework.boot 83 | spring-boot-devtools 84 | runtime 85 | 86 | 87 | org.springframework.boot 88 | spring-boot-starter-test 89 | test 90 | 91 | 92 | 93 | todo-web-application-mysql 94 | 95 | 96 | org.springframework.boot 97 | spring-boot-maven-plugin 98 | 99 | 100 | com.microsoft.azure 101 | azure-webapp-maven-plugin 102 | 1.7.0 103 | 104 | 105 | 106 | 107 | 108 | spring-milestones 109 | Spring Milestones 110 | https://repo.spring.io/milestones 111 | 112 | 113 | 114 | 115 | spring-milestones 116 | Spring Milestones 117 | https://repo.spring.io/milestones 118 | 119 | 120 | 121 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/readme.md: -------------------------------------------------------------------------------- 1 | # Todo Web Application using Spring Boot and MySQL as Database 2 | 3 | Run com.in28minutes.springboot.web.SpringBootFirstWebApplication as a Java Application. 4 | 5 | Runs on default port of Spring Boot - 8080 6 | 7 | Application uses h2 database to run the tests. 8 | 9 | ## Can be run as a Jar or a WAR 10 | 11 | `mvn clean install` generate a war which can deployed to your favorite web server. 12 | 13 | We will deploy to Cloud as a WAR 14 | 15 | ## Web Application 16 | 17 | - http://localhost:8080/login with in28minutes/dummy as credentials 18 | - You can add, delete and update your todos 19 | - Spring Security is used to secure the application 20 | - `com.in28minutes.springboot.web.security.SecurityConfiguration` contains the in memory security credential configuration. 21 | 22 | 23 | ## Changes from H2 Application 24 | 25 | #### pom.xml 26 | 27 | ``` 28 | 29 | com.h2database 30 | h2 31 | test 32 | 33 | 34 | mysql 35 | mysql-connector-java 36 | 37 | ``` 38 | 39 | #### src/main/resources/application.properties 40 | 41 | ``` 42 | #spring.h2.console.enabled=true 43 | #spring.h2.console.settings.web-allow-others=true 44 | 45 | spring.jpa.hibernate.ddl-auto=update 46 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 47 | spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL55Dialect 48 | spring.datasource.url=jdbc:mysql://localhost:3306/todos 49 | spring.datasource.username=todos-user 50 | spring.datasource.password=dummytodos 51 | ``` 52 | 53 | #### src/test/resources/application.properties 54 | 55 | ``` 56 | spring.jpa.hibernate.ddl-auto=create-drop 57 | spring.datasource.driver-class-name=org.h2.Driver 58 | spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 59 | spring.datasource.username=sa 60 | spring.datasource.password=sa 61 | ``` 62 | 63 | #### public class Todo 64 | 65 | ``` 66 | @Size(min=10, message="Enter at least 10 Characters...") 67 | @Column(name="description") 68 | private String desc; 69 | ``` 70 | ## My SQL 71 | 72 | ### Launching MySQL using Docker 73 | 74 | ``` 75 | docker run --detach --env MYSQL_ROOT_PASSWORD=dummypassword --env MYSQL_USER=todos-user --env MYSQL_PASSWORD=dummytodos --env MYSQL_DATABASE=todos --name mysql --publish 3306:3306 mysql:5.7 76 | ``` 77 | 78 | ### My SQL Shell Client 79 | 80 | - https://dev.mysql.com/downloads/shell/ 81 | 82 | - Install on mac using `brew install caskroom/cask/mysql-shell`. 83 | 84 | 85 | ``` 86 | Rangas-MacBook-Air:projects rangakaranam$ mysqlsh 87 | MySQL Shell 8.0.15 88 | Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. 89 | Oracle is a registered trademark of Oracle Corporation and/or its affiliates. 90 | Other names may be trademarks of their respective owners. 91 | 92 | Type '\help' or '\?' for help; '\quit' to exit. 93 | 94 | MySQL JS > \connect todos-user@localhost:3306 95 | Creating a session to 'todos-user@localhost:3306' 96 | Please provide the password for 'todos-user@localhost:3306': 97 | Save password for 'todos-user@localhost:3306'? [Y]es/[N]o/Ne[v]er (default No): v 98 | Fetching schema names for autocompletion... Press ^C to stop. 99 | Your MySQL connection id is 37 100 | Server version: 5.7.26 MySQL Community Server (GPL) 101 | No default schema selected; type \use to set one. 102 | 103 | MySQL localhost:3306 ssl JS > \sql 104 | Switching to SQL mode... Commands end with ; 105 | 106 | MySQL localhost:3306 ssl SQL > use todos 107 | Default schema set to `todos`. 108 | Fetching table and column names from `todos` for auto-completion... Press ^C to stop. 109 | 110 | MySQL localhost:3306 ssl todos SQL > select * from todo ; 111 | +----+--------------+---------+----------------------------+-------------+ 112 | | id | description | is_done | target_date | user | 113 | +----+--------------+---------+----------------------------+-------------+ 114 | | 1 | Default Desc | 0 | 2019-06-26 18:30:00.000000 | in28minutes | 115 | +----+--------------+---------+----------------------------+-------------+ 116 | 1 row in set (0.0032 sec) 117 | 118 | ``` 119 | 120 | ### Create Todo Table for Production 121 | 122 | ``` 123 | create table hibernate_sequence (next_val bigint) engine=InnoDB 124 | insert into hibernate_sequence values ( 1 ) 125 | create table todo (id integer not null, description varchar(255), is_done bit not null, target_date datetime(6), user varchar(255), primary key (id)) engine=InnoDB 126 | ``` 127 | 128 | ### Plugin Configuration Backup 129 | 130 | ``` 131 | 132 | com.microsoft.azure 133 | azure-webapp-maven-plugin 134 | 1.7.0 135 | 136 | V2 137 | todo-web-application-mysql-rg 138 | todo-web-application-mysql-in28minutes 139 | B1 140 | westeurope 141 | 142 | linux 143 | java11 144 | TOMCAT 9.0 145 | 146 | 147 | 148 | 149 | ${project.basedir}/target 150 | 151 | *.war 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | ``` -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/java/com/in28minutes/springboot/web/EnvironmentConfigurationLogger.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web; 2 | 3 | import java.util.Arrays; 4 | import java.util.stream.StreamSupport; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.context.event.ContextRefreshedEvent; 9 | import org.springframework.context.event.EventListener; 10 | import org.springframework.core.env.AbstractEnvironment; 11 | import org.springframework.core.env.EnumerablePropertySource; 12 | import org.springframework.core.env.Environment; 13 | import org.springframework.core.env.MutablePropertySources; 14 | import org.springframework.stereotype.Component; 15 | 16 | @Component 17 | public class EnvironmentConfigurationLogger { 18 | 19 | private static final Logger LOGGER = LoggerFactory.getLogger(EnvironmentConfigurationLogger.class); 20 | 21 | @SuppressWarnings("rawtypes") 22 | @EventListener 23 | public void handleContextRefresh(ContextRefreshedEvent event) { 24 | final Environment environment = event.getApplicationContext().getEnvironment(); 25 | LOGGER.info("====== Environment and configuration ======"); 26 | LOGGER.info("Active profiles: {}", Arrays.toString(environment.getActiveProfiles())); 27 | final MutablePropertySources sources = ((AbstractEnvironment) environment).getPropertySources(); 28 | StreamSupport.stream(sources.spliterator(), false).filter(ps -> ps instanceof EnumerablePropertySource) 29 | .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::stream).distinct() 30 | .forEach(prop -> { 31 | LOGGER.info("{}", prop); 32 | // Object resolved = environment.getProperty(prop, Object.class); 33 | // if (resolved instanceof String) { 34 | // LOGGER.info("{}", environment.getProperty(prop)); 35 | // } 36 | }); 37 | LOGGER.info("==========================================="); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/java/com/in28minutes/springboot/web/SpringBootFirstWebApplication.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 7 | import org.springframework.context.annotation.ComponentScan; 8 | 9 | @SpringBootApplication 10 | @ComponentScan("com.in28minutes.springboot.web") 11 | public class SpringBootFirstWebApplication extends SpringBootServletInitializer { 12 | 13 | @Override 14 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 15 | return application.sources(SpringBootFirstWebApplication.class); 16 | } 17 | 18 | public static void main(String[] args) { 19 | SpringApplication.run(SpringBootFirstWebApplication.class, args); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/java/com/in28minutes/springboot/web/controller/ErrorController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.controller; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.web.bind.annotation.ExceptionHandler; 7 | import org.springframework.web.servlet.ModelAndView; 8 | 9 | @Controller("error") 10 | public class ErrorController { 11 | 12 | @ExceptionHandler(Exception.class) 13 | public ModelAndView handleException 14 | (HttpServletRequest request, Exception ex){ 15 | ModelAndView mv = new ModelAndView(); 16 | 17 | mv.addObject("exception", ex.getLocalizedMessage()); 18 | mv.addObject("url", request.getRequestURL()); 19 | 20 | mv.setViewName("error"); 21 | return mv; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/java/com/in28minutes/springboot/web/controller/LogoutController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.controller; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import javax.servlet.http.HttpServletResponse; 5 | 6 | import org.springframework.security.core.Authentication; 7 | import org.springframework.security.core.context.SecurityContextHolder; 8 | import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RequestMethod; 12 | 13 | @Controller 14 | public class LogoutController { 15 | 16 | @RequestMapping(value = "/logout", method = RequestMethod.GET) 17 | public String logout(HttpServletRequest request, 18 | HttpServletResponse response) { 19 | 20 | Authentication authentication = SecurityContextHolder.getContext() 21 | .getAuthentication(); 22 | 23 | if (authentication != null) { 24 | new SecurityContextLogoutHandler().logout(request, response, 25 | authentication); 26 | } 27 | 28 | return "redirect:/"; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/java/com/in28minutes/springboot/web/controller/TodoController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.controller; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | 6 | import javax.validation.Valid; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.propertyeditors.CustomDateEditor; 10 | import org.springframework.security.core.context.SecurityContextHolder; 11 | import org.springframework.security.core.userdetails.UserDetails; 12 | import org.springframework.stereotype.Controller; 13 | import org.springframework.ui.ModelMap; 14 | import org.springframework.validation.BindingResult; 15 | import org.springframework.web.bind.WebDataBinder; 16 | import org.springframework.web.bind.annotation.InitBinder; 17 | import org.springframework.web.bind.annotation.RequestMapping; 18 | import org.springframework.web.bind.annotation.RequestMethod; 19 | import org.springframework.web.bind.annotation.RequestParam; 20 | 21 | import com.in28minutes.springboot.web.model.Todo; 22 | import com.in28minutes.springboot.web.service.TodoRepository; 23 | 24 | @Controller 25 | public class TodoController { 26 | 27 | @Autowired 28 | TodoRepository repository; 29 | 30 | @InitBinder 31 | public void initBinder(WebDataBinder binder) { 32 | // Date - dd/MM/yyyy 33 | SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); 34 | binder.registerCustomEditor(Date.class, new CustomDateEditor( 35 | dateFormat, false)); 36 | } 37 | 38 | @RequestMapping(value = "/list-todos", method = RequestMethod.GET) 39 | public String showTodos(ModelMap model) { 40 | String name = getLoggedInUserName(model); 41 | model.put("todos", repository.findByUser(name)); 42 | //model.put("todos", service.retrieveTodos(name)); 43 | return "list-todos"; 44 | } 45 | 46 | private String getLoggedInUserName(ModelMap model) { 47 | Object principal = SecurityContextHolder.getContext() 48 | .getAuthentication().getPrincipal(); 49 | 50 | if (principal instanceof UserDetails) { 51 | return ((UserDetails) principal).getUsername(); 52 | } 53 | 54 | return principal.toString(); 55 | } 56 | 57 | @RequestMapping(value = "/add-todo", method = RequestMethod.GET) 58 | public String showAddTodoPage(ModelMap model) { 59 | model.addAttribute("todo", new Todo(0, getLoggedInUserName(model), 60 | "Default Desc", new Date(), false)); 61 | return "todo"; 62 | } 63 | 64 | @RequestMapping(value = "/delete-todo", method = RequestMethod.GET) 65 | public String deleteTodo(@RequestParam int id) { 66 | 67 | //if(id==1) 68 | //throw new RuntimeException("Something went wrong"); 69 | repository.deleteById(id); 70 | //service.deleteTodo(id); 71 | return "redirect:/list-todos"; 72 | } 73 | 74 | @RequestMapping(value = "/update-todo", method = RequestMethod.GET) 75 | public String showUpdateTodoPage(@RequestParam int id, ModelMap model) { 76 | Todo todo = repository.findById(id).get(); 77 | //Todo todo = service.retrieveTodo(id); 78 | model.put("todo", todo); 79 | return "todo"; 80 | } 81 | 82 | @RequestMapping(value = "/update-todo", method = RequestMethod.POST) 83 | public String updateTodo(ModelMap model, @Valid Todo todo, 84 | BindingResult result) { 85 | 86 | if (result.hasErrors()) { 87 | return "todo"; 88 | } 89 | 90 | todo.setUser(getLoggedInUserName(model)); 91 | 92 | repository.save(todo); 93 | //service.updateTodo(todo); 94 | 95 | return "redirect:/list-todos"; 96 | } 97 | 98 | @RequestMapping(value = "/add-todo", method = RequestMethod.POST) 99 | public String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) { 100 | 101 | if (result.hasErrors()) { 102 | return "todo"; 103 | } 104 | 105 | todo.setUser(getLoggedInUserName(model)); 106 | repository.save(todo); 107 | /*service.addTodo(getLoggedInUserName(model), todo.getDesc(), todo.getTargetDate(), 108 | false);*/ 109 | return "redirect:/list-todos"; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/java/com/in28minutes/springboot/web/controller/WelcomeController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.controller; 2 | 3 | import org.springframework.security.core.context.SecurityContextHolder; 4 | import org.springframework.security.core.userdetails.UserDetails; 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.ui.ModelMap; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RequestMethod; 9 | 10 | @Controller 11 | public class WelcomeController { 12 | 13 | @RequestMapping(value = "/", method = RequestMethod.GET) 14 | public String showWelcomePage(ModelMap model) { 15 | model.put("name", getLoggedinUserName()); 16 | return "welcome"; 17 | } 18 | 19 | private String getLoggedinUserName() { 20 | Object principal = SecurityContextHolder.getContext() 21 | .getAuthentication().getPrincipal(); 22 | 23 | if (principal instanceof UserDetails) { 24 | return ((UserDetails) principal).getUsername(); 25 | } 26 | 27 | return principal.toString(); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/java/com/in28minutes/springboot/web/model/Todo.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.model; 2 | 3 | import java.util.Date; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.Id; 9 | import javax.validation.constraints.Size; 10 | 11 | @Entity 12 | public class Todo { 13 | 14 | @Id 15 | @GeneratedValue 16 | private int id; 17 | 18 | private String user; 19 | 20 | @Size(min=10, message="Enter at least 10 Characters...") 21 | @Column(name="description") 22 | private String desc; 23 | 24 | private Date targetDate; 25 | 26 | private boolean isDone; 27 | 28 | public Todo() { 29 | super(); 30 | } 31 | 32 | public Todo(int id, String user, String desc, Date targetDate, 33 | boolean isDone) { 34 | super(); 35 | this.id = id; 36 | this.user = user; 37 | this.desc = desc; 38 | this.targetDate = targetDate; 39 | this.isDone = isDone; 40 | } 41 | 42 | public int getId() { 43 | return id; 44 | } 45 | 46 | public void setId(int id) { 47 | this.id = id; 48 | } 49 | 50 | public String getUser() { 51 | return user; 52 | } 53 | 54 | public void setUser(String user) { 55 | this.user = user; 56 | } 57 | 58 | public String getDesc() { 59 | return desc; 60 | } 61 | 62 | public void setDesc(String desc) { 63 | this.desc = desc; 64 | } 65 | 66 | public Date getTargetDate() { 67 | return targetDate; 68 | } 69 | 70 | public void setTargetDate(Date targetDate) { 71 | this.targetDate = targetDate; 72 | } 73 | 74 | public boolean isDone() { 75 | return isDone; 76 | } 77 | 78 | public void setDone(boolean isDone) { 79 | this.isDone = isDone; 80 | } 81 | 82 | @Override 83 | public int hashCode() { 84 | final int prime = 31; 85 | int result = 1; 86 | result = prime * result + id; 87 | return result; 88 | } 89 | 90 | @Override 91 | public boolean equals(Object obj) { 92 | if (this == obj) { 93 | return true; 94 | } 95 | if (obj == null) { 96 | return false; 97 | } 98 | if (getClass() != obj.getClass()) { 99 | return false; 100 | } 101 | Todo other = (Todo) obj; 102 | if (id != other.id) { 103 | return false; 104 | } 105 | return true; 106 | } 107 | 108 | @Override 109 | public String toString() { 110 | return String.format( 111 | "Todo [id=%s, user=%s, desc=%s, targetDate=%s, isDone=%s]", id, 112 | user, desc, targetDate, isDone); 113 | } 114 | 115 | } -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/java/com/in28minutes/springboot/web/security/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.security; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 7 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 8 | 9 | @Configuration 10 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter{ 11 | //Create User - in28Minutes/dummy 12 | @Autowired 13 | public void configureGlobalSecurity(AuthenticationManagerBuilder auth) 14 | throws Exception { 15 | auth.inMemoryAuthentication().withUser("in28minutes").password("{noop}dummy") 16 | .roles("USER", "ADMIN"); 17 | } 18 | 19 | @Override 20 | protected void configure(HttpSecurity http) throws Exception { 21 | http.authorizeRequests().antMatchers("/login", "/h2-console/**").permitAll() 22 | .antMatchers("/", "/*todo*/**").access("hasRole('USER')").and() 23 | .formLogin(); 24 | 25 | http.csrf().disable(); 26 | http.headers().frameOptions().disable(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/java/com/in28minutes/springboot/web/service/TodoRepository.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.service; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | 7 | import com.in28minutes.springboot.web.model.Todo; 8 | 9 | public interface TodoRepository extends JpaRepository{ 10 | List findByUser(String user); 11 | 12 | //service.retrieveTodos(name) 13 | 14 | //service.deleteTodo(id); 15 | //service.retrieveTodo(id) 16 | //service.updateTodo(todo) 17 | //service.addTodo(getLoggedInUserName(model), todo.getDesc(), todo.getTargetDate(),false); 18 | } 19 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/java/com/in28minutes/springboot/web/service/TodoService.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web.service; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Date; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | 8 | import org.springframework.stereotype.Service; 9 | 10 | import com.in28minutes.springboot.web.model.Todo; 11 | 12 | @Service 13 | public class TodoService { 14 | private static List todos = new ArrayList(); 15 | private static int todoCount = 3; 16 | 17 | static { 18 | todos.add(new Todo(1, "in28minutes", "Learn Spring MVC", new Date(), 19 | false)); 20 | todos.add(new Todo(2, "in28minutes", "Learn Struts", new Date(), false)); 21 | todos.add(new Todo(3, "in28minutes", "Learn Hibernate", new Date(), 22 | false)); 23 | } 24 | 25 | public List retrieveTodos(String user) { 26 | List filteredTodos = new ArrayList(); 27 | for (Todo todo : todos) { 28 | if (todo.getUser().equalsIgnoreCase(user)) { 29 | filteredTodos.add(todo); 30 | } 31 | } 32 | return filteredTodos; 33 | } 34 | 35 | public Todo retrieveTodo(int id) { 36 | for (Todo todo : todos) { 37 | if (todo.getId()==id) { 38 | return todo; 39 | } 40 | } 41 | return null; 42 | } 43 | 44 | public void updateTodo(Todo todo){ 45 | todos.remove(todo); 46 | todos.add(todo); 47 | } 48 | 49 | public void addTodo(String name, String desc, Date targetDate, 50 | boolean isDone) { 51 | todos.add(new Todo(++todoCount, name, desc, targetDate, isDone)); 52 | } 53 | 54 | public void deleteTodo(int id) { 55 | Iterator iterator = todos.iterator(); 56 | while (iterator.hasNext()) { 57 | Todo todo = iterator.next(); 58 | if (todo.getId() == id) { 59 | iterator.remove(); 60 | } 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.mvc.view.prefix=/WEB-INF/jsp/ 2 | spring.mvc.view.suffix=.jsp 3 | logging.level.org.springframework.web=INFO 4 | 5 | management.endpoints.web.base-path=/manage 6 | management.endpoints.web.exposure.include=* 7 | 8 | spring.jpa.show-sql=true 9 | #spring.h2.console.enabled=true 10 | #spring.h2.console.settings.web-allow-others=true 11 | 12 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 13 | spring.jpa.hibernate.ddl-auto=update 14 | spring.datasource.url=jdbc:mysql://${RDS_HOSTNAME:localhost}:${RDS_PORT:3306}/${RDS_DB_NAME:todos}?serverTimezone=UTC 15 | spring.datasource.username=${RDS_USERNAME:todos-user} 16 | spring.datasource.password=${RDS_PASSWORD:dummytodos} 17 | #spring.datasource.url=jdbc:mysql://localhost:3306/todos 18 | #spring.datasource.username=todos-user 19 | #spring.datasource.password=dummytodos 20 | spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/webapp/WEB-INF/jsp/common/footer.jspf: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/webapp/WEB-INF/jsp/common/header.jspf: -------------------------------------------------------------------------------- 1 | <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 2 | <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> 3 | <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> 4 | 5 | 6 | 7 | 8 | First Web Application 9 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/webapp/WEB-INF/jsp/common/navigation.jspf: -------------------------------------------------------------------------------- 1 | 2 | 16 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/webapp/WEB-INF/jsp/error.jsp: -------------------------------------------------------------------------------- 1 | <%@ include file="common/header.jspf"%> 2 | <%@ include file="common/navigation.jspf"%> 3 |
4 | An exception occurred! Please contact Support! 5 |
6 | <%@ include file="common/footer.jspf"%> -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/webapp/WEB-INF/jsp/list-todos.jsp: -------------------------------------------------------------------------------- 1 | <%@ include file="common/header.jspf" %> 2 | <%@ include file="common/navigation.jspf" %> 3 | 4 |
5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 24 | 26 | 27 | 28 | 29 |
Your todos are
DescriptionTarget DateIs it Done?
${todo.desc}${todo.done}UpdateDelete
30 |
31 | Add a Todo 32 |
33 |
34 | <%@ include file="common/footer.jspf" %> -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/webapp/WEB-INF/jsp/todo.jsp: -------------------------------------------------------------------------------- 1 | <%@ include file="common/header.jspf" %> 2 | <%@ include file="common/navigation.jspf" %> 3 |
4 | 5 | 6 |
7 | Description 8 | 10 | 11 |
12 | 13 |
14 | Target Date 15 | 17 | 18 |
19 | 20 | 21 |
22 |
23 | <%@ include file="common/footer.jspf" %> -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/main/webapp/WEB-INF/jsp/welcome.jsp: -------------------------------------------------------------------------------- 1 | <%@ include file="common/header.jspf"%> 2 | <%@ include file="common/navigation.jspf"%> 3 |
4 | Welcome ${name}!! Click here to manage your 5 | todo's. 6 |
7 | <%@ include file="common/footer.jspf"%> -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/test/java/com/in28minutes/springboot/web/SpringBootFirstWebApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.springboot.web; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringBootFirstWebApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /03-todo-web-application-mysql/src/test/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.jpa.hibernate.ddl-auto=create-drop 2 | spring.datasource.driver-class-name=org.h2.Driver 3 | spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 4 | spring.datasource.username=sa 5 | spring.datasource.password=sa 6 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/Dockerfile: -------------------------------------------------------------------------------- 1 | ## Stage 1 - Lets build the "deployable package" 2 | FROM node:7.10 as frontend-build 3 | WORKDIR /fullstack/frontend 4 | 5 | # Step 1 - Download all package dependencies first. 6 | # We will redownload dependencies only when packages change. 7 | COPY package.json package-lock.json ./ 8 | RUN npm install 9 | 10 | # Step 2 - Copy all source and run build 11 | COPY . ./ 12 | RUN npm run build 13 | 14 | ## Stage 2 - Let's build a minimal image with the "deployable package" 15 | FROM nginx:1.12-alpine 16 | COPY --from=frontend-build /fullstack/frontend/build /usr/share/nginx/html 17 | EXPOSE 80 18 | CMD ["nginx", "-g", "daemon off;"] -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/build/.azure/config: -------------------------------------------------------------------------------- 1 | [defaults] 2 | group = ranga_rg_Windows_westeurope 3 | sku = F1 4 | appserviceplan = ServicePlan763a680f-840a-4de0 5 | location = westeurope 6 | web = frontend-full-stack-in28minutes 7 | 8 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/build/asset-manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "main.css": "/static/css/main.e593cbc2.chunk.css", 3 | "main.js": "/static/js/main.dec38524.chunk.js", 4 | "main.js.map": "/static/js/main.dec38524.chunk.js.map", 5 | "runtime~main.js": "/static/js/runtime~main.c5541365.js", 6 | "runtime~main.js.map": "/static/js/runtime~main.c5541365.js.map", 7 | "static/js/2.3f64e426.chunk.js": "/static/js/2.3f64e426.chunk.js", 8 | "static/js/2.3f64e426.chunk.js.map": "/static/js/2.3f64e426.chunk.js.map", 9 | "index.html": "/index.html", 10 | "precache-manifest.761a421da099d8debfc4c14fcfc2a75b.js": "/precache-manifest.761a421da099d8debfc4c14fcfc2a75b.js", 11 | "service-worker.js": "/service-worker.js", 12 | "static/css/main.e593cbc2.chunk.css.map": "/static/css/main.e593cbc2.chunk.css.map" 13 | } -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/build/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/in28minutes/deploy-spring-boot-to-azure/3b94be8dd2a59cb7d4bab6b7b730c99d5cb6fb22/04-spring-boot-react-full-stack-h2/frontend/todo-app/build/favicon.ico -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/build/index.html: -------------------------------------------------------------------------------- 1 | My Todo Application
-------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/build/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/build/precache-manifest.761a421da099d8debfc4c14fcfc2a75b.js: -------------------------------------------------------------------------------- 1 | self.__precacheManifest = [ 2 | { 3 | "revision": "fdfcfda2d9b1bf31db52", 4 | "url": "/static/js/runtime~main.c5541365.js" 5 | }, 6 | { 7 | "revision": "8f06ea94b4608b25ef65", 8 | "url": "/static/js/main.dec38524.chunk.js" 9 | }, 10 | { 11 | "revision": "3be61595d9a1137a984f", 12 | "url": "/static/js/2.3f64e426.chunk.js" 13 | }, 14 | { 15 | "revision": "8f06ea94b4608b25ef65", 16 | "url": "/static/css/main.e593cbc2.chunk.css" 17 | }, 18 | { 19 | "revision": "298a37d270d810f784ef441ec510db7d", 20 | "url": "/index.html" 21 | } 22 | ]; -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/build/service-worker.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Welcome to your Workbox-powered service worker! 3 | * 4 | * You'll need to register this file in your web app and you should 5 | * disable HTTP caching for this file too. 6 | * See https://goo.gl/nhQhGp 7 | * 8 | * The rest of the code is auto-generated. Please don't update this file 9 | * directly; instead, make changes to your Workbox build configuration 10 | * and re-run your build process. 11 | * See https://goo.gl/2aRDsh 12 | */ 13 | 14 | importScripts("https://storage.googleapis.com/workbox-cdn/releases/3.6.3/workbox-sw.js"); 15 | 16 | importScripts( 17 | "/precache-manifest.761a421da099d8debfc4c14fcfc2a75b.js" 18 | ); 19 | 20 | workbox.clientsClaim(); 21 | 22 | /** 23 | * The workboxSW.precacheAndRoute() method efficiently caches and responds to 24 | * requests for URLs in the manifest. 25 | * See https://goo.gl/S9QRab 26 | */ 27 | self.__precacheManifest = [].concat(self.__precacheManifest || []); 28 | workbox.precaching.suppressWarnings(); 29 | workbox.precaching.precacheAndRoute(self.__precacheManifest, {}); 30 | 31 | workbox.routing.registerNavigationRoute("/index.html", { 32 | 33 | blacklist: [/^\/_/,/\/[^\/]+\.[^\/]+$/], 34 | }); 35 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/build/static/css/main.e593cbc2.chunk.css: -------------------------------------------------------------------------------- 1 | @import url(https://unpkg.com/bootstrap@4.1.0/dist/css/bootstrap.min.css);body{margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}code{font-family:source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace}.footer{position:absolute;bottom:0;width:100%;height:40px;background-color:#222}.App{text-align:center}.App-logo{-webkit-animation:App-logo-spin 20s linear infinite;animation:App-logo-spin 20s linear infinite;height:40vmin;pointer-events:none}.App-header{background-color:#282c34;min-height:100vh;display:-webkit-flex;display:flex;-webkit-flex-direction:column;flex-direction:column;-webkit-align-items:center;align-items:center;-webkit-justify-content:center;justify-content:center;font-size:calc(10px + 2vmin);color:#fff}.App-link{color:#61dafb}@-webkit-keyframes App-logo-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes App-logo-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}} 2 | /*# sourceMappingURL=main.e593cbc2.chunk.css.map */ -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/build/static/css/main.e593cbc2.chunk.css.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":["main.e593cbc2.chunk.css","/in28Minutes/git/deploy-java-spring-boot-to-azure-webapps/04-spring-boot-react-full-stack-h2/frontend/todo-app/src/index.css","/in28Minutes/git/deploy-java-spring-boot-to-azure-webapps/04-spring-boot-react-full-stack-h2/frontend/todo-app/src/App.css"],"names":[],"mappings":"AAAA,yEAAyE,CCAzE,KACE,QAAA,CACA,SAAA,CACA,mIDGY,CCAZ,kCAAA,CACA,iCDEF,CCCA,KACE,uEDGF,CEdA,QACE,iBAAA,CACA,QAAA,CACA,UAAA,CACA,WAAA,CACA,qBFiBF,CEdA,KACE,iBFiBF,CEdA,UACE,mDAAA,CAAA,2CAAA,CACA,aAAA,CACA,mBFkBF,CEfA,YACE,wBAAA,CACA,gBAAA,CACA,oBAAA,CAAA,YAAA,CACA,6BAAA,CAAA,qBAAA,CACA,0BAAA,CAAA,kBAAA,CACA,8BAAA,CAAA,sBAAA,CACA,4BAAA,CACA,UFsBF,CEnBA,UACE,aFsBF,CEnBA,iCACE,GACE,8BAAA,CAAA,sBFuBF,CErBA,GACE,+BAAA,CAAA,uBFwBF,CACF,CE9BA,yBACE,GACE,8BAAA,CAAA,sBFkCF,CEhCA,GACE,+BAAA,CAAA,uBFmCF,CACF","file":"main.e593cbc2.chunk.css","sourcesContent":["@import url(https://unpkg.com/bootstrap@4.1.0/dist/css/bootstrap.min.css);\nbody {\n margin: 0;\n padding: 0;\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", \"Roboto\", \"Oxygen\",\n \"Ubuntu\", \"Cantarell\", \"Fira Sans\", \"Droid Sans\", \"Helvetica Neue\",\n sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n font-family: source-code-pro, Menlo, Monaco, Consolas, \"Courier New\",\n monospace;\n}\n\n.footer {\n position: absolute;\n bottom: 0;\n width: 100%;\n height: 40px;\n background-color: #222222;\n}\n\n.App {\n text-align: center;\n}\n\n.App-logo {\n -webkit-animation: App-logo-spin infinite 20s linear;\n animation: App-logo-spin infinite 20s linear;\n height: 40vmin;\n pointer-events: none;\n}\n\n.App-header {\n background-color: #282c34;\n min-height: 100vh;\n display: -webkit-flex;\n display: flex;\n -webkit-flex-direction: column;\n flex-direction: column;\n -webkit-align-items: center;\n align-items: center;\n -webkit-justify-content: center;\n justify-content: center;\n font-size: calc(10px + 2vmin);\n color: white;\n}\n\n.App-link {\n color: #61dafb;\n}\n\n@-webkit-keyframes App-logo-spin {\n from {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n to {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n@keyframes App-logo-spin {\n from {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n to {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n\n","body {\n margin: 0;\n padding: 0;\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", \"Roboto\", \"Oxygen\",\n \"Ubuntu\", \"Cantarell\", \"Fira Sans\", \"Droid Sans\", \"Helvetica Neue\",\n sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n font-family: source-code-pro, Menlo, Monaco, Consolas, \"Courier New\",\n monospace;\n}\n",".footer {\n position: absolute;\n bottom: 0;\n width: 100%;\n height: 40px;\n background-color: #222222;\n}\n\n.App {\n text-align: center;\n}\n\n.App-logo {\n animation: App-logo-spin infinite 20s linear;\n height: 40vmin;\n pointer-events: none;\n}\n\n.App-header {\n background-color: #282c34;\n min-height: 100vh;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n font-size: calc(10px + 2vmin);\n color: white;\n}\n\n.App-link {\n color: #61dafb;\n}\n\n@keyframes App-logo-spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n}\n"]} -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/build/static/js/runtime~main.c5541365.js: -------------------------------------------------------------------------------- 1 | !function(e){function r(r){for(var n,f,i=r[0],l=r[1],a=r[2],c=0,s=[];c0.2%", 25 | "not dead", 26 | "not ie <= 11", 27 | "not op_mini all" 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/in28minutes/deploy-spring-boot-to-azure/3b94be8dd2a59cb7d4bab6b7b730c99d5cb6fb22/04-spring-boot-react-full-stack-h2/frontend/todo-app/public/favicon.ico -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 13 | 14 | 23 | My Todo Application 24 | 25 | 26 | 27 | 28 |
29 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/App.css: -------------------------------------------------------------------------------- 1 | .footer { 2 | position: absolute; 3 | bottom: 0; 4 | width: 100%; 5 | height: 40px; 6 | background-color: #222222; 7 | } 8 | 9 | .App { 10 | text-align: center; 11 | } 12 | 13 | .App-logo { 14 | animation: App-logo-spin infinite 20s linear; 15 | height: 40vmin; 16 | pointer-events: none; 17 | } 18 | 19 | .App-header { 20 | background-color: #282c34; 21 | min-height: 100vh; 22 | display: flex; 23 | flex-direction: column; 24 | align-items: center; 25 | justify-content: center; 26 | font-size: calc(10px + 2vmin); 27 | color: white; 28 | } 29 | 30 | .App-link { 31 | color: #61dafb; 32 | } 33 | 34 | @keyframes App-logo-spin { 35 | from { 36 | transform: rotate(0deg); 37 | } 38 | to { 39 | transform: rotate(360deg); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | //import FirstComponent from './components/learning-examples/FirstComponent' 3 | //import SecondComponent from './components/learning-examples/SecondComponent' 4 | //import ThirdComponent from './components/learning-examples/ThirdComponent' 5 | //import Counter from './components/counter/Counter' 6 | import TodoApp from './components/todo/TodoApp' 7 | import './App.css'; 8 | import './bootstrap.css'; 9 | 10 | class App extends Component { 11 | render() { 12 | return ( 13 |
14 | {/**/} 15 | 16 |
17 | ); 18 | } 19 | } 20 | 21 | // class LearningComponents extends Component { 22 | // render() { 23 | // return ( 24 | //
25 | // My Hello World 26 | // 27 | // 28 | // 29 | //
30 | // ); 31 | // } 32 | // } 33 | 34 | export default App; -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/Constants.js: -------------------------------------------------------------------------------- 1 | /* For Best Practices https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables*/ 2 | export const API_URL = 'http://localhost:8080' 3 | //export const API_URL = 'https://rest-api-full-stack-in28minutes.azurewebsites.net' 4 | export const JPA_API_URL = `${API_URL}/jpa` -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/api/todo/HelloWorldService.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios' 2 | import { API_URL } from '../../Constants' 3 | 4 | class HelloWorldService { 5 | 6 | executeHelloWorldService() { 7 | //console.log('executed service') 8 | return axios.get(`${API_URL}/hello-world`); 9 | } 10 | 11 | executeHelloWorldBeanService() { 12 | //console.log('executed service') 13 | return axios.get(`${API_URL}/hello-world-bean`); 14 | } 15 | 16 | executeHelloWorldPathVariableService(name) { 17 | //console.log('executed service') 18 | // let username = 'in28minutes' 19 | // let password = 'dummy' 20 | 21 | // let basicAuthHeader = 'Basic ' + window.btoa(username + ":" + password) 22 | 23 | return axios.get(`${API_URL}/hello-world/path-variable/${name}` 24 | // , 25 | // { 26 | // headers : { 27 | // authorization: basicAuthHeader 28 | // } 29 | // } 30 | ); 31 | } 32 | 33 | } 34 | 35 | export default new HelloWorldService() -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/api/todo/TodoDataService.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios' 2 | import { JPA_API_URL } from '../../Constants' 3 | 4 | class TodoDataService { 5 | 6 | retrieveAllTodos(name) { 7 | //console.log('executed service') 8 | return axios.get(`${JPA_API_URL}/users/${name}/todos`); 9 | } 10 | 11 | retrieveTodo(name, id) { 12 | //console.log('executed service') 13 | return axios.get(`${JPA_API_URL}/users/${name}/todos/${id}`); 14 | } 15 | 16 | deleteTodo(name, id) { 17 | //console.log('executed service') 18 | return axios.delete(`${JPA_API_URL}/users/${name}/todos/${id}`); 19 | } 20 | 21 | updateTodo(name, id, todo) { 22 | //console.log('executed service') 23 | return axios.put(`${JPA_API_URL}/users/${name}/todos/${id}`, todo); 24 | } 25 | 26 | createTodo(name, todo) { 27 | //console.log('executed service') 28 | return axios.post(`${JPA_API_URL}/users/${name}/todos/`, todo); 29 | } 30 | 31 | } 32 | 33 | export default new TodoDataService() -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/bootstrap.css: -------------------------------------------------------------------------------- 1 | @import url(https://unpkg.com/bootstrap@4.1.0/dist/css/bootstrap.min.css) -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/counter/Counter.css: -------------------------------------------------------------------------------- 1 | /* 2 | button { 3 | background-color: green; 4 | font-size : 16px; 5 | padding : 15px 30px; 6 | color : white; 7 | width : 100px; 8 | } 9 | 10 | .count { 11 | font-size : 50px; 12 | padding : 15px 30px; 13 | } 14 | 15 | .reset { 16 | background-color: red; 17 | width : 200px; 18 | } 19 | 20 | body { 21 | padding : 15px 30px; 22 | } 23 | */ -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/counter/Counter.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import PropTypes from 'prop-types' 3 | import './Counter.css' 4 | 5 | class Counter extends Component { 6 | 7 | constructor() { 8 | 9 | super(); //Error 1 10 | 11 | this.state = { 12 | counter: 0 13 | } 14 | 15 | this.increment = this.increment.bind(this); 16 | this.decrement = this.decrement.bind(this); 17 | this.reset = this.reset.bind(this); 18 | } 19 | 20 | render() { 21 | return ( 22 |
23 | 24 | 25 | 26 | {this.state.counter} 27 |
28 |
29 | ); 30 | } 31 | 32 | reset() { 33 | this.setState({ counter: 0 }); 34 | } 35 | 36 | increment(by) { 37 | //console.log(`increment from child - ${by}`) 38 | this.setState( 39 | (prevState) => { 40 | return { counter: prevState.counter + by } 41 | } 42 | ); 43 | } 44 | 45 | decrement(by) { 46 | //console.log(`increment from child - ${by}`) 47 | this.setState( 48 | (prevState) => { 49 | return { counter: prevState.counter - by } 50 | } 51 | ); 52 | } 53 | 54 | } 55 | 56 | class CounterButton extends Component { 57 | //Define the initial state in a constructor 58 | //state => counter 0 59 | //constructor() { 60 | // super(); //Error 1 61 | 62 | // this.state = { 63 | // counter : 0 64 | // } 65 | 66 | // this.increment = this.increment.bind(this); 67 | // this.decrement = this.decrement.bind(this); 68 | //} 69 | 70 | render() { 71 | //render = () => { 72 | //const style = {fontSize : "50px", padding : "15px 30px"}; 73 | return ( 74 |
75 | 76 | 77 | {/*{this.state.counter}*/} 79 |
80 | ) 81 | } 82 | 83 | // increment() { //Update state - counter++ 84 | // //console.log('increment'); 85 | // //this.state.counter++; //Bad Practice 86 | // this.setState({ 87 | // counter: this.state.counter + this.props.by 88 | // }); 89 | 90 | // this.props.incrementMethod(this.props.by); 91 | // } 92 | 93 | // decrement () { 94 | // this.setState({ 95 | // counter: this.state.counter - this.props.by 96 | // }); 97 | 98 | // this.props.decrementMethod(this.props.by); 99 | // } 100 | } 101 | 102 | CounterButton.defaultProps = { 103 | by: 1 104 | } 105 | 106 | CounterButton.propTypes = { 107 | by: PropTypes.number 108 | } 109 | 110 | export default Counter -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/learning-examples/FirstComponent.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | 3 | //Class Component 4 | class FirstComponent extends Component { 5 | render() { 6 | return ( 7 |
8 | FirstComponent 9 |
10 | ) 11 | } 12 | } 13 | 14 | export default FirstComponent -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/learning-examples/SecondComponent.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | 3 | class SecondComponent extends Component { 4 | render() { 5 | return ( 6 |
7 | Second Component 8 |
9 | ) 10 | } 11 | } 12 | 13 | export default SecondComponent -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/learning-examples/ThirdComponent.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | function ThirdComponent() { 4 | return ( 5 |
6 | Third Component 7 |
8 | ) 9 | } 10 | 11 | export default ThirdComponent -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/todo/AuthenticatedRoute.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import { Route, Redirect } from 'react-router-dom' 3 | import AuthenticationService from './AuthenticationService.js' 4 | 5 | class AuthenticatedRoute extends Component { 6 | render() { 7 | if (AuthenticationService.isUserLoggedIn()) { 8 | return 9 | } else { 10 | return 11 | } 12 | 13 | } 14 | } 15 | 16 | export default AuthenticatedRoute -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/todo/AuthenticationService.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios' 2 | import { API_URL } from '../../Constants' 3 | 4 | export const USER_NAME_SESSION_ATTRIBUTE_NAME = 'authenticatedUser' 5 | 6 | class AuthenticationService { 7 | 8 | executeBasicAuthenticationService(username, password) { 9 | return axios.get(`${API_URL}/basicauth`, 10 | { headers: { authorization: this.createBasicAuthToken(username, password) } }) 11 | } 12 | 13 | executeJwtAuthenticationService(username, password) { 14 | return axios.post(`${API_URL}/authenticate`, { 15 | username, 16 | password 17 | }) 18 | } 19 | 20 | createBasicAuthToken(username, password) { 21 | return 'Basic ' + window.btoa(username + ":" + password) 22 | } 23 | 24 | registerSuccessfulLogin(username, password) { 25 | //let basicAuthHeader = 'Basic ' + window.btoa(username + ":" + password) 26 | //console.log('registerSuccessfulLogin') 27 | sessionStorage.setItem(USER_NAME_SESSION_ATTRIBUTE_NAME, username) 28 | this.setupAxiosInterceptors(this.createBasicAuthToken(username, password)) 29 | } 30 | 31 | registerSuccessfulLoginForJwt(username, token) { 32 | sessionStorage.setItem(USER_NAME_SESSION_ATTRIBUTE_NAME, username) 33 | this.setupAxiosInterceptors(this.createJWTToken(token)) 34 | } 35 | 36 | createJWTToken(token) { 37 | return 'Bearer ' + token 38 | } 39 | 40 | 41 | logout() { 42 | sessionStorage.removeItem(USER_NAME_SESSION_ATTRIBUTE_NAME); 43 | } 44 | 45 | isUserLoggedIn() { 46 | let user = sessionStorage.getItem(USER_NAME_SESSION_ATTRIBUTE_NAME) 47 | if (user === null) return false 48 | return true 49 | } 50 | 51 | getLoggedInUserName() { 52 | let user = sessionStorage.getItem(USER_NAME_SESSION_ATTRIBUTE_NAME) 53 | if (user === null) return '' 54 | return user 55 | } 56 | 57 | setupAxiosInterceptors(token) { 58 | 59 | axios.interceptors.request.use( 60 | (config) => { 61 | if (this.isUserLoggedIn()) { 62 | config.headers.authorization = token 63 | } 64 | return config 65 | } 66 | ) 67 | } 68 | } 69 | 70 | export default new AuthenticationService() -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/todo/ErrorComponent.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | function ErrorComponent() { 4 | return
An Error Occurred. I don't know what to do! Contact support at abcd-efgh-ijkl
5 | } 6 | 7 | export default ErrorComponent -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/todo/FooterComponent.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | 3 | class FooterComponent extends Component { 4 | render() { 5 | return ( 6 |
7 | All Rights Reserved 2018 @in28minutes 8 |
9 | ) 10 | } 11 | } 12 | 13 | export default FooterComponent -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/todo/HeaderComponent.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import { Link } from 'react-router-dom' 3 | import AuthenticationService from './AuthenticationService.js' 4 | 5 | 6 | class HeaderComponent extends Component { 7 | render() { 8 | const isUserLoggedIn = AuthenticationService.isUserLoggedIn(); 9 | //console.log(isUserLoggedIn); 10 | 11 | return ( 12 |
13 | 24 |
25 | ) 26 | } 27 | } 28 | 29 | export default HeaderComponent -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/todo/ListTodosComponent.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import TodoDataService from '../../api/todo/TodoDataService.js' 3 | import AuthenticationService from './AuthenticationService.js' 4 | import moment from 'moment' 5 | 6 | class ListTodosComponent extends Component { 7 | constructor(props) { 8 | console.log('constructor') 9 | super(props) 10 | this.state = { 11 | todos: [], 12 | message: null 13 | } 14 | this.deleteTodoClicked = this.deleteTodoClicked.bind(this) 15 | this.updateTodoClicked = this.updateTodoClicked.bind(this) 16 | this.addTodoClicked = this.addTodoClicked.bind(this) 17 | this.refreshTodos = this.refreshTodos.bind(this) 18 | } 19 | 20 | componentWillUnmount() { 21 | console.log('componentWillUnmount') 22 | } 23 | 24 | shouldComponentUpdate(nextProps, nextState) { 25 | console.log('shouldComponentUpdate') 26 | console.log(nextProps) 27 | console.log(nextState) 28 | return true 29 | } 30 | 31 | componentDidMount() { 32 | console.log('componentDidMount') 33 | this.refreshTodos(); 34 | console.log(this.state) 35 | } 36 | 37 | refreshTodos() { 38 | let username = AuthenticationService.getLoggedInUserName() 39 | TodoDataService.retrieveAllTodos(username) 40 | .then( 41 | response => { 42 | //console.log(response); 43 | this.setState({ todos: response.data }) 44 | } 45 | ) 46 | } 47 | 48 | deleteTodoClicked(id) { 49 | let username = AuthenticationService.getLoggedInUserName() 50 | //console.log(id + " " + username); 51 | TodoDataService.deleteTodo(username, id) 52 | .then( 53 | response => { 54 | this.setState({ message: `Delete of todo ${id} Successful` }) 55 | this.refreshTodos() 56 | } 57 | ) 58 | 59 | } 60 | 61 | addTodoClicked() { 62 | this.props.history.push(`/todos/-1`) 63 | } 64 | 65 | updateTodoClicked(id) { 66 | console.log('update ' + id) 67 | this.props.history.push(`/todos/${id}`) 68 | // /todos/${id} 69 | // let username = AuthenticationService.getLoggedInUserName() 70 | // //console.log(id + " " + username); 71 | // TodoDataService.deleteTodo(username, id) 72 | // .then ( 73 | // response => { 74 | // this.setState({message : `Delete of todo ${id} Successful`}) 75 | // this.refreshTodos() 76 | // } 77 | // ) 78 | 79 | } 80 | 81 | render() { 82 | console.log('render') 83 | return ( 84 |
85 |

List Todos

86 | {this.state.message &&
{this.state.message}
} 87 |
88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | { 100 | this.state.todos.map( 101 | todo => 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | ) 110 | } 111 | 112 |
DescriptionTarget DateIsCompleted?UpdateDelete
{todo.description}{moment(todo.targetDate).format('YYYY-MM-DD')}{todo.done.toString()}
113 |
114 | 115 |
116 |
117 |
118 | ) 119 | } 120 | } 121 | 122 | export default ListTodosComponent -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/todo/LoginComponent.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import AuthenticationService from './AuthenticationService.js' 3 | 4 | class LoginComponent extends Component { 5 | 6 | constructor(props) { 7 | super(props) 8 | 9 | this.state = { 10 | username: 'in28minutes', 11 | password: '', 12 | hasLoginFailed: false, 13 | showSuccessMessage: false 14 | } 15 | // this.handleUsernameChange = this.handleUsernameChange.bind(this) 16 | // this.handlePasswordChange = this.handlePasswordChange.bind(this) 17 | this.handleChange = this.handleChange.bind(this) 18 | this.loginClicked = this.loginClicked.bind(this) 19 | } 20 | 21 | handleChange(event) { 22 | //console.log(this.state); 23 | this.setState( 24 | { 25 | [event.target.name] 26 | : event.target.value 27 | } 28 | ) 29 | } 30 | 31 | // handleUsernameChange(event) { 32 | // console.log(event.target.name); 33 | // this.setState( 34 | // { 35 | // [event.target.name] 36 | // :event.target.value 37 | // } 38 | // ) 39 | // } 40 | 41 | // handlePasswordChange(event) { 42 | // console.log(event.target.value); 43 | // this.setState({password:event.target.value}) 44 | // } 45 | 46 | loginClicked() { 47 | //in28minutes,dummy 48 | // if(this.state.username==='in28minutes' && this.state.password==='dummy'){ 49 | // AuthenticationService.registerSuccessfulLogin(this.state.username,this.state.password) 50 | // this.props.history.push(`/welcome/${this.state.username}`) 51 | // //this.setState({showSuccessMessage:true}) 52 | // //this.setState({hasLoginFailed:false}) 53 | // } 54 | // else { 55 | // this.setState({showSuccessMessage:false}) 56 | // this.setState({hasLoginFailed:true}) 57 | // } 58 | 59 | // AuthenticationService 60 | // .executeBasicAuthenticationService(this.state.username, this.state.password) 61 | // .then(() => { 62 | // AuthenticationService.registerSuccessfulLogin(this.state.username,this.state.password) 63 | // this.props.history.push(`/welcome/${this.state.username}`) 64 | // }).catch( () =>{ 65 | // this.setState({showSuccessMessage:false}) 66 | // this.setState({hasLoginFailed:true}) 67 | // }) 68 | AuthenticationService 69 | .executeJwtAuthenticationService(this.state.username, this.state.password) 70 | .then((response) => { 71 | AuthenticationService.registerSuccessfulLoginForJwt(this.state.username, response.data.token) 72 | this.props.history.push(`/welcome/${this.state.username}`) 73 | }).catch(() => { 74 | this.setState({ showSuccessMessage: false }) 75 | this.setState({ hasLoginFailed: true }) 76 | }) 77 | 78 | } 79 | 80 | render() { 81 | return ( 82 |
83 |

Login

84 |
85 | {/**/} 86 | {this.state.hasLoginFailed &&
Invalid Credentials
} 87 | {this.state.showSuccessMessage &&
Login Sucessful
} 88 | {/**/} 89 | User Name: 90 | Password: 91 | 92 |
93 |
94 | ) 95 | } 96 | } 97 | 98 | export default LoginComponent -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/todo/LogoutComponent.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | 3 | class LogoutComponent extends Component { 4 | render() { 5 | return ( 6 | <> 7 |

You are logged out

8 |
9 | Thank You for Using Our Application. 10 |
11 | 12 | ) 13 | } 14 | } 15 | 16 | export default LogoutComponent -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/todo/TodoApp.jsx: -------------------------------------------------------------------------------- 1 | import React, {Component} from 'react' 2 | import {BrowserRouter as Router, Route, Switch} from 'react-router-dom' 3 | import AuthenticatedRoute from './AuthenticatedRoute.jsx' 4 | import LoginComponent from './LoginComponent.jsx' 5 | import ListTodosComponent from './ListTodosComponent.jsx' 6 | import ErrorComponent from './ErrorComponent.jsx' 7 | import HeaderComponent from './HeaderComponent.jsx' 8 | import FooterComponent from './FooterComponent.jsx' 9 | import LogoutComponent from './LogoutComponent.jsx' 10 | import WelcomeComponent from './WelcomeComponent.jsx' 11 | import TodoComponent from './TodoComponent.jsx' 12 | 13 | class TodoApp extends Component { 14 | render() { 15 | return ( 16 |
17 | 18 | <> 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | {/* 34 | */} 35 |
36 | ) 37 | } 38 | } 39 | 40 | export default TodoApp -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/todo/TodoComponent.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import moment from 'moment' 3 | import { Formik, Form, Field, ErrorMessage } from 'formik'; 4 | import TodoDataService from '../../api/todo/TodoDataService.js' 5 | import AuthenticationService from './AuthenticationService.js' 6 | 7 | class TodoComponent extends Component { 8 | constructor(props) { 9 | super(props) 10 | 11 | this.state = { 12 | id: this.props.match.params.id, 13 | description: '', 14 | targetDate: moment(new Date()).format('YYYY-MM-DD') 15 | } 16 | 17 | this.onSubmit = this.onSubmit.bind(this) 18 | this.validate = this.validate.bind(this) 19 | 20 | } 21 | 22 | componentDidMount() { 23 | 24 | if (this.state.id === -1) { 25 | return 26 | } 27 | 28 | let username = AuthenticationService.getLoggedInUserName() 29 | 30 | TodoDataService.retrieveTodo(username, this.state.id) 31 | .then(response => this.setState({ 32 | description: response.data.description, 33 | targetDate: moment(response.data.targetDate).format('YYYY-MM-DD') 34 | })) 35 | } 36 | 37 | validate(values) { 38 | let errors = {} 39 | if (!values.description) { 40 | errors.description = 'Enter a Description' 41 | } else if (values.description.length < 5) { 42 | errors.description = 'Enter atleast 5 Characters in Description' 43 | } 44 | 45 | if (!moment(values.targetDate).isValid()) { 46 | errors.targetDate = 'Enter a valid Target Date' 47 | } 48 | 49 | return errors 50 | 51 | } 52 | 53 | onSubmit(values) { 54 | let username = AuthenticationService.getLoggedInUserName() 55 | 56 | let todo = { 57 | id: this.state.id, 58 | description: values.description, 59 | targetDate: values.targetDate 60 | } 61 | 62 | if (this.state.id === -1) { 63 | TodoDataService.createTodo(username, todo) 64 | .then(() => this.props.history.push('/todos')) 65 | } else { 66 | TodoDataService.updateTodo(username, this.state.id, todo) 67 | .then(() => this.props.history.push('/todos')) 68 | } 69 | 70 | console.log(values); 71 | } 72 | 73 | render() { 74 | 75 | let { description, targetDate } = this.state 76 | //let targetDate = this.state.targetDate 77 | 78 | return ( 79 |
80 |

Todo

81 |
82 | 90 | { 91 | (props) => ( 92 |
93 | 95 | 97 |
98 | 99 | 100 |
101 |
102 | 103 | 104 |
105 | 106 | 107 | ) 108 | } 109 |
110 | 111 |
112 |
113 | ) 114 | } 115 | } 116 | 117 | export default TodoComponent -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/components/todo/WelcomeComponent.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import { Link } from 'react-router-dom' 3 | import HelloWorldService from '../../api/todo/HelloWorldService.js' 4 | 5 | class WelcomeComponent extends Component { 6 | 7 | constructor(props) { 8 | super(props) 9 | this.retrieveWelcomeMessage = this.retrieveWelcomeMessage.bind(this) 10 | this.state = { 11 | welcomeMessage: '' 12 | } 13 | this.handleSuccessfulResponse = this.handleSuccessfulResponse.bind(this) 14 | this.handleError = this.handleError.bind(this) 15 | } 16 | 17 | render() { 18 | return ( 19 | <> 20 |

Welcome!

21 |
22 | Welcome {this.props.match.params.name}. 23 | You can manage your todos here. 24 |
25 |
26 | Click here to get a customized welcome message. 27 | 29 |
30 |
31 | {this.state.welcomeMessage} 32 |
33 | 34 | 35 | ) 36 | } 37 | 38 | retrieveWelcomeMessage() { 39 | // HelloWorldService.executeHelloWorldService() 40 | // .then( response => this.handleSuccessfulResponse(response) ) 41 | 42 | // HelloWorldService.executeHelloWorldBeanService() 43 | // .then( response => this.handleSuccessfulResponse(response) ) 44 | 45 | HelloWorldService.executeHelloWorldPathVariableService(this.props.match.params.name) 46 | .then(response => this.handleSuccessfulResponse(response)) 47 | .catch(error => this.handleError(error)) 48 | } 49 | 50 | handleSuccessfulResponse(response) { 51 | console.log(response) 52 | this.setState({ welcomeMessage: response.data.message }) 53 | } 54 | 55 | handleError(error) { 56 | 57 | console.log(error.response) 58 | 59 | let errorMessage = ''; 60 | 61 | if (error.message) 62 | errorMessage += error.message 63 | 64 | if (error.response && error.response.data) { 65 | errorMessage += error.response.data.message 66 | } 67 | 68 | this.setState({ welcomeMessage: errorMessage }) 69 | } 70 | 71 | } 72 | 73 | 74 | export default WelcomeComponent -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 6 | sans-serif; 7 | -webkit-font-smoothing: antialiased; 8 | -moz-osx-font-smoothing: grayscale; 9 | } 10 | 11 | code { 12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 13 | monospace; 14 | } 15 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/frontend/todo-app/src/web.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 4.0.0 7 | com.in28minutes.rest.webservices 8 | 04-rest-api-full-stack 9 | 0.0.1-SNAPSHOT 10 | jar 11 | rest-api-full-stack 12 | Demo project for Spring Boot 13 | 14 | org.springframework.boot 15 | spring-boot-starter-parent 16 | 2.1.7.RELEASE 17 | 18 | 19 | 20 | 21 | UTF-8 22 | UTF-8 23 | 1.8 24 | 3.1.1 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-data-jpa 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-web 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-starter-security 38 | 39 | 40 | io.jsonwebtoken 41 | jjwt 42 | 0.9.1 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-devtools 47 | runtime 48 | 49 | 50 | com.h2database 51 | h2 52 | runtime 53 | 54 | 55 | javax.xml.bind 56 | jaxb-api 57 | 58 | 59 | com.sun.xml.bind 60 | jaxb-impl 61 | 2.3.1 62 | 63 | 64 | org.glassfish.jaxb 65 | jaxb-runtime 66 | 67 | 68 | javax.activation 69 | activation 70 | 1.1.1 71 | 72 | 73 | org.springframework.boot 74 | spring-boot-starter-test 75 | test 76 | 77 | 78 | 79 | rest-api-full-stack 80 | 81 | 82 | org.springframework.boot 83 | spring-boot-maven-plugin 84 | 85 | 86 | com.microsoft.azure 87 | azure-webapp-maven-plugin 88 | 1.7.0 89 | 90 | 91 | 92 | 93 | 94 | spring-snapshots 95 | Spring Snapshots 96 | https://repo.spring.io/snapshot 97 | 98 | true 99 | 100 | 101 | 102 | spring-milestones 103 | Spring Milestones 104 | https://repo.spring.io/milestone 105 | 106 | false 107 | 108 | 109 | 110 | 111 | 112 | spring-snapshots 113 | Spring Snapshots 114 | https://repo.spring.io/snapshot 115 | 116 | true 117 | 118 | 119 | 120 | spring-milestones 121 | Spring Milestones 122 | https://repo.spring.io/milestone 123 | 124 | false 125 | 126 | 127 | 128 | 129 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/react_00_architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/in28minutes/deploy-spring-boot-to-azure/3b94be8dd2a59cb7d4bab6b7b730c99d5cb6fb22/04-spring-boot-react-full-stack-h2/restful-web-services/react_00_architecture.png -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/basic/auth/AuthenticationBean.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.basic.auth; 2 | public class AuthenticationBean { 3 | 4 | private String message; 5 | 6 | public AuthenticationBean(String message) { 7 | this.message = message; 8 | } 9 | 10 | public String getMessage() { 11 | return message; 12 | } 13 | 14 | public void setMessage(String message) { 15 | this.message = message; 16 | } 17 | 18 | @Override 19 | public String toString() { 20 | return String.format("HelloWorldBean [message=%s]", message); 21 | } 22 | 23 | } 24 | 25 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/basic/auth/BasicAuthenticationController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.basic.auth; 2 | import org.springframework.web.bind.annotation.GetMapping; 3 | import org.springframework.web.bind.annotation.RestController; 4 | 5 | //Controller 6 | //@CrossOrigin(origins="http://localhost:4200")Replace with global config 7 | @RestController 8 | public class BasicAuthenticationController { 9 | 10 | @GetMapping(path = "/basicauth") 11 | public AuthenticationBean helloWorldBean() { 12 | //throw new RuntimeException("Some Error has Happened! Contact Support at ***-***"); 13 | return new AuthenticationBean("You are authenticated"); 14 | } 15 | } -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/basic/auth/SpringSecurityConfigurationBasicAuth.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.basic.auth; 2 | import org.springframework.context.annotation.Configuration; 3 | import org.springframework.http.HttpMethod; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 6 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 7 | 8 | @Configuration 9 | @EnableWebSecurity 10 | public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter{ 11 | 12 | @Override 13 | protected void configure(HttpSecurity http) throws Exception { 14 | http 15 | .csrf().disable() 16 | .authorizeRequests() 17 | .antMatchers(HttpMethod.OPTIONS,"/**").permitAll() 18 | .anyRequest().authenticated() 19 | .and() 20 | //.formLogin().and() 21 | .httpBasic(); 22 | } 23 | } -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/RestfulWebServicesApplication.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.web.servlet.config.annotation.CorsRegistry; 7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 8 | 9 | @SpringBootApplication 10 | public class RestfulWebServicesApplication { 11 | 12 | @Bean 13 | public WebMvcConfigurer corsConfigurer() { 14 | return new WebMvcConfigurer() { 15 | @Override 16 | public void addCorsMappings(CorsRegistry registry) { 17 | registry.addMapping("/**").allowedMethods("*").allowedOrigins("*"); 18 | } 19 | }; 20 | } 21 | 22 | public static void main(String[] args) { 23 | SpringApplication.run(RestfulWebServicesApplication.class, args); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/helloworld/HelloWorldBean.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.helloworld; 2 | 3 | public class HelloWorldBean { 4 | 5 | private String message; 6 | 7 | public HelloWorldBean(String message) { 8 | this.message = message; 9 | } 10 | 11 | public String getMessage() { 12 | return message; 13 | } 14 | 15 | public void setMessage(String message) { 16 | this.message = message; 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | return String.format("Hello World Bean [message=%s]", message); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/helloworld/HelloWorldController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.helloworld; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.PathVariable; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @RestController 8 | public class HelloWorldController { 9 | 10 | @GetMapping(path = "/hello-world") 11 | public String helloWorld() { 12 | return "Hello World"; 13 | } 14 | 15 | @GetMapping(path = "/hello-world-bean") 16 | public HelloWorldBean helloWorldBean() { 17 | return new HelloWorldBean("Hello World"); 18 | } 19 | 20 | ///hello-world/path-variable/in28minutes 21 | @GetMapping(path = "/hello-world/path-variable/{name}") 22 | public HelloWorldBean helloWorldPathVariable(@PathVariable String name) { 23 | return new HelloWorldBean(String.format("Hello World, %s", name)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/jwt/JWTWebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.jwt; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.http.HttpMethod; 8 | import org.springframework.security.authentication.AuthenticationManager; 9 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 10 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 11 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 12 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 13 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 14 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 15 | import org.springframework.security.config.http.SessionCreationPolicy; 16 | import org.springframework.security.core.userdetails.UserDetailsService; 17 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 18 | import org.springframework.security.crypto.password.PasswordEncoder; 19 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 20 | 21 | @Configuration 22 | @EnableWebSecurity 23 | @EnableGlobalMethodSecurity(prePostEnabled = true) 24 | public class JWTWebSecurityConfig extends WebSecurityConfigurerAdapter { 25 | 26 | @Autowired 27 | private JwtUnAuthorizedResponseAuthenticationEntryPoint jwtUnAuthorizedResponseAuthenticationEntryPoint; 28 | 29 | @Autowired 30 | private UserDetailsService jwtInMemoryUserDetailsService; 31 | 32 | @Autowired 33 | private JwtTokenAuthorizationOncePerRequestFilter jwtAuthenticationTokenFilter; 34 | 35 | @Value("${jwt.get.token.uri}") 36 | private String authenticationPath; 37 | 38 | @Autowired 39 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 40 | auth 41 | .userDetailsService(jwtInMemoryUserDetailsService) 42 | .passwordEncoder(passwordEncoderBean()); 43 | } 44 | 45 | @Bean 46 | public PasswordEncoder passwordEncoderBean() { 47 | return new BCryptPasswordEncoder(); 48 | } 49 | 50 | @Bean 51 | @Override 52 | public AuthenticationManager authenticationManagerBean() throws Exception { 53 | return super.authenticationManagerBean(); 54 | } 55 | 56 | @Override 57 | protected void configure(HttpSecurity httpSecurity) throws Exception { 58 | httpSecurity 59 | .csrf().disable() 60 | .exceptionHandling().authenticationEntryPoint(jwtUnAuthorizedResponseAuthenticationEntryPoint).and() 61 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() 62 | .authorizeRequests() 63 | .anyRequest().authenticated(); 64 | 65 | httpSecurity 66 | .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); 67 | 68 | httpSecurity 69 | .headers() 70 | .frameOptions().sameOrigin() //H2 Console Needs this setting 71 | .cacheControl(); //disable caching 72 | } 73 | 74 | @Override 75 | public void configure(WebSecurity webSecurity) throws Exception { 76 | webSecurity 77 | .ignoring() 78 | .antMatchers( 79 | HttpMethod.POST, 80 | authenticationPath 81 | ) 82 | .antMatchers(HttpMethod.OPTIONS, "/**") 83 | .and() 84 | .ignoring() 85 | .antMatchers( 86 | HttpMethod.GET, 87 | "/" //Other Stuff You want to Ignore 88 | ) 89 | .and() 90 | .ignoring() 91 | .antMatchers("/h2-console/**/**");//Should not be in Production! 92 | } 93 | } 94 | 95 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/jwt/JwtInMemoryUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.jwt; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Optional; 6 | 7 | import org.springframework.security.core.userdetails.UserDetails; 8 | import org.springframework.security.core.userdetails.UserDetailsService; 9 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 10 | 11 | 12 | //This is not used! 13 | //@Service 14 | public class JwtInMemoryUserDetailsService implements UserDetailsService { 15 | 16 | static List inMemoryUserList = new ArrayList<>(); 17 | 18 | static { 19 | inMemoryUserList.add(new JwtUserDetails(1L, "in28minutes", 20 | "$2a$10$3zHzb.Npv1hfZbLEU5qsdOju/tk2je6W6PnNnY.c1ujWPcZh4PL6e", "ROLE_USER_2")); 21 | } 22 | 23 | @Override 24 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 25 | Optional findFirst = inMemoryUserList.stream() 26 | .filter(user -> user.getUsername().equals(username)).findFirst(); 27 | 28 | if (!findFirst.isPresent()) { 29 | throw new UsernameNotFoundException(String.format("USER_NOT_FOUND '%s'.", username)); 30 | } 31 | 32 | return findFirst.get(); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/jwt/JwtTokenAuthorizationOncePerRequestFilter.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.jwt; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.FilterChain; 6 | import javax.servlet.ServletException; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.beans.factory.annotation.Value; 14 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 15 | import org.springframework.security.core.context.SecurityContextHolder; 16 | import org.springframework.security.core.userdetails.UserDetails; 17 | import org.springframework.security.core.userdetails.UserDetailsService; 18 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 19 | import org.springframework.stereotype.Component; 20 | import org.springframework.web.filter.OncePerRequestFilter; 21 | 22 | import io.jsonwebtoken.ExpiredJwtException; 23 | 24 | @Component 25 | public class JwtTokenAuthorizationOncePerRequestFilter extends OncePerRequestFilter { 26 | 27 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 28 | 29 | @Autowired 30 | private UserDetailsService jwtInMemoryUserDetailsService; 31 | 32 | @Autowired 33 | private JwtTokenUtil jwtTokenUtil; 34 | 35 | @Value("${jwt.http.request.header}") 36 | private String tokenHeader; 37 | 38 | @Override 39 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { 40 | logger.debug("Authentication Request For '{}'", request.getRequestURL()); 41 | 42 | final String requestTokenHeader = request.getHeader(this.tokenHeader); 43 | 44 | String username = null; 45 | String jwtToken = null; 46 | if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) { 47 | jwtToken = requestTokenHeader.substring(7); 48 | try { 49 | username = jwtTokenUtil.getUsernameFromToken(jwtToken); 50 | } catch (IllegalArgumentException e) { 51 | logger.error("JWT_TOKEN_UNABLE_TO_GET_USERNAME", e); 52 | } catch (ExpiredJwtException e) { 53 | logger.warn("JWT_TOKEN_EXPIRED", e); 54 | } 55 | } else { 56 | logger.warn("JWT_TOKEN_DOES_NOT_START_WITH_BEARER_STRING"); 57 | } 58 | 59 | logger.debug("JWT_TOKEN_USERNAME_VALUE '{}'", username); 60 | if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { 61 | 62 | UserDetails userDetails = this.jwtInMemoryUserDetailsService.loadUserByUsername(username); 63 | 64 | if (jwtTokenUtil.validateToken(jwtToken, userDetails)) { 65 | UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); 66 | usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); 67 | SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); 68 | } 69 | } 70 | 71 | chain.doFilter(request, response); 72 | } 73 | } 74 | 75 | 76 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/jwt/JwtTokenUtil.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.jwt; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | import java.util.function.Function; 8 | 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.security.core.userdetails.UserDetails; 11 | import org.springframework.stereotype.Component; 12 | 13 | import io.jsonwebtoken.Claims; 14 | import io.jsonwebtoken.Clock; 15 | import io.jsonwebtoken.Jwts; 16 | import io.jsonwebtoken.SignatureAlgorithm; 17 | import io.jsonwebtoken.impl.DefaultClock; 18 | 19 | @Component 20 | public class JwtTokenUtil implements Serializable { 21 | 22 | static final String CLAIM_KEY_USERNAME = "sub"; 23 | static final String CLAIM_KEY_CREATED = "iat"; 24 | private static final long serialVersionUID = -3301605591108950415L; 25 | private Clock clock = DefaultClock.INSTANCE; 26 | 27 | @Value("${jwt.signing.key.secret}") 28 | private String secret; 29 | 30 | @Value("${jwt.token.expiration.in.seconds}") 31 | private Long expiration; 32 | 33 | public String getUsernameFromToken(String token) { 34 | return getClaimFromToken(token, Claims::getSubject); 35 | } 36 | 37 | public Date getIssuedAtDateFromToken(String token) { 38 | return getClaimFromToken(token, Claims::getIssuedAt); 39 | } 40 | 41 | public Date getExpirationDateFromToken(String token) { 42 | return getClaimFromToken(token, Claims::getExpiration); 43 | } 44 | 45 | public T getClaimFromToken(String token, Function claimsResolver) { 46 | final Claims claims = getAllClaimsFromToken(token); 47 | return claimsResolver.apply(claims); 48 | } 49 | 50 | private Claims getAllClaimsFromToken(String token) { 51 | return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); 52 | } 53 | 54 | private Boolean isTokenExpired(String token) { 55 | final Date expiration = getExpirationDateFromToken(token); 56 | return expiration.before(clock.now()); 57 | } 58 | 59 | private Boolean ignoreTokenExpiration(String token) { 60 | // here you specify tokens, for that the expiration is ignored 61 | return false; 62 | } 63 | 64 | public String generateToken(UserDetails userDetails) { 65 | Map claims = new HashMap<>(); 66 | return doGenerateToken(claims, userDetails.getUsername()); 67 | } 68 | 69 | private String doGenerateToken(Map claims, String subject) { 70 | final Date createdDate = clock.now(); 71 | final Date expirationDate = calculateExpirationDate(createdDate); 72 | 73 | return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(createdDate) 74 | .setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, secret).compact(); 75 | } 76 | 77 | public Boolean canTokenBeRefreshed(String token) { 78 | return (!isTokenExpired(token) || ignoreTokenExpiration(token)); 79 | } 80 | 81 | public String refreshToken(String token) { 82 | final Date createdDate = clock.now(); 83 | final Date expirationDate = calculateExpirationDate(createdDate); 84 | 85 | final Claims claims = getAllClaimsFromToken(token); 86 | claims.setIssuedAt(createdDate); 87 | claims.setExpiration(expirationDate); 88 | 89 | return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact(); 90 | } 91 | 92 | public Boolean validateToken(String token, UserDetails userDetails) { 93 | JwtUserDetails user = (JwtUserDetails) userDetails; 94 | final String username = getUsernameFromToken(token); 95 | return (username.equals(user.getUsername()) && !isTokenExpired(token)); 96 | } 97 | 98 | private Date calculateExpirationDate(Date createdDate) { 99 | return new Date(createdDate.getTime() + expiration * 1000); 100 | } 101 | } 102 | 103 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/jwt/JwtUnAuthorizedResponseAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.jwt; 2 | 3 | import java.io.IOException; 4 | import java.io.Serializable; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | import org.springframework.security.core.AuthenticationException; 10 | import org.springframework.security.web.AuthenticationEntryPoint; 11 | import org.springframework.stereotype.Component; 12 | 13 | @Component 14 | public class JwtUnAuthorizedResponseAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable { 15 | 16 | private static final long serialVersionUID = -8970718410437077606L; 17 | 18 | @Override 19 | public void commence(HttpServletRequest request, HttpServletResponse response, 20 | AuthenticationException authException) throws IOException { 21 | response.sendError(HttpServletResponse.SC_UNAUTHORIZED, 22 | "You would need to provide the Jwt Token to Access This resource"); 23 | } 24 | } -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/jwt/JwtUserDetails.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.jwt; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.List; 6 | 7 | import org.springframework.security.core.GrantedAuthority; 8 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | 11 | import com.fasterxml.jackson.annotation.JsonIgnore; 12 | 13 | public class JwtUserDetails implements UserDetails { 14 | 15 | private static final long serialVersionUID = 5155720064139820502L; 16 | 17 | private final Long id; 18 | private final String username; 19 | private final String password; 20 | private final Collection authorities; 21 | 22 | public JwtUserDetails(Long id, String username, String password, String role) { 23 | this.id = id; 24 | this.username = username; 25 | this.password = password; 26 | 27 | List authorities = new ArrayList(); 28 | authorities.add(new SimpleGrantedAuthority(role)); 29 | 30 | this.authorities = authorities; 31 | } 32 | 33 | @JsonIgnore 34 | public Long getId() { 35 | return id; 36 | } 37 | 38 | @Override 39 | public String getUsername() { 40 | return username; 41 | } 42 | 43 | @JsonIgnore 44 | @Override 45 | public boolean isAccountNonExpired() { 46 | return true; 47 | } 48 | 49 | @JsonIgnore 50 | @Override 51 | public boolean isAccountNonLocked() { 52 | return true; 53 | } 54 | 55 | @JsonIgnore 56 | @Override 57 | public boolean isCredentialsNonExpired() { 58 | return true; 59 | } 60 | 61 | @JsonIgnore 62 | @Override 63 | public String getPassword() { 64 | return password; 65 | } 66 | 67 | @Override 68 | public Collection getAuthorities() { 69 | return authorities; 70 | } 71 | 72 | @Override 73 | public boolean isEnabled() { 74 | return true; 75 | } 76 | 77 | } 78 | 79 | 80 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/jwt/JwtUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.jwt; 2 | import org.springframework.beans.factory.annotation.Autowired; 3 | import org.springframework.security.core.userdetails.UserDetails; 4 | import org.springframework.security.core.userdetails.UserDetailsService; 5 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 6 | import org.springframework.stereotype.Service; 7 | 8 | @Service 9 | public class JwtUserDetailsService implements UserDetailsService { 10 | 11 | @Autowired 12 | private UserRepository userRepository; 13 | 14 | @Override 15 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 16 | User user = userRepository.findByUsername(username); 17 | 18 | if (user == null) { 19 | throw new UsernameNotFoundException(String.format("USER_NOT_FOUND '%s'.", username)); 20 | } else { 21 | return create(user); 22 | } 23 | } 24 | 25 | public static JwtUserDetails create(User user) { 26 | return new JwtUserDetails(user.getId(), user.getUsername(), user.getPassword(), user.getRole()); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/jwt/User.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.jwt; 2 | import javax.persistence.Column; 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | import javax.persistence.SequenceGenerator; 8 | import javax.persistence.Table; 9 | import javax.validation.constraints.NotNull; 10 | import javax.validation.constraints.Size; 11 | 12 | @Entity 13 | @Table(name = "USER") 14 | public class User { 15 | 16 | @Id 17 | @Column(name = "ID") 18 | @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq") 19 | @SequenceGenerator(name = "user_seq", sequenceName = "user_seq", allocationSize = 1) 20 | private Long id; 21 | 22 | @Column(name = "USERNAME", length = 50, unique = true) 23 | @NotNull 24 | @Size(min = 4, max = 50) 25 | private String username; 26 | 27 | @Column(name = "PASSWORD", length = 100) 28 | @Size(min = 4, max = 100) 29 | @NotNull 30 | private String password; 31 | 32 | @Column(name = "ROLE", length = 100) 33 | @Size(min = 4, max = 100) 34 | @NotNull 35 | private String role; 36 | 37 | public Long getId() { 38 | return id; 39 | } 40 | 41 | public void setId(Long id) { 42 | this.id = id; 43 | } 44 | 45 | public String getUsername() { 46 | return username; 47 | } 48 | 49 | public void setUsername(String username) { 50 | this.username = username; 51 | } 52 | 53 | public String getPassword() { 54 | return password; 55 | } 56 | 57 | public void setPassword(String password) { 58 | this.password = password; 59 | } 60 | 61 | public String getRole() { 62 | return role; 63 | } 64 | 65 | public void setRole(String role) { 66 | this.role = role; 67 | } 68 | 69 | 70 | } -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/jwt/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.jwt; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface UserRepository extends JpaRepository { 6 | User findByUsername(String username); 7 | } 8 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/jwt/resource/AuthenticationException.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.jwt.resource; 2 | public class AuthenticationException extends RuntimeException { 3 | /** 4 | * 5 | */ 6 | private static final long serialVersionUID = 5978387939943664344L; 7 | 8 | public AuthenticationException(String message, Throwable cause) { 9 | super(message, cause); 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/jwt/resource/JwtAuthenticationRestController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.jwt.resource; 2 | 3 | import java.util.Objects; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.security.authentication.AuthenticationManager; 12 | import org.springframework.security.authentication.BadCredentialsException; 13 | import org.springframework.security.authentication.DisabledException; 14 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 15 | import org.springframework.security.core.userdetails.UserDetails; 16 | import org.springframework.security.core.userdetails.UserDetailsService; 17 | import org.springframework.web.bind.annotation.ExceptionHandler; 18 | import org.springframework.web.bind.annotation.RequestBody; 19 | import org.springframework.web.bind.annotation.RequestMapping; 20 | import org.springframework.web.bind.annotation.RequestMethod; 21 | import org.springframework.web.bind.annotation.RestController; 22 | 23 | import com.in28minutes.rest.webservices.restfulwebservices.jwt.JwtTokenUtil; 24 | 25 | @RestController 26 | //@CrossOrigin(origins="http://localhost:4200")Replace with global config 27 | public class JwtAuthenticationRestController { 28 | 29 | @Value("${jwt.http.request.header}") 30 | private String tokenHeader; 31 | 32 | @Autowired 33 | private AuthenticationManager authenticationManager; 34 | 35 | @Autowired 36 | private JwtTokenUtil jwtTokenUtil; 37 | 38 | @Autowired 39 | private UserDetailsService jwtInMemoryUserDetailsService; 40 | 41 | @RequestMapping(value = "${jwt.get.token.uri}", method = RequestMethod.POST) 42 | public ResponseEntity createAuthenticationToken(@RequestBody JwtTokenRequest authenticationRequest) 43 | throws AuthenticationException { 44 | 45 | authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword()); 46 | 47 | final UserDetails userDetails = jwtInMemoryUserDetailsService.loadUserByUsername(authenticationRequest.getUsername()); 48 | 49 | final String token = jwtTokenUtil.generateToken(userDetails); 50 | 51 | return ResponseEntity.ok(new JwtTokenResponse(token)); 52 | } 53 | 54 | @RequestMapping(value = "${jwt.refresh.token.uri}", method = RequestMethod.GET) 55 | public ResponseEntity refreshAndGetAuthenticationToken(HttpServletRequest request) { 56 | String authToken = request.getHeader(tokenHeader); 57 | final String token = authToken.substring(7); 58 | String username = jwtTokenUtil.getUsernameFromToken(token); 59 | 60 | jwtInMemoryUserDetailsService.loadUserByUsername(username); 61 | 62 | if (jwtTokenUtil.canTokenBeRefreshed(token)) { 63 | String refreshedToken = jwtTokenUtil.refreshToken(token); 64 | return ResponseEntity.ok(new JwtTokenResponse(refreshedToken)); 65 | } else { 66 | return ResponseEntity.badRequest().body(null); 67 | } 68 | } 69 | 70 | @ExceptionHandler({ AuthenticationException.class }) 71 | public ResponseEntity handleAuthenticationException(AuthenticationException e) { 72 | return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage()); 73 | } 74 | 75 | private void authenticate(String username, String password) { 76 | Objects.requireNonNull(username); 77 | Objects.requireNonNull(password); 78 | 79 | try { 80 | authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); 81 | } catch (DisabledException e) { 82 | throw new AuthenticationException("USER_DISABLED", e); 83 | } catch (BadCredentialsException e) { 84 | throw new AuthenticationException("INVALID_CREDENTIALS", e); 85 | } 86 | } 87 | } 88 | 89 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/jwt/resource/JwtTokenRequest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.jwt.resource; 2 | 3 | import java.io.Serializable; 4 | 5 | public class JwtTokenRequest implements Serializable { 6 | 7 | private static final long serialVersionUID = -5616176897013108345L; 8 | 9 | private String username; 10 | private String password; 11 | 12 | public JwtTokenRequest() { 13 | super(); 14 | } 15 | 16 | public JwtTokenRequest(String username, String password) { 17 | this.setUsername(username); 18 | this.setPassword(password); 19 | } 20 | 21 | public String getUsername() { 22 | return this.username; 23 | } 24 | 25 | public void setUsername(String username) { 26 | this.username = username; 27 | } 28 | 29 | public String getPassword() { 30 | return this.password; 31 | } 32 | 33 | public void setPassword(String password) { 34 | this.password = password; 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/jwt/resource/JwtTokenResponse.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.jwt.resource; 2 | 3 | import java.io.Serializable; 4 | 5 | public class JwtTokenResponse implements Serializable { 6 | 7 | private static final long serialVersionUID = 8317676219297719109L; 8 | 9 | private final String token; 10 | 11 | public JwtTokenResponse(String token) { 12 | this.token = token; 13 | } 14 | 15 | public String getToken() { 16 | return this.token; 17 | } 18 | } -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/todo/Todo.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.todo; 2 | 3 | import java.util.Date; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.Id; 8 | 9 | @Entity 10 | public class Todo { 11 | @Id 12 | @GeneratedValue 13 | private Long id; 14 | private String username; 15 | private String description; 16 | private Date targetDate; 17 | private boolean isDone; 18 | 19 | public Todo() { 20 | 21 | } 22 | 23 | public Todo(long id, String username, String description, Date targetDate, boolean isDone) { 24 | super(); 25 | this.id = id; 26 | this.username = username; 27 | this.description = description; 28 | this.targetDate = targetDate; 29 | this.isDone = isDone; 30 | } 31 | 32 | public Long getId() { 33 | return id; 34 | } 35 | 36 | public void setId(Long id) { 37 | this.id = id; 38 | } 39 | 40 | public String getUsername() { 41 | return username; 42 | } 43 | 44 | public void setUsername(String username) { 45 | this.username = username; 46 | } 47 | 48 | public String getDescription() { 49 | return description; 50 | } 51 | 52 | public void setDescription(String description) { 53 | this.description = description; 54 | } 55 | 56 | public Date getTargetDate() { 57 | return targetDate; 58 | } 59 | 60 | public void setTargetDate(Date targetDate) { 61 | this.targetDate = targetDate; 62 | } 63 | 64 | public boolean isDone() { 65 | return isDone; 66 | } 67 | 68 | public void setDone(boolean isDone) { 69 | this.isDone = isDone; 70 | } 71 | 72 | @Override 73 | public int hashCode() { 74 | final int prime = 31; 75 | int result = 1; 76 | result = prime * result + (int) (id ^ (id >>> 32)); 77 | return result; 78 | } 79 | 80 | @Override 81 | public boolean equals(Object obj) { 82 | if (this == obj) 83 | return true; 84 | if (obj == null) 85 | return false; 86 | if (getClass() != obj.getClass()) 87 | return false; 88 | Todo other = (Todo) obj; 89 | if (id != other.id) 90 | return false; 91 | return true; 92 | } 93 | 94 | 95 | } -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/todo/TodoJpaRepository.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.todo; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | @Repository 9 | public interface TodoJpaRepository extends JpaRepository{ 10 | List findByUsername(String username); 11 | } -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/todo/TodoJpaResource.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.todo; 2 | 3 | import java.net.URI; 4 | import java.util.List; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.DeleteMapping; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.PathVariable; 12 | import org.springframework.web.bind.annotation.PostMapping; 13 | import org.springframework.web.bind.annotation.PutMapping; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | import org.springframework.web.bind.annotation.RestController; 16 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder; 17 | 18 | @RestController 19 | public class TodoJpaResource { 20 | 21 | @Autowired 22 | private TodoJpaRepository todoJpaRepository; 23 | 24 | 25 | @GetMapping("/jpa/users/{username}/todos") 26 | public List getAllTodos(@PathVariable String username){ 27 | return todoJpaRepository.findByUsername(username); 28 | //return todoService.findAll(); 29 | } 30 | 31 | @GetMapping("/jpa/users/{username}/todos/{id}") 32 | public Todo getTodo(@PathVariable String username, @PathVariable long id){ 33 | return todoJpaRepository.findById(id).get(); 34 | //return todoService.findById(id); 35 | } 36 | 37 | // DELETE /users/{username}/todos/{id} 38 | @DeleteMapping("/jpa/users/{username}/todos/{id}") 39 | public ResponseEntity deleteTodo( 40 | @PathVariable String username, @PathVariable long id) { 41 | 42 | todoJpaRepository.deleteById(id); 43 | 44 | return ResponseEntity.noContent().build(); 45 | } 46 | 47 | 48 | //Edit/Update a Todo 49 | //PUT /users/{user_name}/todos/{todo_id} 50 | @PutMapping("/jpa/users/{username}/todos/{id}") 51 | public ResponseEntity updateTodo( 52 | @PathVariable String username, 53 | @PathVariable long id, @RequestBody Todo todo){ 54 | 55 | todo.setUsername(username); 56 | 57 | Todo todoUpdated = todoJpaRepository.save(todo); 58 | 59 | return new ResponseEntity(todoUpdated, HttpStatus.OK); 60 | } 61 | 62 | @PostMapping("/jpa/users/{username}/todos") 63 | public ResponseEntity createTodo( 64 | @PathVariable String username, @RequestBody Todo todo){ 65 | 66 | todo.setUsername(username); 67 | 68 | Todo createdTodo = todoJpaRepository.save(todo); 69 | 70 | //Location 71 | //Get current resource url 72 | ///{id} 73 | URI uri = ServletUriComponentsBuilder.fromCurrentRequest() 74 | .path("/{id}").buildAndExpand(createdTodo.getId()).toUri(); 75 | 76 | return ResponseEntity.created(uri).build(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | logging.level.org.springframework = info 2 | 3 | #spring.security.user.name=in28minutes 4 | #spring.security.user.password=dummy 5 | 6 | jwt.signing.key.secret=mySecret 7 | jwt.get.token.uri=/authenticate 8 | jwt.refresh.token.uri=/refresh 9 | jwt.http.request.header=Authorization 10 | jwt.token.expiration.in.seconds=604800 11 | 12 | spring.jpa.show-sql=true 13 | spring.h2.console.enabled=true 14 | spring.h2.console.settings.web-allow-others=true 15 | 16 | server.port = 8080 17 | 18 | #eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJpbjI4bWludXRlcyIsImV4cCI6MTU2Mjg0ODAwMCwiaWF0IjoxNTYyMjQzMjAwfQ.Nmix4DqNSB13ufoy845GUETluidrp9afwafdTVtfKxr4UkUYb75mfjLHY2rD7BVDEqREoCtguTnoV3ISrdn6Eg 19 | -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | /*https://www.browserling.com/tools/bcrypt Use Rounds 10*/ 2 | 3 | /*in28minutes/dummy*/ 4 | INSERT INTO USER (ID, USERNAME, PASSWORD, ROLE) 5 | VALUES (1, 'in28minutes', '$2a$10$3zHzb.Npv1hfZbLEU5qsdOju/tk2je6W6PnNnY.c1ujWPcZh4PL6e','ROLE_USER'); 6 | 7 | /*in28minutes2/mypassword*/ 8 | INSERT INTO USER (ID, USERNAME, PASSWORD, ROLE) 9 | VALUES (2, 'in28minutes2', '$2a$10$i9AckmxMkb4yKtLCdxeQheCm2pXWB3qZ2G189/Ph/DUci1DvLO.Rq','ROLE_USER'); 10 | 11 | 12 | 13 | 14 | insert into todo(id, username,description,target_date,is_done) 15 | values(10001, 'in28minutes', 'Learn JPA', sysdate(), false); 16 | 17 | insert into todo(id, username,description,target_date,is_done) 18 | values(10002, 'in28minutes', 'Learn Data JPA', sysdate(), false); 19 | 20 | insert into todo(id, username,description,target_date,is_done) 21 | values(10003, 'in28minutes', 'Learn Microservices', sysdate(), false); -------------------------------------------------------------------------------- /04-spring-boot-react-full-stack-h2/restful-web-services/src/test/java/com/in28minutes/rest/webservices/restfulwebservices/RestfulWebServicesApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class RestfulWebServicesApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /05-todo-rest-api-h2-containerized/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:8-jdk-alpine 2 | VOLUME /tmp 3 | EXPOSE 5000 4 | ADD target/*.jar app.jar 5 | ENV JAVA_OPTS="" 6 | ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ] -------------------------------------------------------------------------------- /05-todo-rest-api-h2-containerized/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.in28minutes.rest.webservices 8 | todo-rest-api-h2 9 | 1.0.0.RELEASE 10 | jar 11 | 05-todo-rest-api-h2-containerized 12 | 13 | 14 | org.springframework.boot 15 | spring-boot-starter-parent 16 | 2.1.0.RELEASE 17 | 18 | 19 | 20 | 21 | UTF-8 22 | UTF-8 23 | 1.8 24 | 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-web 36 | 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-devtools 41 | runtime 42 | 43 | 44 | 45 | com.h2database 46 | h2 47 | runtime 48 | 49 | 50 | 51 | 52 | javax.xml.bind 53 | jaxb-api 54 | 2.3.0 55 | 56 | 57 | com.sun.xml.bind 58 | jaxb-impl 59 | 2.3.0 60 | 61 | 62 | org.glassfish.jaxb 63 | jaxb-runtime 64 | 2.3.0 65 | 66 | 67 | javax.activation 68 | activation 69 | 1.1.1 70 | 71 | 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-starter-test 76 | test 77 | 78 | 79 | 80 | 81 | 82 | 83 | org.springframework.boot 84 | spring-boot-maven-plugin 85 | 86 | 87 | 88 | 89 | com.spotify 90 | dockerfile-maven-plugin 91 | 1.4.10 92 | 93 | 94 | default 95 | 96 | build 97 | 98 | 99 | 100 | 101 | 102 | in28min/${project.artifactId} 103 | ${project.version} 104 | true 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | spring-snapshots 113 | Spring Snapshots 114 | https://repo.spring.io/snapshot 115 | 116 | true 117 | 118 | 119 | 120 | spring-milestones 121 | Spring Milestones 122 | https://repo.spring.io/milestone 123 | 124 | false 125 | 126 | 127 | 128 | 129 | 130 | 131 | spring-snapshots 132 | Spring Snapshots 133 | https://repo.spring.io/snapshot 134 | 135 | true 136 | 137 | 138 | 139 | spring-milestones 140 | Spring Milestones 141 | https://repo.spring.io/milestone 142 | 143 | false 144 | 145 | 146 | 147 | -------------------------------------------------------------------------------- /05-todo-rest-api-h2-containerized/readme.md: -------------------------------------------------------------------------------- 1 | # Todo and Hello World Rest APIs Connecting to H2 In memory database running on port 5000 2 | 3 | Run com.in28minutes.rest.webservices.restfulwebservices.RestfulWebServicesApplication as a Java Application. 4 | 5 | 6 | ## Containerization 7 | 8 | ### Troubleshooting 9 | 10 | - Problem - Caused by: com.spotify.docker.client.shaded.javax.ws.rs.ProcessingException: java.io.IOException: No such file or directory 11 | - Solution - Check if docker is up and running! 12 | - Problem - Error creating the Docker image on MacOS - java.io.IOException: Cannot run program “docker-credential-osxkeychain”: error=2, No such file or directory 13 | - Solution - https://medium.com/@dakshika/error-creating-the-docker-image-on-macos-wso2-enterprise-integrator-tooling-dfb5b537b44e 14 | 15 | ### Creating Containers 16 | 17 | 18 | - mvn package 19 | - docker run in28min/todo-rest-api-h2:0.0.1-SNAPSHOT 20 | - docker run -p 5000:5000 in28min/todo-rest-api-h2:0.0.1-SNAPSHOT 21 | - docker run -p 5000:5000 in28min/todo-rest-api-h2:1.0.0.RELEASE 22 | 23 | To test execute API at http://localhost:5000/users/in28minutes/todos. 24 | 25 | ``` 26 | docker login 27 | ``` 28 | 29 | 30 | ## Hello World URLS 31 | 32 | - http://localhost:5000/hello-world 33 | 34 | ```txt 35 | Hello World 36 | ``` 37 | 38 | - http://localhost:5000/hello-world-bean 39 | 40 | ```json 41 | {"message":"Hello World - Changed"} 42 | ``` 43 | 44 | - http://localhost:5000/hello-world/path-variable/in28minutes 45 | 46 | ```json 47 | {"message":"Hello World, in28minutes"} 48 | ``` 49 | 50 | 51 | ## Todo JPA Resource URLs 52 | 53 | - GET - http://localhost:5000/jpa/users/in28minutes/todos 54 | 55 | ``` 56 | [ 57 | { 58 | "id": 10001, 59 | "username": "in28minutes", 60 | "description": "Learn JPA", 61 | "targetDate": "2019-06-27T06:30:30.696+0000", 62 | "done": false 63 | }, 64 | { 65 | "id": 10002, 66 | "username": "in28minutes", 67 | "description": "Learn Data JPA", 68 | "targetDate": "2019-06-27T06:30:30.700+0000", 69 | "done": false 70 | }, 71 | { 72 | "id": 10003, 73 | "username": "in28minutes", 74 | "description": "Learn Microservices", 75 | "targetDate": "2019-06-27T06:30:30.701+0000", 76 | "done": false 77 | } 78 | ] 79 | ``` 80 | 81 | #### Retrieve a specific todo 82 | 83 | - GET - http://localhost:5000/jpa/users/in28minutes/todos/10001 84 | 85 | ``` 86 | { 87 | "id": 10001, 88 | "username": "in28minutes", 89 | "description": "Learn JPA", 90 | "targetDate": "2019-06-27T06:30:30.696+0000", 91 | "done": false 92 | } 93 | ``` 94 | 95 | #### Creating a new todo 96 | 97 | - POST to http://localhost:5000/jpa/users/in28minutes/todos with BODY of Request given below 98 | 99 | ``` 100 | { 101 | "username": "in28minutes", 102 | "description": "Learn to Drive a Car", 103 | "targetDate": "2030-11-09T10:49:23.566+0000", 104 | "done": false 105 | } 106 | ``` 107 | 108 | #### Updating a new todo 109 | 110 | - http://localhost:5000/jpa/users/in28minutes/todos/10001 with BODY of Request given below 111 | 112 | ``` 113 | { 114 | "id": 10001, 115 | "username": "in28minutes", 116 | "description": "Learn to Drive a Car", 117 | "targetDate": "2045-11-09T10:49:23.566+0000", 118 | "done": false 119 | } 120 | ``` 121 | 122 | #### Delete todo 123 | 124 | - DELETE to http://localhost:5000/jpa/users/in28minutes/todos/10001 125 | 126 | 127 | ## H2 Console 128 | 129 | - http://localhost:5000/h2-console 130 | - Use `jdbc:h2:mem:testdb` as JDBC URL 131 | 132 | ## Azure Resource Commands 133 | 134 | ``` 135 | az group create --name container-resource-group --location westeurope 136 | az appservice plan create --name container-service-plan --resource-group container-resource-group --sku P1v2 --is-linux 137 | az webapp create --resource-group container-resource-group --plan container-service-plan --name todo-rest-api-h2-container --deployment-container-image-name in28min/todo-rest-api-h2:1.0.0.RELEASE 138 | ``` 139 | 140 | 141 | ## Continuous Deployment 142 | 143 | - https://docs.microsoft.com/en-us/azure/app-service/containers/app-service-linux-ci-cd 144 | - https://docs.docker.com/docker-hub/webhooks/ -------------------------------------------------------------------------------- /05-todo-rest-api-h2-containerized/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/RestfulWebServicesApplication.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class RestfulWebServicesApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(RestfulWebServicesApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /05-todo-rest-api-h2-containerized/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/helloworld/HelloWorldBean.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.helloworld; 2 | 3 | public class HelloWorldBean { 4 | 5 | private String message; 6 | 7 | public HelloWorldBean(String message) { 8 | this.message = message; 9 | } 10 | 11 | public String getMessage() { 12 | return message; 13 | } 14 | 15 | public void setMessage(String message) { 16 | this.message = message; 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | return String.format("HelloWorldBean [message=%s]", message); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /05-todo-rest-api-h2-containerized/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/helloworld/HelloWorldController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.helloworld; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.PathVariable; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @RestController 8 | public class HelloWorldController { 9 | 10 | @GetMapping(path = "/hello-world") 11 | public String helloWorld() { 12 | return "Hello World"; 13 | } 14 | 15 | @GetMapping(path = "/hello-world-bean") 16 | public HelloWorldBean helloWorldBean() { 17 | return new HelloWorldBean("Hello World"); 18 | } 19 | 20 | @GetMapping(path = "/hello-world/path-variable/{name}") 21 | public HelloWorldBean helloWorldPathVariable(@PathVariable String name) { 22 | return new HelloWorldBean(String.format("Hello World, %s", name)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /05-todo-rest-api-h2-containerized/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/todo/Todo.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.todo; 2 | 3 | import java.util.Date; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.Id; 8 | 9 | @Entity 10 | public class Todo { 11 | @Id 12 | @GeneratedValue 13 | private Long id; 14 | private String username; 15 | private String description; 16 | private Date targetDate; 17 | private boolean isDone; 18 | 19 | public Todo() { 20 | 21 | } 22 | 23 | public Todo(long id, String username, String description, Date targetDate, boolean isDone) { 24 | super(); 25 | this.id = id; 26 | this.username = username; 27 | this.description = description; 28 | this.targetDate = targetDate; 29 | this.isDone = isDone; 30 | } 31 | 32 | public Long getId() { 33 | return id; 34 | } 35 | 36 | public void setId(Long id) { 37 | this.id = id; 38 | } 39 | 40 | public String getUsername() { 41 | return username; 42 | } 43 | 44 | public void setUsername(String username) { 45 | this.username = username; 46 | } 47 | 48 | public String getDescription() { 49 | return description; 50 | } 51 | 52 | public void setDescription(String description) { 53 | this.description = description; 54 | } 55 | 56 | public Date getTargetDate() { 57 | return targetDate; 58 | } 59 | 60 | public void setTargetDate(Date targetDate) { 61 | this.targetDate = targetDate; 62 | } 63 | 64 | public boolean isDone() { 65 | return isDone; 66 | } 67 | 68 | public void setDone(boolean isDone) { 69 | this.isDone = isDone; 70 | } 71 | 72 | @Override 73 | public int hashCode() { 74 | final int prime = 31; 75 | int result = 1; 76 | result = prime * result + (int) (id ^ (id >>> 32)); 77 | return result; 78 | } 79 | 80 | @Override 81 | public boolean equals(Object obj) { 82 | if (this == obj) 83 | return true; 84 | if (obj == null) 85 | return false; 86 | if (getClass() != obj.getClass()) 87 | return false; 88 | Todo other = (Todo) obj; 89 | if (id != other.id) 90 | return false; 91 | return true; 92 | } 93 | 94 | 95 | } -------------------------------------------------------------------------------- /05-todo-rest-api-h2-containerized/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/todo/TodoJpaRepository.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.todo; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | @Repository 9 | public interface TodoJpaRepository extends JpaRepository{ 10 | List findByUsername(String username); 11 | } -------------------------------------------------------------------------------- /05-todo-rest-api-h2-containerized/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/todo/TodoJpaResource.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.todo; 2 | 3 | import java.net.URI; 4 | import java.util.List; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.DeleteMapping; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.PathVariable; 12 | import org.springframework.web.bind.annotation.PostMapping; 13 | import org.springframework.web.bind.annotation.PutMapping; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | import org.springframework.web.bind.annotation.RestController; 16 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder; 17 | 18 | @RestController 19 | public class TodoJpaResource { 20 | 21 | @Autowired 22 | private TodoJpaRepository todoJpaRepository; 23 | 24 | 25 | @GetMapping("/jpa/users/{username}/todos") 26 | public List getAllTodos(@PathVariable String username){ 27 | return todoJpaRepository.findByUsername(username); 28 | //return todoService.findAll(); 29 | } 30 | 31 | @GetMapping("/jpa/users/{username}/todos/{id}") 32 | public Todo getTodo(@PathVariable String username, @PathVariable long id){ 33 | return todoJpaRepository.findById(id).get(); 34 | //return todoService.findById(id); 35 | } 36 | 37 | // DELETE /users/{username}/todos/{id} 38 | @DeleteMapping("/jpa/users/{username}/todos/{id}") 39 | public ResponseEntity deleteTodo( 40 | @PathVariable String username, @PathVariable long id) { 41 | 42 | todoJpaRepository.deleteById(id); 43 | 44 | return ResponseEntity.noContent().build(); 45 | } 46 | 47 | 48 | //Edit/Update a Todo 49 | //PUT /users/{user_name}/todos/{todo_id} 50 | @PutMapping("/jpa/users/{username}/todos/{id}") 51 | public ResponseEntity updateTodo( 52 | @PathVariable String username, 53 | @PathVariable long id, @RequestBody Todo todo){ 54 | 55 | todo.setUsername(username); 56 | 57 | Todo todoUpdated = todoJpaRepository.save(todo); 58 | 59 | return new ResponseEntity(todo, HttpStatus.OK); 60 | } 61 | 62 | @PostMapping("/jpa/users/{username}/todos") 63 | public ResponseEntity createTodo( 64 | @PathVariable String username, @RequestBody Todo todo){ 65 | 66 | todo.setId(-1L); 67 | 68 | Todo createdTodo = todoJpaRepository.save(todo); 69 | 70 | //Location 71 | //Get current resource url 72 | ///{id} 73 | URI uri = ServletUriComponentsBuilder.fromCurrentRequest() 74 | .path("/{id}").buildAndExpand(createdTodo.getId()).toUri(); 75 | 76 | return ResponseEntity.created(uri).build(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /05-todo-rest-api-h2-containerized/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.jpa.show-sql=true 2 | spring.h2.console.enabled=true 3 | spring.h2.console.settings.web-allow-others=true 4 | 5 | logging.level.org.springframework = info 6 | server.port=5000 -------------------------------------------------------------------------------- /05-todo-rest-api-h2-containerized/src/test/java/com/in28minutes/rest/webservices/restfulwebservices/RestfulWebServicesApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class RestfulWebServicesApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/.ebextensions/sg-extensions.config: -------------------------------------------------------------------------------- 1 | Resources: 2 | sslSecurityGroupIngress: 3 | Type: AWS::EC2::SecurityGroupIngress 4 | Properties: 5 | GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]} 6 | IpProtocol: tcp 7 | ToPort: 5000 8 | FromPort: 5000 9 | CidrIp: 0.0.0.0/0 -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:8-jdk-alpine 2 | VOLUME /tmp 3 | EXPOSE 5000 4 | ADD target/*.jar app.jar 5 | ENV JAVA_OPTS="" 6 | ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ] -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3.3' 2 | services: 3 | todo-rest-api: 4 | image: in28min/todo-rest-api-mysql:1.0.0.RELEASE 5 | ports: 6 | - "5000:5000" 7 | restart: always 8 | depends_on: 9 | - mysql 10 | environment: 11 | RDS_HOSTNAME: mysql 12 | RDS_PORT: 3306 13 | RDS_DB_NAME: todos 14 | RDS_USERNAME: todos-user 15 | RDS_PASSWORD: dummytodos 16 | 17 | mysql: 18 | image: mysql:5.7 19 | ports: 20 | - "3306:3306" 21 | restart: always 22 | environment: 23 | MYSQL_ROOT_PASSWORD: dummypassword 24 | MYSQL_USER: todos-user 25 | MYSQL_PASSWORD: dummytodos 26 | MYSQL_DATABASE: todos 27 | -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.in28minutes.rest.webservices 8 | todo-rest-api-mysql 9 | 1.0.0.RELEASE 10 | jar 11 | 12 | 06-todo-rest-api-mysql-containerized 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.1.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-data-jpa 32 | 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-web 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-devtools 42 | runtime 43 | 44 | 45 | 46 | com.h2database 47 | h2 48 | test 49 | 50 | 51 | 52 | mysql 53 | mysql-connector-java 54 | 55 | 56 | 57 | javax.xml.bind 58 | jaxb-api 59 | 2.3.0 60 | 61 | 62 | com.sun.xml.bind 63 | jaxb-impl 64 | 2.3.0 65 | 66 | 67 | org.glassfish.jaxb 68 | jaxb-runtime 69 | 2.3.0 70 | 71 | 72 | javax.activation 73 | activation 74 | 1.1.1 75 | 76 | 77 | 78 | org.springframework.boot 79 | spring-boot-starter-test 80 | test 81 | 82 | 83 | 84 | 85 | 86 | 87 | org.springframework.boot 88 | spring-boot-maven-plugin 89 | 90 | 91 | 92 | 93 | com.spotify 94 | dockerfile-maven-plugin 95 | 1.4.10 96 | 97 | 98 | default 99 | 100 | build 101 | 102 | 103 | 104 | 105 | 106 | in28min/${project.artifactId} 107 | ${project.version} 108 | true 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | spring-snapshots 117 | Spring Snapshots 118 | https://repo.spring.io/snapshot 119 | 120 | true 121 | 122 | 123 | 124 | spring-milestones 125 | Spring Milestones 126 | https://repo.spring.io/milestone 127 | 128 | false 129 | 130 | 131 | 132 | 133 | 134 | 135 | spring-snapshots 136 | Spring Snapshots 137 | https://repo.spring.io/snapshot 138 | 139 | true 140 | 141 | 142 | 143 | spring-milestones 144 | Spring Milestones 145 | https://repo.spring.io/milestone 146 | 147 | false 148 | 149 | 150 | 151 | 152 | -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/readme.md: -------------------------------------------------------------------------------- 1 | # Todo and Hello World Rest APIs Connecting to MySQL 2 | 3 | - Image URL - https://hub.docker.com/r/in28min/todo-rest-api-mysql 4 | - Image - in28min/todo-rest-api-mysql:1.0.0.RELEASE 5 | - Runs on port 5000 6 | - Run com.in28minutes.rest.webservices.restfulwebservices.RestfulWebServicesApplication as a Java Application. 7 | 8 | 9 | ## Containerization 10 | 11 | ### Troubleshooting 12 | 13 | - Problem - Caused by: com.spotify.docker.client.shaded.javax.ws.rs.ProcessingException: java.io.IOException: No such file or directory 14 | - Solution - Check if docker is up and running! 15 | - Problem - Error creating the Docker image on MacOS - java.io.IOException: Cannot run program “docker-credential-osxkeychain”: error=2, No such file or directory 16 | - Solution - https://medium.com/@dakshika/error-creating-the-docker-image-on-macos-wso2-enterprise-integrator-tooling-dfb5b537b44e 17 | 18 | ### Creating Containers and Running Locally 19 | 20 | https://hub.docker.com/r/in28min/todo-rest-api-mysql 21 | 22 | ### Run MySQL 23 | 24 | ``` 25 | docker run --detach --env MYSQL_ROOT_PASSWORD=dummypassword --env MYSQL_USER=todos-user --env MYSQL_PASSWORD=dummytodos --env MYSQL_DATABASE=todos --name mysql --publish 3306:3306 mysql:5.7 26 | ``` 27 | 28 | ### Run REST API Container 29 | 30 | ``` 31 | mvn clean package 32 | docker run --name todos-api --publish 5000:5000 --link mysql:mysql in28min/todo-rest-api-mysql:1.0.0.RELEASE 33 | ``` 34 | 35 | ### Test 36 | 37 | Run http://localhost:5000/users/in28minutes/todos 38 | 39 | 40 | ### Push Your REST API Container to Docker Repo 41 | 42 | ``` 43 | docker login 44 | 45 | docker push in28min/todo-rest-api-mysql:0.0.1-SNAPSHOT 46 | ``` 47 | 48 | 49 | ## Hello World URLS 50 | 51 | - http://localhost:5000/hello-world 52 | 53 | ```txt 54 | Hello World 55 | ``` 56 | 57 | - http://localhost:5000/hello-world-bean 58 | 59 | ```json 60 | {"message":"Hello World - Changed"} 61 | ``` 62 | 63 | - http://localhost:5000/hello-world/path-variable/in28minutes 64 | 65 | ```json 66 | {"message":"Hello World, in28minutes"} 67 | ``` 68 | 69 | 70 | 71 | ## Todo JPA Resource URLs 72 | 73 | - GET - http://localhost:5000/jpa/users/in28minutes/todos 74 | 75 | ``` 76 | [ 77 | { 78 | "id": 10001, 79 | "username": "in28minutes", 80 | "description": "Learn JPA", 81 | "targetDate": "2019-06-27T06:30:30.696+0000", 82 | "done": false 83 | }, 84 | { 85 | "id": 10002, 86 | "username": "in28minutes", 87 | "description": "Learn Data JPA", 88 | "targetDate": "2019-06-27T06:30:30.700+0000", 89 | "done": false 90 | }, 91 | { 92 | "id": 10003, 93 | "username": "in28minutes", 94 | "description": "Learn Microservices", 95 | "targetDate": "2019-06-27T06:30:30.701+0000", 96 | "done": false 97 | } 98 | ] 99 | ``` 100 | 101 | #### Retrieve a specific todo 102 | 103 | - GET - http://localhost:5000/jpa/users/in28minutes/todos/10001 104 | 105 | ``` 106 | { 107 | "id": 10001, 108 | "username": "in28minutes", 109 | "description": "Learn JPA", 110 | "targetDate": "2019-06-27T06:30:30.696+0000", 111 | "done": false 112 | } 113 | ``` 114 | 115 | #### Creating a new todo 116 | 117 | - POST to http://localhost:5000/jpa/users/in28minutes/todos with BODY of Request given below 118 | 119 | ``` 120 | { 121 | "username": "in28minutes", 122 | "description": "Learn to Drive a Car", 123 | "targetDate": "2030-11-09T10:49:23.566+0000", 124 | "done": false 125 | } 126 | ``` 127 | 128 | #### Updating a new todo 129 | 130 | - http://localhost:5000/jpa/users/in28minutes/todos/10001 with BODY of Request given below 131 | 132 | ``` 133 | { 134 | "id": 10001, 135 | "username": "in28minutes", 136 | "description": "Learn to Drive a Car", 137 | "targetDate": "2045-11-09T10:49:23.566+0000", 138 | "done": false 139 | } 140 | ``` 141 | 142 | #### Delete todo 143 | 144 | - DELETE to http://localhost:5000/jpa/users/in28minutes/todos/10001 145 | 146 | 147 | ## H2 Console 148 | 149 | - http://localhost:5000/h2-console 150 | - Use `jdbc:h2:mem:testdb` as JDBC URL 151 | 152 | ## Azure Resource Commands 153 | 154 | ``` 155 | az group create --name docker-compose-resource-group --location westeurope 156 | az appservice plan create --name docker-compose-service-plan --sku P1v2 --resource-group docker-compose-resource-group --is-linux 157 | az webapp create --resource-group docker-compose-resource-group --plan docker-compose-service-plan --name todo-rest-api-mysql-docker-compose --multicontainer-config-type compose --multicontainer-config-file docker-compose.yaml 158 | ``` -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/RestfulWebServicesApplication.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class RestfulWebServicesApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(RestfulWebServicesApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/helloworld/HelloWorldBean.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.helloworld; 2 | 3 | public class HelloWorldBean { 4 | 5 | private String message; 6 | 7 | public HelloWorldBean(String message) { 8 | this.message = message; 9 | } 10 | 11 | public String getMessage() { 12 | return message; 13 | } 14 | 15 | public void setMessage(String message) { 16 | this.message = message; 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | return String.format("HelloWorldBean [message=%s]", message); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/helloworld/HelloWorldController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.helloworld; 2 | 3 | import org.springframework.web.bind.annotation.CrossOrigin; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.PathVariable; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @RestController 9 | public class HelloWorldController { 10 | 11 | @GetMapping(path = "/hello-world") 12 | public String helloWorld() { 13 | return "Hello World"; 14 | } 15 | 16 | @GetMapping(path = "/hello-world-bean") 17 | public HelloWorldBean helloWorldBean() { 18 | return new HelloWorldBean("Hello World"); 19 | } 20 | 21 | ///hello-world/path-variable/in28minutes 22 | @GetMapping(path = "/hello-world/path-variable/{name}") 23 | public HelloWorldBean helloWorldPathVariable(@PathVariable String name) { 24 | //throw new RuntimeException("Something went wrong"); 25 | return new HelloWorldBean(String.format("Hello World, %s", name)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/todo/Todo.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.todo; 2 | 3 | import java.util.Date; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.Id; 8 | 9 | @Entity 10 | public class Todo { 11 | @Id 12 | @GeneratedValue 13 | private Long id; 14 | private String username; 15 | private String description; 16 | private Date targetDate; 17 | private boolean isDone; 18 | 19 | public Todo() { 20 | 21 | } 22 | 23 | public Todo(long id, String username, String description, Date targetDate, boolean isDone) { 24 | super(); 25 | this.id = id; 26 | this.username = username; 27 | this.description = description; 28 | this.targetDate = targetDate; 29 | this.isDone = isDone; 30 | } 31 | 32 | public Long getId() { 33 | return id; 34 | } 35 | 36 | public void setId(Long id) { 37 | this.id = id; 38 | } 39 | 40 | public String getUsername() { 41 | return username; 42 | } 43 | 44 | public void setUsername(String username) { 45 | this.username = username; 46 | } 47 | 48 | public String getDescription() { 49 | return description; 50 | } 51 | 52 | public void setDescription(String description) { 53 | this.description = description; 54 | } 55 | 56 | public Date getTargetDate() { 57 | return targetDate; 58 | } 59 | 60 | public void setTargetDate(Date targetDate) { 61 | this.targetDate = targetDate; 62 | } 63 | 64 | public boolean isDone() { 65 | return isDone; 66 | } 67 | 68 | public void setDone(boolean isDone) { 69 | this.isDone = isDone; 70 | } 71 | 72 | @Override 73 | public int hashCode() { 74 | final int prime = 31; 75 | int result = 1; 76 | result = prime * result + (int) (id ^ (id >>> 32)); 77 | return result; 78 | } 79 | 80 | @Override 81 | public boolean equals(Object obj) { 82 | if (this == obj) 83 | return true; 84 | if (obj == null) 85 | return false; 86 | if (getClass() != obj.getClass()) 87 | return false; 88 | Todo other = (Todo) obj; 89 | if (id != other.id) 90 | return false; 91 | return true; 92 | } 93 | 94 | 95 | } -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/todo/TodoJpaRepository.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.todo; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | @Repository 9 | public interface TodoJpaRepository extends JpaRepository{ 10 | List findByUsername(String username); 11 | } -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/todo/TodoJpaResource.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices.todo; 2 | 3 | import java.net.URI; 4 | import java.util.List; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.DeleteMapping; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.PathVariable; 12 | import org.springframework.web.bind.annotation.PostMapping; 13 | import org.springframework.web.bind.annotation.PutMapping; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | import org.springframework.web.bind.annotation.RestController; 16 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder; 17 | 18 | @RestController 19 | public class TodoJpaResource { 20 | 21 | @Autowired 22 | private TodoJpaRepository todoJpaRepository; 23 | 24 | 25 | @GetMapping("/jpa/users/{username}/todos") 26 | public List getAllTodos(@PathVariable String username){ 27 | return todoJpaRepository.findByUsername(username); 28 | //return todoService.findAll(); 29 | } 30 | 31 | @GetMapping("/jpa/users/{username}/todos/{id}") 32 | public Todo getTodo(@PathVariable String username, @PathVariable long id){ 33 | return todoJpaRepository.findById(id).get(); 34 | //return todoService.findById(id); 35 | } 36 | 37 | // DELETE /users/{username}/todos/{id} 38 | @DeleteMapping("/jpa/users/{username}/todos/{id}") 39 | public ResponseEntity deleteTodo( 40 | @PathVariable String username, @PathVariable long id) { 41 | 42 | todoJpaRepository.deleteById(id); 43 | 44 | return ResponseEntity.noContent().build(); 45 | } 46 | 47 | 48 | //Edit/Update a Todo 49 | //PUT /users/{user_name}/todos/{todo_id} 50 | @PutMapping("/jpa/users/{username}/todos/{id}") 51 | public ResponseEntity updateTodo( 52 | @PathVariable String username, 53 | @PathVariable long id, @RequestBody Todo todo){ 54 | 55 | todo.setUsername(username); 56 | 57 | Todo todoUpdated = todoJpaRepository.save(todo); 58 | 59 | return new ResponseEntity(todo, HttpStatus.OK); 60 | } 61 | 62 | @PostMapping("/jpa/users/{username}/todos") 63 | public ResponseEntity createTodo( 64 | @PathVariable String username, @RequestBody Todo todo){ 65 | 66 | todo.setId(-1L); 67 | 68 | Todo createdTodo = todoJpaRepository.save(todo); 69 | 70 | //Location 71 | //Get current resource url 72 | ///{id} 73 | URI uri = ServletUriComponentsBuilder.fromCurrentRequest() 74 | .path("/{id}").buildAndExpand(createdTodo.getId()).toUri(); 75 | 76 | return ResponseEntity.created(uri).build(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.jpa.show-sql=true 2 | #spring.h2.console.enabled=true 3 | 4 | logging.level.org.springframework = info 5 | server.port=5000 6 | 7 | #AWS 8 | spring.jpa.hibernate.ddl-auto=update 9 | spring.datasource.url=jdbc:mysql://${RDS_HOSTNAME:mysql}:${RDS_PORT:3306}/${RDS_DB_NAME:todos} 10 | spring.datasource.username=${RDS_USERNAME:todos-user} 11 | spring.datasource.password=${RDS_PASSWORD:dummytodos} 12 | spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/src/test/java/com/in28minutes/rest/webservices/restfulwebservices/RestfulWebServicesApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class RestfulWebServicesApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /06-todo-rest-api-mysql-containerized/src/test/resources/application.properties: -------------------------------------------------------------------------------- 1 | #AWS 2 | spring.jpa.hibernate.ddl-auto=create-drop 3 | spring.datasource.driver-class-name=org.h2.Driver 4 | spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 5 | spring.datasource.username=sa 6 | spring.datasource.password=sa 7 | -------------------------------------------------------------------------------- /07-hello-world-rest-api/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 4.0.0 7 | com.in28minutes.rest.webservices 8 | 07-hello-world-rest-api 9 | 0.0.1-SNAPSHOT 10 | jar 11 | Demo project for Spring Boot 12 | 07-hello-world-rest-api 13 | 14 | org.springframework.boot 15 | spring-boot-starter-parent 16 | 2.1.7.RELEASE 17 | 18 | 19 | 20 | 21 | UTF-8 22 | UTF-8 23 | 1.8 24 | 3.1.1 25 | 26 | ${project.build.directory}/${project.build.finalName}.jar 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-devtools 36 | runtime 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-test 41 | test 42 | 43 | 44 | 45 | hello-world-rest-api 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-maven-plugin 50 | 51 | 52 | com.microsoft.azure 53 | azure-webapp-maven-plugin 54 | 1.7.0 55 | 56 | V2 57 | hello-world-rest-api-v2-rg 58 | hello-world-rest-api-v2-in28minutes 59 | B1 60 | westeurope 61 | 62 | 63 | JAVA_OPTS 64 | -Dserver.port=80 65 | 66 | 67 | 68 | linux 69 | java11 70 | java11 71 | 72 | 73 | stage 74 | parent 75 | 76 | 77 | 78 | 79 | ${project.basedir}/target 80 | 81 | *.jar 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | spring-snapshots 93 | Spring Snapshots 94 | https://repo.spring.io/snapshot 95 | 96 | true 97 | 98 | 99 | 100 | spring-milestones 101 | Spring Milestones 102 | https://repo.spring.io/milestone 103 | 104 | false 105 | 106 | 107 | 108 | 109 | 110 | spring-snapshots 111 | Spring Snapshots 112 | https://repo.spring.io/snapshot 113 | 114 | true 115 | 116 | 117 | 118 | spring-milestones 119 | Spring Milestones 120 | https://repo.spring.io/milestone 121 | 122 | false 123 | 124 | 125 | 126 | 127 | -------------------------------------------------------------------------------- /07-hello-world-rest-api/readme.md: -------------------------------------------------------------------------------- 1 | # Hello World Rest API 2 | 3 | ### Running the Application 4 | 5 | Run com.in28minutes.rest.webservices.restfulwebservices.RestfulWebServicesApplication as a Java Application. 6 | 7 | - http://localhost:8080/hello-world 8 | 9 | ```txt 10 | Hello World 11 | ``` 12 | 13 | - http://localhost:8080/hello-world-bean 14 | 15 | ```json 16 | {"message":"Hello World"} 17 | ``` 18 | 19 | - http://localhost:8080/hello-world/path-variable/in28minutes 20 | 21 | ```json 22 | {"message":"Hello World, in28minutes"} 23 | ``` 24 | 25 | ### Plugin configuration 26 | 27 | ``` 28 | 29 | com.microsoft.azure 30 | azure-webapp-maven-plugin 31 | 1.7.0 32 | 33 | ``` 34 | 35 | ### Azure CLI 36 | 37 | - https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest 38 | 39 | ### Final Plugin Configuration 40 | ``` 41 | 42 | com.microsoft.azure 43 | azure-webapp-maven-plugin 44 | 1.7.0 45 | 46 | V2 47 | hello-world-rest-api-rg 48 | hello-world-rest-api-in28minutes 49 | B1 50 | westeurope 51 | 52 | 53 | JAVA_OPTS 54 | -Dserver.port=80 55 | 56 | 57 | 58 | linux 59 | java11 60 | java11 61 | 62 | 63 | 64 | 65 | ${project.basedir}/target 66 | 67 | *.jar 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | ``` 76 | ### Logging Configuration 77 | 78 | ``` 79 | -Dlogging.level.org.springframework=DEBUG 80 | ``` 81 | 82 | ### Installing curl and watch on windows 83 | ``` 84 | https://curl.haxx.se/windows/ 85 | ``` 86 | 87 | ### Installing watch on MAC 88 | ``` 89 | http://osxdaily.com/2010/08/22/install-watch-command-on-os-x/ 90 | ``` 91 | -------------------------------------------------------------------------------- /07-hello-world-rest-api/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/HelloWorldBean.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | public class HelloWorldBean { 4 | 5 | private String message; 6 | 7 | public HelloWorldBean(String message) { 8 | this.message = message; 9 | } 10 | 11 | public String getMessage() { 12 | return message; 13 | } 14 | 15 | public void setMessage(String message) { 16 | this.message = message; 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | return String.format("HelloWorldBean [message=%s]", message); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /07-hello-world-rest-api/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/HelloWorldController.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | import java.util.Collections; 4 | import java.util.List; 5 | import java.util.Random; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.PathVariable; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | @RestController 13 | public class HelloWorldController { 14 | 15 | @Autowired 16 | private InstanceInformationService instanceService; 17 | 18 | @GetMapping(path = "/hello-world") 19 | public String helloWorld() { 20 | return "Hello World"; 21 | } 22 | 23 | @GetMapping(path = "/hello-world-bean") 24 | public HelloWorldBean helloWorldBean() { 25 | // throw new RuntimeException("Some Error has Happened! Contact Support at 26 | // ***-***"); 27 | return new HelloWorldBean("Hello World V1 "); 28 | } 29 | 30 | /// hello-world/path-variable/in28minutes 31 | @GetMapping(path = "/hello-world/path-variable/{name}") 32 | public HelloWorldBean helloWorldPathVariable(@PathVariable String name) { 33 | return new HelloWorldBean(String.format("Hello World, %s", name)); 34 | } 35 | 36 | @GetMapping(path = "/hello-world-bean-list") 37 | public List helloWorldBeanList() { 38 | return Collections.nCopies((new Random()).nextInt(1000), 39 | new HelloWorldBean("Hello World v2 " + instanceService.retrieveInstanceInfo())); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /07-hello-world-rest-api/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/InstanceInformationService.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.stereotype.Service; 5 | 6 | @Service 7 | public class InstanceInformationService { 8 | 9 | private static final String ENV_INSTANCE_GUID = "WEBSITE_INSTANCE_ID"; 10 | 11 | private static final String DEFAULT_ENV_INSTANCE_GUID = "UNKNOWN"; 12 | 13 | //@Value(${ENVIRONMENT_VARIABLE_NAME:DEFAULT_VALUE}) 14 | @Value("${" + ENV_INSTANCE_GUID + ":" + DEFAULT_ENV_INSTANCE_GUID + "}") 15 | private String instanceGuid; 16 | 17 | public String retrieveInstanceInfo() { 18 | return instanceGuid; 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /07-hello-world-rest-api/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/RestfulWebServicesApplication.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class RestfulWebServicesApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(RestfulWebServicesApplication.class, args); 11 | } 12 | } -------------------------------------------------------------------------------- /07-hello-world-rest-api/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | logging.level.org.springframework = debug 2 | -------------------------------------------------------------------------------- /07-hello-world-rest-api/src/test/java/com/in28minutes/rest/webservices/restfulwebservices/RestfulWebServicesApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.rest.webservices.restfulwebservices; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class RestfulWebServicesApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------