├── Filedemo
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── filedemo
│ │ │ ├── FiledemoApplication.java
│ │ │ └── web
│ │ │ └── FileController.java
│ └── resources
│ │ ├── application.properties
│ │ └── templates
│ │ ├── upload.html
│ │ └── uploadstatus.html
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── filedemo
│ └── FiledemoApplicationTests.java
├── FiledemoDb
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── filedemo
│ │ │ ├── FiledemoApplication.java
│ │ │ ├── domain
│ │ │ ├── FileModel.java
│ │ │ └── FileModelRepository.java
│ │ │ └── web
│ │ │ └── FileController.java
│ └── resources
│ │ ├── application.properties
│ │ └── templates
│ │ ├── filelist.html
│ │ ├── upload.html
│ │ └── uploadstatus.html
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── filedemo
│ └── FiledemoApplicationTests.java
├── HelloForm
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── course
│ │ │ ├── HelloFormApplication.java
│ │ │ ├── domain
│ │ │ └── Message.java
│ │ │ └── web
│ │ │ └── MessageController.java
│ └── resources
│ │ ├── application.properties
│ │ └── templates
│ │ ├── hello.html
│ │ └── result.html
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── course
│ └── HelloFormApplicationTests.java
├── HelloFormValidation
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── course
│ │ │ ├── HelloFormApplication.java
│ │ │ ├── domain
│ │ │ └── Message.java
│ │ │ └── web
│ │ │ └── MessageController.java
│ └── resources
│ │ ├── application.properties
│ │ └── templates
│ │ ├── hello.html
│ │ └── result.html
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── course
│ └── HelloFormApplicationTests.java
├── HelloRest
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── course
│ │ │ ├── RestdemoApplication.java
│ │ │ ├── domain
│ │ │ └── Message.java
│ │ │ └── web
│ │ │ └── MessageController.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── example
│ └── demo
│ └── RestdemoApplicationTests.java
├── HelloTest
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── course
│ │ │ ├── HellotestApplication.java
│ │ │ └── web
│ │ │ └── HelloController.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── course
│ ├── HellotestApplicationTests.java
│ └── WebLayerTest.java
├── LICENSE
├── README.md
├── SecureStudentList
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── course
│ │ │ ├── StudentListApplication.java
│ │ │ ├── WebSecurityConfig.java
│ │ │ ├── domain
│ │ │ ├── Department.java
│ │ │ ├── DepartmentRepository.java
│ │ │ ├── Student.java
│ │ │ └── StudentRepository.java
│ │ │ └── web
│ │ │ └── StudentController.java
│ └── resources
│ │ ├── application.properties
│ │ ├── static
│ │ └── css
│ │ │ └── bootstrap.min.css
│ │ └── templates
│ │ ├── addstudent.html
│ │ └── studentlist.html
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── course
│ └── BookListApplicationTests.java
├── SecureStudentListUser
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── course
│ │ │ ├── StudentListApplication.java
│ │ │ ├── WebSecurityConfig.java
│ │ │ ├── domain
│ │ │ ├── AppUser.java
│ │ │ ├── AppUserRepository.java
│ │ │ ├── Department.java
│ │ │ ├── DepartmentRepository.java
│ │ │ ├── Student.java
│ │ │ └── StudentRepository.java
│ │ │ └── web
│ │ │ ├── StudentController.java
│ │ │ └── UserDetailServiceImpl.java
│ └── resources
│ │ ├── application.properties
│ │ ├── static
│ │ └── css
│ │ │ └── bootstrap.min.css
│ │ └── templates
│ │ ├── addstudent.html
│ │ ├── login.html
│ │ └── studentlist.html
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── course
│ └── BookListApplicationTests.java
├── SecurityDemo
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── course
│ │ │ ├── SecuritydemoApplication.java
│ │ │ ├── WebSecurityConfig.java
│ │ │ └── web
│ │ │ └── DemoController.java
│ └── resources
│ │ ├── application.properties
│ │ └── templates
│ │ ├── hello.html
│ │ ├── home.html
│ │ └── login.html
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── course
│ └── SecuritydemoApplicationTests.java
├── StudentJpaTest
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── course
│ │ │ ├── StudentListApplication.java
│ │ │ ├── WebSecurityConfig.java
│ │ │ ├── domain
│ │ │ ├── AppUser.java
│ │ │ ├── AppUserRepository.java
│ │ │ ├── Department.java
│ │ │ ├── DepartmentRepository.java
│ │ │ ├── Student.java
│ │ │ └── StudentRepository.java
│ │ │ └── web
│ │ │ ├── StudentController.java
│ │ │ └── UserDetailServiceImpl.java
│ └── resources
│ │ ├── application.properties
│ │ ├── static
│ │ └── css
│ │ │ └── bootstrap.min.css
│ │ └── templates
│ │ ├── addstudent.html
│ │ ├── login.html
│ │ └── studentlist.html
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── course
│ ├── StudentListApplicationTests.java
│ └── StudentRepositoryTest.java
├── StudentList
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── course
│ │ │ ├── StudentListApplication.java
│ │ │ └── domain
│ │ │ ├── Student.java
│ │ │ └── StudentRepository.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── course
│ └── BookListApplicationTests.java
├── StudentListCrud
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── course
│ │ │ ├── StudentListApplication.java
│ │ │ ├── domain
│ │ │ ├── Student.java
│ │ │ └── StudentRepository.java
│ │ │ └── web
│ │ │ └── StudentController.java
│ └── resources
│ │ ├── application.properties
│ │ ├── static
│ │ └── css
│ │ │ └── bootstrap.min.css
│ │ └── templates
│ │ ├── addstudent.html
│ │ └── studentlist.html
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── course
│ ├── BookListApplicationTests.java
│ └── StudentListApplicationTests.java
├── StudentListGraphQL
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── README.txt
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── course
│ │ │ ├── StudentListApplication.java
│ │ │ ├── domain
│ │ │ ├── Department.java
│ │ │ ├── DepartmentRepository.java
│ │ │ ├── Student.java
│ │ │ └── StudentRepository.java
│ │ │ └── web
│ │ │ ├── Mutation.java
│ │ │ ├── Query.java
│ │ │ └── StudentController.java
│ └── resources
│ │ ├── application.properties
│ │ ├── static
│ │ └── css
│ │ │ └── bootstrap.min.css
│ │ ├── studentlist.graphqls
│ │ └── templates
│ │ ├── addstudent.html
│ │ └── studentlist.html
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── course
│ └── BookListApplicationTests.java
├── StudentListJDBC
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── demo
│ │ │ ├── DatabasedemoApplication.java
│ │ │ ├── domain
│ │ │ ├── Student.java
│ │ │ ├── StudentDAO.java
│ │ │ ├── StudentDAOImpl.java
│ │ │ └── StudentRowMapper.java
│ │ │ └── web
│ │ │ └── StudentController.java
│ └── resources
│ │ ├── application.properties
│ │ ├── schema.sql
│ │ └── templates
│ │ ├── addstudent.html
│ │ └── studentlist.html
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── demo
│ └── DatabasedemoApplicationTests.java
├── StudentListOneToMany
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── course
│ │ │ ├── StudentListApplication.java
│ │ │ ├── domain
│ │ │ ├── Department.java
│ │ │ ├── DepartmentRepository.java
│ │ │ ├── Student.java
│ │ │ └── StudentRepository.java
│ │ │ └── web
│ │ │ └── StudentController.java
│ └── resources
│ │ ├── application.properties
│ │ ├── static
│ │ └── css
│ │ │ └── bootstrap.min.css
│ │ └── templates
│ │ ├── addstudent.html
│ │ ├── editstudent.html
│ │ └── studentlist.html
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── course
│ └── BookListApplicationTests.java
├── StudentListRest
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── fi
│ │ │ └── haagahelia
│ │ │ └── course
│ │ │ ├── StudentListApplication.java
│ │ │ ├── domain
│ │ │ ├── Department.java
│ │ │ ├── DepartmentRepository.java
│ │ │ ├── Student.java
│ │ │ └── StudentRepository.java
│ │ │ └── web
│ │ │ └── StudentController.java
│ └── resources
│ │ ├── application.properties
│ │ ├── static
│ │ └── css
│ │ │ └── bootstrap.min.css
│ │ └── templates
│ │ ├── addstudent.html
│ │ └── studentlist.html
│ └── test
│ └── java
│ └── fi
│ └── haagahelia
│ └── course
│ └── BookListApplicationTests.java
└── StudentListSignup
├── .gitignore
├── .mvn
└── wrapper
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
├── main
├── java
│ └── fi
│ │ └── haagahelia
│ │ └── course
│ │ ├── StudentListSignUpApplication.java
│ │ ├── WebSecurityConfig.java
│ │ ├── domain
│ │ ├── AppUser.java
│ │ ├── AppUserRepository.java
│ │ ├── Department.java
│ │ ├── DepartmentRepository.java
│ │ ├── SignupForm.java
│ │ ├── Student.java
│ │ └── StudentRepository.java
│ │ └── web
│ │ ├── StudentController.java
│ │ ├── UserController.java
│ │ └── UserDetailServiceImpl.java
└── resources
│ ├── application.properties
│ ├── static
│ └── css
│ │ └── bootstrap.min.css
│ └── templates
│ ├── addstudent.html
│ ├── login.html
│ ├── signup.html
│ └── studentlist.html
└── test
└── java
└── fi
└── haagahelia
└── course
├── StudentListApplicationTests.java
└── StudentRepositoryTest.java
/Filedemo/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/Filedemo/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/Filedemo/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/Filedemo/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
2 |
--------------------------------------------------------------------------------
/Filedemo/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 2.2.4.RELEASE
9 |
10 |
11 | fi.haagahelia
12 | filedemo
13 | 0.0.1-SNAPSHOT
14 | filedemo
15 | Demo project for Spring Boot
16 |
17 |
18 | 1.8
19 |
20 |
21 |
22 |
23 | org.springframework.boot
24 | spring-boot-starter-thymeleaf
25 |
26 |
27 | org.springframework.boot
28 | spring-boot-starter-web
29 |
30 |
31 |
32 | org.springframework.boot
33 | spring-boot-starter-test
34 | test
35 |
36 |
37 |
38 |
39 |
40 |
41 | org.springframework.boot
42 | spring-boot-maven-plugin
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/Filedemo/src/main/java/fi/haagahelia/filedemo/FiledemoApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.filedemo;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class FiledemoApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(FiledemoApplication.class, args);
11 | }
12 |
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/Filedemo/src/main/java/fi/haagahelia/filedemo/web/FileController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.filedemo.web;
2 |
3 | import java.io.IOException;
4 | import java.nio.file.Files;
5 | import java.nio.file.Path;
6 | import java.nio.file.Paths;
7 |
8 | import org.springframework.beans.factory.annotation.Value;
9 | import org.springframework.stereotype.Controller;
10 | import org.springframework.ui.Model;
11 | import org.springframework.web.bind.annotation.GetMapping;
12 | import org.springframework.web.bind.annotation.PostMapping;
13 | import org.springframework.web.bind.annotation.RequestParam;
14 | import org.springframework.web.multipart.MultipartFile;
15 |
16 | @Controller
17 | public class FileController {
18 |
19 | @Value("${upload.path}")
20 | private String uploadFolder;
21 |
22 | @GetMapping("/")
23 | public String index() {
24 | return "upload";
25 | }
26 |
27 | @PostMapping("/upload")
28 | public String fileUpload(@RequestParam("file") MultipartFile file, Model model) {
29 | if (file.isEmpty()) {
30 | model.addAttribute("msg", "Upload failed");
31 | return "uploadstatus";
32 | }
33 |
34 | try {
35 | byte[] bytes = file.getBytes();
36 | Path path = Paths.get(uploadFolder + file.getOriginalFilename());
37 | Files.write(path, bytes);
38 | model.addAttribute("msg", "File " + file.getOriginalFilename() + " uploaded");
39 | } catch (IOException e) {
40 | e.printStackTrace();
41 | }
42 |
43 | return "uploadstatus";
44 | }
45 | }
--------------------------------------------------------------------------------
/Filedemo/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.servlet.multipart.max-file-size=128MB
2 | spring.servlet.multipart.max-request-size=128MB
3 | spring.servlet.multipart.enabled=true
4 |
5 | upload.path=c:\\temp\\
--------------------------------------------------------------------------------
/Filedemo/src/main/resources/templates/upload.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | File upload demo
5 |
6 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Filedemo/src/main/resources/templates/uploadstatus.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Filedemo/src/test/java/fi/haagahelia/filedemo/FiledemoApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.filedemo;
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 FiledemoApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/FiledemoDb/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/FiledemoDb/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/FiledemoDb/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/FiledemoDb/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
2 |
--------------------------------------------------------------------------------
/FiledemoDb/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 2.2.4.RELEASE
9 |
10 |
11 | fi.haagahelia
12 | filedemodb
13 | 0.0.1-SNAPSHOT
14 | filedemodb
15 | Demo project for Spring Boot
16 |
17 |
18 | 1.8
19 |
20 |
21 |
22 |
23 | org.springframework.boot
24 | spring-boot-starter-thymeleaf
25 |
26 |
27 | org.springframework.boot
28 | spring-boot-starter-web
29 |
30 |
31 | org.springframework.boot
32 | spring-boot-starter-data-jpa
33 |
34 |
35 | org.springframework.boot
36 | spring-boot-starter-test
37 | test
38 |
39 |
40 | com.h2database
41 | h2
42 | runtime
43 |
44 |
45 |
46 |
47 |
48 |
49 | org.springframework.boot
50 | spring-boot-maven-plugin
51 |
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/FiledemoDb/src/main/java/fi/haagahelia/filedemo/FiledemoApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.filedemo;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class FiledemoApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(FiledemoApplication.class, args);
11 | }
12 |
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/FiledemoDb/src/main/java/fi/haagahelia/filedemo/domain/FileModel.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.filedemo.domain;
2 |
3 | import javax.persistence.Entity;
4 | import javax.persistence.GeneratedValue;
5 | import javax.persistence.GenerationType;
6 | import javax.persistence.Id;
7 | import javax.persistence.Lob;
8 |
9 | @Entity
10 | public class FileModel {
11 | @Id
12 | @GeneratedValue(strategy = GenerationType.AUTO)
13 | private long id;
14 | private String fileName, mimeType, base64str;
15 |
16 | @Lob
17 | private byte[] file;
18 |
19 | public FileModel() {}
20 |
21 | public FileModel(String fileName, String mimeType, byte[] file) {
22 | this.fileName = fileName;
23 | this.mimeType = mimeType;
24 | this.file = file;
25 | }
26 |
27 | public long getId() {
28 | return id;
29 | }
30 |
31 | public void setId(long id) {
32 | this.id = id;
33 | }
34 |
35 | public String getFileName() {
36 | return fileName;
37 | }
38 |
39 | public void setFileName(String fileName) {
40 | this.fileName = fileName;
41 | }
42 |
43 | public String getMimeType() {
44 | return mimeType;
45 | }
46 |
47 | public void setMimeType(String mimeType) {
48 | this.mimeType = mimeType;
49 | }
50 |
51 | public byte[] getFile() {
52 | return file;
53 | }
54 |
55 | public void setFile(byte[] file) {
56 | this.file = file;
57 | }
58 |
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/FiledemoDb/src/main/java/fi/haagahelia/filedemo/domain/FileModelRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.filedemo.domain;
2 |
3 | import org.springframework.data.repository.CrudRepository;
4 |
5 | public interface FileModelRepository extends CrudRepository {
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/FiledemoDb/src/main/java/fi/haagahelia/filedemo/web/FileController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.filedemo.web;
2 |
3 | import java.io.IOException;
4 | import java.util.Base64;
5 | import java.util.Optional;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.beans.factory.annotation.Value;
9 | import org.springframework.http.HttpHeaders;
10 | import org.springframework.http.ResponseEntity;
11 | import org.springframework.stereotype.Controller;
12 | import org.springframework.ui.Model;
13 | import org.springframework.web.bind.annotation.GetMapping;
14 | import org.springframework.web.bind.annotation.PathVariable;
15 | import org.springframework.web.bind.annotation.PostMapping;
16 | import org.springframework.web.bind.annotation.RequestParam;
17 | import org.springframework.web.multipart.MultipartFile;
18 |
19 | import fi.haagahelia.filedemo.domain.FileModel;
20 | import fi.haagahelia.filedemo.domain.FileModelRepository;
21 |
22 | @Controller
23 | public class FileController {
24 | @Autowired
25 | private FileModelRepository repository;
26 |
27 | @Value("${upload.path}")
28 | private String uploadFolder;
29 |
30 | @GetMapping("/")
31 | public String index() {
32 | return "upload";
33 | }
34 |
35 | @PostMapping("/upload")
36 | public String fileUpload(@RequestParam("file") MultipartFile file, Model model) {
37 | // Image Base64.getEncoder().encodeToString(file.file)
38 | //
39 | if (file.isEmpty()) {
40 | model.addAttribute("msg", "Upload failed");
41 | return "uploadstatus";
42 | }
43 |
44 | try {
45 | FileModel fileModel = new FileModel(file.getOriginalFilename(), file.getContentType(), file.getBytes());
46 | repository.save(fileModel);
47 |
48 | return "redirect:/files";
49 | } catch (IOException e) {
50 | e.printStackTrace();
51 | }
52 |
53 | return "uploadstatus";
54 | }
55 |
56 | @GetMapping("/files")
57 | public String fileList(Model model) {
58 | model.addAttribute("files", repository.findAll());
59 | return "filelist";
60 | }
61 |
62 | @GetMapping("/file/{id}")
63 | public ResponseEntity getFile(@PathVariable Long id) {
64 | Optional fileOptional = repository.findById(id);
65 |
66 | if(fileOptional.isPresent()) {
67 | FileModel file = fileOptional.get();
68 | return ResponseEntity.ok()
69 | .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"")
70 | .body(file.getFile());
71 | }
72 |
73 | return ResponseEntity.status(404).body(null);
74 | }
75 |
76 | }
--------------------------------------------------------------------------------
/FiledemoDb/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.servlet.multipart.max-file-size=128MB
2 | spring.servlet.multipart.max-request-size=128MB
3 | spring.servlet.multipart.enabled=true
4 |
5 | upload.path=c:\\temp\\
6 |
7 | spring.jpa.show-sql=true
8 |
9 | spring.h2.console.enabled=true
10 | spring.h2.console.path=/h2-console
--------------------------------------------------------------------------------
/FiledemoDb/src/main/resources/templates/filelist.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Files
5 |
6 |
7 |
8 | Files
9 |
10 |
11 | Name |
12 | Type |
13 |
14 |
15 | |
16 | |
17 | Download |
18 |
19 |
20 | Upload
21 |
22 |
--------------------------------------------------------------------------------
/FiledemoDb/src/main/resources/templates/upload.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | File upload demo
5 |
6 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/FiledemoDb/src/main/resources/templates/uploadstatus.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/FiledemoDb/src/test/java/fi/haagahelia/filedemo/FiledemoApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.filedemo;
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 FiledemoApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/HelloForm/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/HelloForm/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/HelloForm/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/HelloForm/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/HelloForm/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | fi.haagahelia.course
7 | helloForm
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | helloFormValid
12 | Demo project for Spring Boot
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.2.4.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter
31 |
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-starter-web
36 |
37 |
38 |
39 | org.springframework.boot
40 | spring-boot-starter-thymeleaf
41 |
42 |
43 |
44 | org.springframework.boot
45 | spring-boot-starter-test
46 | test
47 |
48 |
49 |
50 |
51 |
52 |
53 | org.springframework.boot
54 | spring-boot-maven-plugin
55 |
56 |
57 |
58 |
59 |
60 |
61 |
--------------------------------------------------------------------------------
/HelloForm/src/main/java/fi/haagahelia/course/HelloFormApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class HelloFormApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(HelloFormApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/HelloForm/src/main/java/fi/haagahelia/course/domain/Message.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 |
4 | public class Message {
5 | private long id;
6 |
7 | private String msg;
8 |
9 | public long getId() {
10 | return id;
11 | }
12 | public void setId(long id) {
13 | this.id = id;
14 | }
15 | public String getMsg() {
16 | return msg;
17 | }
18 | public void setMsg(String msg) {
19 | this.msg = msg;
20 | }
21 |
22 | @Override
23 | public String toString() {
24 | return "Message [msg=" + msg + "]";
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/HelloForm/src/main/java/fi/haagahelia/course/web/MessageController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import javax.validation.Valid;
4 |
5 | import org.springframework.stereotype.Controller;
6 | import org.springframework.ui.Model;
7 | import org.springframework.validation.BindingResult;
8 | import org.springframework.web.bind.annotation.ModelAttribute;
9 | import org.springframework.web.bind.annotation.RequestMapping;
10 | import org.springframework.web.bind.annotation.RequestMethod;
11 |
12 | import fi.haagahelia.course.domain.Message;
13 |
14 | @Controller
15 | public class MessageController {
16 |
17 | @RequestMapping(value = "/hello", method = RequestMethod.GET)
18 | public String greetingForm(Model model) {
19 | model.addAttribute("message", new Message());
20 | return "hello";
21 | }
22 |
23 | @RequestMapping(value = "/hello", method = RequestMethod.POST)
24 | public String greetingSubmit(@ModelAttribute Message msg, Model model) {
25 | model.addAttribute("message", msg);
26 | return "result";
27 | }
28 | }
--------------------------------------------------------------------------------
/HelloForm/src/main/resources/application.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/HelloForm/src/main/resources/application.properties
--------------------------------------------------------------------------------
/HelloForm/src/main/resources/templates/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Getting Started: Handling Form Submission
5 |
6 |
7 |
8 | Form
9 |
21 |
22 |
--------------------------------------------------------------------------------
/HelloForm/src/main/resources/templates/result.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Getting Started: Handling Form Submission
5 |
6 |
7 |
8 | Result
9 |
10 |
11 | Submit another message
12 |
13 |
--------------------------------------------------------------------------------
/HelloForm/src/test/java/fi/haagahelia/course/HelloFormApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
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 HelloFormApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/HelloFormValidation/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/HelloFormValidation/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/HelloFormValidation/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/HelloFormValidation/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/HelloFormValidation/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | fi.haagahelia.course
7 | helloForm
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | helloFormValid
12 | Demo project for Spring Boot
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.2.4.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter
31 |
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-starter-web
36 |
37 |
38 |
39 | org.springframework.boot
40 | spring-boot-starter-thymeleaf
41 |
42 |
43 |
44 | org.springframework.boot
45 | spring-boot-starter-test
46 | test
47 |
48 |
49 |
50 |
51 |
52 |
53 | org.springframework.boot
54 | spring-boot-maven-plugin
55 |
56 |
57 |
58 |
59 |
60 |
61 |
--------------------------------------------------------------------------------
/HelloFormValidation/src/main/java/fi/haagahelia/course/HelloFormApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class HelloFormApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(HelloFormApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/HelloFormValidation/src/main/java/fi/haagahelia/course/domain/Message.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import javax.validation.constraints.NotNull;
4 | import javax.validation.constraints.Size;
5 |
6 | public class Message {
7 | @NotNull
8 | private long id;
9 |
10 | @Size(min=5, max=30)
11 | private String msg;
12 |
13 | public long getId() {
14 | return id;
15 | }
16 | public void setId(long id) {
17 | this.id = id;
18 | }
19 | public String getMsg() {
20 | return msg;
21 | }
22 | public void setMsg(String msg) {
23 | this.msg = msg;
24 | }
25 |
26 | @Override
27 | public String toString() {
28 | return "Message [msg=" + msg + "]";
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/HelloFormValidation/src/main/java/fi/haagahelia/course/web/MessageController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import javax.validation.Valid;
4 |
5 | import org.springframework.stereotype.Controller;
6 | import org.springframework.ui.Model;
7 | import org.springframework.validation.BindingResult;
8 | import org.springframework.web.bind.annotation.ModelAttribute;
9 | import org.springframework.web.bind.annotation.RequestMapping;
10 | import org.springframework.web.bind.annotation.RequestMethod;
11 |
12 | import fi.haagahelia.course.domain.Message;
13 |
14 | @Controller
15 | public class MessageController {
16 |
17 | @RequestMapping(value="/hello", method=RequestMethod.GET)
18 | public String greetingForm(Model model) {
19 | model.addAttribute("message", new Message());
20 | return "hello";
21 | }
22 |
23 | @RequestMapping(value="/hello", method=RequestMethod.POST)
24 | public String greetingSubmit(@Valid Message msg, BindingResult bindingResult, Model model) {
25 | if (bindingResult.hasErrors()) {
26 | return "hello";
27 | }
28 |
29 | model.addAttribute("message", msg);
30 | return "result";
31 | }
32 |
33 | }
--------------------------------------------------------------------------------
/HelloFormValidation/src/main/resources/application.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/HelloFormValidation/src/main/resources/application.properties
--------------------------------------------------------------------------------
/HelloFormValidation/src/main/resources/templates/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Getting Started: Handling Form Submission
5 |
6 |
7 |
8 | Form
9 |
21 |
22 |
--------------------------------------------------------------------------------
/HelloFormValidation/src/main/resources/templates/result.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Getting Started: Handling Form Submission
5 |
6 |
7 |
8 | Result
9 |
10 |
11 | Submit another message
12 |
13 |
--------------------------------------------------------------------------------
/HelloFormValidation/src/test/java/fi/haagahelia/course/HelloFormApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
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 HelloFormApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/HelloRest/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/HelloRest/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/HelloRest/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/HelloRest/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/HelloRest/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | com.example
7 | restdemo
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | restdemo
12 | REST demo project for Spring Boot
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 3.0.1
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 17
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-devtools
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-starter
35 |
36 |
37 |
38 | org.springframework.boot
39 | spring-boot-starter-web
40 |
41 |
42 |
43 | org.springframework.boot
44 | spring-boot-starter-test
45 | test
46 |
47 |
48 |
49 |
50 |
51 |
52 | org.springframework.boot
53 | spring-boot-maven-plugin
54 |
55 |
56 |
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/HelloRest/src/main/java/fi/haagahelia/course/RestdemoApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class RestdemoApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(RestdemoApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/HelloRest/src/main/java/fi/haagahelia/course/domain/Message.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | public class Message {
4 | private long id;
5 | private String text;
6 |
7 | public Message(long id, String text) {
8 | super();
9 | this.id = id;
10 | this.text = text;
11 | }
12 |
13 | public long getId() {
14 | return id;
15 | }
16 |
17 | public void setId(long id) {
18 | this.id = id;
19 | }
20 |
21 | public String getText() {
22 | return text;
23 | }
24 |
25 | public void setText(String text) {
26 | this.text = text;
27 | }
28 |
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/HelloRest/src/main/java/fi/haagahelia/course/web/MessageController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import java.util.concurrent.atomic.AtomicLong;
4 |
5 | import org.springframework.web.bind.annotation.RequestMapping;
6 | import org.springframework.web.bind.annotation.RequestParam;
7 | import org.springframework.web.bind.annotation.RestController;
8 |
9 | import fi.haagahelia.course.domain.Message;
10 |
11 | @RestController
12 | public class MessageController {
13 |
14 | private final AtomicLong counter = new AtomicLong();
15 |
16 | @RequestMapping("/hello")
17 | public Message msg(@RequestParam(value="name", defaultValue="World") String name) {
18 | return new Message(counter.incrementAndGet(), "Hello " + name);
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/HelloRest/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.datasource.url=jdbc:h2:mem:testdb
2 |
--------------------------------------------------------------------------------
/HelloRest/src/test/java/com/example/demo/RestdemoApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.example.demo;
2 |
3 |
4 | import org.junit.jupiter.api.Test;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 |
7 | @SpringBootTest
8 | class RestdemoApplicationTests {
9 |
10 | @Test
11 | void contextLoads() {
12 | }
13 |
14 | }
15 |
16 |
--------------------------------------------------------------------------------
/HelloTest/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/HelloTest/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/HelloTest/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/HelloTest/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/HelloTest/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | fi.haagahelia.course
7 | hellotest
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | hellotest
12 | Demo project for Spring Boot
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 3.0.2
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 17
25 |
26 |
27 |
28 |
41 |
42 | org.springframework.boot
43 | spring-boot-starter-web
44 |
45 |
46 | org.springframework.boot
47 | spring-boot-devtools
48 |
49 |
50 | org.springframework.boot
51 | spring-boot-starter-test
52 | test
53 |
54 |
55 |
56 |
57 |
58 |
59 |
66 |
67 |
68 | org.springframework.boot
69 | spring-boot-maven-plugin
70 |
71 |
72 |
73 |
74 |
75 |
76 |
--------------------------------------------------------------------------------
/HelloTest/src/main/java/fi/haagahelia/course/HellotestApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class HellotestApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(HellotestApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/HelloTest/src/main/java/fi/haagahelia/course/web/HelloController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import org.springframework.stereotype.Controller;
4 | import org.springframework.web.bind.annotation.RequestMapping;
5 | import org.springframework.web.bind.annotation.ResponseBody;
6 |
7 | @Controller
8 | public class HelloController {
9 |
10 | @RequestMapping("/")
11 | public @ResponseBody String greeting() {
12 | return "Hello World";
13 | }
14 |
15 | }
--------------------------------------------------------------------------------
/HelloTest/src/main/resources/application.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/HelloTest/src/main/resources/application.properties
--------------------------------------------------------------------------------
/HelloTest/src/test/java/fi/haagahelia/course/HellotestApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 |
5 | import org.junit.jupiter.api.Test;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.boot.test.context.SpringBootTest;
8 |
9 | import fi.haagahelia.course.web.HelloController;
10 |
11 | /**
12 | * Testing that the context is creating your controller
13 | *
14 | * @author h01270
15 | *
16 | */
17 | //@ExtendWith(SpringExtension.class) not needed when using JUnit5
18 | @SpringBootTest
19 | public class HellotestApplicationTests {
20 |
21 | @Autowired
22 | private HelloController controller;
23 |
24 | @Test
25 | public void contexLoads() throws Exception {
26 | assertThat(controller).isNotNull();
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/HelloTest/src/test/java/fi/haagahelia/course/WebLayerTest.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 |
4 | import static org.hamcrest.Matchers.containsString;
5 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
6 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
7 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
8 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
9 |
10 | import org.junit.jupiter.api.Test;
11 | import org.springframework.beans.factory.annotation.Autowired;
12 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
13 | import org.springframework.boot.test.context.SpringBootTest;
14 | import org.springframework.test.web.servlet.MockMvc;
15 |
16 | /**
17 | * Testing the web layer
18 | *
19 | * Spring application context is started, but without the server
20 | *
21 | * @author h01270
22 | *
23 | */
24 | //@ExtendWith(SpringExtension.class) not needed when using JUnit5
25 | @SpringBootTest
26 | @AutoConfigureMockMvc
27 | public class WebLayerTest {
28 |
29 | @Autowired
30 | private MockMvc mockMvc;
31 |
32 | @Test
33 | public void testDefaultMessage() throws Exception {
34 | this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
35 | .andExpect(content().string(containsString("Hello World")));
36 | }
37 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Juha Hinkula
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Server Programming
2 | Server programming course demos (Spring Boot)
3 |
4 | ## Week 1 - Models & Views
5 | - HelloForm - Simple form
6 | - HelloFromValidation - Form with validation
7 |
8 | ## Week 2 - JPA, Databases (Hibernate, H2, MariaDB)
9 | - StudentList - Studentlist application skeleton
10 | - StudentListCRUD - Studentlist application with CRUD operations
11 | - StudentJDBC - Studenlist application using JDBC (MariaDB)
12 | - StudentOneToMany - Studentlist application with OneToMany relationship
13 |
14 | ## Week 3 - REST API & File upload
15 | - HelloRest
16 | - StudentListRest - REST API using Spring Data REST
17 | - Filedemo - File upload demo
18 | - FiledemoDb - File upload & download demo with H2 DB
19 |
20 | ## Week 4 - Spring Security
21 | - SecureDemo - Spring Security added to studentlist
22 | - SecureStudentList - Studentlist with in-memory users (user/user and admin/admin)
23 | - SecureStudentListUser - Studentlist with User entity and encrypted passwords
24 | - SecureSignup - Secured studentlist with sign-up
25 |
26 | ## Week 5 - Testing (JUnit)
27 | - HelloTest -Simple JUnit test demo
28 | - StudentJpaTest - Studentlist application with JPA tests
29 |
--------------------------------------------------------------------------------
/SecureStudentList/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/SecureStudentList/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/SecureStudentList/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/SecureStudentList/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/SecureStudentList/src/main/java/fi/haagahelia/course/StudentListApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | import org.springframework.boot.CommandLineRunner;
7 | import org.springframework.boot.SpringApplication;
8 | import org.springframework.boot.autoconfigure.SpringBootApplication;
9 | import org.springframework.context.annotation.Bean;
10 |
11 | import fi.haagahelia.course.domain.Department;
12 | import fi.haagahelia.course.domain.DepartmentRepository;
13 | import fi.haagahelia.course.domain.Student;
14 | import fi.haagahelia.course.domain.StudentRepository;
15 |
16 | @SpringBootApplication
17 | public class StudentListApplication {
18 | private static final Logger log = LoggerFactory.getLogger(StudentListApplication.class);
19 |
20 | public static void main(String[] args) {
21 | SpringApplication.run(StudentListApplication.class, args);
22 | }
23 |
24 | @Bean
25 | public CommandLineRunner studentDemo(StudentRepository srepository, DepartmentRepository drepository) {
26 | return (args) -> {
27 | log.info("save a couple of students");
28 | drepository.save(new Department("IT"));
29 | drepository.save(new Department("Business"));
30 | drepository.save(new Department("Law"));
31 |
32 | srepository.save(new Student("John", "Johnson", "john@john.com", drepository.findByName("IT").get(0)));
33 | srepository.save(new Student("Katy", "Kateson", "kate@kate.com", drepository.findByName("Business").get(0)));
34 |
35 | log.info("fetch all students");
36 | for (Student student : srepository.findAll()) {
37 | log.info(student.toString());
38 | }
39 |
40 | };
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/SecureStudentList/src/main/java/fi/haagahelia/course/WebSecurityConfig.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import org.springframework.context.annotation.Bean;
7 | import org.springframework.context.annotation.Configuration;
8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
9 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
10 | import org.springframework.security.core.userdetails.User;
11 | import org.springframework.security.core.userdetails.UserDetails;
12 | import org.springframework.security.core.userdetails.UserDetailsService;
13 | import org.springframework.security.crypto.factory.PasswordEncoderFactories;
14 | import org.springframework.security.crypto.password.PasswordEncoder;
15 | import org.springframework.security.provisioning.InMemoryUserDetailsManager;
16 | import org.springframework.security.web.SecurityFilterChain;
17 |
18 | @Configuration
19 | @EnableWebSecurity
20 | public class WebSecurityConfig {
21 |
22 | @Bean
23 | public SecurityFilterChain configure(HttpSecurity http) throws Exception {
24 | http.authorizeHttpRequests().requestMatchers("/css/**").permitAll() // Enable css when logged out
25 | .anyRequest().authenticated().and().formLogin().defaultSuccessUrl("/studentlist", true).permitAll()
26 | .and().logout().permitAll().and().httpBasic();
27 | return http.build();
28 | }
29 |
30 | @Bean
31 | public UserDetailsService userDetailsService() {
32 |
33 | System.out.println("in-memory users - luodaan näitä kaksi kappaletta");
34 | List users = new ArrayList();
35 |
36 | PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
37 |
38 | UserDetails user1 = User.withUsername("user").password(passwordEncoder.encode("user")).roles("USER").build();
39 |
40 | users.add(user1);
41 |
42 | UserDetails user2 = User.withUsername("admin").password(passwordEncoder.encode("admin")).roles("USER", "ADMIN")
43 | .build();
44 |
45 | users.add(user2);
46 |
47 | return new InMemoryUserDetailsManager(users);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/SecureStudentList/src/main/java/fi/haagahelia/course/domain/Department.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import jakarta.persistence.*;
6 | @Entity
7 | public class Department {
8 | @Id
9 | @GeneratedValue(strategy=GenerationType.AUTO)
10 | private Long departmentid;
11 | private String name;
12 |
13 | @OneToMany(cascade = CascadeType.ALL, mappedBy = "department")
14 | private List students;
15 |
16 | public Department() {}
17 |
18 | public Department(String name) {
19 | super();
20 | this.name = name;
21 | }
22 |
23 | public Long getDepartmentid() {
24 | return departmentid;
25 | }
26 |
27 | public void setDepartmentid(Long departmentid) {
28 | this.departmentid = departmentid;
29 | }
30 |
31 | public String getName() {
32 | return name;
33 | }
34 |
35 | public void setName(String name) {
36 | this.name = name;
37 | }
38 |
39 | public List getStudents() {
40 | return students;
41 | }
42 |
43 | public void setStudents(List students) {
44 | this.students = students;
45 | }
46 |
47 | @Override
48 | public String toString() {
49 | return "Department [departmentid=" + departmentid + ", name=" + name + "]";
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/SecureStudentList/src/main/java/fi/haagahelia/course/domain/DepartmentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 | import org.springframework.data.repository.CrudRepository;
5 |
6 | public interface DepartmentRepository extends CrudRepository {
7 |
8 | List findByName(String name);
9 |
10 | }
--------------------------------------------------------------------------------
/SecureStudentList/src/main/java/fi/haagahelia/course/domain/Student.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import jakarta.persistence.*;
4 |
5 | import com.fasterxml.jackson.annotation.JsonIgnore;
6 |
7 | @Entity
8 | public class Student {
9 | @Id
10 | @GeneratedValue(strategy=GenerationType.AUTO)
11 | private Long id;
12 | private String firstName;
13 | private String lastName;
14 | private String email;
15 |
16 | @ManyToOne
17 | @JsonIgnore
18 | @JoinColumn(name = "departmentid")
19 | private Department department;
20 |
21 | public Student() {}
22 |
23 | public Student(String firstName, String lastName, String email, Department department) {
24 | super();
25 | this.firstName = firstName;
26 | this.lastName = lastName;
27 | this.email = email;
28 | this.department = department;
29 | }
30 |
31 | public Long getId() {
32 | return id;
33 | }
34 |
35 | public void setId(Long id) {
36 | this.id = id;
37 | }
38 |
39 | public String getFirstName() {
40 | return firstName;
41 | }
42 |
43 | public void setFirstName(String firstName) {
44 | this.firstName = firstName;
45 | }
46 |
47 | public String getLastName() {
48 | return lastName;
49 | }
50 |
51 | public void setLastName(String lastName) {
52 | this.lastName = lastName;
53 | }
54 |
55 | public String getEmail() {
56 | return email;
57 | }
58 |
59 | public void setEmail(String email) {
60 | this.email = email;
61 | }
62 |
63 | public Department getDepartment() {
64 | return department;
65 | }
66 |
67 | public void setDepartment(Department department) {
68 | this.department = department;
69 | }
70 |
71 | @Override
72 | public String toString() {
73 | if (this.department != null)
74 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + " department =" + this.getDepartment() + "]";
75 | else
76 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/SecureStudentList/src/main/java/fi/haagahelia/course/domain/StudentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.repository.CrudRepository;
6 |
7 | public interface StudentRepository extends CrudRepository {
8 |
9 | List findByLastName(String lastName);
10 |
11 | }
--------------------------------------------------------------------------------
/SecureStudentList/src/main/java/fi/haagahelia/course/web/StudentController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Controller;
8 | import org.springframework.ui.Model;
9 | import org.springframework.web.bind.annotation.PathVariable;
10 | import org.springframework.web.bind.annotation.RequestMapping;
11 | import org.springframework.web.bind.annotation.RequestMethod;
12 | import org.springframework.web.bind.annotation.ResponseBody;
13 |
14 | import fi.haagahelia.course.domain.DepartmentRepository;
15 | import fi.haagahelia.course.domain.Student;
16 | import fi.haagahelia.course.domain.StudentRepository;
17 |
18 | @Controller
19 | public class StudentController {
20 | @Autowired
21 | private StudentRepository repository;
22 |
23 | @Autowired
24 | private DepartmentRepository drepository;
25 |
26 | // Show all students
27 | @RequestMapping(value="/studentlist")
28 | public String studentList(Model model) {
29 | model.addAttribute("students", repository.findAll());
30 | return "studentlist";
31 | }
32 |
33 | // RESTful service to get all students
34 | @RequestMapping(value="/students")
35 | public @ResponseBody List studentListRest() {
36 | return (List) repository.findAll();
37 | }
38 |
39 | // RESTful service to get student by id
40 | @RequestMapping(value="/student/{id}", method = RequestMethod.GET)
41 | public @ResponseBody Optional findStudentRest(@PathVariable("id") Long studentId) {
42 | return repository.findById(studentId);
43 | }
44 |
45 | // Add new student
46 | @RequestMapping(value = "/add")
47 | public String addStudent(Model model){
48 | model.addAttribute("student", new Student());
49 | model.addAttribute("departments", drepository.findAll());
50 | return "addstudent";
51 | }
52 |
53 | // Save new student
54 | @RequestMapping(value = "/save", method = RequestMethod.POST)
55 | public String save(Student student){
56 | repository.save(student);
57 | return "redirect:studentlist";
58 | }
59 |
60 | // Delete student
61 | @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
62 | public String deleteStudent(@PathVariable("id") Long studentId, Model model) {
63 | repository.deleteById(studentId);
64 | return "redirect:../studentlist";
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/SecureStudentList/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.jpa.show-sql=true
2 | spring.datasource.url=jdbc:h2:mem:testdb
3 |
--------------------------------------------------------------------------------
/SecureStudentList/src/main/resources/templates/addstudent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 | Add student
9 |
30 |
31 |
--------------------------------------------------------------------------------
/SecureStudentList/src/main/resources/templates/studentlist.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 |
9 |
10 |
11 |
Students
12 |
13 |
14 |
Welcome
15 |
16 |
17 |
20 |
21 |
22 |
23 | Name |
24 | Email |
25 | Department |
26 | |
27 |
28 |
29 | |
30 | |
31 | |
32 | Delete |
33 |
34 |
35 |
Add Student
36 |
37 |
38 |
--------------------------------------------------------------------------------
/SecureStudentList/src/test/java/fi/haagahelia/course/BookListApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 |
4 | import org.springframework.boot.test.context.SpringBootTest;
5 | import org.springframework.test.context.junit4.SpringRunner;
6 |
7 |
8 | @SpringBootTest
9 | public class BookListApplicationTests {
10 |
11 |
12 | public void contextLoads() {
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/SecureStudentListUser/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/SecureStudentListUser/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/SecureStudentListUser/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/SecureStudentListUser/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/SecureStudentListUser/src/main/java/fi/haagahelia/course/StudentListApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | import org.springframework.boot.CommandLineRunner;
7 | import org.springframework.boot.SpringApplication;
8 | import org.springframework.boot.autoconfigure.SpringBootApplication;
9 | import org.springframework.context.annotation.Bean;
10 |
11 | import fi.haagahelia.course.domain.Department;
12 | import fi.haagahelia.course.domain.DepartmentRepository;
13 | import fi.haagahelia.course.domain.Student;
14 | import fi.haagahelia.course.domain.StudentRepository;
15 | import fi.haagahelia.course.domain.AppUser;
16 | import fi.haagahelia.course.domain.AppUserRepository;
17 |
18 | @SpringBootApplication
19 | public class StudentListApplication {
20 | private static final Logger log = LoggerFactory.getLogger(StudentListApplication.class);
21 |
22 | public static void main(String[] args) {
23 | SpringApplication.run(StudentListApplication.class, args);
24 | }
25 |
26 | @Bean
27 | public CommandLineRunner studentDemo(StudentRepository srepository, DepartmentRepository drepository, AppUserRepository urepository) {
28 | return (args) -> {
29 | log.info("save a couple of students");
30 | drepository.save(new Department("IT"));
31 | drepository.save(new Department("Business"));
32 | drepository.save(new Department("Law"));
33 |
34 | srepository.save(new Student("John", "Johnson", "john@john.com", drepository.findByName("IT").get(0)));
35 | srepository.save(new Student("Katy", "Kateson", "kate@kate.com", drepository.findByName("Business").get(0)));
36 |
37 | // Create users: admin/admin user/user
38 | AppUser user1 = new AppUser("user", "$2a$06$3jYRJrg0ghaaypjZ/.g4SethoeA51ph3UD4kZi9oPkeMTpjKU5uo6", "USER");
39 | AppUser user2 = new AppUser("admin", "$2a$10$0MMwY.IQqpsVc1jC8u7IJ.2rT8b0Cd3b3sfIBGV2zfgnPGtT4r0.C", "ADMIN");
40 | urepository.save(user1);
41 | urepository.save(user2);
42 |
43 | log.info("fetch all students");
44 | for (Student student : srepository.findAll()) {
45 | log.info(student.toString());
46 | }
47 |
48 | };
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/SecureStudentListUser/src/main/java/fi/haagahelia/course/WebSecurityConfig.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 |
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.context.annotation.Bean;
6 | import org.springframework.context.annotation.Configuration;
7 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
8 | import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
10 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
11 | import org.springframework.security.web.SecurityFilterChain;
12 |
13 | import fi.haagahelia.course.web.UserDetailServiceImpl;
14 |
15 | @Configuration
16 | @EnableMethodSecurity(securedEnabled = true)
17 | public class WebSecurityConfig {
18 | @Autowired
19 | private UserDetailServiceImpl userDetailsService;
20 |
21 | @Bean
22 | public SecurityFilterChain configure(HttpSecurity http) throws Exception {
23 |
24 | http.authorizeHttpRequests().requestMatchers("/css/**").permitAll()
25 | .and()
26 | .authorizeHttpRequests().anyRequest().authenticated()
27 | .and()
28 | .headers().frameOptions().disable() //for h2 console
29 | .and()
30 | .formLogin()
31 | .loginPage("/login")
32 | .defaultSuccessUrl("/studentlist", true)
33 | .permitAll()
34 | .and()
35 | .logout().permitAll();
36 |
37 | return http.build();
38 | }
39 |
40 |
41 | @Autowired
42 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
43 | auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
44 | }}
45 |
--------------------------------------------------------------------------------
/SecureStudentListUser/src/main/java/fi/haagahelia/course/domain/AppUser.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 |
4 |
5 | import jakarta.persistence.*;
6 |
7 | @Entity
8 | @Table(name="UserTable")
9 | public class AppUser {
10 |
11 | @Id
12 | @GeneratedValue(strategy = GenerationType.IDENTITY)
13 | @Column(name = "id", nullable = false, updatable = false)
14 | private Long id;
15 |
16 | // Username with unique constraint
17 | @Column(name = "username", nullable = false, unique = true)
18 | private String username;
19 |
20 | @Column(name = "password", nullable = false)
21 | private String passwordHash;
22 |
23 | @Column(name = "role", nullable = false)
24 | private String role;
25 |
26 | public AppUser() {
27 | }
28 |
29 | public AppUser(String username, String passwordHash, String role) {
30 | super();
31 | this.username = username;
32 | this.passwordHash = passwordHash;
33 | this.role = role;
34 | }
35 |
36 | public Long getId() {
37 | return id;
38 | }
39 |
40 | public void setId(Long id) {
41 | this.id = id;
42 | }
43 |
44 | public String getUsername() {
45 | return username;
46 | }
47 |
48 | public void setUsername(String username) {
49 | this.username = username;
50 | }
51 |
52 | public String getPasswordHash() {
53 | return passwordHash;
54 | }
55 |
56 | public void setPasswordHash(String passwordHash) {
57 | this.passwordHash = passwordHash;
58 | }
59 |
60 | public String getRole() {
61 | return role;
62 | }
63 |
64 | public void setRole(String role) {
65 | this.role = role;
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/SecureStudentListUser/src/main/java/fi/haagahelia/course/domain/AppUserRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.repository.CrudRepository;
6 |
7 | public interface AppUserRepository extends CrudRepository {
8 | AppUser findByUsername(String username);
9 | }
--------------------------------------------------------------------------------
/SecureStudentListUser/src/main/java/fi/haagahelia/course/domain/Department.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 | import jakarta.persistence.*;
5 |
6 | @Entity
7 | public class Department {
8 | @Id
9 | @GeneratedValue(strategy=GenerationType.AUTO)
10 | private Long departmentid;
11 | private String name;
12 |
13 | @OneToMany(cascade = CascadeType.ALL, mappedBy = "department")
14 | private List students;
15 |
16 | public Department() {}
17 |
18 | public Department(String name) {
19 | super();
20 | this.name = name;
21 | }
22 |
23 | public Long getDepartmentid() {
24 | return departmentid;
25 | }
26 |
27 | public void setDepartmentid(Long departmentid) {
28 | this.departmentid = departmentid;
29 | }
30 |
31 | public String getName() {
32 | return name;
33 | }
34 |
35 | public void setName(String name) {
36 | this.name = name;
37 | }
38 |
39 | public List getStudents() {
40 | return students;
41 | }
42 |
43 | public void setStudents(List students) {
44 | this.students = students;
45 | }
46 |
47 | @Override
48 | public String toString() {
49 | return "Department [departmentid=" + departmentid + ", name=" + name + "]";
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/SecureStudentListUser/src/main/java/fi/haagahelia/course/domain/DepartmentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 | import org.springframework.data.repository.CrudRepository;
5 |
6 | public interface DepartmentRepository extends CrudRepository {
7 |
8 | List findByName(String name);
9 |
10 | }
--------------------------------------------------------------------------------
/SecureStudentListUser/src/main/java/fi/haagahelia/course/domain/Student.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 |
4 |
5 | import com.fasterxml.jackson.annotation.JsonIgnore;
6 | import jakarta.persistence.*;
7 |
8 | @Entity
9 | public class Student {
10 | @Id
11 | @GeneratedValue(strategy=GenerationType.AUTO)
12 | private Long id;
13 | private String firstName;
14 | private String lastName;
15 | private String email;
16 |
17 | @ManyToOne
18 | @JsonIgnore
19 | @JoinColumn(name = "departmentid")
20 | private Department department;
21 |
22 | public Student() {}
23 |
24 | public Student(String firstName, String lastName, String email, Department department) {
25 | super();
26 | this.firstName = firstName;
27 | this.lastName = lastName;
28 | this.email = email;
29 | this.department = department;
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 getFirstName() {
41 | return firstName;
42 | }
43 |
44 | public void setFirstName(String firstName) {
45 | this.firstName = firstName;
46 | }
47 |
48 | public String getLastName() {
49 | return lastName;
50 | }
51 |
52 | public void setLastName(String lastName) {
53 | this.lastName = lastName;
54 | }
55 |
56 | public String getEmail() {
57 | return email;
58 | }
59 |
60 | public void setEmail(String email) {
61 | this.email = email;
62 | }
63 |
64 | public Department getDepartment() {
65 | return department;
66 | }
67 |
68 | public void setDepartment(Department department) {
69 | this.department = department;
70 | }
71 |
72 | @Override
73 | public String toString() {
74 | if (this.department != null)
75 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + " department =" + this.getDepartment() + "]";
76 | else
77 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/SecureStudentListUser/src/main/java/fi/haagahelia/course/domain/StudentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.repository.CrudRepository;
6 |
7 | public interface StudentRepository extends CrudRepository {
8 |
9 | List findByLastName(String lastName);
10 |
11 | }
--------------------------------------------------------------------------------
/SecureStudentListUser/src/main/java/fi/haagahelia/course/web/UserDetailServiceImpl.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.security.core.authority.AuthorityUtils;
5 | import org.springframework.security.core.userdetails.UserDetails;
6 | import org.springframework.security.core.userdetails.UserDetailsService;
7 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
8 | import org.springframework.stereotype.Service;
9 |
10 | import fi.haagahelia.course.domain.AppUser;
11 | import fi.haagahelia.course.domain.AppUserRepository;
12 |
13 | /**
14 | * This class is used by spring security to authenticate and authorize user
15 | **/
16 | @Service
17 | public class UserDetailServiceImpl implements UserDetailsService {
18 | private final AppUserRepository repository;
19 |
20 | @Autowired
21 | public UserDetailServiceImpl(AppUserRepository userRepository) {
22 | this.repository = userRepository;
23 | }
24 |
25 | @Override
26 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
27 | {
28 | AppUser curruser = repository.findByUsername(username);
29 | UserDetails user = new org.springframework.security.core.userdetails.User(username, curruser.getPasswordHash(),
30 | AuthorityUtils.createAuthorityList(curruser.getRole()));
31 | return user;
32 | }
33 | }
--------------------------------------------------------------------------------
/SecureStudentListUser/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.jpa.show-sql=true
2 | spring.datasource.url=jdbc:h2:mem:testdb
3 |
--------------------------------------------------------------------------------
/SecureStudentListUser/src/main/resources/templates/addstudent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 |
9 | Add student
10 |
33 |
34 |
--------------------------------------------------------------------------------
/SecureStudentListUser/src/main/resources/templates/login.html:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 | Spring Security Example
6 |
7 |
8 |
9 |
10 |
11 | Invalid username and password.
12 |
13 |
14 | You have been logged out.
15 |
16 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/SecureStudentListUser/src/main/resources/templates/studentlist.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 |
9 |
10 |
11 |
Students
12 |
13 |
17 |
18 |
21 |
22 |
23 |
24 | Name |
25 | Email |
26 | Department |
27 | |
28 |
29 |
30 | |
31 | |
32 | |
33 | Delete |
34 |
35 |
36 |
Add Student
37 |
38 |
39 |
--------------------------------------------------------------------------------
/SecureStudentListUser/src/test/java/fi/haagahelia/course/BookListApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 |
4 | import org.springframework.boot.test.context.SpringBootTest;
5 | import org.springframework.test.context.junit4.SpringRunner;
6 |
7 |
8 | @SpringBootTest
9 | public class BookListApplicationTests {
10 |
11 |
12 | public void contextLoads() {
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/SecurityDemo/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 |
4 | ### STS ###
5 | .classpath
6 | .factorypath
7 | .project
8 | .settings
9 | .springBeans
10 |
11 | ### IntelliJ IDEA ###
12 | .idea
13 | *.iws
14 | *.iml
15 | *.ipr
16 |
17 | ### NetBeans ###
18 | nbproject/private/
19 | build/
20 | nbbuild/
21 | dist/
22 | nbdist/
23 | .nb-gradle/
--------------------------------------------------------------------------------
/SecurityDemo/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/SecurityDemo/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/SecurityDemo/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/SecurityDemo/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | fi.haagahelia.course
7 | securitydemo
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | securitydemo
12 | Demo project for Spring Boot
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 3.0.2
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 17
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-security
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-starter-thymeleaf
35 |
36 |
37 | org.springframework.boot
38 | spring-boot-starter-web
39 |
40 |
41 |
42 | org.springframework.boot
43 | spring-boot-starter-test
44 | test
45 |
46 |
47 |
48 |
49 |
50 |
51 | org.springframework.boot
52 | spring-boot-maven-plugin
53 |
54 |
55 |
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/SecurityDemo/src/main/java/fi/haagahelia/course/SecuritydemoApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SecuritydemoApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SecuritydemoApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/SecurityDemo/src/main/java/fi/haagahelia/course/WebSecurityConfig.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import org.springframework.context.annotation.Bean;
7 | import org.springframework.context.annotation.Configuration;
8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
9 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
10 | import org.springframework.security.core.userdetails.User;
11 | import org.springframework.security.core.userdetails.UserDetails;
12 | import org.springframework.security.core.userdetails.UserDetailsService;
13 | import org.springframework.security.provisioning.InMemoryUserDetailsManager;
14 |
15 | @Configuration
16 | @EnableWebSecurity
17 | public class WebSecurityConfig {
18 | protected void configure(HttpSecurity http) throws Exception {
19 | http
20 | .authorizeRequests()
21 | .requestMatchers("/", "/home").permitAll()
22 | .anyRequest().authenticated()
23 | .and()
24 | .formLogin()
25 | .loginPage("/login")
26 | .defaultSuccessUrl("/home", true)
27 | .permitAll()
28 | .and()
29 | .logout()
30 | .permitAll();
31 | }
32 |
33 |
34 | @Bean
35 | public UserDetailsService userDetailsService() {
36 | List users = new ArrayList();
37 | UserDetails user = User.withDefaultPasswordEncoder()
38 | .username("user")
39 | .password("user")
40 | .roles("USER")
41 | .build();
42 |
43 | users.add(user);
44 |
45 | user = User.withDefaultPasswordEncoder()
46 | .username("admin")
47 | .password("admin")
48 | .roles("USER", "ADMIN")
49 | .build();
50 |
51 | users.add(user);
52 |
53 | return new InMemoryUserDetailsManager(users);
54 | }
55 | }
--------------------------------------------------------------------------------
/SecurityDemo/src/main/java/fi/haagahelia/course/web/DemoController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import org.springframework.security.core.context.SecurityContextHolder;
4 | import org.springframework.security.core.userdetails.User;
5 | import org.springframework.security.core.userdetails.UserDetails;
6 | import org.springframework.stereotype.Controller;
7 | import org.springframework.ui.Model;
8 | import org.springframework.web.bind.annotation.RequestMapping;
9 | import org.springframework.web.bind.annotation.RequestMethod;
10 |
11 | @Controller
12 | public class DemoController {
13 |
14 | @RequestMapping(value={"/", "/home"})
15 | public String homeSecure() {
16 | return "home";
17 | }
18 |
19 | @RequestMapping(value="/hello")
20 | public String helloSecure(Model model) {
21 | UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
22 | String username = user.getUsername();
23 | System.out.println("USERNAME: " + username);
24 | model.addAttribute("name", username);
25 | return "hello";
26 | }
27 |
28 | @RequestMapping(value="/login")
29 | public String login() {
30 | return "login";
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/SecurityDemo/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.datasource.url=jdbc:h2:mem:testdb
2 |
--------------------------------------------------------------------------------
/SecurityDemo/src/main/resources/templates/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 | Hello World!
6 |
7 |
8 |
9 |
10 | Hello
11 |
12 | Author name:
13 |
16 |
17 |
--------------------------------------------------------------------------------
/SecurityDemo/src/main/resources/templates/home.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Spring Security Example
5 |
6 |
7 | Welcome!
8 |
9 | Click here to see a greeting.
10 |
11 |
--------------------------------------------------------------------------------
/SecurityDemo/src/main/resources/templates/login.html:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 | Spring Security Example
6 |
7 |
8 |
9 | Invalid username and password.
10 |
11 |
12 | You have been logged out.
13 |
14 |
19 |
20 |
--------------------------------------------------------------------------------
/SecurityDemo/src/test/java/fi/haagahelia/course/SecuritydemoApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 |
4 | import org.springframework.boot.test.context.SpringBootTest;
5 | import org.springframework.test.context.junit4.SpringRunner;
6 |
7 |
8 | @SpringBootTest
9 | public class SecuritydemoApplicationTests {
10 |
11 |
12 | public void contextLoads() {
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/StudentJpaTest/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/StudentJpaTest/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/StudentJpaTest/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/StudentJpaTest/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/StudentJpaTest/src/main/java/fi/haagahelia/course/StudentListApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | import org.springframework.boot.CommandLineRunner;
7 | import org.springframework.boot.SpringApplication;
8 | import org.springframework.boot.autoconfigure.SpringBootApplication;
9 | import org.springframework.context.annotation.Bean;
10 |
11 | import fi.haagahelia.course.domain.Department;
12 | import fi.haagahelia.course.domain.DepartmentRepository;
13 | import fi.haagahelia.course.domain.Student;
14 | import fi.haagahelia.course.domain.StudentRepository;
15 | import fi.haagahelia.course.domain.AppUser;
16 | import fi.haagahelia.course.domain.AppUserRepository;
17 |
18 | @SpringBootApplication
19 | public class StudentListApplication {
20 | private static final Logger log = LoggerFactory.getLogger(StudentListApplication.class);
21 |
22 | public static void main(String[] args) {
23 | SpringApplication.run(StudentListApplication.class, args);
24 | }
25 |
26 | @Bean
27 | public CommandLineRunner studentDemo(StudentRepository srepository, DepartmentRepository drepository, AppUserRepository urepository) {
28 | return (args) -> {
29 | log.info("save a couple of students");
30 | drepository.save(new Department("IT"));
31 | drepository.save(new Department("Business"));
32 | drepository.save(new Department("Law"));
33 |
34 | srepository.save(new Student("John", "Johnson", "john@john.com", drepository.findByName("IT").get(0)));
35 | srepository.save(new Student("Katy", "Kateson", "kate@kate.com", drepository.findByName("Business").get(0)));
36 |
37 | // Create users: admin/admin user/user
38 | AppUser user1 = new AppUser("user", "$2a$06$3jYRJrg0ghaaypjZ/.g4SethoeA51ph3UD4kZi9oPkeMTpjKU5uo6", "USER");
39 | AppUser user2 = new AppUser("admin", "$2a$10$0MMwY.IQqpsVc1jC8u7IJ.2rT8b0Cd3b3sfIBGV2zfgnPGtT4r0.C", "ADMIN");
40 | urepository.save(user1);
41 | urepository.save(user2);
42 |
43 | log.info("fetch all students");
44 | for (Student student : srepository.findAll()) {
45 | log.info(student.toString());
46 | }
47 |
48 | };
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/StudentJpaTest/src/main/java/fi/haagahelia/course/WebSecurityConfig.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.context.annotation.Bean;
5 | import org.springframework.context.annotation.Configuration;
6 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
7 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
8 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
10 | import org.springframework.security.web.SecurityFilterChain;
11 |
12 | import fi.haagahelia.course.web.UserDetailServiceImpl;
13 |
14 | @Configuration
15 | //@EnableGlobalMethodSecurity(prePostEnabled = true) not needed with SB3
16 | @EnableWebSecurity
17 | public class WebSecurityConfig {
18 | @Autowired
19 | private UserDetailServiceImpl userDetailsService;
20 |
21 | @Bean
22 | public SecurityFilterChain configure(HttpSecurity http) throws Exception {
23 |
24 | http.authorizeHttpRequests().requestMatchers("/css/**").permitAll()
25 | .and()
26 | .authorizeHttpRequests().anyRequest().authenticated()
27 | // for h2 console
28 | .and()
29 | .headers().frameOptions().disable()
30 | .and()
31 | .formLogin().defaultSuccessUrl("/studentlist", true)
32 | .and()
33 | .logout().permitAll();
34 |
35 | http.cors().and().csrf().disable();
36 |
37 | return http.build();
38 | }
39 |
40 | @Autowired
41 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
42 | auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/StudentJpaTest/src/main/java/fi/haagahelia/course/domain/AppUser.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import jakarta.persistence.Column;
4 | import jakarta.persistence.Entity;
5 | import jakarta.persistence.GeneratedValue;
6 | import jakarta.persistence.GenerationType;
7 | import jakarta.persistence.Id;
8 |
9 | @Entity
10 | public class AppUser {
11 |
12 | @Id
13 | @GeneratedValue(strategy = GenerationType.IDENTITY)
14 | @Column(name = "id", nullable = false, updatable = false)
15 | private Long id;
16 |
17 | // Username with unique constraint
18 | @Column(name = "username", nullable = false, unique = true)
19 | private String username;
20 |
21 | @Column(name = "password", nullable = false)
22 | private String passwordHash;
23 |
24 | @Column(name = "role", nullable = false)
25 | private String role;
26 |
27 | public AppUser() {
28 | }
29 |
30 | public AppUser(String username, String passwordHash, String role) {
31 | super();
32 | this.username = username;
33 | this.passwordHash = passwordHash;
34 | this.role = role;
35 | }
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 getPasswordHash() {
54 | return passwordHash;
55 | }
56 |
57 | public void setPasswordHash(String passwordHash) {
58 | this.passwordHash = passwordHash;
59 | }
60 |
61 | public String getRole() {
62 | return role;
63 | }
64 |
65 | public void setRole(String role) {
66 | this.role = role;
67 | }
68 |
69 | }
--------------------------------------------------------------------------------
/StudentJpaTest/src/main/java/fi/haagahelia/course/domain/AppUserRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.repository.CrudRepository;
6 |
7 | public interface AppUserRepository extends CrudRepository {
8 | AppUser findByUsername(String username);
9 | }
--------------------------------------------------------------------------------
/StudentJpaTest/src/main/java/fi/haagahelia/course/domain/Department.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import jakarta.persistence.CascadeType;
6 | import jakarta.persistence.Entity;
7 | import jakarta.persistence.GeneratedValue;
8 | import jakarta.persistence.GenerationType;
9 | import jakarta.persistence.Id;
10 | import jakarta.persistence.OneToMany;
11 |
12 | @Entity
13 | public class Department {
14 | @Id
15 | @GeneratedValue(strategy=GenerationType.AUTO)
16 | private Long departmentid;
17 | private String name;
18 |
19 | @OneToMany(cascade = CascadeType.ALL, mappedBy = "department")
20 | private List students;
21 |
22 | public Department() {}
23 |
24 | public Department(String name) {
25 | super();
26 | this.name = name;
27 | }
28 |
29 | public Long getDepartmentid() {
30 | return departmentid;
31 | }
32 |
33 | public void setDepartmentid(Long departmentid) {
34 | this.departmentid = departmentid;
35 | }
36 |
37 | public String getName() {
38 | return name;
39 | }
40 |
41 | public void setName(String name) {
42 | this.name = name;
43 | }
44 |
45 | public List getStudents() {
46 | return students;
47 | }
48 |
49 | public void setStudents(List students) {
50 | this.students = students;
51 | }
52 |
53 | @Override
54 | public String toString() {
55 | return "Department [departmentid=" + departmentid + ", name=" + name + "]";
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/StudentJpaTest/src/main/java/fi/haagahelia/course/domain/DepartmentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 | import org.springframework.data.repository.CrudRepository;
5 |
6 | public interface DepartmentRepository extends CrudRepository {
7 |
8 | List findByName(String name);
9 |
10 | }
--------------------------------------------------------------------------------
/StudentJpaTest/src/main/java/fi/haagahelia/course/domain/Student.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import com.fasterxml.jackson.annotation.JsonIgnore;
4 |
5 | import jakarta.persistence.Entity;
6 | import jakarta.persistence.GeneratedValue;
7 | import jakarta.persistence.GenerationType;
8 | import jakarta.persistence.Id;
9 | import jakarta.persistence.JoinColumn;
10 | import jakarta.persistence.ManyToOne;
11 |
12 | @Entity
13 | public class Student {
14 | @Id
15 | @GeneratedValue(strategy=GenerationType.AUTO)
16 | private Long id;
17 | private String firstName;
18 | private String lastName;
19 | private String email;
20 |
21 | @ManyToOne
22 | @JsonIgnore
23 | @JoinColumn(name = "departmentid")
24 | private Department department;
25 |
26 | public Student() {}
27 |
28 | public Student(String firstName, String lastName, String email, Department department) {
29 | super();
30 | this.firstName = firstName;
31 | this.lastName = lastName;
32 | this.email = email;
33 | this.department = department;
34 | }
35 |
36 | public Long getId() {
37 | return id;
38 | }
39 |
40 | public void setId(Long id) {
41 | this.id = id;
42 | }
43 |
44 | public String getFirstName() {
45 | return firstName;
46 | }
47 |
48 | public void setFirstName(String firstName) {
49 | this.firstName = firstName;
50 | }
51 |
52 | public String getLastName() {
53 | return lastName;
54 | }
55 |
56 | public void setLastName(String lastName) {
57 | this.lastName = lastName;
58 | }
59 |
60 | public String getEmail() {
61 | return email;
62 | }
63 |
64 | public void setEmail(String email) {
65 | this.email = email;
66 | }
67 |
68 | public Department getDepartment() {
69 | return department;
70 | }
71 |
72 | public void setDepartment(Department department) {
73 | this.department = department;
74 | }
75 |
76 | @Override
77 | public String toString() {
78 | if (this.department != null)
79 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + " department =" + this.getDepartment() + "]";
80 | else
81 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/StudentJpaTest/src/main/java/fi/haagahelia/course/domain/StudentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.repository.CrudRepository;
6 |
7 | public interface StudentRepository extends CrudRepository {
8 |
9 | List findByLastName(String lastName);
10 |
11 | }
--------------------------------------------------------------------------------
/StudentJpaTest/src/main/java/fi/haagahelia/course/web/UserDetailServiceImpl.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.security.core.authority.AuthorityUtils;
5 | import org.springframework.security.core.userdetails.UserDetails;
6 | import org.springframework.security.core.userdetails.UserDetailsService;
7 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
8 | import org.springframework.stereotype.Service;
9 |
10 | import fi.haagahelia.course.domain.AppUser;
11 | import fi.haagahelia.course.domain.AppUserRepository;
12 |
13 | /**
14 | * This class is used by spring security to authenticate and authorize user
15 | **/
16 | @Service
17 | public class UserDetailServiceImpl implements UserDetailsService {
18 | private final AppUserRepository repository;
19 |
20 | @Autowired
21 | public UserDetailServiceImpl(AppUserRepository userRepository) {
22 | this.repository = userRepository;
23 | }
24 |
25 | @Override
26 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
27 | {
28 | AppUser curruser = repository.findByUsername(username);
29 | UserDetails user = new org.springframework.security.core.userdetails.User(username, curruser.getPasswordHash(),
30 | AuthorityUtils.createAuthorityList(curruser.getRole()));
31 | return user;
32 | }
33 | }
--------------------------------------------------------------------------------
/StudentJpaTest/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.jpa.show-sql=true
2 | spring.datasource.url=jdbc:h2:mem:testdb
3 |
--------------------------------------------------------------------------------
/StudentJpaTest/src/main/resources/templates/addstudent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 |
9 | Add student
10 |
33 |
34 |
--------------------------------------------------------------------------------
/StudentJpaTest/src/main/resources/templates/login.html:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 | Spring Security Example
6 |
7 |
8 |
9 | Invalid username and password.
10 |
11 |
12 | You have been logged out.
13 |
14 |
19 |
20 |
--------------------------------------------------------------------------------
/StudentJpaTest/src/main/resources/templates/studentlist.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 |
9 |
10 |
Students
11 |
12 |
16 |
17 |
20 |
21 |
22 |
23 | Name |
24 | Email |
25 | Department |
26 | |
27 |
28 |
29 | |
30 | |
31 | |
32 | Delete |
33 |
34 |
35 | Add Student
36 |
37 |
--------------------------------------------------------------------------------
/StudentJpaTest/src/test/java/fi/haagahelia/course/StudentListApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 |
4 | import org.junit.jupiter.api.Test;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 |
7 |
8 | //@ExtendWith(SpringExtension.class)
9 | @SpringBootTest
10 | public class StudentListApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/StudentJpaTest/src/test/java/fi/haagahelia/course/StudentRepositoryTest.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 |
5 | import java.util.List;
6 |
7 |
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
10 | import org.junit.jupiter.api.extension.ExtendWith;
11 | import org.springframework.test.context.junit.jupiter.SpringExtension;
12 | import org.junit.jupiter.api.Test;
13 |
14 | import fi.haagahelia.course.domain.Department;
15 | import fi.haagahelia.course.domain.Student;
16 | import fi.haagahelia.course.domain.StudentRepository;
17 |
18 | //@ExtendWith(SpringExtension.class)
19 | //@DataJpaTest
20 |
21 | @ExtendWith(SpringExtension.class)
22 | @SpringBootTest(classes = StudentListApplication.class)
23 | @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
24 | public class StudentRepositoryTest {
25 |
26 | @Autowired
27 | private StudentRepository repository;
28 |
29 | @Test
30 | public void findByLastnameShouldReturnStudent() {
31 | List students = repository.findByLastName("Johnson");
32 |
33 | assertThat(students).hasSize(1);
34 | assertThat(students.get(0).getFirstName()).isEqualTo("John");
35 | }
36 |
37 | @Test
38 | public void createNewStudent() {
39 | Student student = new Student("Mickey", "Mouse", "mm@mouse.com", new Department("BITE"));
40 | repository.save(student);
41 | assertThat(student.getId()).isNotNull();
42 | }
43 | @Test
44 | public void deleteNewStudent() {
45 | List students = repository.findByLastName("Johnson");
46 | Student student = students.get(0);
47 | repository.delete(student);
48 | List newStudents = repository.findByLastName("Johnson");
49 | assertThat(newStudents).hasSize(0);
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/StudentList/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/StudentList/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/StudentList/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/StudentList/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/StudentList/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | fi.haagahelia.course
7 | StudentList
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | StudentList
12 | Demo project for Spring Boot
13 |
14 |
15 |
16 |
17 | org.springframework.boot
18 | spring-boot-starter-parent
19 | 3.0.2
20 |
21 |
22 |
23 |
24 | UTF-8
25 | UTF-8
26 | 17
27 |
28 |
29 |
30 |
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-starter-data-jpa
35 |
36 |
37 | org.springframework.boot
38 | spring-boot-devtools
39 |
40 |
41 | org.springframework.boot
42 | spring-boot-starter-thymeleaf
43 |
44 |
45 | org.springframework.boot
46 | spring-boot-starter-web
47 |
48 |
49 |
50 | com.h2database
51 | h2
52 | runtime
53 |
54 |
55 | org.springframework.boot
56 | spring-boot-starter-test
57 | test
58 |
59 |
60 |
61 |
62 |
63 |
64 | org.springframework.boot
65 | spring-boot-maven-plugin
66 |
67 |
68 |
69 |
70 |
71 |
72 |
--------------------------------------------------------------------------------
/StudentList/src/main/java/fi/haagahelia/course/StudentListApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | import org.springframework.boot.CommandLineRunner;
7 | import org.springframework.boot.SpringApplication;
8 | import org.springframework.boot.autoconfigure.SpringBootApplication;
9 | import org.springframework.context.annotation.Bean;
10 |
11 | import fi.haagahelia.course.domain.Student;
12 | import fi.haagahelia.course.domain.StudentRepository;
13 |
14 | @SpringBootApplication
15 | public class StudentListApplication {
16 | private static final Logger log = LoggerFactory.getLogger(StudentListApplication.class);
17 |
18 | public static void main(String[] args) {
19 | SpringApplication.run(StudentListApplication.class, args);
20 | }
21 |
22 | @Bean
23 | public CommandLineRunner studentDemo(StudentRepository repository) {
24 | return (args) -> {
25 | log.info("save a couple of students");
26 | repository.save(new Student("John", "Johnson", "john@john.com"));
27 | repository.save(new Student("Katy", "Kateson", "kate@kate.com"));
28 |
29 | log.info("fetch all students");
30 | for (Student student : repository.findAll()) {
31 | log.info(student.toString());
32 | }
33 |
34 | };
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/StudentList/src/main/java/fi/haagahelia/course/domain/Student.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import javax.persistence.Entity;
4 | import javax.persistence.GeneratedValue;
5 | import javax.persistence.GenerationType;
6 | import javax.persistence.Id;
7 |
8 | @Entity
9 | public class Student {
10 | @Id
11 | @GeneratedValue(strategy=GenerationType.AUTO)
12 | private Long id;
13 | private String firstName;
14 | private String lastName;
15 | private String email;
16 |
17 | protected Student() {}
18 |
19 | public Student(String firstName, String lastName, String email) {
20 | super();
21 | this.firstName = firstName;
22 | this.lastName = lastName;
23 | this.email = email;
24 | }
25 |
26 | public Long getId() {
27 | return id;
28 | }
29 |
30 | public void setId(Long id) {
31 | this.id = id;
32 | }
33 |
34 | public String getFirstName() {
35 | return firstName;
36 | }
37 |
38 | public void setFirstName(String firstName) {
39 | this.firstName = firstName;
40 | }
41 |
42 | public String getLastName() {
43 | return lastName;
44 | }
45 |
46 | public void setLastName(String lastName) {
47 | this.lastName = lastName;
48 | }
49 |
50 | public String getEmail() {
51 | return email;
52 | }
53 |
54 | public void setEmail(String email) {
55 | this.email = email;
56 | }
57 |
58 | @Override
59 | public String toString() {
60 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/StudentList/src/main/java/fi/haagahelia/course/domain/StudentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.repository.CrudRepository;
6 |
7 | public interface StudentRepository extends CrudRepository {
8 |
9 | List findByLastName(String lastName);
10 |
11 | }
--------------------------------------------------------------------------------
/StudentList/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.jpa.show-sql=true
2 | spring.datasource.url=jdbc:h2:mem:testdb
3 |
--------------------------------------------------------------------------------
/StudentList/src/test/java/fi/haagahelia/course/BookListApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
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 BookListApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/StudentListCrud/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/StudentListCrud/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/StudentListCrud/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/StudentListCrud/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
3 |
--------------------------------------------------------------------------------
/StudentListCrud/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 | org.springframework.boot
6 | spring-boot-starter-parent
7 | 3.0.2
8 |
9 |
10 | fi.haagahelia.course
11 | StudentListCrud
12 | 0.0.1-SNAPSHOT
13 | StudentList
14 | Demo project for Spring Boot
15 |
16 | 17
17 |
18 |
19 |
20 | org.springframework.boot
21 | spring-boot-starter-data-jpa
22 |
23 |
24 | org.springframework.boot
25 | spring-boot-starter-thymeleaf
26 |
27 |
28 | org.springframework.boot
29 | spring-boot-starter-web
30 |
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-devtools
35 | runtime
36 | true
37 |
38 |
39 | com.h2database
40 | h2
41 | runtime
42 |
43 |
44 | org.springframework.boot
45 | spring-boot-starter-test
46 | test
47 |
48 |
49 |
50 |
51 |
52 |
53 | org.springframework.boot
54 | spring-boot-maven-plugin
55 |
56 |
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/StudentListCrud/src/main/java/fi/haagahelia/course/StudentListApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 | import org.springframework.boot.CommandLineRunner;
6 | import org.springframework.boot.SpringApplication;
7 | import org.springframework.boot.autoconfigure.SpringBootApplication;
8 | import org.springframework.context.annotation.Bean;
9 |
10 | import fi.haagahelia.course.domain.Student;
11 | import fi.haagahelia.course.domain.StudentRepository;
12 |
13 | @SpringBootApplication
14 | public class StudentListApplication {
15 |
16 | private static final Logger log = LoggerFactory.getLogger(StudentListApplication.class);
17 |
18 | public static void main(String[] args) {
19 | SpringApplication.run(StudentListApplication.class, args);
20 | }
21 |
22 | @Bean
23 | public CommandLineRunner studentDemo(StudentRepository repository) {
24 | return (args) -> {
25 | log.info("save a couple of students");
26 | repository.save(new Student("Aku", "Johnson", "john@john.com"));
27 | repository.save(new Student("Ankka", "Kateson", "kate@kate.com"));
28 |
29 | repository.save(new Student("Musta", "Naamio", "mm@bengali.org"));
30 |
31 | log.info("fetch all students");
32 | for (Student student : repository.findAll()) {
33 | log.info(student.toString());
34 | }
35 | log.info("haetaan kaikki Naamiot");
36 | for (Student student : repository.findByLastName("Naamio")) {
37 | log.info(student.toString());
38 | }
39 |
40 | };
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/StudentListCrud/src/main/java/fi/haagahelia/course/domain/Student.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import jakarta.persistence.Entity;
4 | import jakarta.persistence.GeneratedValue;
5 | import jakarta.persistence.GenerationType;
6 | import jakarta.persistence.Id;
7 |
8 | @Entity
9 | public class Student {
10 | @Id
11 | @GeneratedValue(strategy=GenerationType.AUTO)
12 | private Long id;
13 | private String Name;
14 | private String firstName;
15 | private String lastName;
16 | private String email;
17 |
18 | public Student() {}
19 |
20 | public Student(String firstName, String lastName, String email) {
21 | super();
22 | this.firstName = firstName;
23 | this.lastName = lastName;
24 | this.email = email;
25 | }
26 |
27 | public Long getId() {
28 | return id;
29 | }
30 |
31 | public void setId(Long id) {
32 | this.id = id;
33 | }
34 |
35 | public String getFirstName() {
36 | return firstName;
37 | }
38 |
39 | public void setFirstName(String firstName) {
40 | this.firstName = firstName;
41 | }
42 |
43 | public String getLastName() {
44 | return lastName;
45 | }
46 |
47 | public void setLastName(String lastName) {
48 | this.lastName = lastName;
49 | }
50 |
51 | public String getEmail() {
52 | return email;
53 | }
54 |
55 | public void setEmail(String email) {
56 | this.email = email;
57 | }
58 |
59 | @Override
60 | public String toString() {
61 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/StudentListCrud/src/main/java/fi/haagahelia/course/domain/StudentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.repository.CrudRepository;
6 |
7 | public interface StudentRepository extends CrudRepository {
8 |
9 | List findByLastName(String lastName);
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/StudentListCrud/src/main/java/fi/haagahelia/course/web/StudentController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.stereotype.Controller;
5 | import org.springframework.ui.Model;
6 | import org.springframework.web.bind.annotation.PathVariable;
7 | import org.springframework.web.bind.annotation.RequestMapping;
8 | import org.springframework.web.bind.annotation.RequestMethod;
9 |
10 | import fi.haagahelia.course.domain.Student;
11 | import fi.haagahelia.course.domain.StudentRepository;
12 |
13 | @Controller
14 | public class StudentController {
15 | @Autowired
16 | private StudentRepository repository;
17 |
18 | @RequestMapping(value= {"/", "/studentlist"})
19 | public String studentList(Model model) {
20 | model.addAttribute("students", repository.findAll());
21 | return "studentlist";
22 | }
23 |
24 | @RequestMapping(value = "/add")
25 | public String addStudent(Model model){
26 | model.addAttribute("student", new Student());
27 | return "addstudent";
28 | }
29 |
30 | @RequestMapping(value = "/save", method = RequestMethod.POST)
31 | public String save(Student student){
32 | repository.save(student);
33 | return "redirect:studentlist";
34 | }
35 |
36 | @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
37 | public String deleteStudent(@PathVariable("id") Long studentId, Model model) {
38 | repository.deleteById(studentId);
39 | return "redirect:../studentlist";
40 | }
41 | }
--------------------------------------------------------------------------------
/StudentListCrud/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.jpa.show-sql=true
2 | spring.datasource.url=jdbc:h2:mem:testdb
3 | spring.h2.console.path=/h2-console
4 |
5 |
--------------------------------------------------------------------------------
/StudentListCrud/src/main/resources/templates/addstudent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 | Add student
9 |
23 |
24 |
--------------------------------------------------------------------------------
/StudentListCrud/src/main/resources/templates/studentlist.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 | Students
9 |
10 |
11 | Name |
12 | Email |
13 |
14 |
15 | |
16 | |
17 | Delete |
18 |
19 |
20 | Add Student
21 |
22 |
--------------------------------------------------------------------------------
/StudentListCrud/src/test/java/fi/haagahelia/course/BookListApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class BookListApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/StudentListCrud/src/test/java/fi/haagahelia/course/StudentListApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class StudentListApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/StudentListGraphQL/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/StudentListGraphQL/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/StudentListGraphQL/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/StudentListGraphQL/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/StudentListGraphQL/README.txt:
--------------------------------------------------------------------------------
1 | To test this application go to:
2 |
3 | http://localhost:8080/graphiql
4 |
5 | Sample GraphQL query:
6 |
7 | {
8 | students {
9 | email
10 | firstName
11 | lastName
12 | department {name}
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/StudentListGraphQL/src/main/java/fi/haagahelia/course/StudentListApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import java.util.stream.Stream;
4 |
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 |
8 | import org.springframework.boot.CommandLineRunner;
9 | import org.springframework.boot.SpringApplication;
10 | import org.springframework.boot.autoconfigure.SpringBootApplication;
11 | import org.springframework.context.annotation.Bean;
12 |
13 | import fi.haagahelia.course.domain.Department;
14 | import fi.haagahelia.course.domain.DepartmentRepository;
15 | import fi.haagahelia.course.domain.Student;
16 | import fi.haagahelia.course.domain.StudentRepository;
17 |
18 | @SpringBootApplication
19 | public class StudentListApplication {
20 | private static final Logger log = LoggerFactory.getLogger(StudentListApplication.class);
21 |
22 | public static void main(String[] args) {
23 | SpringApplication.run(StudentListApplication.class, args);
24 | }
25 |
26 | @Bean
27 | public CommandLineRunner studentDemo(StudentRepository srepository, DepartmentRepository drepository) {
28 | return (args) -> {
29 | log.info("save a couple of students");
30 |
31 | Stream.of("IT", "Business", "Law").forEach(name -> {
32 | drepository.save(new Department(name));
33 | });
34 |
35 | srepository.save(new Student("John", "Johnson", "john@john.com", drepository.findByName("IT").get(0)));
36 | srepository.save(new Student("Katy", "Kateson", "kate@kate.com", drepository.findByName("Business").get(0)));
37 | srepository.save(new Student("Matt", "More", "matt@matt.com", drepository.findByName("Business").get(0)));
38 | srepository.save(new Student("Jack", "Russell", "jack@jack.com", drepository.findByName("IT").get(0)));
39 | srepository.save(new Student("Mary", "Mitchell", "mary@mary.com", drepository.findByName("Law").get(0)));
40 |
41 | log.info("fetch all students");
42 | for (Student student : srepository.findAll()) {
43 | log.info(student.toString());
44 | }
45 |
46 | };
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/StudentListGraphQL/src/main/java/fi/haagahelia/course/domain/Department.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import javax.persistence.CascadeType;
6 | import javax.persistence.Entity;
7 | import javax.persistence.FetchType;
8 | import javax.persistence.GeneratedValue;
9 | import javax.persistence.GenerationType;
10 | import javax.persistence.Id;
11 | import javax.persistence.OneToMany;
12 |
13 | @Entity
14 | public class Department {
15 | @Id
16 | @GeneratedValue(strategy=GenerationType.AUTO)
17 | private Long departmentid;
18 | private String name;
19 |
20 | @OneToMany(cascade = CascadeType.ALL, mappedBy = "department")
21 | private List students;
22 |
23 | public Department() {}
24 |
25 | public Department(String name) {
26 | super();
27 | this.name = name;
28 | }
29 |
30 | public Long getDepartmentid() {
31 | return departmentid;
32 | }
33 |
34 | public void setDepartmentid(Long departmentid) {
35 | this.departmentid = departmentid;
36 | }
37 |
38 | public String getName() {
39 | return name;
40 | }
41 |
42 | public void setName(String name) {
43 | this.name = name;
44 | }
45 |
46 | public List getStudents() {
47 | return students;
48 | }
49 |
50 | public void setStudents(List students) {
51 | this.students = students;
52 | }
53 |
54 | @Override
55 | public String toString() {
56 | return "Department [departmentid=" + departmentid + ", name=" + name + "]";
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/StudentListGraphQL/src/main/java/fi/haagahelia/course/domain/DepartmentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 | import org.springframework.data.repository.CrudRepository;
5 |
6 | public interface DepartmentRepository extends CrudRepository {
7 |
8 | List findByName(String name);
9 |
10 | }
--------------------------------------------------------------------------------
/StudentListGraphQL/src/main/java/fi/haagahelia/course/domain/Student.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import javax.persistence.Entity;
4 | import javax.persistence.FetchType;
5 | import javax.persistence.GeneratedValue;
6 | import javax.persistence.GenerationType;
7 | import javax.persistence.Id;
8 | import javax.persistence.JoinColumn;
9 | import javax.persistence.ManyToOne;
10 |
11 | import com.fasterxml.jackson.annotation.JsonIgnore;
12 |
13 | @Entity
14 | public class Student {
15 | @Id
16 | @GeneratedValue(strategy=GenerationType.AUTO)
17 | private Long id;
18 | private String firstName;
19 | private String lastName;
20 | private String email;
21 |
22 | @ManyToOne
23 | @JsonIgnore
24 | @JoinColumn(name = "departmentid")
25 | private Department department;
26 |
27 | public Student() {}
28 |
29 | public Student(String firstName, String lastName, String email) {
30 | super();
31 | this.firstName = firstName;
32 | this.lastName = lastName;
33 | this.email = email;
34 | }
35 |
36 | public Student(String firstName, String lastName, String email, Department department) {
37 | super();
38 | this.firstName = firstName;
39 | this.lastName = lastName;
40 | this.email = email;
41 | this.department = department;
42 | }
43 |
44 | public Long getId() {
45 | return id;
46 | }
47 |
48 | public void setId(Long id) {
49 | this.id = id;
50 | }
51 |
52 | public String getFirstName() {
53 | return firstName;
54 | }
55 |
56 | public void setFirstName(String firstName) {
57 | this.firstName = firstName;
58 | }
59 |
60 | public String getLastName() {
61 | return lastName;
62 | }
63 |
64 | public void setLastName(String lastName) {
65 | this.lastName = lastName;
66 | }
67 |
68 | public String getEmail() {
69 | return email;
70 | }
71 |
72 | public void setEmail(String email) {
73 | this.email = email;
74 | }
75 |
76 | public Department getDepartment() {
77 | return department;
78 | }
79 |
80 | public void setDepartment(Department department) {
81 | this.department = department;
82 | }
83 |
84 | @Override
85 | public String toString() {
86 | if (this.department != null)
87 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + " department =" + this.getDepartment() + "]";
88 | else
89 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/StudentListGraphQL/src/main/java/fi/haagahelia/course/domain/StudentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.repository.CrudRepository;
6 |
7 | public interface StudentRepository extends CrudRepository {
8 |
9 | List findByLastName(String lastName);
10 |
11 | }
--------------------------------------------------------------------------------
/StudentListGraphQL/src/main/java/fi/haagahelia/course/web/Mutation.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.stereotype.Component;
5 | import com.coxautodev.graphql.tools.GraphQLMutationResolver;
6 |
7 | import fi.haagahelia.course.domain.Department;
8 | import fi.haagahelia.course.domain.DepartmentRepository;
9 | import fi.haagahelia.course.domain.Student;
10 | import fi.haagahelia.course.domain.StudentRepository;
11 |
12 | @Component
13 | public class Mutation implements GraphQLMutationResolver {
14 |
15 | @Autowired
16 | private DepartmentRepository drepository;
17 |
18 | @Autowired
19 | private StudentRepository srepository;
20 |
21 | public Department createDepartment(String name) {
22 | return drepository.save(new Department(name));
23 | }
24 |
25 | public Student createStudent(String firstname, String lastname, String email) {
26 | return srepository.save(new Student(firstname, lastname, email));
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/StudentListGraphQL/src/main/java/fi/haagahelia/course/web/Query.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import com.coxautodev.graphql.tools.GraphQLQueryResolver;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.stereotype.Component;
9 | import fi.haagahelia.course.domain.*;
10 |
11 | @Component
12 | public class Query implements GraphQLQueryResolver {
13 | @Autowired
14 | private StudentRepository repository;
15 |
16 | public List students() {
17 | List students = new ArrayList<>();
18 | students = (List) repository.findAll();
19 | return students;
20 | }
21 | }
--------------------------------------------------------------------------------
/StudentListGraphQL/src/main/java/fi/haagahelia/course/web/StudentController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Controller;
8 | import org.springframework.ui.Model;
9 | import org.springframework.web.bind.annotation.PathVariable;
10 | import org.springframework.web.bind.annotation.RequestMapping;
11 | import org.springframework.web.bind.annotation.RequestMethod;
12 | import org.springframework.web.bind.annotation.ResponseBody;
13 |
14 | import fi.haagahelia.course.domain.DepartmentRepository;
15 | import fi.haagahelia.course.domain.Student;
16 | import fi.haagahelia.course.domain.StudentRepository;
17 |
18 | @Controller
19 | public class StudentController {
20 | @Autowired
21 | private StudentRepository repository;
22 |
23 | @Autowired
24 | private DepartmentRepository drepository;
25 |
26 | // Show all students
27 | @RequestMapping(value="/studentlist")
28 | public String studentList(Model model) {
29 | model.addAttribute("students", repository.findAll());
30 | return "studentlist";
31 | }
32 |
33 | // RESTful service to get all students
34 | @RequestMapping(value="/students", method = RequestMethod.GET)
35 | public @ResponseBody List studentListRest() {
36 | return (List) repository.findAll();
37 | }
38 |
39 | // RESTful service to get student by id
40 | @RequestMapping(value="/student/{id}", method = RequestMethod.GET)
41 | public @ResponseBody Optional findStudentRest(@PathVariable("id") Long studentId) {
42 | return repository.findById(studentId);
43 | }
44 |
45 | // Add new student
46 | @RequestMapping(value = "/add")
47 | public String addStudent(Model model){
48 | model.addAttribute("student", new Student());
49 | model.addAttribute("departments", drepository.findAll());
50 | return "addstudent";
51 | }
52 |
53 | // Save new student
54 | @RequestMapping(value = "/save", method = RequestMethod.POST)
55 | public String save(Student student){
56 | repository.save(student);
57 | return "redirect:studentlist";
58 | }
59 |
60 | // Delete student
61 | @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
62 | public String deleteStudent(@PathVariable("id") Long studentId, Model model) {
63 | repository.deleteById(studentId);
64 | return "redirect:../studentlist";
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/StudentListGraphQL/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.jpa.show-sql=true
2 |
3 | graphql.playground.endpoint=/graphql
4 | graphql.playground.mapping=/playground
5 | graphql.playground.ebabled=true
--------------------------------------------------------------------------------
/StudentListGraphQL/src/main/resources/studentlist.graphqls:
--------------------------------------------------------------------------------
1 | type Query {
2 | students: [Student]
3 | }
4 |
5 | type Mutation {
6 | createDepartment(name: String!): Department
7 | createStudent(firstName: String!, lastName: String!, email: String!): Student
8 | }
9 |
10 | type Department {
11 | departmentid: Int!
12 | name: String
13 | }
14 |
15 | type Student {
16 | id: Int!
17 | firstName: String
18 | lastName: String
19 | email: String
20 | department: Department
21 | }
22 |
23 |
24 |
--------------------------------------------------------------------------------
/StudentListGraphQL/src/main/resources/templates/addstudent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 | Add student
9 |
30 |
31 |
--------------------------------------------------------------------------------
/StudentListGraphQL/src/main/resources/templates/studentlist.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 | Students
9 |
10 |
11 | Name |
12 | Email |
13 | Department |
14 |
15 |
16 | |
17 | |
18 | |
19 | Delete |
20 |
21 |
22 | Add Student
23 |
24 |
--------------------------------------------------------------------------------
/StudentListGraphQL/src/test/java/fi/haagahelia/course/BookListApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
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 BookListApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/StudentListJDBC/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/StudentListJDBC/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/StudentListJDBC/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/StudentListJDBC/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/StudentListJDBC/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | fi.haagahelia.demo
7 | SpringBootJDBC
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | SpringBootJDBC
12 | JDBC demo project for Spring Boot
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 3.0.1
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 17
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-jdbc
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-starter-thymeleaf
35 |
36 |
37 | org.springframework.boot
38 | spring-boot-starter-web
39 |
40 |
41 | mysql
42 | mysql-connector-java
43 | runtime
44 |
45 |
46 | org.springframework.boot
47 | spring-boot-starter-test
48 | test
49 |
50 |
51 |
52 |
53 |
54 |
55 | org.springframework.boot
56 | spring-boot-maven-plugin
57 |
58 |
59 |
60 |
61 |
62 |
63 |
--------------------------------------------------------------------------------
/StudentListJDBC/src/main/java/fi/haagahelia/demo/DatabasedemoApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.demo;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 | import org.springframework.boot.CommandLineRunner;
6 | import org.springframework.boot.SpringApplication;
7 | import org.springframework.boot.autoconfigure.SpringBootApplication;
8 | import org.springframework.context.annotation.Bean;
9 |
10 | import fi.haagahelia.demo.domain.Student;
11 | import fi.haagahelia.demo.domain.StudentDAOImpl;
12 |
13 | @SpringBootApplication
14 | public class DatabasedemoApplication {
15 | private static final Logger log = LoggerFactory.getLogger(DatabasedemoApplication.class);
16 |
17 | public static void main(String[] args) {
18 | SpringApplication.run(DatabasedemoApplication.class, args);
19 | }
20 |
21 | @Bean
22 | public CommandLineRunner demo(StudentDAOImpl studentDAO) {
23 | return (args) -> {
24 | // Database is created by using resources/schema.sql
25 |
26 | // Insert some demo data
27 | studentDAO.save(new Student("John", "West"));
28 | studentDAO.save(new Student("Mike", "Mars"));
29 | studentDAO.save(new Student("Kate", "Johnson"));
30 |
31 | };
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/StudentListJDBC/src/main/java/fi/haagahelia/demo/domain/Student.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.demo.domain;
2 |
3 | public class Student {
4 | private long id;
5 | private String firstName;
6 | private String lastName;
7 |
8 | public Student () {
9 | this.id = 0;
10 | this.firstName = null;
11 | this.lastName = null;
12 | }
13 |
14 | public Student (long id, String firstName, String lastName) {
15 | this.id = id;
16 | this.firstName = firstName;
17 | this.lastName = lastName;
18 | }
19 |
20 | public Student (String firstName, String lastName) {
21 | this.id = 0;
22 | this.firstName = firstName;
23 | this.lastName = lastName;
24 | }
25 |
26 | public long getId() {
27 | return id;
28 | }
29 |
30 | public void setId(long id) {
31 | this.id = id;
32 | }
33 |
34 | public String getFirstName() {
35 | return firstName;
36 | }
37 |
38 | public void setFirstName(String firstName) {
39 | this.firstName = firstName;
40 | }
41 |
42 | public String getLastName() {
43 | return lastName;
44 | }
45 |
46 | public void setLastName(String lastName) {
47 | this.lastName = lastName;
48 | }
49 |
50 | @Override
51 | public String toString() {
52 | return String.format(
53 | "Person[id=%d, firstName='%s', lastName='%s']",
54 | id, firstName, lastName);
55 | }
56 |
57 | }
--------------------------------------------------------------------------------
/StudentListJDBC/src/main/java/fi/haagahelia/demo/domain/StudentDAO.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.demo.domain;
2 |
3 | import java.util.List;
4 |
5 |
6 | public interface StudentDAO {
7 | public void save(Student student);
8 |
9 | public Student findOne(int id);
10 |
11 | public List findAll();
12 | }
13 |
--------------------------------------------------------------------------------
/StudentListJDBC/src/main/java/fi/haagahelia/demo/domain/StudentDAOImpl.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.demo.domain;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.jdbc.core.JdbcTemplate;
7 | import org.springframework.jdbc.core.RowMapper;
8 | import org.springframework.stereotype.Repository;
9 |
10 | @Repository
11 | public class StudentDAOImpl implements StudentDAO { // Impl = Implementation class
12 |
13 | @Autowired
14 | private JdbcTemplate jdbcTemplate;
15 |
16 | public JdbcTemplate getJdbcTemplate() {
17 | return jdbcTemplate;
18 | }
19 |
20 | public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
21 | this.jdbcTemplate = jdbcTemplate;
22 | }
23 |
24 | public void save(Student student) {
25 | String sql = "insert into student(first_name, last_name) values(?,?)";
26 | Object[] parameters = new Object[] { student.getFirstName(),
27 | student.getLastName() };
28 |
29 | jdbcTemplate.update(sql, parameters);
30 |
31 | }
32 |
33 | public Student findOne(int id) {
34 | String sql = "select student_id, first_name, last_name from student where student_id = ?";
35 | Object[] parameters = new Object[] { id };
36 | RowMapper mapper = new StudentRowMapper();
37 |
38 | Student student = jdbcTemplate.queryForObject(sql, parameters, mapper);
39 | return student;
40 |
41 | }
42 |
43 | public List findAll() {
44 |
45 | String sql = "select student_id, first_name, last_name from student";
46 | RowMapper mapper = new StudentRowMapper();
47 | List students = jdbcTemplate.query(sql, mapper);
48 |
49 | return students;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/StudentListJDBC/src/main/java/fi/haagahelia/demo/domain/StudentRowMapper.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.demo.domain;
2 |
3 | import java.sql.ResultSet;
4 | import java.sql.SQLException;
5 |
6 | import org.springframework.jdbc.core.RowMapper;
7 |
8 | public class StudentRowMapper implements RowMapper {
9 |
10 | public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
11 | Student student = new Student();
12 | student.setFirstName(rs.getString("first_name"));
13 | student.setLastName(rs.getString("last_name"));
14 | student.setId(rs.getLong("student_id"));
15 |
16 | return student;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/StudentListJDBC/src/main/java/fi/haagahelia/demo/web/StudentController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.demo.web;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Controller;
7 | import org.springframework.ui.Model;
8 | import org.springframework.web.bind.annotation.RequestMapping;
9 | import org.springframework.web.bind.annotation.RequestMethod;
10 |
11 | import fi.haagahelia.demo.domain.Student;
12 | import fi.haagahelia.demo.domain.StudentDAO;
13 |
14 | @Controller
15 | public class StudentController {
16 | @Autowired
17 | private StudentDAO studentDAO;
18 |
19 | @RequestMapping(value="/studentlist")
20 | public String studentList(Model model) {
21 | // Fetch all students
22 | List students = studentDAO.findAll();
23 | // Add studentlist to model and return view name
24 | model.addAttribute("students", students);
25 | return "studentlist";
26 | }
27 |
28 | // Add new student
29 | @RequestMapping(value = "/add")
30 | public String addStudent(Model model){
31 | model.addAttribute("student", new Student());
32 | return "addstudent";
33 | }
34 |
35 | // Save new student
36 | @RequestMapping(value = "/save", method = RequestMethod.POST)
37 | public String save(Student student){
38 | studentDAO.save(student);
39 | return "redirect:studentlist";
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/StudentListJDBC/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
2 | spring.datasource.url=jdbc:mysql://localhost:3306/YOUR_DB_NAME?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
3 | spring.datasource.username=YOUR_DB_USERNAME
4 | spring.datasource.password=YOUR_DB_PASSWORD
5 | spring.datasource.initialization-mode=always
6 |
7 |
8 |
--------------------------------------------------------------------------------
/StudentListJDBC/src/main/resources/schema.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE IF NOT EXISTS student (
2 | student_id int(5) NOT NULL AUTO_INCREMENT,
3 | first_name varchar(50) DEFAULT NULL,
4 | last_name varchar(50) DEFAULT NULL,
5 | PRIMARY KEY(student_id)
6 | );
--------------------------------------------------------------------------------
/StudentListJDBC/src/main/resources/templates/addstudent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 | Add student
9 |
20 |
21 |
--------------------------------------------------------------------------------
/StudentListJDBC/src/main/resources/templates/studentlist.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 | Students
9 |
10 |
11 | Name |
12 |
13 |
14 | |
15 |
16 |
17 | Add Student
18 |
19 |
--------------------------------------------------------------------------------
/StudentListJDBC/src/test/java/fi/haagahelia/demo/DatabasedemoApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.demo;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class DatabasedemoApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/StudentListOneToMany/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/StudentListOneToMany/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/StudentListOneToMany/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/StudentListOneToMany/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/StudentListOneToMany/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | fi.haagahelia.course
8 | StudentListOneToMany
9 | 0.0.1-SNAPSHOT
10 | jar
11 |
12 | StudentListOneToMany
13 | Demo project for Spring Boot
14 |
15 |
16 | org.springframework.boot
17 | spring-boot-starter-parent
18 | 3.0.2
19 |
20 |
21 |
22 |
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-data-jpa
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-devtools
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-starter-thymeleaf
35 |
36 |
37 | org.springframework.boot
38 | spring-boot-starter-web
39 |
40 |
41 |
42 | com.h2database
43 | h2
44 | runtime
45 |
46 |
47 | org.springframework.boot
48 | spring-boot-starter-test
49 | test
50 |
51 |
52 |
53 |
54 |
55 |
56 | org.springframework.boot
57 | spring-boot-maven-plugin
58 |
59 |
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/StudentListOneToMany/src/main/java/fi/haagahelia/course/StudentListApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | import org.springframework.boot.CommandLineRunner;
7 | import org.springframework.boot.SpringApplication;
8 | import org.springframework.boot.autoconfigure.SpringBootApplication;
9 | import org.springframework.context.annotation.Bean;
10 |
11 | import fi.haagahelia.course.domain.Department;
12 | import fi.haagahelia.course.domain.DepartmentRepository;
13 | import fi.haagahelia.course.domain.Student;
14 | import fi.haagahelia.course.domain.StudentRepository;
15 |
16 | @SpringBootApplication
17 | public class StudentListApplication {
18 | private static final Logger log = LoggerFactory.getLogger(StudentListApplication.class);
19 |
20 | public static void main(String[] args) {
21 | SpringApplication.run(StudentListApplication.class, args);
22 | }
23 |
24 | @Bean
25 | public CommandLineRunner studentDemo(StudentRepository srepository, DepartmentRepository drepository) {
26 | return (args) -> {
27 | log.info("save a couple of students");
28 | drepository.save(new Department("IT"));
29 | drepository.save(new Department("Business"));
30 | drepository.save(new Department("Law"));
31 |
32 | srepository.save(new Student("John", "Johnson", "john@john.com", drepository.findByName("IT").get(0)));
33 | srepository.save(new Student("Katy", "Kateson", "kate@kate.com", drepository.findByName("Business").get(0)));
34 |
35 | log.info("fetch all students");
36 | for (Student student : srepository.findAll()) {
37 | log.info(student.toString());
38 | }
39 |
40 | };
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/StudentListOneToMany/src/main/java/fi/haagahelia/course/domain/Department.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import jakarta.persistence.*;
6 |
7 | @Entity
8 | public class Department {
9 | @Id
10 | @GeneratedValue(strategy=GenerationType.AUTO)
11 | private Long departmentid;
12 | private String name;
13 |
14 | @OneToMany(cascade = CascadeType.ALL, mappedBy = "department")
15 | private List students;
16 |
17 | public Department() {}
18 |
19 | public Department(String name) {
20 | super();
21 | this.name = name;
22 | }
23 |
24 | public Long getDepartmentid() {
25 | return departmentid;
26 | }
27 |
28 | public void setDepartmentid(Long departmentid) {
29 | this.departmentid = departmentid;
30 | }
31 |
32 | public String getName() {
33 | return name;
34 | }
35 |
36 | public void setName(String name) {
37 | this.name = name;
38 | }
39 |
40 | public List getStudents() {
41 | return students;
42 | }
43 |
44 | public void setStudents(List students) {
45 | this.students = students;
46 | }
47 |
48 | @Override
49 | public String toString() {
50 | return "Department [departmentid=" + departmentid + ", name=" + name + "]";
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/StudentListOneToMany/src/main/java/fi/haagahelia/course/domain/DepartmentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 | import org.springframework.data.repository.CrudRepository;
5 |
6 | public interface DepartmentRepository extends CrudRepository {
7 |
8 | List findByName(String name);
9 |
10 | }
--------------------------------------------------------------------------------
/StudentListOneToMany/src/main/java/fi/haagahelia/course/domain/Student.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 |
4 |
5 | import jakarta.persistence.*;
6 |
7 | @Entity
8 | public class Student {
9 | @Id
10 | @GeneratedValue(strategy=GenerationType.AUTO)
11 | private Long id;
12 | private String firstName;
13 | private String lastName;
14 | private String email;
15 |
16 | @ManyToOne
17 | @JoinColumn(name = "departmentid")
18 | private Department department;
19 |
20 | public Student() {}
21 |
22 | public Student(String firstName, String lastName, String email, Department department) {
23 | super();
24 | this.firstName = firstName;
25 | this.lastName = lastName;
26 | this.email = email;
27 | this.department = department;
28 | }
29 |
30 | public Long getId() {
31 | return id;
32 | }
33 |
34 | public void setId(Long id) {
35 | this.id = id;
36 | }
37 |
38 | public String getFirstName() {
39 | return firstName;
40 | }
41 |
42 | public void setFirstName(String firstName) {
43 | this.firstName = firstName;
44 | }
45 |
46 | public String getLastName() {
47 | return lastName;
48 | }
49 |
50 | public void setLastName(String lastName) {
51 | this.lastName = lastName;
52 | }
53 |
54 | public String getEmail() {
55 | return email;
56 | }
57 |
58 | public void setEmail(String email) {
59 | this.email = email;
60 | }
61 |
62 | public Department getDepartment() {
63 | return department;
64 | }
65 |
66 | public void setDepartment(Department department) {
67 | this.department = department;
68 | }
69 |
70 | @Override
71 | public String toString() {
72 | if (this.department != null)
73 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + " department =" + this.getDepartment() + "]";
74 | else
75 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/StudentListOneToMany/src/main/java/fi/haagahelia/course/domain/StudentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.repository.CrudRepository;
6 |
7 | public interface StudentRepository extends CrudRepository {
8 |
9 | List findByLastName(String lastName);
10 |
11 | }
--------------------------------------------------------------------------------
/StudentListOneToMany/src/main/java/fi/haagahelia/course/web/StudentController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.stereotype.Controller;
5 | import org.springframework.ui.Model;
6 | import org.springframework.web.bind.annotation.PathVariable;
7 | import org.springframework.web.bind.annotation.RequestMapping;
8 | import org.springframework.web.bind.annotation.RequestMethod;
9 |
10 | import fi.haagahelia.course.domain.DepartmentRepository;
11 | import fi.haagahelia.course.domain.Student;
12 | import fi.haagahelia.course.domain.StudentRepository;
13 |
14 | @Controller
15 | public class StudentController {
16 | @Autowired
17 | private StudentRepository repository;
18 |
19 | @Autowired
20 | private DepartmentRepository drepository;
21 |
22 | // Show all students
23 | @RequestMapping(value={"/", "/studentlist"})
24 | public String studentList(Model model) {
25 | model.addAttribute("students", repository.findAll());
26 | return "studentlist";
27 | }
28 |
29 | // Add new student
30 | @RequestMapping(value = "/add")
31 | public String addStudent(Model model){
32 | model.addAttribute("student", new Student());
33 | model.addAttribute("departments", drepository.findAll());
34 | return "addstudent";
35 | }
36 |
37 | // Save new student
38 | @RequestMapping(value = "/save", method = RequestMethod.POST)
39 | public String save(Student student){
40 | repository.save(student);
41 | return "redirect:studentlist";
42 | }
43 |
44 | // Delete student
45 | @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
46 | public String deleteStudent(@PathVariable("id") Long studentId, Model model) {
47 | repository.deleteById(studentId);
48 | return "redirect:../studentlist";
49 | }
50 |
51 |
52 | // Edit student
53 | @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
54 | public String editStudent(@PathVariable("id") Long studentId, Model model) {
55 | model.addAttribute("student", repository.findById(studentId));
56 | model.addAttribute("departments", drepository.findAll());
57 | return "editstudent";
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/StudentListOneToMany/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.jpa.show-sql=true
2 | spring.datasource.url=jdbc:h2:mem:testdb
3 | logging.level.org.hibernate.type.descriptor.sql.BasicBinder=trace
4 |
--------------------------------------------------------------------------------
/StudentListOneToMany/src/main/resources/templates/addstudent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 | Add student
9 |
30 |
31 |
--------------------------------------------------------------------------------
/StudentListOneToMany/src/main/resources/templates/editstudent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 | Add student
9 |
31 |
32 |
--------------------------------------------------------------------------------
/StudentListOneToMany/src/main/resources/templates/studentlist.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 | Students
9 |
10 |
11 | Name |
12 | Email |
13 | Department |
14 |
15 |
16 | |
17 | |
18 | |
19 | Edit |
20 | Delete |
21 |
22 |
23 | Add Student
24 |
25 |
--------------------------------------------------------------------------------
/StudentListOneToMany/src/test/java/fi/haagahelia/course/BookListApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class BookListApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/StudentListRest/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/StudentListRest/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/StudentListRest/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/StudentListRest/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/StudentListRest/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | fi.haagahelia.course
7 | StudentListRest
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | StudentListRest
12 | Demo project for Spring Boot
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 3.0.1
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 17
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-data-jpa
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-starter-data-rest
35 |
36 |
37 | org.springframework.boot
38 | spring-boot-devtools
39 |
40 |
41 | org.springframework.boot
42 | spring-boot-starter-thymeleaf
43 |
44 |
45 | org.springframework.boot
46 | spring-boot-starter-web
47 |
48 |
49 | org.springframework.boot
50 | spring-boot-starter-actuator
51 |
52 |
53 | com.h2database
54 | h2
55 | runtime
56 |
57 |
58 | org.springframework.boot
59 | spring-boot-starter-test
60 | test
61 |
62 |
63 |
64 |
65 |
66 |
67 | org.springframework.boot
68 | spring-boot-maven-plugin
69 |
70 |
71 |
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/StudentListRest/src/main/java/fi/haagahelia/course/StudentListApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | import org.springframework.boot.CommandLineRunner;
7 | import org.springframework.boot.SpringApplication;
8 | import org.springframework.boot.autoconfigure.SpringBootApplication;
9 | import org.springframework.context.annotation.Bean;
10 |
11 | import fi.haagahelia.course.domain.Department;
12 | import fi.haagahelia.course.domain.DepartmentRepository;
13 | import fi.haagahelia.course.domain.Student;
14 | import fi.haagahelia.course.domain.StudentRepository;
15 |
16 | @SpringBootApplication
17 | public class StudentListApplication {
18 | private static final Logger log = LoggerFactory.getLogger(StudentListApplication.class);
19 |
20 | public static void main(String[] args) {
21 | SpringApplication.run(StudentListApplication.class, args);
22 | }
23 |
24 | @Bean
25 | public CommandLineRunner studentDemo(StudentRepository srepository, DepartmentRepository drepository) {
26 | return (args) -> {
27 | log.info("save a couple of students");
28 | drepository.save(new Department("IT"));
29 | drepository.save(new Department("Business"));
30 | drepository.save(new Department("Law"));
31 |
32 | srepository.save(new Student("John", "Johnson", "john@john.com", drepository.findByName("IT").get(0)));
33 | srepository.save(new Student("Katy", "Kateson", "kate@kate.com", drepository.findByName("Business").get(0)));
34 |
35 | log.info("fetch all students");
36 | for (Student student : srepository.findAll()) {
37 | log.info(student.toString());
38 | }
39 |
40 | };
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/StudentListRest/src/main/java/fi/haagahelia/course/domain/Department.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import jakarta.persistence.CascadeType;
6 | import jakarta.persistence.Entity;
7 | import jakarta.persistence.FetchType;
8 | import jakarta.persistence.GeneratedValue;
9 | import jakarta.persistence.GenerationType;
10 | import jakarta.persistence.Id;
11 | import jakarta.persistence.OneToMany;
12 |
13 |
14 | import com.fasterxml.jackson.annotation.JsonIgnore;
15 |
16 |
17 | @Entity
18 | public class Department {
19 | @Id
20 | @GeneratedValue(strategy=GenerationType.AUTO)
21 | private Long departmentid;
22 | private String name;
23 |
24 | @JsonIgnore
25 | @OneToMany(cascade = CascadeType.ALL, mappedBy = "department")
26 | private List students;
27 |
28 | public Department() {}
29 |
30 | public Department(String name) {
31 | super();
32 | this.name = name;
33 | }
34 |
35 | public Long getDepartmentid() {
36 | return departmentid;
37 | }
38 |
39 | public void setDepartmentid(Long departmentid) {
40 | this.departmentid = departmentid;
41 | }
42 |
43 | public String getName() {
44 | return name;
45 | }
46 |
47 | public void setName(String name) {
48 | this.name = name;
49 | }
50 |
51 | public List getStudents() {
52 | return students;
53 | }
54 |
55 | public void setStudents(List students) {
56 | this.students = students;
57 | }
58 |
59 | @Override
60 | public String toString() {
61 | return "Department [departmentid=" + departmentid + ", name=" + name + "]";
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/StudentListRest/src/main/java/fi/haagahelia/course/domain/DepartmentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 | import org.springframework.data.repository.CrudRepository;
5 |
6 | public interface DepartmentRepository extends CrudRepository {
7 |
8 | List findByName(String name);
9 |
10 | }
--------------------------------------------------------------------------------
/StudentListRest/src/main/java/fi/haagahelia/course/domain/Student.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import jakarta.persistence.Entity;
4 | import jakarta.persistence.FetchType;
5 | import jakarta.persistence.GeneratedValue;
6 | import jakarta.persistence.GenerationType;
7 | import jakarta.persistence.Id;
8 | import jakarta.persistence.JoinColumn;
9 | import jakarta.persistence.ManyToOne;
10 |
11 | import com.fasterxml.jackson.annotation.JsonIgnore;
12 | import com.fasterxml.jackson.annotation.JsonManagedReference;
13 |
14 | @Entity
15 | public class Student {
16 | @Id
17 | @GeneratedValue(strategy=GenerationType.AUTO)
18 | private Long id;
19 | private String firstName;
20 | private String lastName;
21 | private String email;
22 |
23 | @ManyToOne
24 | @JoinColumn(name = "departmentid")
25 | private Department department;
26 |
27 | public Student() {}
28 |
29 | public Student(String firstName, String lastName, String email, Department department) {
30 | super();
31 | this.firstName = firstName;
32 | this.lastName = lastName;
33 | this.email = email;
34 | this.department = department;
35 | }
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 getFirstName() {
46 | return firstName;
47 | }
48 |
49 | public void setFirstName(String firstName) {
50 | this.firstName = firstName;
51 | }
52 |
53 | public String getLastName() {
54 | return lastName;
55 | }
56 |
57 | public void setLastName(String lastName) {
58 | this.lastName = lastName;
59 | }
60 |
61 | public String getEmail() {
62 | return email;
63 | }
64 |
65 | public void setEmail(String email) {
66 | this.email = email;
67 | }
68 |
69 | public Department getDepartment() {
70 | return department;
71 | }
72 |
73 | public void setDepartment(Department department) {
74 | this.department = department;
75 | }
76 |
77 | @Override
78 | public String toString() {
79 | if (this.department != null)
80 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + " department =" + this.getDepartment() + "]";
81 | else
82 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/StudentListRest/src/main/java/fi/haagahelia/course/domain/StudentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.repository.CrudRepository;
6 |
7 | public interface StudentRepository extends CrudRepository {
8 |
9 | List findByLastName(String lastName);
10 |
11 | }
--------------------------------------------------------------------------------
/StudentListRest/src/main/java/fi/haagahelia/course/web/StudentController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Controller;
8 | import org.springframework.ui.Model;
9 | import org.springframework.web.bind.annotation.PathVariable;
10 | import org.springframework.web.bind.annotation.RequestMapping;
11 | import org.springframework.web.bind.annotation.RequestMethod;
12 | import org.springframework.web.bind.annotation.ResponseBody;
13 |
14 | import fi.haagahelia.course.domain.DepartmentRepository;
15 | import fi.haagahelia.course.domain.Student;
16 | import fi.haagahelia.course.domain.StudentRepository;
17 |
18 | @Controller
19 | public class StudentController {
20 |
21 | @Autowired
22 | private StudentRepository repository;
23 |
24 | @Autowired
25 | private DepartmentRepository drepository;
26 |
27 | // Show all students
28 | @RequestMapping(value="/studentlist")
29 | public String studentList(Model model) {
30 | model.addAttribute("students", repository.findAll());
31 | return "studentlist";
32 | }
33 |
34 | // RESTful service to get all students
35 | @RequestMapping(value="/students", method = RequestMethod.GET)
36 | public @ResponseBody List studentListRest() {
37 | return (List) repository.findAll();
38 | }
39 |
40 | // RESTful service to get student by id
41 | @RequestMapping(value="/student/{id}", method = RequestMethod.GET)
42 | public @ResponseBody Optional findStudentRest(@PathVariable("id") Long studentId) {
43 | return repository.findById(studentId);
44 | }
45 |
46 | // Add new student
47 | @RequestMapping(value = "/add")
48 | public String addStudent(Model model){
49 | model.addAttribute("student", new Student());
50 | model.addAttribute("departments", drepository.findAll());
51 | return "addstudent";
52 | }
53 |
54 | // Save new student
55 | @RequestMapping(value = "/save", method = RequestMethod.POST)
56 | public String save(Student student){
57 | repository.save(student);
58 | return "redirect:studentlist";
59 | }
60 |
61 | // Delete student
62 | @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
63 | public String deleteStudent(@PathVariable("id") Long studentId, Model model) {
64 | repository.deleteById(studentId);
65 | return "redirect:../studentlist";
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/StudentListRest/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.jpa.show-sql=true
2 | spring.data.rest.basePath=/api
3 | spring.datasource.url=jdbc:h2:mem:testdb
4 |
--------------------------------------------------------------------------------
/StudentListRest/src/main/resources/templates/addstudent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 | Add student
9 |
30 |
31 |
--------------------------------------------------------------------------------
/StudentListRest/src/main/resources/templates/studentlist.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 | Students
9 |
10 |
11 | Name |
12 | Email |
13 | Department |
14 |
15 |
16 | |
17 | |
18 | |
19 | Delete |
20 |
21 |
22 | Add Student
23 |
24 |
--------------------------------------------------------------------------------
/StudentListRest/src/test/java/fi/haagahelia/course/BookListApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class BookListApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/StudentListSignup/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Maven
7 | log/
8 | target/
--------------------------------------------------------------------------------
/StudentListSignup/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juhahinkula/ServerProgramming/1ae4f52fde5fb17569bf4a0ba019c2cc614155de/StudentListSignup/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/StudentListSignup/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
2 |
--------------------------------------------------------------------------------
/StudentListSignup/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | fi.haagahelia.course
7 | StudentListSignUp
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | StudentListSignUp
12 | Demo project for Spring Boot
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 3.0.1
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-data-jpa
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-devtools
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-starter-thymeleaf
35 |
36 |
37 | org.thymeleaf.extras
38 | thymeleaf-extras-springsecurity6
39 |
40 |
41 | org.springframework.boot
42 | spring-boot-starter-web
43 |
44 |
45 | org.springframework.boot
46 | spring-boot-starter-validation
47 |
48 |
49 | org.springframework.boot
50 | spring-boot-starter-actuator
51 |
52 |
53 | com.h2database
54 | h2
55 | runtime
56 |
57 |
58 | org.springframework.boot
59 | spring-boot-starter-security
60 |
61 |
62 | org.springframework.boot
63 | spring-boot-starter-test
64 | test
65 |
66 |
67 |
68 |
69 |
70 |
71 | org.springframework.boot
72 | spring-boot-maven-plugin
73 |
74 |
75 |
76 |
77 |
78 |
79 |
--------------------------------------------------------------------------------
/StudentListSignup/src/main/java/fi/haagahelia/course/StudentListSignUpApplication.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | import org.springframework.boot.CommandLineRunner;
7 | import org.springframework.boot.SpringApplication;
8 | import org.springframework.boot.autoconfigure.SpringBootApplication;
9 | import org.springframework.context.annotation.Bean;
10 |
11 | import fi.haagahelia.course.domain.Department;
12 | import fi.haagahelia.course.domain.DepartmentRepository;
13 | import fi.haagahelia.course.domain.Student;
14 | import fi.haagahelia.course.domain.StudentRepository;
15 | import fi.haagahelia.course.domain.AppUser;
16 | import fi.haagahelia.course.domain.AppUserRepository;
17 |
18 | @SpringBootApplication
19 | public class StudentListSignUpApplication {
20 | private static final Logger log = LoggerFactory.getLogger(StudentListSignUpApplication.class);
21 |
22 | public static void main(String[] args) {
23 | SpringApplication.run(StudentListSignUpApplication.class, args);
24 | }
25 |
26 | @Bean
27 | public CommandLineRunner studentDemo(StudentRepository srepository, DepartmentRepository drepository, AppUserRepository urepository) {
28 | return (args) -> {
29 | log.info("save a couple of students");
30 | drepository.save(new Department("IT"));
31 | drepository.save(new Department("Business"));
32 | drepository.save(new Department("Law"));
33 |
34 | srepository.save(new Student("John", "Johnson", "john@john.com", drepository.findByName("IT").get(0)));
35 | srepository.save(new Student("Katy", "Kateson", "kate@kate.com", drepository.findByName("Business").get(0)));
36 |
37 | // Create users: admin/admin user/user
38 | AppUser user1 = new AppUser("user", "$2a$06$3jYRJrg0ghaaypjZ/.g4SethoeA51ph3UD4kZi9oPkeMTpjKU5uo6", "USER");
39 | AppUser user2 = new AppUser("admin", "$2a$10$0MMwY.IQqpsVc1jC8u7IJ.2rT8b0Cd3b3sfIBGV2zfgnPGtT4r0.C", "ADMIN");
40 | urepository.save(user1);
41 | urepository.save(user2);
42 |
43 | log.info("fetch all students");
44 | for (Student student : srepository.findAll()) {
45 | log.info(student.toString());
46 | }
47 |
48 | };
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/StudentListSignup/src/main/java/fi/haagahelia/course/WebSecurityConfig.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.context.annotation.Bean;
5 | import org.springframework.context.annotation.Configuration;
6 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
7 | import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
9 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
10 | import org.springframework.security.web.SecurityFilterChain;
11 |
12 | import fi.haagahelia.course.web.UserDetailServiceImpl;
13 |
14 | @Configuration
15 | @EnableMethodSecurity(securedEnabled = true)
16 | public class WebSecurityConfig {
17 | @Autowired
18 | private UserDetailServiceImpl userDetailsService;
19 |
20 | @Bean
21 | public SecurityFilterChain configure(HttpSecurity http) throws Exception {
22 |
23 | http.authorizeHttpRequests().requestMatchers("/css/**").permitAll()
24 | .and()
25 | .authorizeHttpRequests().requestMatchers("/signup", "/saveuser").permitAll()
26 | .and()
27 | .authorizeHttpRequests().anyRequest().authenticated()
28 | .and()
29 | .headers().frameOptions().disable() //for h2 console
30 | .and()
31 | .formLogin()
32 | .loginPage("/login")
33 | .defaultSuccessUrl("/studentlist", true)
34 | .permitAll()
35 | .and()
36 | .logout().permitAll();
37 |
38 | return http.build();
39 | }
40 |
41 |
42 | @Autowired
43 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
44 | auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
45 | }}
46 |
--------------------------------------------------------------------------------
/StudentListSignup/src/main/java/fi/haagahelia/course/domain/AppUser.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import jakarta.persistence.*;
4 |
5 |
6 | @Entity
7 | public class AppUser {
8 | @Id
9 | @GeneratedValue(strategy = GenerationType.IDENTITY)
10 | @Column(name = "id", nullable = false, updatable = false)
11 | private Long id;
12 |
13 | // Username with unique constraint
14 | @Column(name = "username", nullable = false, unique = true)
15 | private String username;
16 |
17 | @Column(name = "password", nullable = false)
18 | private String passwordHash;
19 |
20 | @Column(name = "role", nullable = false)
21 | private String role;
22 |
23 | public AppUser() {
24 | }
25 |
26 | public AppUser(String username, String passwordHash, String role) {
27 | super();
28 | this.username = username;
29 | this.passwordHash = passwordHash;
30 | this.role = role;
31 | }
32 |
33 | public Long getId() {
34 | return id;
35 | }
36 |
37 | public void setId(Long id) {
38 | this.id = id;
39 | }
40 |
41 | public String getUsername() {
42 | return username;
43 | }
44 |
45 | public void setUsername(String username) {
46 | this.username = username;
47 | }
48 |
49 | public String getPasswordHash() {
50 | return passwordHash;
51 | }
52 |
53 | public void setPasswordHash(String passwordHash) {
54 | this.passwordHash = passwordHash;
55 | }
56 |
57 | public String getRole() {
58 | return role;
59 | }
60 |
61 | public void setRole(String role) {
62 | this.role = role;
63 | }
64 |
65 | }
--------------------------------------------------------------------------------
/StudentListSignup/src/main/java/fi/haagahelia/course/domain/AppUserRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import org.springframework.data.repository.CrudRepository;
4 |
5 | public interface AppUserRepository extends CrudRepository {
6 | AppUser findByUsername(String username);
7 | }
--------------------------------------------------------------------------------
/StudentListSignup/src/main/java/fi/haagahelia/course/domain/Department.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import jakarta.persistence.*;
6 |
7 |
8 | @Entity
9 | public class Department {
10 | @Id
11 | @GeneratedValue(strategy=GenerationType.AUTO)
12 | private Long departmentid;
13 | private String name;
14 |
15 | @OneToMany(cascade = CascadeType.ALL, mappedBy = "department")
16 | private List students;
17 |
18 | public Department() {}
19 |
20 | public Department(String name) {
21 | super();
22 | this.name = name;
23 | }
24 |
25 | public Long getDepartmentid() {
26 | return departmentid;
27 | }
28 |
29 | public void setDepartmentid(Long departmentid) {
30 | this.departmentid = departmentid;
31 | }
32 |
33 | public String getName() {
34 | return name;
35 | }
36 |
37 | public void setName(String name) {
38 | this.name = name;
39 | }
40 |
41 | public List getStudents() {
42 | return students;
43 | }
44 |
45 | public void setStudents(List students) {
46 | this.students = students;
47 | }
48 |
49 | @Override
50 | public String toString() {
51 | return "Department [departmentid=" + departmentid + ", name=" + name + "]";
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/StudentListSignup/src/main/java/fi/haagahelia/course/domain/DepartmentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 | import org.springframework.data.repository.CrudRepository;
5 |
6 | public interface DepartmentRepository extends CrudRepository {
7 |
8 | List findByName(String name);
9 |
10 | }
--------------------------------------------------------------------------------
/StudentListSignup/src/main/java/fi/haagahelia/course/domain/SignupForm.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import jakarta.validation.constraints.*;
4 |
5 | public class SignupForm {
6 | @NotEmpty
7 | @Size(min=5, max=30)
8 | private String username = "";
9 |
10 | @NotEmpty
11 | @Size(min=7, max=30)
12 | private String password = "";
13 |
14 | @NotEmpty
15 | @Size(min=7, max=30)
16 | private String passwordCheck = "";
17 |
18 | @NotEmpty
19 | private String role = "USER";
20 |
21 | public String getUsername() {
22 | return username;
23 | }
24 |
25 | public void setUsername(String username) {
26 | this.username = username;
27 | }
28 |
29 | public String getPassword() {
30 | return password;
31 | }
32 |
33 | public void setPassword(String password) {
34 | this.password = password;
35 | }
36 |
37 | public String getPasswordCheck() {
38 | return passwordCheck;
39 | }
40 |
41 | public void setPasswordCheck(String passwordCheck) {
42 | this.passwordCheck = passwordCheck;
43 | }
44 |
45 | public String getRole() {
46 | return role;
47 | }
48 |
49 | public void setRole(String role) {
50 | this.role = role;
51 | }
52 |
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/StudentListSignup/src/main/java/fi/haagahelia/course/domain/Student.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import jakarta.persistence.*;
4 |
5 |
6 |
7 | import com.fasterxml.jackson.annotation.JsonIgnore;
8 |
9 | @Entity
10 | public class Student {
11 | @Id
12 | @GeneratedValue(strategy=GenerationType.AUTO)
13 | private Long id;
14 | private String firstName;
15 | private String lastName;
16 | private String email;
17 |
18 | @ManyToOne
19 | @JsonIgnore
20 | @JoinColumn(name = "departmentid")
21 | private Department department;
22 |
23 | public Student() {}
24 |
25 | public Student(String firstName, String lastName, String email, Department department) {
26 | super();
27 | this.firstName = firstName;
28 | this.lastName = lastName;
29 | this.email = email;
30 | this.department = department;
31 | }
32 |
33 | public Long getId() {
34 | return id;
35 | }
36 |
37 | public void setId(Long id) {
38 | this.id = id;
39 | }
40 |
41 | public String getFirstName() {
42 | return firstName;
43 | }
44 |
45 | public void setFirstName(String firstName) {
46 | this.firstName = firstName;
47 | }
48 |
49 | public String getLastName() {
50 | return lastName;
51 | }
52 |
53 | public void setLastName(String lastName) {
54 | this.lastName = lastName;
55 | }
56 |
57 | public String getEmail() {
58 | return email;
59 | }
60 |
61 | public void setEmail(String email) {
62 | this.email = email;
63 | }
64 |
65 | public Department getDepartment() {
66 | return department;
67 | }
68 |
69 | public void setDepartment(Department department) {
70 | this.department = department;
71 | }
72 |
73 | @Override
74 | public String toString() {
75 | if (this.department != null)
76 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + " department =" + this.getDepartment() + "]";
77 | else
78 | return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/StudentListSignup/src/main/java/fi/haagahelia/course/domain/StudentRepository.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.domain;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.data.repository.CrudRepository;
6 |
7 | public interface StudentRepository extends CrudRepository {
8 |
9 | List findByLastName(String lastName);
10 |
11 | }
--------------------------------------------------------------------------------
/StudentListSignup/src/main/java/fi/haagahelia/course/web/StudentController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.security.access.prepost.PreAuthorize;
8 | import org.springframework.stereotype.Controller;
9 | import org.springframework.ui.Model;
10 | import org.springframework.web.bind.annotation.PathVariable;
11 | import org.springframework.web.bind.annotation.RequestMapping;
12 | import org.springframework.web.bind.annotation.RequestMethod;
13 | import org.springframework.web.bind.annotation.ResponseBody;
14 |
15 | import fi.haagahelia.course.domain.DepartmentRepository;
16 | import fi.haagahelia.course.domain.Student;
17 | import fi.haagahelia.course.domain.StudentRepository;
18 |
19 | @Controller
20 | public class StudentController {
21 | @Autowired
22 | private StudentRepository repository;
23 |
24 | @Autowired
25 | private DepartmentRepository drepository;
26 |
27 | // Show all students
28 | @RequestMapping(value="/login")
29 | public String login() {
30 | return "login";
31 | }
32 |
33 | // Show all students
34 | @RequestMapping(value="/studentlist")
35 | public String studentList(Model model) {
36 | model.addAttribute("students", repository.findAll());
37 | return "studentlist";
38 | }
39 |
40 | // RESTful service to get all students
41 | @RequestMapping(value="/students")
42 | public @ResponseBody List studentListRest() {
43 | return (List) repository.findAll();
44 | }
45 |
46 | // RESTful service to get student by id
47 | @RequestMapping(value="/student/{id}", method = RequestMethod.GET)
48 | public @ResponseBody Optional findStudentRest(@PathVariable("id") Long studentId) {
49 | return repository.findById(studentId);
50 | }
51 |
52 | // Add new student
53 | @RequestMapping(value = "/add")
54 | public String addStudent(Model model){
55 | model.addAttribute("student", new Student());
56 | model.addAttribute("departments", drepository.findAll());
57 | return "addstudent";
58 | }
59 |
60 | // Save new student
61 | @RequestMapping(value = "/save", method = RequestMethod.POST)
62 | public String save(Student student){
63 | repository.save(student);
64 | return "redirect:studentlist";
65 | }
66 |
67 | // Delete student
68 | @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
69 | @PreAuthorize("hasAuthority('ADMIN')")
70 | public String deleteStudent(@PathVariable("id") Long studentId, Model model) {
71 | repository.deleteById(studentId);
72 | return "redirect:../studentlist";
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/StudentListSignup/src/main/java/fi/haagahelia/course/web/UserController.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
5 | import org.springframework.stereotype.Controller;
6 | import org.springframework.ui.Model;
7 | import org.springframework.validation.BindingResult;
8 | import org.springframework.web.bind.annotation.ModelAttribute;
9 | import org.springframework.web.bind.annotation.RequestMapping;
10 | import org.springframework.web.bind.annotation.RequestMethod;
11 |
12 |
13 | import jakarta.validation.*;
14 |
15 | import fi.haagahelia.course.domain.SignupForm;
16 | import fi.haagahelia.course.domain.AppUser;
17 | import fi.haagahelia.course.domain.AppUserRepository;
18 |
19 | @Controller
20 | public class UserController {
21 | @Autowired
22 | private AppUserRepository repository;
23 |
24 | @RequestMapping(value = "signup")
25 | public String addStudent(Model model){
26 | model.addAttribute("signupform", new SignupForm());
27 | return "signup";
28 | }
29 |
30 | /**
31 | * Create new user
32 | * Check if user already exists & form validation
33 | *
34 | * @param signupForm
35 | * @param bindingResult
36 | * @return
37 | */
38 | @RequestMapping(value = "saveuser", method = RequestMethod.POST)
39 | public String save(@Valid @ModelAttribute("signupform") SignupForm signupForm, BindingResult bindingResult) {
40 | if (!bindingResult.hasErrors()) { // validation errors
41 | if (signupForm.getPassword().equals(signupForm.getPasswordCheck())) { // check password match
42 | String pwd = signupForm.getPassword();
43 | BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
44 | String hashPwd = bc.encode(pwd);
45 |
46 | AppUser newUser = new AppUser();
47 | newUser.setPasswordHash(hashPwd);
48 | newUser.setUsername(signupForm.getUsername());
49 | newUser.setRole("USER");
50 | if (repository.findByUsername(signupForm.getUsername()) == null) { // Check if user exists
51 | repository.save(newUser);
52 | }
53 | else {
54 | bindingResult.rejectValue("username", "err.username", "Username already exists");
55 | return "signup";
56 | }
57 | }
58 | else {
59 | bindingResult.rejectValue("passwordCheck", "err.passCheck", "Passwords does not match");
60 | return "signup";
61 | }
62 | }
63 | else {
64 | return "signup";
65 | }
66 | return "redirect:/login";
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/StudentListSignup/src/main/java/fi/haagahelia/course/web/UserDetailServiceImpl.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course.web;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.security.core.authority.AuthorityUtils;
5 | import org.springframework.security.core.userdetails.UserDetails;
6 | import org.springframework.security.core.userdetails.UserDetailsService;
7 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
8 | import org.springframework.stereotype.Service;
9 |
10 | import fi.haagahelia.course.domain.AppUser;
11 | import fi.haagahelia.course.domain.AppUserRepository;
12 |
13 | /**
14 | * This class is used by spring security to authenticate and authorize user
15 | **/
16 | @Service
17 | public class UserDetailServiceImpl implements UserDetailsService {
18 | private final AppUserRepository repository;
19 |
20 | @Autowired
21 | public UserDetailServiceImpl(AppUserRepository userRepository) {
22 | this.repository = userRepository;
23 | }
24 |
25 | @Override
26 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
27 | AppUser curruser = repository.findByUsername(username);
28 | UserDetails user = new org.springframework.security.core.userdetails.User(username, curruser.getPasswordHash(),
29 | AuthorityUtils.createAuthorityList(curruser.getRole()));
30 | return user;
31 | }
32 | }
--------------------------------------------------------------------------------
/StudentListSignup/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.jpa.show-sql=true
2 | spring.datasource.url=jdbc:h2:mem:testdb
3 |
--------------------------------------------------------------------------------
/StudentListSignup/src/main/resources/templates/addstudent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 |
9 |
10 |
Add student
11 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/StudentListSignup/src/main/resources/templates/login.html:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 | Spring Security Example
6 |
7 |
8 |
9 |
10 |
11 | Invalid username and password.
12 |
13 |
14 | You have been logged out.
15 |
16 |
21 |
Sign-up
22 |
23 |
24 |
--------------------------------------------------------------------------------
/StudentListSignup/src/main/resources/templates/signup.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Add student
5 |
6 |
7 |
8 |
9 |
30 |
31 |
--------------------------------------------------------------------------------
/StudentListSignup/src/main/resources/templates/studentlist.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Studentlist
5 |
6 |
7 |
8 |
9 |
10 |
11 |
Students
12 |
13 |
14 | Welcome ,
15 | your role is
16 |
17 |
18 |
21 |
22 |
23 |
24 | Name |
25 | Email |
26 | Department |
27 | |
28 |
29 |
30 | |
31 | |
32 | |
33 | Delete |
34 |
35 |
36 |
Add Student
37 |
38 |
39 |
--------------------------------------------------------------------------------
/StudentListSignup/src/test/java/fi/haagahelia/course/StudentListApplicationTests.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class BookListApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/StudentListSignup/src/test/java/fi/haagahelia/course/StudentRepositoryTest.java:
--------------------------------------------------------------------------------
1 | package fi.haagahelia.course;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 |
5 | import java.util.List;
6 | import org.junit.jupiter.api.Test;
7 | import org.springframework.boot.test.context.SpringBootTest;
8 |
9 |
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
12 | import org.springframework.test.context.junit4.SpringRunner;
13 |
14 | import fi.haagahelia.course.domain.Department;
15 | import fi.haagahelia.course.domain.Student;
16 | import fi.haagahelia.course.domain.StudentRepository;
17 |
18 |
19 | @DataJpaTest
20 | public class StudentRepositoryTest {
21 |
22 |
23 |
24 | }
--------------------------------------------------------------------------------