Compare commits

..

19 Commits
v1.1.0 ... main

Author SHA1 Message Date
5f6caa7fc2 feat: Implement feature to acknowledge project time frames when assigning employees to projects (SCRUM-7 SCRUM-2) (!38)
All checks were successful
Build / Build and analyze (push) Successful in 1m34s
Quality Check / Tests (push) Successful in 1m0s
Quality Check / Checkstyle Main (push) Successful in 25s
Release / Release (push) Successful in 43s
Co-authored-by: Phan Huy Tran <p.tran@neusta.de>
Reviewed-on: #38
Co-authored-by: Phan Huy Tran <ptran@noreply.localhost>
Co-committed-by: Phan Huy Tran <ptran@noreply.localhost>
2024-10-25 05:01:10 +00:00
97e211946f feat: Implement feature to get all projects from an employee (SCRUM-31) (!37)
All checks were successful
Quality Check / Checkstyle Main (push) Successful in 37s
Build / Build and analyze (push) Successful in 1m48s
Release / Release (push) Successful in 37s
Quality Check / Tests (push) Successful in 49s
Co-authored-by: Phan Huy Tran <p.tran@neusta.de>
Reviewed-on: #37
Reviewed-by: Jan Gleytenhoover <krisellp9@gmail.com>
2024-10-23 10:50:49 +00:00
202805e3dd feat: Implement feature to list all employees from a project (SCRUM-46) (!36)
All checks were successful
Quality Check / Tests (push) Successful in 1m8s
Quality Check / Checkstyle Main (push) Successful in 37s
Build / Build and analyze (push) Successful in 1m48s
Release / Release (push) Successful in 39s
Co-authored-by: Phan Huy Tran <p.tran@neusta.de>
Reviewed-on: #36
2024-10-23 10:19:33 +00:00
76b0201cf2 feat(employee): add action to remove employee from project (SCRUM-23) (!35)
All checks were successful
Quality Check / Tests (push) Successful in 1m7s
Quality Check / Checkstyle Main (push) Successful in 35s
Build / Build and analyze (push) Successful in 1m45s
Release / Release (push) Successful in 36s
Reviewed-on: #35
Reviewed-by: Phan Huy Tran <ptran@noreply.localhost>
Co-authored-by: Jan Klattenhoff <jan@kjan.de>
Co-committed-by: Jan Klattenhoff <jan@kjan.de>
2024-10-23 09:51:12 +00:00
1008278fde feat: Implement add employee to project route (SCRUM-2) (!32)
All checks were successful
Quality Check / Tests (push) Successful in 1m8s
Build / Build and analyze (push) Successful in 1m48s
Quality Check / Checkstyle Main (push) Successful in 38s
Release / Release (push) Successful in 45s
Co-authored-by: Phan Huy Tran <p.tran@neusta.de>
Reviewed-on: #32
Reviewed-by: Jan Gleytenhoover <krisellp9@gmail.com>
Co-authored-by: Phan Huy Tran <ptran@noreply.localhost>
Co-committed-by: Phan Huy Tran <ptran@noreply.localhost>
2024-10-23 08:39:25 +00:00
1e38efaa63 refactor(test): remove access modifiers from test classes (!31)
All checks were successful
Quality Check / Tests (push) Successful in 1m1s
Quality Check / Checkstyle Main (push) Successful in 46s
Build / Build and analyze (push) Successful in 2m0s
Release / Release (push) Successful in 39s
Reviewed-on: #31
Reviewed-by: Phan Huy Tran <ptran@noreply.localhost>
Co-authored-by: Jan Klattenhoff <jan@kjan.de>
Co-committed-by: Jan Klattenhoff <jan@kjan.de>
2024-10-02 10:29:39 +00:00
8230337839 refactor: remove unused imports and clean up code (!30)
All checks were successful
Quality Check / Tests (push) Successful in 57s
Quality Check / Checkstyle Main (push) Successful in 45s
Build / Build and analyze (push) Successful in 1m54s
Release / Release (push) Successful in 39s
Reviewed-on: #30
Reviewed-by: Phan Huy Tran <ptran@noreply.localhost>
Co-authored-by: Jan Klattenhoff <jan@kjan.de>
Co-committed-by: Jan Klattenhoff <jan@kjan.de>
2024-10-02 10:09:07 +00:00
b2ef8ce2ab feat(project): Delete project (SCRUM-35) (!29)
All checks were successful
Quality Check / Tests (push) Successful in 59s
Quality Check / Checkstyle Main (push) Successful in 44s
Build / Build and analyze (push) Successful in 1m56s
Release / Release (push) Successful in 41s
Reviewed-on: #29
Reviewed-by: Phan Huy Tran <ptran@noreply.localhost>
Co-authored-by: Jan Klattenhoff <jan@kjan.de>
Co-committed-by: Jan Klattenhoff <jan@kjan.de>
2024-10-02 09:43:10 +00:00
4eb7626c10 feat: Implement Update Project Route (SCRUM-11) (!28)
All checks were successful
Quality Check / Tests (push) Successful in 58s
Quality Check / Checkstyle Main (push) Successful in 46s
Build / Build and analyze (push) Successful in 1m58s
Release / Release (push) Successful in 37s
Co-authored-by: Phan Huy Tran <p.tran@neusta.de>
Reviewed-on: #28
Reviewed-by: Jan Gleytenhoover <krisellp9@gmail.com>
Co-authored-by: Phan Huy Tran <ptran@noreply.localhost>
Co-committed-by: Phan Huy Tran <ptran@noreply.localhost>
2024-10-02 08:52:19 +00:00
cbb77cc1ca refactor: Fix yellow code smells (!27)
All checks were successful
Quality Check / Tests (push) Successful in 1m0s
Quality Check / Checkstyle Main (push) Successful in 45s
Build / Build and analyze (push) Successful in 1m56s
Release / Release (push) Successful in 35s
Reviewed-on: #27
Reviewed-by: Phan Huy Tran <ptran@noreply.localhost>
Co-authored-by: Jan Klattenhoff <jan@kjan.de>
Co-committed-by: Jan Klattenhoff <jan@kjan.de>
2024-10-02 08:43:01 +00:00
a04a180712 refactor: Fix some code smells (!26)
All checks were successful
Quality Check / Tests (push) Successful in 1m1s
Quality Check / Checkstyle Main (push) Successful in 46s
Build / Build and analyze (push) Successful in 1m56s
Release / Release (push) Successful in 38s
Reviewed-on: #26
Reviewed-by: Phan Huy Tran <ptran@noreply.localhost>
Co-authored-by: Jan Klattenhoff <jan@kjan.de>
Co-committed-by: Jan Klattenhoff <jan@kjan.de>
2024-10-02 07:48:32 +00:00
c317b226fe feat: Implement get project by ID Route (!25)
All checks were successful
Build / Build and analyze (push) Successful in 1m25s
Quality Check / Tests (push) Successful in 42s
Quality Check / Checkstyle Main (push) Successful in 37s
Release / Release (push) Successful in 39s
Quality Check / Tests (pull_request) Successful in 59s
Quality Check / Checkstyle Main (pull_request) Successful in 43s
gitea-sonarqube-bot OK
Build PR / Build and analyze (pull_request) Successful in 1m52s
Co-authored-by: Phan Huy Tran <p.tran@neusta.de>
Reviewed-on: #25
Reviewed-by: Jan Gleytenhoover <krisellp9@gmail.com>
Co-authored-by: Phan Huy Tran <ptran@noreply.localhost>
Co-committed-by: Phan Huy Tran <ptran@noreply.localhost>
2024-10-02 07:04:08 +00:00
d047bce4ec refactor: Add and refactor http requests (!24)
All checks were successful
Quality Check / Tests (push) Successful in 1m2s
Quality Check / Checkstyle Main (push) Successful in 49s
Build / Build and analyze (push) Successful in 1m58s
Release / Release (push) Successful in 35s
Co-authored-by: Phan Huy Tran <p.tran@neusta.de>
Reviewed-on: #24
Reviewed-by: Jan Gleytenhoover <krisellp9@gmail.com>
Co-authored-by: Phan Huy Tran <ptran@noreply.localhost>
Co-committed-by: Phan Huy Tran <ptran@noreply.localhost>
2024-10-02 06:34:16 +00:00
e5b4e2c012 chore(deps): update plugin org.sonarqube to v5.1.0.4882 (!18)
All checks were successful
Quality Check / Tests (push) Successful in 1m5s
Quality Check / Checkstyle Main (push) Successful in 50s
Build / Build and analyze (push) Successful in 2m7s
Release / Release (push) Successful in 36s
This PR contains the following updates:

| Package | Change | Age | Adoption | Passing | Confidence |
|---|---|---|---|---|---|
| org.sonarqube | `5.0.0.4638` -> `5.1.0.4882` | [![age](https://developer.mend.io/api/mc/badges/age/maven/org.sonarqube/5.1.0.4882?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://developer.mend.io/api/mc/badges/adoption/maven/org.sonarqube/5.1.0.4882?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://developer.mend.io/api/mc/badges/compatibility/maven/org.sonarqube/5.0.0.4638/5.1.0.4882?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://developer.mend.io/api/mc/badges/confidence/maven/org.sonarqube/5.0.0.4638/5.1.0.4882?slim=true)](https://docs.renovatebot.com/merge-confidence/) |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOC45NS4wIiwidXBkYXRlZEluVmVyIjoiMzguOTguMCIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==-->

Reviewed-on: #18
Reviewed-by: Jan Gleytenhoover <krisellp9@gmail.com>
Co-authored-by: Renovate <renovate@kjan.de>
Co-committed-by: Renovate <renovate@kjan.de>
2024-09-27 12:52:40 +00:00
1669b29bbd chore(deps): update postgres docker tag to v17 (!22)
All checks were successful
Quality Check / Tests (push) Successful in 1m3s
Build / Build and analyze (push) Successful in 1m56s
Quality Check / Checkstyle Main (push) Successful in 53s
Release / Release (push) Successful in 37s
This PR contains the following updates:

| Package | Update | Change |
|---|---|---|
| postgres | major | `16.4` -> `17.0` |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOC45Ny4xIiwidXBkYXRlZEluVmVyIjoiMzguOTguMCIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==-->

Reviewed-on: #22
Reviewed-by: Jan Gleytenhoover <krisellp9@gmail.com>
Co-authored-by: Renovate <renovate@kjan.de>
Co-committed-by: Renovate <renovate@kjan.de>
2024-09-27 11:58:17 +00:00
750041a9eb feat: SonarQube PR analysis (!21)
All checks were successful
Quality Check / Tests (push) Successful in 1m11s
Build / Build and analyze (push) Successful in 2m5s
Quality Check / Checkstyle Main (push) Successful in 51s
Release / Release (push) Successful in 39s
Reviewed-on: #21
2024-09-27 09:11:11 +00:00
921f585598 chore(deps): update actions/cache action to v4 (!19)
All checks were successful
Quality Check / Tests (push) Successful in 1m4s
Quality Check / Checkstyle Main (push) Successful in 51s
Release / Release (push) Successful in 44s
Build / Build and analyze (push) Successful in 3m30s
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [actions/cache](https://github.com/actions/cache) | action | major | `v1` -> `v4` |

---

### Release Notes

<details>
<summary>actions/cache (actions/cache)</summary>

### [`v4`](https://github.com/actions/cache/compare/v3...v4)

[Compare Source](https://github.com/actions/cache/compare/v3...v4)

### [`v3`](https://github.com/actions/cache/compare/v2...v3)

[Compare Source](https://github.com/actions/cache/compare/v2...v3)

### [`v2`](https://github.com/actions/cache/compare/v1...v2)

[Compare Source](https://github.com/actions/cache/compare/v1...v2)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOC45NS4wIiwidXBkYXRlZEluVmVyIjoiMzguOTUuMCIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==-->

Reviewed-on: #19
Reviewed-by: Jan Gleytenhoover <krisellp9@gmail.com>
Co-authored-by: Renovate <renovate@kjan.de>
Co-committed-by: Renovate <renovate@kjan.de>
2024-09-26 05:25:14 +00:00
e5f7f19274 fix: Fix Sonarqube java version (!17)
All checks were successful
Quality Check / Tests (push) Successful in 1m9s
Quality Check / Checkstyle Main (push) Successful in 57s
Build / Build and analyze (push) Successful in 2m16s
Release / Release (push) Successful in 46s
Reviewed-on: #17
2024-09-25 15:15:45 +00:00
34609a6eed feat: Add sonarqube (!16)
Some checks failed
Quality Check / Tests (push) Successful in 1m23s
Quality Check / Checkstyle Main (push) Successful in 53s
Build / Build and analyze (push) Failing after 2m44s
Release / Release (push) Successful in 43s
Reviewed-on: #16
2024-09-25 14:15:06 +00:00
66 changed files with 2377 additions and 796 deletions

@ -0,0 +1,45 @@
name: Build PR
on: # test
pull_request:
types:
- opened
- reopened
- synchronize
- ready_for_review
jobs:
build:
name: Build and analyze
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Set up JDK 21
uses: actions/setup-java@v1
with:
java-version: 21
- name: Cache SonarQube packages
uses: actions/cache@v4
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Gradle packages
uses: actions/cache@v4
with:
path: ~/.gradle/caches
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
restore-keys: ${{ runner.os }}-gradle
- name: Coverage
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
run: ./gradlew test jacocoTestReport sonar
- name: Build and analyze
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
run: ./gradlew build sonar --info -Dsonar.pullrequest.branch=${{ github.event.pull_request.head.ref }} -Dsonar.pullrequest.base=${{ github.event.pull_request.base.ref }} -Dsonar.pullrequest.key=${{github.event.pull_request.number}}

@ -0,0 +1,42 @@
name: Build
on:
push:
branches:
- main
jobs:
build:
name: Build and analyze
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Set up JDK 21
uses: actions/setup-java@v1
with:
java-version: 21
- name: Cache SonarQube packages
uses: actions/cache@v4
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Gradle packages
uses: actions/cache@v4
with:
path: ~/.gradle/caches
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
restore-keys: ${{ runner.os }}-gradle
- name: Coverage
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
run: ./gradlew test jacocoTestReport sonar
- name: Build and analyze
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
run: ./gradlew build sonar --info

@ -3,6 +3,9 @@
![Gitea Release](https://img.shields.io/gitea/v/release/jank/LF8?gitea_url=https%3A%2F%2Fgit.kjan.de&style=plastic) ![Gitea Release](https://img.shields.io/gitea/v/release/jank/LF8?gitea_url=https%3A%2F%2Fgit.kjan.de&style=plastic)
![Gitea Last Commit](https://img.shields.io/gitea/last-commit/jank/LF8?gitea_url=https%3A%2F%2Fgit.kjan.de&style=plastic) ![Gitea Last Commit](https://img.shields.io/gitea/last-commit/jank/LF8?gitea_url=https%3A%2F%2Fgit.kjan.de&style=plastic)
## Code analysis coverage issues and results of linting MAY be found here:
https://sonarqube.kjan.de/dashboard?id=LF8&codeScope=overall
# Starter für das LF08 Projekt # Starter für das LF08 Projekt
## Requirements ## Requirements
@ -59,7 +62,7 @@ docker compose up
# Keycloak # Keycloak
### Keycloak Token ### Keycloak Token
1. Auf der Projektebene [GetBearerToken.http](GetBearerToken.http) öffnen. 1. Auf der Projektebene [GetBearerToken.http](requests/GetBearerToken.http) öffnen.
2. Neben der Request auf den grünen Pfeil drücken 2. Neben der Request auf den grünen Pfeil drücken
3. Aus dem Reponse das access_token kopieren 3. Aus dem Reponse das access_token kopieren

@ -1,62 +1,85 @@
plugins { plugins {
java java
id("org.springframework.boot") version "3.3.4" id("org.springframework.boot") version "3.3.4"
id("io.spring.dependency-management") version "1.1.6" id("io.spring.dependency-management") version "1.1.6"
id("checkstyle") id("checkstyle")
} id("org.sonarqube") version "5.1.0.4882"
id("jacoco")
tasks.withType<Checkstyle> { }
reports {
// Disable HTML report tasks.jacocoTestReport {
html.required.set(false) dependsOn(tasks.test) // Ensure tests are run before generating the report
reports {
// Disable XML report xml.required = true
xml.required.set(false) csv.required = true
} }
} }
group = "de.szut" sonar {
version = "0.0.1-SNAPSHOT" properties {
property("sonar.projectKey", "LF8")
tasks.test { property("sonar.projectName", "LF8")
useJUnitPlatform() }
}
// Activate the 'test' profile for Spring during tests
systemProperty("spring.profiles.active", "test") tasks.withType<Checkstyle> {
} reports {
// Disable HTML report
java { html.required.set(false)
toolchain {
languageVersion = JavaLanguageVersion.of(21) // Disable XML report
} xml.required.set(false)
} }
}
configurations {
compileOnly { group = "de.szut"
extendsFrom(configurations.annotationProcessor.get()) version = "0.0.1-SNAPSHOT"
}
} tasks.test {
useJUnitPlatform()
repositories {
mavenCentral() // Activate the 'test' profile for Spring during tests
} systemProperty("spring.profiles.active", "test")
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa") java {
implementation("org.springframework.boot:spring-boot-starter-web") toolchain {
implementation("org.springframework.boot:spring-boot-starter-validation") languageVersion = JavaLanguageVersion.of(21)
compileOnly("org.projectlombok:lombok") }
annotationProcessor("org.projectlombok:lombok") }
testImplementation("org.springframework.boot:spring-boot-starter-test")
testRuntimeOnly("org.junit.platform:junit-platform-launcher") configurations {
implementation("org.springframework.boot:spring-boot-starter-security") compileOnly {
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server:3.3.4") extendsFrom(configurations.annotationProcessor.get())
implementation("org.springframework.boot:spring-boot-starter-oauth2-client:3.3.4") }
runtimeOnly("org.postgresql:postgresql") }
implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0")
testImplementation("com.h2database:h2") repositories {
} mavenCentral()
}
tasks.withType<Test> {
useJUnitPlatform() val springDocVersion = "2.6.0"
} val oauth2Version = "3.3.4"
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:$springDocVersion")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server:$oauth2Version")
implementation("org.springframework.boot:spring-boot-starter-oauth2-client:$oauth2Version")
testImplementation("com.h2database:h2")
testImplementation("org.springframework.boot:spring-boot-starter-test")
compileOnly("org.projectlombok:lombok")
annotationProcessor("org.projectlombok:lombok")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
runtimeOnly("org.postgresql:postgresql")
}
tasks.withType<Test> {
useJUnitPlatform()
finalizedBy(tasks.jacocoTestReport) // Run JaCoCo report after tests
}

@ -7,7 +7,7 @@ volumes:
services: services:
postgres_for_lf8_starter: postgres_for_lf8_starter:
container_name: lf8_starter_postgres_container container_name: lf8_starter_postgres_container
image: postgres:16.4 image: postgres:17.0
volumes: volumes:
- lf8_starter_postgres_data:/var/lib/postgresql/data - lf8_starter_postgres_data:/var/lib/postgresql/data
environment: environment:

@ -0,0 +1,15 @@
POST https://employee.szut.dev/employees
Authorization: Bearer {{auth_token}}
Content-Type: application/json
{
"firstName": "Jan1",
"lastName": "Klattenhoff1",
"street": "Pirolweg 171",
"postcode": "27777",
"city": "Gandakersee1",
"phone": "0176849848161",
"skillSet": [
"1"
]
}

@ -0,0 +1,2 @@
DELETE https://employee.szut.dev/employees/310
Authorization: Bearer {{auth_token}}

@ -0,0 +1,2 @@
GET https://employee.szut.dev/employees
Authorization: Bearer {{auth_token}}

@ -0,0 +1,2 @@
GET https://employee.szut.dev/employees/315
Authorization: Bearer {{auth_token}}

@ -0,0 +1,3 @@
GET http://localhost:8080/employees/315/projects
Authorization: Bearer {{auth_token}}
Content-Type: application/json

@ -0,0 +1,2 @@
POST http://localhost:8080/projects/1/employees/312
Authorization: Bearer {{auth_token}}

@ -6,10 +6,10 @@ Content-Type: application/json
{ {
"name": "name", "name": "name",
"leading_employee": 1, "leading_employee": 1,
"employees": [2, 3], "employees": [312],
"contractor": 4, "contractor": 4,
"contractor_name": "Peter File", "contractor_name": "Peter File",
"comment": "goal of project", "comment": "goal of project",
"start_date": "01.01.2000", "start_date": "02.01.2020",
"planned_end_date": "01.01.2001" "planned_end_date": "01.01.2023"
} }

@ -0,0 +1,3 @@
### GET request to example server
GET http://localhost:8080/projects
Authorization: Bearer {{auth_token}}

@ -0,0 +1,2 @@
GET http://localhost:8080/projects/2/employees
Authorization: Bearer {{auth_token}}

@ -0,0 +1,3 @@
### GET request to example server
GET http://localhost:8080/projects/1
Authorization: Bearer {{auth_token}}

@ -0,0 +1,15 @@
### GET request to example server
PUT http://localhost:8080/projects/1
Authorization: Bearer {{auth_token}}
Content-Type: application/json
{
"name": "newName",
"leading_employee": 2,
"employees": [],
"contractor": 9,
"contractor_name": "New Contractor name",
"comment": "new goal of project",
"start_date": "01.01.2010",
"planned_end_date": "01.01.2021"
}

@ -1,60 +1,77 @@
package de.szut.lf8_starter.config; package de.szut.lf8_starter.config;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityRequirement; import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.security.SecurityScheme; import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.servers.Server; import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContext; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Configuration;
@Configuration
@Configuration public class OpenAPIConfiguration {
public class OpenAPIConfiguration {
private ServletContext context;
private ServletContext context;
public OpenAPIConfiguration(ServletContext context) {
public OpenAPIConfiguration(ServletContext context) { this.context = context;
this.context = context; }
}
@Bean
@Bean public OpenAPI springShopOpenAPI(
public OpenAPI springShopOpenAPI( // @Value("${info.app.version}") String appVersion,
// @Value("${info.app.version}") String appVersion, ) {
) { final String securitySchemeName = "bearerAuth";
final String securitySchemeName = "bearerAuth";
return new OpenAPI()
return new OpenAPI() .addServersItem(new Server().url(this.context.getContextPath()))
.addServersItem(new Server().url(this.context.getContextPath())) .info(new Info()
.info(new Info() .title("LF8 project starter")
.title("LF8 project starter") .description("""
.description("\n## Auth\n" + ## Auth
"\n## Authentication\n" + "\nThis Hello service uses JWTs to authenticate requests. You will receive a bearer token by making a POST-Request in IntelliJ on:\n\n" +
"\n" + ## Authentication
"```\nPOST http://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token\nContent-Type: application/x-www-form-urlencoded\ngrant_type=password&client_id=employee-management-service&username=user&password=test\n```\n" +
"\n" + This Hello service uses JWTs to authenticate requests. You will receive a bearer token by making a POST-Request in IntelliJ on:
"\nor by CURL\n" +
"```\ncurl -X POST 'http://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token'\n--header 'Content-Type: application/x-www-form-urlencoded'\n--data-urlencode 'grant_type=password'\n--data-urlencode 'client_id=employee-management-service'\n--data-urlencode 'username=user'\n--data-urlencode 'password=test'\n```\n" + ```
"\nTo get a bearer-token in Postman, you have to follow the instructions in \n [Postman-Documentation](https://documenter.getpostman.com/view/7294517/SzmfZHnd).") POST http://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token
Content-Type: application/x-www-form-urlencoded
.version("0.1")) grant_type=password&client_id=employee-management-service&username=user&password=test
.addSecurityItem(new SecurityRequirement().addList(securitySchemeName)) ```
.components(
new Components() or by CURL:
.addSecuritySchemes(securitySchemeName,
new SecurityScheme() ```
.name(securitySchemeName) curl -X POST 'http://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token'
.type(SecurityScheme.Type.HTTP) --header 'Content-Type: application/x-www-form-urlencoded'
.scheme("bearer") --data-urlencode 'grant_type=password'
.bearerFormat("JWT") --data-urlencode 'client_id=employee-management-service'
) --data-urlencode 'username=user'
); --data-urlencode 'password=test'
} ```
To get a bearer-token in Postman, you have to follow the instructions in
} [Postman-Documentation](https://documenter.getpostman.com/view/7294517/SzmfZHnd).
""")
.version("0.1"))
.addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
.components(
new Components()
.addSecuritySchemes(securitySchemeName,
new SecurityScheme()
.name(securitySchemeName)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
)
);
}
}

@ -1,33 +1,33 @@
package de.szut.lf8_starter.config; package de.szut.lf8_starter.config;
import de.szut.lf8_starter.hello.HelloEntity; import de.szut.lf8_starter.hello.HelloEntity;
import de.szut.lf8_starter.hello.HelloRepository; import de.szut.lf8_starter.hello.HelloRepository;
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner; import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
@Component @Component
public class SampleDataCreator implements ApplicationRunner { public class SampleDataCreator implements ApplicationRunner {
private HelloRepository repository; private HelloRepository repository;
public SampleDataCreator(HelloRepository repository) { public SampleDataCreator(HelloRepository repository) {
this.repository = repository; this.repository = repository;
} }
public void run(ApplicationArguments args) { public void run(ApplicationArguments args) {
repository.save(new HelloEntity("Hallo Welt!")); repository.save(new HelloEntity("Hallo Welt!"));
repository.save(new HelloEntity("Schöner Tag heute")); repository.save(new HelloEntity("Schöner Tag heute"));
repository.save(new HelloEntity("FooBar")); repository.save(new HelloEntity("FooBar"));
} }
@Bean @Bean
public RestTemplate restTemplate() { public RestTemplate restTemplate() {
return new RestTemplate(); return new RestTemplate();
} }
} }

@ -0,0 +1,73 @@
package de.szut.lf8_starter.employee;
import de.szut.lf8_starter.exceptionHandling.ResourceNotFoundException;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectRepository;
import de.szut.lf8_starter.project.dto.employee.GetEmployeeDto;
import de.szut.lf8_starter.project.dto.project.GetProjectDto;
import de.szut.lf8_starter.project.mapper.ProjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
@Service
public class EmployeeService {
private final RestTemplate restTemplate;
private final ProjectRepository projectRepository;
private final ProjectMapper projectMapper;
public EmployeeService(RestTemplate restTemplate, ProjectRepository projectRepository, ProjectMapper projectMapper) {
this.restTemplate = restTemplate;
this.projectRepository = projectRepository;
this.projectMapper = projectMapper;
}
public boolean employeeExists(String accessToken, Long employeeId) {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken.replace("Bearer ", ""));
HttpEntity<String> requestEntity = new HttpEntity<>(headers);
String url = "https://employee.szut.dev/employees/" + employeeId;
try {
restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
} catch (HttpClientErrorException.NotFound e) {
return false;
}
return true;
}
public GetEmployeeDto getEmployee(String accessToken, Long employeeId) {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken.replace("Bearer ", ""));
HttpEntity<String> requestEntity = new HttpEntity<>(headers);
String url = "https://employee.szut.dev/employees/" + employeeId;
try {
return restTemplate.exchange(url, HttpMethod.GET, requestEntity, GetEmployeeDto.class).getBody();
} catch (HttpClientErrorException.NotFound e) {
throw new ResourceNotFoundException("Employee not found");
}
}
public List<GetProjectDto> getProjects(Long employeeId) {
ArrayList<ProjectEntity> projects = this.projectRepository.findAllByEmployeeId(employeeId);
ArrayList<GetProjectDto> projectDtos = new ArrayList<>();
for (ProjectEntity project : projects) {
projectDtos.add(this.projectMapper.mapToGetDto(project));
}
return projectDtos;
}
}

@ -1,51 +1,59 @@
package de.szut.lf8_starter.exceptionHandling; package de.szut.lf8_starter.exceptionHandling;
import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.ConstraintViolationException; import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import java.util.Date;
import java.util.Date;
@ControllerAdvice
@ApiResponses(value = { @ControllerAdvice
@ApiResponse(responseCode = "500", description = "invalid JSON posted", @ApiResponses(value = {
content = @Content) @ApiResponse(responseCode = "500", description = "invalid JSON posted",
}) content = @Content)
public class GlobalExceptionHandler { })
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> handleHelloEntityNotFoundException(ResourceNotFoundException ex, WebRequest request) { @ExceptionHandler(ResourceNotFoundException.class)
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false)); public ResponseEntity<ErrorDetails> handleHelloEntityNotFoundException(ResourceNotFoundException ex, WebRequest request) {
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND); ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
} return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorDetails> handleAllOtherExceptions(Exception ex, WebRequest request) { @ExceptionHandler(Exception.class)
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getClass() + " " + ex.getMessage(), request.getDescription(false)); public ResponseEntity<ErrorDetails> handleAllOtherExceptions(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getClass() + " " + ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
} return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorDetails> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, WebRequest request) { @ExceptionHandler(MethodArgumentNotValidException.class)
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false)); public ResponseEntity<ErrorDetails> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
} return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<ErrorDetails> handleConstraintViolationException(ConstraintViolationException ex, WebRequest request) { @ExceptionHandler(HttpMessageNotReadableException.class)
String errorMessage = ex.getConstraintViolations().stream().findFirst().get().getMessage(); public ResponseEntity<ErrorDetails> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
ErrorDetails errorDetails = new ErrorDetails(new Date(), errorMessage, request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST); }
}
} @ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<ErrorDetails> handleConstraintViolationException(ConstraintViolationException ex, WebRequest request) {
String errorMessage = ex.getConstraintViolations().stream().findFirst().get().getMessage();
ErrorDetails errorDetails = new ErrorDetails(new Date(), errorMessage, request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
}
}

@ -1,99 +1,62 @@
package de.szut.lf8_starter.hello; package de.szut.lf8_starter.hello;
import de.szut.lf8_starter.exceptionHandling.ResourceNotFoundException; import de.szut.lf8_starter.exceptionHandling.ResourceNotFoundException;
import de.szut.lf8_starter.hello.dto.HelloCreateDto; import de.szut.lf8_starter.hello.dto.HelloCreateDto;
import de.szut.lf8_starter.hello.dto.HelloGetDto; import de.szut.lf8_starter.hello.dto.HelloGetDto;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; @RestController
import java.util.stream.Collectors; @RequestMapping(value = "hello")
@PreAuthorize("hasAnyAuthority('user')")
@RestController public class HelloController {
@RequestMapping(value = "hello") private final HelloService service;
@PreAuthorize("hasAnyAuthority('user')") private final HelloMapper helloMapper;
public class HelloController {
private final HelloService service; public HelloController(HelloService service, HelloMapper mappingService) {
private final HelloMapper helloMapper; this.service = service;
this.helloMapper = mappingService;
public HelloController(HelloService service, HelloMapper mappingService) { }
this.service = service;
this.helloMapper = mappingService; @Operation(summary = "creates a new hello with its id and message")
} @ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "created hello",
@Operation(summary = "creates a new hello with its id and message") content = {@Content(mediaType = "application/json",
@ApiResponses(value = { schema = @Schema(implementation = HelloGetDto.class))}),
@ApiResponse(responseCode = "201", description = "created hello", @ApiResponse(responseCode = "400", description = "invalid JSON posted",
content = {@Content(mediaType = "application/json", content = @Content),
schema = @Schema(implementation = HelloGetDto.class))}), @ApiResponse(responseCode = "401", description = "not authorized",
@ApiResponse(responseCode = "400", description = "invalid JSON posted", content = @Content)})
content = @Content), @PostMapping
@ApiResponse(responseCode = "401", description = "not authorized", public HelloGetDto create(@RequestBody @Valid HelloCreateDto helloCreateDto) {
content = @Content)}) HelloEntity helloEntity = this.helloMapper.mapCreateDtoToEntity(helloCreateDto);
@PostMapping helloEntity = this.service.create(helloEntity);
public HelloGetDto create(@RequestBody @Valid HelloCreateDto helloCreateDto) { return this.helloMapper.mapToGetDto(helloEntity);
HelloEntity helloEntity = this.helloMapper.mapCreateDtoToEntity(helloCreateDto); }
helloEntity = this.service.create(helloEntity);
return this.helloMapper.mapToGetDto(helloEntity); @Operation(summary = "deletes a Hello by id")
} @ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "delete successful"),
@Operation(summary = "delivers a list of hellos") @ApiResponse(responseCode = "401", description = "not authorized",
@ApiResponses(value = { content = @Content),
@ApiResponse(responseCode = "200", description = "list of hellos", @ApiResponse(responseCode = "404", description = "resource not found",
content = {@Content(mediaType = "application/json", content = @Content)})
schema = @Schema(implementation = HelloGetDto.class))}), @DeleteMapping("/{id}")
@ApiResponse(responseCode = "401", description = "not authorized", @ResponseStatus(code = HttpStatus.NO_CONTENT)
content = @Content)}) public void deleteHelloById(@PathVariable long id) {
@GetMapping var entity = this.service.readById(id);
public List<HelloGetDto> findAll() { if (entity == null) {
return this.service throw new ResourceNotFoundException("HelloEntity not found on id = " + id);
.readAll() } else {
.stream() this.service.delete(entity);
.map(e -> this.helloMapper.mapToGetDto(e)) }
.collect(Collectors.toList()); }
} }
@Operation(summary = "deletes a Hello by id")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "delete successful"),
@ApiResponse(responseCode = "401", description = "not authorized",
content = @Content),
@ApiResponse(responseCode = "404", description = "resource not found",
content = @Content)})
@DeleteMapping("/{id}")
@ResponseStatus(code = HttpStatus.NO_CONTENT)
public void deleteHelloById(@PathVariable long id) {
var entity = this.service.readById(id);
if (entity == null) {
throw new ResourceNotFoundException("HelloEntity not found on id = " + id);
} else {
this.service.delete(entity);
}
}
@Operation(summary = "find hellos by message")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "List of hellos who have the given message",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = HelloGetDto.class))}),
@ApiResponse(responseCode = "404", description = "qualification description does not exist",
content = @Content),
@ApiResponse(responseCode = "401", description = "not authorized",
content = @Content)})
@GetMapping("/findByMessage")
public List<HelloGetDto> findAllEmployeesByQualification(@RequestParam String message) {
return this.service
.findByMessage(message)
.stream()
.map(e -> this.helloMapper.mapToGetDto(e))
.collect(Collectors.toList());
}
}

@ -1,27 +1,27 @@
package de.szut.lf8_starter.hello; package de.szut.lf8_starter.hello;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Getter @Getter
@Setter @Setter
@Entity @Entity
@Table(name = "hello") @Table(name = "hello")
public class HelloEntity { public class HelloEntity {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private long id; private long id;
private String message; private String message;
public HelloEntity(String message) { public HelloEntity(String message) {
this.message = message; this.message = message;
} }
} }

@ -1,20 +1,20 @@
package de.szut.lf8_starter.hello; package de.szut.lf8_starter.hello;
import de.szut.lf8_starter.hello.dto.HelloCreateDto; import de.szut.lf8_starter.hello.dto.HelloCreateDto;
import de.szut.lf8_starter.hello.dto.HelloGetDto; import de.szut.lf8_starter.hello.dto.HelloGetDto;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class HelloMapper { public class HelloMapper {
public HelloGetDto mapToGetDto(HelloEntity entity) { public HelloGetDto mapToGetDto(HelloEntity entity) {
return new HelloGetDto(entity.getId(), entity.getMessage()); return new HelloGetDto(entity.getId(), entity.getMessage());
} }
public HelloEntity mapCreateDtoToEntity(HelloCreateDto dto) { public HelloEntity mapCreateDtoToEntity(HelloCreateDto dto) {
var entity = new HelloEntity(); var entity = new HelloEntity();
entity.setMessage(dto.getMessage()); entity.setMessage(dto.getMessage());
return entity; return entity;
} }
} }

@ -1,12 +1,12 @@
package de.szut.lf8_starter.hello; package de.szut.lf8_starter.hello;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List; import java.util.List;
public interface HelloRepository extends JpaRepository<HelloEntity, Long> { public interface HelloRepository extends JpaRepository<HelloEntity, Long> {
List<HelloEntity> findByMessage(String message); List<HelloEntity> findByMessage(String message);
} }

@ -1,40 +1,40 @@
package de.szut.lf8_starter.hello; package de.szut.lf8_starter.hello;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@Service @Service
public class HelloService { public class HelloService {
private final HelloRepository repository; private final HelloRepository repository;
public HelloService(HelloRepository repository) { public HelloService(HelloRepository repository) {
this.repository = repository; this.repository = repository;
} }
public HelloEntity create(HelloEntity entity) { public HelloEntity create(HelloEntity entity) {
return this.repository.save(entity); return this.repository.save(entity);
} }
public List<HelloEntity> readAll() { public List<HelloEntity> readAll() {
return this.repository.findAll(); return this.repository.findAll();
} }
public HelloEntity readById(long id) { public HelloEntity readById(long id) {
Optional<HelloEntity> optionalQualification = this.repository.findById(id); Optional<HelloEntity> optionalQualification = this.repository.findById(id);
if (optionalQualification.isEmpty()) { if (optionalQualification.isEmpty()) {
return null; return null;
} }
return optionalQualification.get(); return optionalQualification.get();
} }
public void delete(HelloEntity entity) { public void delete(HelloEntity entity) {
this.repository.delete(entity); this.repository.delete(entity);
} }
public List<HelloEntity> findByMessage(String message) { public List<HelloEntity> findByMessage(String message) {
return this.repository.findByMessage(message); return this.repository.findByMessage(message);
} }
} }

@ -1,20 +1,20 @@
package de.szut.lf8_starter.hello.dto; package de.szut.lf8_starter.hello.dto;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@Getter @Getter
@Setter @Setter
public class HelloCreateDto { public class HelloCreateDto {
@Size(min = 3, message = "at least length of 3") @Size(min = 3, message = "at least length of 3")
private String message; private String message;
@JsonCreator @JsonCreator
public HelloCreateDto(String message) { public HelloCreateDto(String message) {
this.message = message; this.message = message;
} }
} }

@ -1,17 +1,17 @@
package de.szut.lf8_starter.hello.dto; package de.szut.lf8_starter.hello.dto;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@AllArgsConstructor @AllArgsConstructor
@Getter @Getter
@Setter @Setter
public class HelloGetDto { public class HelloGetDto {
private long id; private long id;
private String message; private String message;
} }

@ -1,39 +0,0 @@
package de.szut.lf8_starter.project;
import de.szut.lf8_starter.project.dto.CreateProjectDto;
import de.szut.lf8_starter.project.dto.GetProjectDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/projects")
public class CreateProjectAction {
private final ProjectService projectService;
private final ProjectMapper projectMapper;
public CreateProjectAction(ProjectService projectService, ProjectMapper mappingService) {
this.projectService = projectService;
this.projectMapper = mappingService;
}
@Operation(summary = "Creates a new Project")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "created project", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = GetProjectDto.class))}),
@ApiResponse(responseCode = "400", description = "invalid JSON posted", content = @Content),
@ApiResponse(responseCode = "401", description = "not authorized", content = @Content)})
@PostMapping
@ResponseStatus(code = HttpStatus.CREATED)
public GetProjectDto create(@RequestBody @Valid CreateProjectDto createProjectDto) {
ProjectEntity projectEntity = this.projectMapper.mapCreateDtoToEntity(createProjectDto);
projectEntity = this.projectService.create(projectEntity);
return this.projectMapper.mapToGetDto(projectEntity);
}
}

@ -25,7 +25,7 @@ public class ProjectEntity {
private long leadingEmployee; private long leadingEmployee;
@ElementCollection @ElementCollection(fetch = FetchType.EAGER)
private List<Long> employees; private List<Long> employees;
private long contractor; private long contractor;

@ -1,41 +0,0 @@
package de.szut.lf8_starter.project;
import de.szut.lf8_starter.project.dto.CreateProjectDto;
import de.szut.lf8_starter.project.dto.GetProjectDto;
import org.springframework.stereotype.Service;
@Service
public class ProjectMapper {
public ProjectEntity mapCreateDtoToEntity(CreateProjectDto createProjectDto) {
ProjectEntity projectEntity = new ProjectEntity();
projectEntity.setName(createProjectDto.getName());
projectEntity.setComment(createProjectDto.getComment());
projectEntity.setLeadingEmployee(createProjectDto.getLeadingEmployee());
projectEntity.setEmployees(createProjectDto.getEmployees());
projectEntity.setContractor(createProjectDto.getContractor());
projectEntity.setContractorName(createProjectDto.getContractorName());
projectEntity.setStartDate(createProjectDto.getStartDate());
projectEntity.setPlannedEndDate(createProjectDto.getPlannedEndDate());
projectEntity.setEndDate(createProjectDto.getEndDate());
return projectEntity;
}
public GetProjectDto mapToGetDto(ProjectEntity projectEntity) {
GetProjectDto getProjectDto = new GetProjectDto();
getProjectDto.setId(projectEntity.getId());
getProjectDto.setName(projectEntity.getName());
getProjectDto.setComment(projectEntity.getComment());
getProjectDto.setLeadingEmployee(projectEntity.getLeadingEmployee());
getProjectDto.setEmployees(projectEntity.getEmployees());
getProjectDto.setContractor(projectEntity.getContractor());
getProjectDto.setContractorName(projectEntity.getContractorName());
getProjectDto.setStartDate(projectEntity.getStartDate());
getProjectDto.setPlannedEndDate(projectEntity.getPlannedEndDate());
getProjectDto.setEndDate(projectEntity.getEndDate());
return getProjectDto;
}
}

@ -1,8 +1,14 @@
package de.szut.lf8_starter.project; package de.szut.lf8_starter.project;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.ArrayList;
@Repository @Repository
public interface ProjectRepository extends JpaRepository<ProjectEntity, Long> { public interface ProjectRepository extends JpaRepository<ProjectEntity, Long> {
@Query("SELECT p FROM ProjectEntity p WHERE :employeeId MEMBER OF p.employees")
ArrayList<ProjectEntity> findAllByEmployeeId(@Param("employeeId") Long employeeId);
} }

@ -1,22 +1,50 @@
package de.szut.lf8_starter.project; package de.szut.lf8_starter.project;
import org.springframework.stereotype.Service; import de.szut.lf8_starter.project.dto.project.GetProjectDto;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.List;
@Service import java.util.Optional;
public class ProjectService {
private final ProjectRepository projectRepository; @Service
public class ProjectService {
public ProjectService(ProjectRepository projectRepository) { private final ProjectRepository projectRepository;
this.projectRepository = projectRepository;
} public ProjectService(ProjectRepository projectRepository) {
this.projectRepository = projectRepository;
public ProjectEntity create(ProjectEntity projectEntity) { }
return this.projectRepository.save(projectEntity);
} public ProjectEntity create(ProjectEntity projectEntity) {
return this.projectRepository.save(projectEntity);
public List<ProjectEntity> readAll() { }
return this.projectRepository.findAll();
} public List<ProjectEntity> readAll() {
} return this.projectRepository.findAll();
}
public Optional<ProjectEntity> findById(Long id) {
return projectRepository.findById(id);
}
public void update(ProjectEntity project) {
this.projectRepository.save(project);
}
public void delete(Long id) {
this.projectRepository.deleteById(id);
}
public boolean isOverlapping(GetProjectDto getProjectDto, ProjectEntity existingProjectEntity) {
return isDateRangeOverlapping(getProjectDto, existingProjectEntity) || isDateEqual(getProjectDto, existingProjectEntity);
}
private boolean isDateRangeOverlapping(GetProjectDto getProjectDto, ProjectEntity existingProjectEntity) {
return getProjectDto.getStartDate().isBefore(existingProjectEntity.getPlannedEndDate())
&& getProjectDto.getPlannedEndDate().isAfter(existingProjectEntity.getStartDate());
}
private boolean isDateEqual(GetProjectDto getProjectDto, ProjectEntity existingProjectEntity) {
return getProjectDto.getStartDate().isEqual(existingProjectEntity.getStartDate())
|| getProjectDto.getPlannedEndDate().isEqual(existingProjectEntity.getPlannedEndDate());
}
}

@ -0,0 +1,63 @@
package de.szut.lf8_starter.project.action.crud;
import de.szut.lf8_starter.employee.EmployeeService;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectService;
import de.szut.lf8_starter.project.dto.project.CreateProjectDto;
import de.szut.lf8_starter.project.dto.project.GetProjectDto;
import de.szut.lf8_starter.project.mapper.ProjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/projects")
public class CreateProjectAction {
private final EmployeeService employeeService;
private final ProjectService projectService;
private final ProjectMapper projectMapper;
public CreateProjectAction(EmployeeService employeeService, ProjectService projectService, ProjectMapper mappingService) {
this.employeeService = employeeService;
this.projectService = projectService;
this.projectMapper = mappingService;
}
@Operation(summary = "Creates a new Project")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "created project", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = GetProjectDto.class))}),
@ApiResponse(responseCode = "400", description = "invalid JSON posted", content = @Content),
@ApiResponse(responseCode = "401", description = "not authorized", content = @Content),
@ApiResponse(responseCode = "409", description = "Project dates conflict", content = @Content)
})
@PostMapping
@ResponseStatus(code = HttpStatus.CREATED)
public ResponseEntity<Object> create(
@RequestBody @Valid CreateProjectDto createProjectDto,
@RequestHeader("Authorization") String accessToken
) {
ProjectEntity project = this.projectMapper.mapCreateDtoToEntity(createProjectDto);
for (Long employeeId : createProjectDto.getEmployees()) {
if (!this.employeeService.employeeExists(accessToken, employeeId)) {
return new ResponseEntity<>("Employee with ID: " + employeeId + " not found", HttpStatus.NOT_FOUND);
}
for (GetProjectDto getProjectDto : this.employeeService.getProjects(employeeId)) {
if (projectService.isOverlapping(getProjectDto, project)) {
return new ResponseEntity<>("Project dates conflict with an existing project for Employee with ID: " + employeeId, HttpStatus.CONFLICT);
}
}
}
this.projectService.create(project);
return new ResponseEntity<>(this.projectMapper.mapToGetDto(project), HttpStatus.CREATED);
}
}

@ -1,32 +1,36 @@
package de.szut.lf8_starter.project; package de.szut.lf8_starter.project.action.crud;
import de.szut.lf8_starter.project.dto.GetProjectDto; import de.szut.lf8_starter.project.ProjectService;
import de.szut.lf8_starter.project.dto.project.GetProjectDto;
import de.szut.lf8_starter.project.mapper.ProjectMapper;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping(value = "projects") @RequestMapping(value = "projects")
public class ProjectController { public class GetAllProjectsAction {
private final ProjectService service; private final ProjectService service;
private final ProjectMapper projectMapper; private final ProjectMapper projectMapper;
public ProjectController(ProjectService service, ProjectMapper projectMapper) {
public GetAllProjectsAction(ProjectService service, ProjectMapper projectMapper) {
this.service = service; this.service = service;
this.projectMapper = projectMapper; this.projectMapper = projectMapper;
} }
@Operation(summary = "returns all projects") @Operation(summary = "returns all projects")
@ApiResponses(value = { @ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "all projects", @ApiResponse(responseCode = "200", description = "all projects", content = {
content = {@Content(mediaType = "application/json", @Content(mediaType = "application/json", schema = @Schema(implementation = GetProjectDto.class))
schema = @Schema(implementation = GetProjectDto.class))}), }),
@ApiResponse(responseCode = "401", description = "not authorized", @ApiResponse(responseCode = "401", description = "not authorized", content = @Content)})
content = @Content)})
@GetMapping @GetMapping
public List<GetProjectDto> findAll() { public List<GetProjectDto> findAll() {
return this.service return this.service

@ -0,0 +1,49 @@
package de.szut.lf8_starter.project.action.crud;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectService;
import de.szut.lf8_starter.project.dto.project.GetProjectDto;
import de.szut.lf8_starter.project.mapper.ProjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
@RequestMapping(value = "projects")
public class GetProjectAction {
private final ProjectService projectService;
private final ProjectMapper projectMapper;
public GetProjectAction(ProjectService projectService, ProjectMapper projectMapper) {
this.projectService = projectService;
this.projectMapper = projectMapper;
}
@Operation(summary = "Find project by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Project found", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = GetProjectDto.class))
}),
@ApiResponse(responseCode = "404", description = "Project not found", content = @Content)
})
@GetMapping("/{id}")
public ResponseEntity<GetProjectDto> findArticleById(@PathVariable Long id) {
Optional<ProjectEntity> project = this.projectService.findById(id);
if (project.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(this.projectMapper.mapToGetDto(project.get()), HttpStatus.OK);
}
}

@ -0,0 +1,43 @@
package de.szut.lf8_starter.project.action.crud;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectService;
import de.szut.lf8_starter.project.dto.project.GetProjectDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
@RequestMapping(value = "projects")
public class RemoveProjectAction {
private final ProjectService projectService;
public RemoveProjectAction(ProjectService projectService) {
this.projectService = projectService;
}
@Operation(summary = "Remove project by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "Project deleted", content = {}),
@ApiResponse(responseCode = "404", description = "Project not found", content = @Content)
})
@DeleteMapping("/{id}")
public ResponseEntity<GetProjectDto> findArticleById(@PathVariable Long id) {
Optional<ProjectEntity> project = this.projectService.findById(id);
if (project.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
this.projectService.delete(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}

@ -0,0 +1,50 @@
package de.szut.lf8_starter.project.action.crud;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectService;
import de.szut.lf8_starter.project.dto.project.GetProjectDto;
import de.szut.lf8_starter.project.dto.project.UpdateProjectDto;
import de.szut.lf8_starter.project.mapper.ProjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@RequestMapping(value = "/projects")
public class UpdateProjectAction {
private final ProjectService projectService;
private final ProjectMapper projectMapper;
public UpdateProjectAction(ProjectService projectService, ProjectMapper mappingService) {
this.projectService = projectService;
this.projectMapper = mappingService;
}
@Operation(summary = "Update a project by ID")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Project updated successfully",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = GetProjectDto.class))),
@ApiResponse(responseCode = "404", description = "Project not found", content = @Content)
})
@PutMapping("/{id}")
public ResponseEntity<GetProjectDto> updateSupplier(@PathVariable Long id, @Valid @RequestBody UpdateProjectDto updateProjectDto) {
Optional<ProjectEntity> project = this.projectService.findById(id);
if (project.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
ProjectEntity updatedProject = this.projectMapper.mapUpdateDtoToEntity(updateProjectDto, project.get());
this.projectService.update(updatedProject);
return new ResponseEntity<>(this.projectMapper.mapToGetDto(updatedProject), HttpStatus.OK);
}
}

@ -0,0 +1,65 @@
package de.szut.lf8_starter.project.action.employee;
import de.szut.lf8_starter.employee.EmployeeService;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectService;
import de.szut.lf8_starter.project.dto.project.GetProjectDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
public class AddEmployeeToProjectAction {
private final ProjectService projectService;
private final EmployeeService employeeService;
public AddEmployeeToProjectAction(ProjectService projectService, EmployeeService employeeService) {
this.projectService = projectService;
this.employeeService = employeeService;
}
@Operation(summary = "Add an employee to a project")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "Employee added to project"),
@ApiResponse(responseCode = "404", description = "Project or employee not found", content = @Content),
@ApiResponse(responseCode = "409", description = "Project dates conflict", content = @Content)
})
@PostMapping("/projects/{projectId}/employees/{employeeId}")
public ResponseEntity<Object> create(
@PathVariable Long projectId,
@PathVariable Long employeeId,
@RequestHeader("Authorization") String accessToken
) {
Optional<ProjectEntity> optionalProject = this.projectService.findById(projectId);
if (optionalProject.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
ProjectEntity projectEntity = optionalProject.get();
if (!this.employeeService.employeeExists(accessToken, employeeId)) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
for (GetProjectDto getProjectDto : this.employeeService.getProjects(employeeId)) {
if (this.projectService.isOverlapping(getProjectDto, projectEntity)) {
return new ResponseEntity<>("Project dates conflict with an existing project for Employee with ID: " + employeeId, HttpStatus.CONFLICT);
}
}
projectEntity.getEmployees().add(employeeId);
this.projectService.update(projectEntity);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}

@ -0,0 +1,51 @@
package de.szut.lf8_starter.project.action.employee;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectService;
import de.szut.lf8_starter.project.dto.employee.GetEmployeesFromProjectDto;
import de.szut.lf8_starter.project.mapper.EmployeeFromProjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
public class GetEmployeeFromProjectAction {
private final ProjectService projectService;
private final EmployeeFromProjectMapper employeeFromProjectMapper;
public GetEmployeeFromProjectAction(ProjectService projectService, EmployeeFromProjectMapper employeeFromProjectMapper) {
this.projectService = projectService;
this.employeeFromProjectMapper = employeeFromProjectMapper;
}
@Operation(summary = "Get all employees from project")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Outputs projects with employees"),
@ApiResponse(responseCode = "404", description = "Project not found", content = @Content)
})
@GetMapping("/projects/{projectId}/employees")
public ResponseEntity<Object> create(
@PathVariable Long projectId,
@RequestHeader("Authorization") String accessToken
) {
Optional<ProjectEntity> project = projectService.findById(projectId);
if (project.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
GetEmployeesFromProjectDto getEmployeesFromProjectDto = this.employeeFromProjectMapper
.mapToGetEmployeesFromProjectDto(project.get(), accessToken);
return new ResponseEntity<>(getEmployeesFromProjectDto, HttpStatus.OK);
}
}

@ -0,0 +1,39 @@
package de.szut.lf8_starter.project.action.employee;
import de.szut.lf8_starter.employee.EmployeeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GetProjectsFromEmployee {
private final EmployeeService employeeService;
public GetProjectsFromEmployee(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@Operation(summary = "Get all projects from employee")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Get all projects from employee", content = @Content),
@ApiResponse(responseCode = "404", description = "Employee not found", content = @Content)
})
@GetMapping("/employees/{employeeId}/projects")
public ResponseEntity<Object> create(
@PathVariable Long employeeId,
@RequestHeader("Authorization") String accessToken
) {
if (!this.employeeService.employeeExists(accessToken, employeeId)) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(this.employeeService.getProjects(employeeId), HttpStatus.OK);
}
}

@ -0,0 +1,52 @@
package de.szut.lf8_starter.project.action.employee;
import de.szut.lf8_starter.employee.EmployeeService;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
public class RemoveEmployeeFromProjectAction {
private final ProjectService projectService;
private final EmployeeService employeeService;
public RemoveEmployeeFromProjectAction(ProjectService projectService, EmployeeService employeeService) {
this.projectService = projectService;
this.employeeService = employeeService;
}
@Operation(summary = "Remove an employee from a project")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "Employee removed from project"),
@ApiResponse(responseCode = "404", description = "Project or employee not found", content = @Content)
})
@DeleteMapping("/projects/{projectId}/employees/{employeeId}")
public ResponseEntity<Object> remove(
@PathVariable Long projectId,
@PathVariable Long employeeId,
@RequestHeader("Authorization") String accessToken
) {
Optional<ProjectEntity> project = this.projectService.findById(projectId);
if (project.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
if (!this.employeeService.employeeExists(accessToken, employeeId)) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
project.get().getEmployees().remove(employeeId);
this.projectService.update(project.get());
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}

@ -0,0 +1,22 @@
package de.szut.lf8_starter.project.dto.employee;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class EmployeeDto {
private long id;
private String firstName;
private String lastName;
private String street;
private String postcode;
private String city;
private String phone;
private List<String> skillSet;
}

@ -0,0 +1,11 @@
package de.szut.lf8_starter.project.dto.employee;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class GetEmployeeDto {
private long id;
private GetSkillDto[] skillSet;
}

@ -0,0 +1,17 @@
package de.szut.lf8_starter.project.dto.employee;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
@Getter
@Setter
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class GetEmployeesFromProjectDto {
private long projectId;
private String projectDescription;
private ArrayList<GetEmployeeDto> employees;
}

@ -0,0 +1,13 @@
package de.szut.lf8_starter.project.dto.employee;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class GetSkillDto {
private String skill;
}

@ -1,4 +1,4 @@
package de.szut.lf8_starter.project.dto; package de.szut.lf8_starter.project.dto.project;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.PropertyNamingStrategies;

@ -1,10 +1,8 @@
package de.szut.lf8_starter.project.dto; package de.szut.lf8_starter.project.dto.project;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming; import com.fasterxml.jackson.databind.annotation.JsonNaming;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;

@ -0,0 +1,36 @@
package de.szut.lf8_starter.project.dto.project;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDate;
import java.util.List;
@Getter
@Setter
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class UpdateProjectDto {
private String name;
private Long leadingEmployee;
private List<Long> employees;
private Long contractor;
private String contractorName;
private String comment;
@JsonFormat(pattern = "dd.MM.yyyy")
private LocalDate startDate;
@JsonFormat(pattern = "dd.MM.yyyy")
private LocalDate plannedEndDate;
@JsonFormat(pattern = "dd.MM.yyyy")
private LocalDate endDate;
}

@ -0,0 +1,35 @@
package de.szut.lf8_starter.project.mapper;
import de.szut.lf8_starter.employee.EmployeeService;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.dto.employee.GetEmployeeDto;
import de.szut.lf8_starter.project.dto.employee.GetEmployeesFromProjectDto;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@Service
public class EmployeeFromProjectMapper {
private final EmployeeService employeeService;
public EmployeeFromProjectMapper(EmployeeService employeeService) {
this.employeeService = employeeService;
}
public GetEmployeesFromProjectDto mapToGetEmployeesFromProjectDto(ProjectEntity projectEntity, String accessToken) {
GetEmployeesFromProjectDto getEmployeesFromProjectDto = new GetEmployeesFromProjectDto();
getEmployeesFromProjectDto.setProjectId(projectEntity.getId());
getEmployeesFromProjectDto.setProjectDescription(projectEntity.getComment());
ArrayList<GetEmployeeDto> employeeDtos = new ArrayList<>();
for (long id : projectEntity.getEmployees()) {
GetEmployeeDto getEmployeeDto = this.employeeService.getEmployee(accessToken, id);
employeeDtos.add(getEmployeeDto);
}
getEmployeesFromProjectDto.setEmployees(employeeDtos);
return getEmployeesFromProjectDto;
}
}

@ -0,0 +1,62 @@
package de.szut.lf8_starter.project.mapper;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.dto.project.CreateProjectDto;
import de.szut.lf8_starter.project.dto.project.GetProjectDto;
import de.szut.lf8_starter.project.dto.project.UpdateProjectDto;
import org.springframework.stereotype.Service;
@Service
public class ProjectMapper {
public ProjectEntity mapCreateDtoToEntity(CreateProjectDto createProjectDto) {
ProjectEntity projectEntity = new ProjectEntity();
projectEntity.setName(createProjectDto.getName());
projectEntity.setComment(createProjectDto.getComment());
projectEntity.setLeadingEmployee(createProjectDto.getLeadingEmployee());
projectEntity.setEmployees(createProjectDto.getEmployees());
projectEntity.setContractor(createProjectDto.getContractor());
projectEntity.setContractorName(createProjectDto.getContractorName());
projectEntity.setStartDate(createProjectDto.getStartDate());
projectEntity.setPlannedEndDate(createProjectDto.getPlannedEndDate());
projectEntity.setEndDate(createProjectDto.getEndDate());
return projectEntity;
}
public GetProjectDto mapToGetDto(ProjectEntity projectEntity) {
GetProjectDto getProjectDto = new GetProjectDto();
getProjectDto.setId(projectEntity.getId());
getProjectDto.setName(projectEntity.getName());
getProjectDto.setComment(projectEntity.getComment());
getProjectDto.setLeadingEmployee(projectEntity.getLeadingEmployee());
getProjectDto.setEmployees(projectEntity.getEmployees());
getProjectDto.setContractor(projectEntity.getContractor());
getProjectDto.setContractorName(projectEntity.getContractorName());
getProjectDto.setStartDate(projectEntity.getStartDate());
getProjectDto.setPlannedEndDate(projectEntity.getPlannedEndDate());
getProjectDto.setEndDate(projectEntity.getEndDate());
return getProjectDto;
}
public ProjectEntity mapUpdateDtoToEntity(UpdateProjectDto updateProjectDto, ProjectEntity projectEntity) {
projectEntity.setName(updateProjectDto.getName() != null ? updateProjectDto.getName() : projectEntity.getName());
projectEntity.setLeadingEmployee(updateProjectDto.getLeadingEmployee() != null ? updateProjectDto.getLeadingEmployee() : projectEntity.getLeadingEmployee());
projectEntity.setContractor(updateProjectDto.getContractor() != null ? updateProjectDto.getContractor() : projectEntity.getContractor());
projectEntity.setContractorName(updateProjectDto.getContractorName() != null ? updateProjectDto.getContractorName() : projectEntity.getContractorName());
projectEntity.setComment(updateProjectDto.getComment() != null ? updateProjectDto.getComment() : projectEntity.getComment());
projectEntity.setStartDate(updateProjectDto.getStartDate() != null ? updateProjectDto.getStartDate() : projectEntity.getStartDate());
projectEntity.setPlannedEndDate(updateProjectDto.getPlannedEndDate() != null ? updateProjectDto.getPlannedEndDate() : projectEntity.getPlannedEndDate());
projectEntity.setEndDate(updateProjectDto.getEndDate() != null ? updateProjectDto.getEndDate() : projectEntity.getEndDate());
if (updateProjectDto.getEmployees() != null) {
projectEntity.getEmployees().clear();
projectEntity.setEmployees(updateProjectDto.getEmployees());
}
return projectEntity;
}
}

@ -1,49 +1,49 @@
package de.szut.lf8_starter.security; package de.szut.lf8_starter.security;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.oidc.user.OidcUser; import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
@Slf4j @Slf4j
@Component @Component
public class KeycloakLogoutHandler implements LogoutHandler { public class KeycloakLogoutHandler implements LogoutHandler {
private final RestTemplate restTemplate; private final RestTemplate restTemplate;
public KeycloakLogoutHandler(RestTemplate restTemplate) { public KeycloakLogoutHandler(RestTemplate restTemplate) {
this.restTemplate = restTemplate; this.restTemplate = restTemplate;
} }
@Override @Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication auth) { public void logout(HttpServletRequest request, HttpServletResponse response, Authentication auth) {
logout(request, auth); logout(auth);
} }
public void logout(HttpServletRequest request, Authentication auth) { public void logout(Authentication auth) {
logoutFromKeycloak((OidcUser) auth.getPrincipal()); logoutFromKeycloak((OidcUser) auth.getPrincipal());
} }
private void logoutFromKeycloak(OidcUser user) { private void logoutFromKeycloak(OidcUser user) {
String endSessionEndpoint = user.getIssuer() + "/protocol/openid-connect/logout"; String endSessionEndpoint = user.getIssuer() + "/protocol/openid-connect/logout";
UriComponentsBuilder builder = UriComponentsBuilder UriComponentsBuilder builder = UriComponentsBuilder
.fromUriString(endSessionEndpoint) .fromUriString(endSessionEndpoint)
.queryParam("id_token_hint", user.getIdToken().getTokenValue()); .queryParam("id_token_hint", user.getIdToken().getTokenValue());
ResponseEntity<String> logoutResponse = restTemplate.getForEntity(builder.toUriString(), String.class); ResponseEntity<String> logoutResponse = restTemplate.getForEntity(builder.toUriString(), String.class);
if (logoutResponse.getStatusCode().is2xxSuccessful()) { if (logoutResponse.getStatusCode().is2xxSuccessful()) {
log.info("Successfulley logged out from Keycloak"); log.info("Successfulley logged out from Keycloak");
} else { } else {
log.error("Could not propagate logout to Keycloak"); log.error("Could not propagate logout to Keycloak");
} }
} }
} }

@ -1,98 +1,87 @@
package de.szut.lf8_starter.security; package de.szut.lf8_starter.security;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Configuration; import org.springframework.security.config.Customizer;
import org.springframework.context.annotation.Profile; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.Customizer; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper; import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.core.session.SessionRegistry; import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.core.session.SessionRegistryImpl; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority; import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority; import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; @Configuration
import org.springframework.security.web.SecurityFilterChain; @EnableWebSecurity
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy; class KeycloakSecurityConfig {
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.session.HttpSessionEventPublisher; private static final String REALM_ACCESS_CLAIM = "realm_access";
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; private static final String ROLES_CLAIM = "roles";
@Configuration KeycloakSecurityConfig() {
@EnableWebSecurity }
class KeycloakSecurityConfig {
@Bean
private static final String GROUPS = "groups"; public SessionRegistry sessionRegistry() {
private static final String REALM_ACCESS_CLAIM = "realm_access"; return new SessionRegistryImpl();
private static final String ROLES_CLAIM = "roles"; }
private final KeycloakLogoutHandler keycloakLogoutHandler; @Bean
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
KeycloakSecurityConfig(KeycloakLogoutHandler keycloakLogoutHandler) { return new RegisterSessionAuthenticationStrategy(sessionRegistry());
this.keycloakLogoutHandler = keycloakLogoutHandler; }
}
@Bean
@Bean public HttpSessionEventPublisher httpSessionEventPublisher() {
public SessionRegistry sessionRegistry() { return new HttpSessionEventPublisher();
return new SessionRegistryImpl(); }
}
@Bean @Bean
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { public SecurityFilterChain resourceServerFilterChain(HttpSecurity http) throws Exception {
return new RegisterSessionAuthenticationStrategy(sessionRegistry());
} http.authorizeHttpRequests(auth -> auth
.requestMatchers(new AntPathRequestMatcher("/welcome"))
@Bean .permitAll()
public HttpSessionEventPublisher httpSessionEventPublisher() { .requestMatchers(
return new HttpSessionEventPublisher(); new AntPathRequestMatcher("/swagger"),
} new AntPathRequestMatcher("/swagger-ui/**"),
new AntPathRequestMatcher("/v3/api-docs/**"))
.permitAll()
@Bean .requestMatchers(new AntPathRequestMatcher("/hello/**"))
public SecurityFilterChain resourceServerFilterChain(HttpSecurity http) throws Exception { .hasRole("user")
.requestMatchers(new AntPathRequestMatcher("/roles"))
http.authorizeHttpRequests(auth -> auth .authenticated()
.requestMatchers(new AntPathRequestMatcher("/welcome")) .requestMatchers(new AntPathRequestMatcher("/"))
.permitAll() .permitAll()
.requestMatchers( .anyRequest()
new AntPathRequestMatcher("/swagger"), .authenticated()).oauth2ResourceServer(spec -> spec.jwt(Customizer.withDefaults()));
new AntPathRequestMatcher("/swagger-ui/**"), return http.build();
new AntPathRequestMatcher("/v3/api-docs/**")) }
.permitAll()
.requestMatchers(new AntPathRequestMatcher("/hello/**")) @Bean
.hasRole("user") public JwtAuthenticationConverter jwtAuthenticationConverter() {
.requestMatchers(new AntPathRequestMatcher("/roles")) JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
.authenticated() jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwt -> {
.requestMatchers(new AntPathRequestMatcher("/")) List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
.permitAll()
.anyRequest() Map<String, Object> realmAccess = jwt.getClaim(REALM_ACCESS_CLAIM);
.authenticated()).oauth2ResourceServer(spec -> spec.jwt(Customizer.withDefaults())); if (realmAccess != null && realmAccess.containsKey(ROLES_CLAIM)) {
return http.build(); List<String> roles = (List<String>) realmAccess.get(ROLES_CLAIM);
} for (String role : roles) {
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role));
@Bean }
public JwtAuthenticationConverter jwtAuthenticationConverter() { }
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwt -> { return grantedAuthorities;
List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); });
return jwtAuthenticationConverter;
Map<String, Object> realmAccess = jwt.getClaim("realm_access"); }
if (realmAccess != null && realmAccess.containsKey("roles")) { }
List<String> roles = (List<String>) realmAccess.get("roles");
for (String role : roles) {
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role));
}
}
return grantedAuthorities;
});
return jwtAuthenticationConverter;
}
}

@ -1,27 +1,25 @@
package de.szut.lf8_starter.welcome; package de.szut.lf8_starter.welcome;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.http.ResponseEntity; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.Collection;
import java.security.Principal; @RestController
public class WelcomeController {
@RestController
public class WelcomeController { @GetMapping("/welcome")
public String welcome() {
@GetMapping("/welcome") return "welcome to lf8_starter";
public String welcome() { }
return "welcome to lf8_starter";
} @GetMapping("/roles")
public ResponseEntity<Collection<GrantedAuthority>> getRoles(Authentication authentication) {
@GetMapping("/roles") return ResponseEntity.ok((Collection<GrantedAuthority>) authentication.getAuthorities());
public ResponseEntity<?> getRoles(Authentication authentication) { }
return ResponseEntity.ok(authentication.getAuthorities());
}
}
}

@ -2,7 +2,6 @@ package de.szut.lf8_starter;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
@SpringBootTest @SpringBootTest
class Lf8StarterApplicationTests { class Lf8StarterApplicationTests {

@ -0,0 +1,160 @@
package de.szut.lf8_starter.integration.project;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.*;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class AddEmployeeToProjectTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private RestTemplate restTemplate;
@Autowired
private ProjectRepository projectRepository;
@Test
void addEmployeeToProjectTest() throws Exception {
ProjectEntity project = new ProjectEntity();
project.setComment("comment");
project.setContractor(1);
project.setContractorName("contractorName");
project.setEndDate(LocalDate.of(2024, 1, 1));
project.setLeadingEmployee(1);
project.setName("name");
project.setStartDate(LocalDate.of(2021, 1, 1));
project.setEmployees(List.of(1L, 2L, 3L));
this.projectRepository.save(project);
mockMvc.perform(post("/projects/{projectId}/employees/{employeeId}", 1, 312)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
ProjectEntity updatedProject = projectRepository.findById(1L).get();
assert updatedProject.getEmployees().contains(312L);
}
@Test
void addEmployeeToPastProjectTest() throws Exception {
ProjectEntity project = new ProjectEntity();
project.setComment("past project");
project.setContractor(1);
project.setContractorName("contractorName");
project.setPlannedEndDate(LocalDate.of(1991, 1, 1));
project.setLeadingEmployee(1);
project.setName("past project");
project.setStartDate(LocalDate.of(1990, 1, 1));
project.setEmployees(List.of(1L, 2L, 3L));
this.projectRepository.save(project);
mockMvc.perform(post("/projects/{projectId}/employees/{employeeId}", project.getId(), 312)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
ProjectEntity updatedProject = projectRepository.findById(project.getId()).get();
assert updatedProject.getEmployees().contains(312L);
}
@Test
void addEmployeeToFutureProjectTest() throws Exception {
ProjectEntity project = new ProjectEntity();
project.setComment("future project");
project.setContractor(1);
project.setContractorName("contractorName");
project.setPlannedEndDate(LocalDate.of(2101, 1, 1));
project.setLeadingEmployee(1);
project.setName("future project");
project.setStartDate(LocalDate.of(2100, 1, 1));
project.setEmployees(List.of(1L, 2L, 3L));
this.projectRepository.save(project);
mockMvc.perform(post("/projects/{projectId}/employees/{employeeId}", project.getId(), 312)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
ProjectEntity updatedProject = projectRepository.findById(project.getId()).get();
assert updatedProject.getEmployees().contains(312L);
}
@Test
void addEmployeeToProjectWithOverlappingDatesTest() throws Exception {
ProjectEntity project1 = new ProjectEntity();
project1.setComment("project 1");
project1.setContractor(1);
project1.setContractorName("contractorName");
project1.setPlannedEndDate(LocalDate.of(2023, 1, 1));
project1.setLeadingEmployee(1);
project1.setName("project 1");
project1.setStartDate(LocalDate.of(2022, 1, 1));
project1.setEmployees(List.of(1L, 2L, 3L));
this.projectRepository.save(project1);
ProjectEntity project2 = new ProjectEntity();
project2.setComment("project 2");
project2.setContractor(1);
project2.setContractorName("contractorName");
project2.setPlannedEndDate(LocalDate.of(2023, 6, 1));
project2.setLeadingEmployee(1);
project2.setName("project 2");
project2.setStartDate(LocalDate.of(2022, 6, 1));
project2.setEmployees(List.of(1L, 2L, 3L));
this.projectRepository.save(project2);
mockMvc.perform(post("/projects/{projectId}/employees/{employeeId}", project1.getId(), 312)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
mockMvc.perform(post("/projects/{projectId}/employees/{employeeId}", project2.getId(), 312)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isConflict());
}
private String getBearerToken() {
String url = "https://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", "password");
map.add("client_id", "employee-management-service");
map.add("username", "user");
map.add("password", "test");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<Map> response = this.restTemplate.exchange(url, HttpMethod.POST, request, Map.class);
return Objects.requireNonNull(response.getBody()).get("access_token").toString();
}
}

@ -1,30 +1,41 @@
package de.szut.lf8_starter.integration.project; package de.szut.lf8_starter.integration.project;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectRepository; import de.szut.lf8_starter.project.ProjectRepository;
import org.json.JSONObject; import org.json.JSONObject;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType; import org.springframework.http.*;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.Arrays; import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest @SpringBootTest
@AutoConfigureMockMvc(addFilters = false) @AutoConfigureMockMvc(addFilters = false)
public class CreateProjectActionTest { @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class CreateProjectActionTest {
@Autowired @Autowired
private MockMvc mockMvc; private MockMvc mockMvc;
@Autowired @Autowired
private ProjectRepository projectRepository; private ProjectRepository projectRepository;
@Autowired
private RestTemplate restTemplate;
@Test @Test
void createProjectTest() throws Exception { void createProjectTest() throws Exception {
@ -32,7 +43,7 @@ public class CreateProjectActionTest {
{ {
"name": "name", "name": "name",
"leading_employee": 1, "leading_employee": 1,
"employees": [2, 3], "employees": [312],
"contractor": 4, "contractor": 4,
"contractor_name": "Peter File", "contractor_name": "Peter File",
"comment": "goal of project", "comment": "goal of project",
@ -41,13 +52,16 @@ public class CreateProjectActionTest {
} }
"""; """;
final var contentAsString = this.mockMvc.perform( final String contentAsString = this.mockMvc.perform(
post("/projects").content(content).contentType(MediaType.APPLICATION_JSON) post("/projects")
) .content(content)
.contentType(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
)
.andExpect(status().isCreated()) .andExpect(status().isCreated())
.andExpect(jsonPath("name", is("name"))) .andExpect(jsonPath("name", is("name")))
.andExpect(jsonPath("leading_employee", is(1))) .andExpect(jsonPath("leading_employee", is(1)))
.andExpect(jsonPath("employees", is(Arrays.asList(2, 3)))) .andExpect(jsonPath("employees", is(List.of(312))))
.andExpect(jsonPath("contractor", is(4))) .andExpect(jsonPath("contractor", is(4)))
.andExpect(jsonPath("contractor_name", is("Peter File"))) .andExpect(jsonPath("contractor_name", is("Peter File")))
.andExpect(jsonPath("comment", is("goal of project"))) .andExpect(jsonPath("comment", is("goal of project")))
@ -57,15 +71,166 @@ public class CreateProjectActionTest {
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
final var id = Long.parseLong(new JSONObject(contentAsString).get("id").toString()); final long id = Long.parseLong(new JSONObject(contentAsString).get("id").toString());
final var project = this.projectRepository.findById(id); final Optional<ProjectEntity> project = this.projectRepository.findById(id);
assertThat(project.get().getName()).isEqualTo("name"); assertThat(project.get().getName()).isEqualTo("name");
assertThat(project.get().getLeadingEmployee()).isEqualTo(1); assertThat(project.get().getLeadingEmployee()).isEqualTo(1);
assertThat(project.get().getContractor()).isEqualTo(4); assertThat(project.get().getContractor()).isEqualTo(4);
assertThat(project.get().getContractorName()).isEqualTo("Peter File"); assertThat(project.get().getContractorName()).isEqualTo("Peter File");
assertThat(project.get().getComment()).isEqualTo("goal of project"); assertThat(project.get().getComment()).isEqualTo("goal of project");
assertThat(project.get().getStartDate()).isEqualTo(LocalDate.of(2000, 1, 1)); assertThat(project.get().getStartDate()).isEqualTo(LocalDate.of(2000, 1, 1));
assertThat(project.get().getPlannedEndDate()).isEqualTo(LocalDate.of(2001, 1, 1)); assertThat(project.get().getPlannedEndDate()).isEqualTo(LocalDate.of(2001, 1, 1));
}
@Test
void createProjectShouldReturnConflictResponseOnConflictingProjects() throws Exception {
String content = """
{
"name": "name",
"leading_employee": 1,
"employees": [312],
"contractor": 4,
"contractor_name": "Peter File",
"comment": "goal of project",
"start_date": "01.01.2000",
"planned_end_date": "01.01.2001"
}
""";
this.mockMvc.perform(
post("/projects")
.content(content)
.contentType(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
)
.andExpect(status().isCreated());
this.mockMvc.perform(
post("/projects")
.content(content)
.contentType(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
)
.andExpect(status().isConflict());
}
@Test
void createProjectWithPastStartDate() throws Exception {
String content = """
{
"name": "past project",
"leading_employee": 1,
"employees": [312],
"contractor": 4,
"contractor_name": "Past Contractor",
"comment": "past project",
"start_date": "01.01.1990",
"planned_end_date": "01.01.1991"
}
""";
this.mockMvc.perform(
post("/projects")
.content(content)
.contentType(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
)
.andExpect(status().isCreated())
.andExpect(jsonPath("name", is("past project")))
.andExpect(jsonPath("start_date", is("01.01.1990")))
.andExpect(jsonPath("planned_end_date", is("01.01.1991")));
}
@Test
void createProjectWithFutureStartDate() throws Exception {
String content = """
{
"name": "future project",
"leading_employee": 1,
"employees": [312],
"contractor": 4,
"contractor_name": "Future Contractor",
"comment": "future project",
"start_date": "01.01.2100",
"planned_end_date": "01.01.2101"
}
""";
this.mockMvc.perform(
post("/projects")
.content(content)
.contentType(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
)
.andExpect(status().isCreated())
.andExpect(jsonPath("name", is("future project")))
.andExpect(jsonPath("start_date", is("01.01.2100")))
.andExpect(jsonPath("planned_end_date", is("01.01.2101")));
}
@Test
void createProjectWithOverlappingDates() throws Exception {
String content1 = """
{
"name": "project 1",
"leading_employee": 1,
"employees": [312],
"contractor": 4,
"contractor_name": "Contractor 1",
"comment": "project 1",
"start_date": "01.01.2022",
"planned_end_date": "01.01.2023"
}
""";
String content2 = """
{
"name": "project 2",
"leading_employee": 1,
"employees": [312],
"contractor": 4,
"contractor_name": "Contractor 2",
"comment": "project 2",
"start_date": "01.06.2022",
"planned_end_date": "01.06.2023"
}
""";
this.mockMvc.perform(
post("/projects")
.content(content1)
.contentType(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
)
.andExpect(status().isCreated());
this.mockMvc.perform(
post("/projects")
.content(content2)
.contentType(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
)
.andExpect(status().isConflict());
}
private String getBearerToken() {
String url = "https://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", "password");
map.add("client_id", "employee-management-service");
map.add("username", "user");
map.add("password", "test");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<Map> response = this.restTemplate.exchange(url, HttpMethod.POST, request, Map.class);
return Objects.requireNonNull(response.getBody()).get("access_token").toString();
} }
} }

@ -0,0 +1,84 @@
package de.szut.lf8_starter.integration.project;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.*;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class GetEmployeesFromProjectTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ProjectRepository projectRepository;
@Autowired
private RestTemplate restTemplate;
@Test
void getEmployeesFromProjectTest() throws Exception {
ProjectEntity project = new ProjectEntity();
project.setId(1);
project.setComment("comment");
project.setContractor(1);
project.setContractorName("contractorName");
project.setEndDate(LocalDate.of(2024, 1, 1));
project.setLeadingEmployee(1);
project.setName("name");
project.setStartDate(LocalDate.of(2021, 1, 1));
project.setEmployees(List.of(315L));
this.projectRepository.save(project);
this.mockMvc.perform(get("/projects/1/employees")
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
).andExpect(status().isOk())
.andExpect(jsonPath("project_id").value(1))
.andExpect(jsonPath("project_description").value("comment"))
.andExpect(jsonPath("employees[0].id").value(315))
.andExpect(jsonPath("employees[0].skillSet[0].skill").value("Product Owner"));
}
@Test
void getEmployeesFromProjectShouldReturnNotFoundResponseWhenProjectIsNotFound() throws Exception {
this.mockMvc.perform(get("/projects/1111/employees")
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
).andExpect(status().isNotFound());
}
private String getBearerToken() {
String url = "https://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", "password");
map.add("client_id", "employee-management-service");
map.add("username", "user");
map.add("password", "test");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<Map> response = this.restTemplate.exchange(url, HttpMethod.POST, request, Map.class);
return Objects.requireNonNull(response.getBody()).get("access_token").toString();
}
}

@ -0,0 +1,61 @@
package de.szut.lf8_starter.integration.project;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDate;
import java.util.List;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class GetProjectActionTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ProjectRepository projectRepository;
@Test
void getProjectTest() throws Exception {
ProjectEntity project = new ProjectEntity();
project.setId(1);
project.setComment("comment");
project.setContractor(1);
project.setContractorName("contractorName");
project.setEndDate(LocalDate.of(2024, 1, 1));
project.setLeadingEmployee(1);
project.setName("name");
project.setStartDate(LocalDate.of(2021, 1, 1));
project.setEmployees(List.of(1L, 2L, 3L));
this.projectRepository.save(project);
this.mockMvc.perform(get("/projects/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("id").value(1))
.andExpect(jsonPath("comment").value("comment"))
.andExpect(jsonPath("contractor").value(1))
.andExpect(jsonPath("contractor_name").value("contractorName"))
.andExpect(jsonPath("end_date").value("01.01.2024"))
.andExpect(jsonPath("leading_employee").value(1))
.andExpect(jsonPath("name").value("name"))
.andExpect(jsonPath("start_date").value("01.01.2021"))
.andExpect(jsonPath("employees").isArray())
.andExpect(jsonPath("employees", hasSize(3)));
}
@Test
void getProjectShouldReturnNotFoundResponseWhenProjectIsNotFound() throws Exception {
this.mockMvc.perform(get("/projects/1111")).andExpect(status().isNotFound());
}
}

@ -0,0 +1,88 @@
package de.szut.lf8_starter.integration.project;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.*;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class GetProjectsFromEmployeeTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ProjectRepository projectRepository;
@Autowired
private RestTemplate restTemplate;
@Test
void getProjectsFromEmployeeTest() throws Exception {
ProjectEntity project = new ProjectEntity();
project.setId(1);
project.setComment("comment");
project.setContractor(1);
project.setContractorName("contractorName");
project.setEndDate(LocalDate.of(2024, 1, 1));
project.setLeadingEmployee(1);
project.setName("name");
project.setStartDate(LocalDate.of(2021, 1, 1));
project.setEmployees(List.of(315L));
this.projectRepository.save(project);
this.mockMvc.perform(get("/employees/315/projects")
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
).andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(1))
.andExpect(jsonPath("$[0].name").value("name"))
.andExpect(jsonPath("$[0].leading_employee").value(1))
.andExpect(jsonPath("$[0].employees[0]").value(315))
.andExpect(jsonPath("$[0].contractor").value(1))
.andExpect(jsonPath("$[0].contractor_name").value("contractorName"))
.andExpect(jsonPath("$[0].comment").value("comment"))
.andExpect(jsonPath("$[0].start_date").value("01.01.2021"));
}
@Test
void GetProjectsFromEmployeeShouldReturnNotFoundResponseWhenEmployeeIsNotFound() throws Exception {
this.mockMvc.perform(get("/employees/1111/projects")
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
).andExpect(status().isNotFound());
}
private String getBearerToken() {
String url = "https://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", "password");
map.add("client_id", "employee-management-service");
map.add("username", "user");
map.add("password", "test");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<Map> response = this.restTemplate.exchange(url, HttpMethod.POST, request, Map.class);
return Objects.requireNonNull(response.getBody()).get("access_token").toString();
}
}

@ -1,37 +0,0 @@
package de.szut.lf8_starter.integration.project;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDate;
import java.util.List;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc(addFilters = true)
public class ProjectFindAllNotAuthenticated {
@Autowired
private ProjectRepository projectRepository;
@Autowired
private MockMvc mockMvc;
@Autowired
private TestRestTemplate restTemplate;
@Test
void findAllProjects() throws Exception {
this.mockMvc.perform(get("/projects"))
.andExpect(status().isUnauthorized());
}
}

@ -6,6 +6,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDate; import java.time.LocalDate;
@ -18,7 +19,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc(addFilters = false) @AutoConfigureMockMvc(addFilters = false)
public class ProjectFindAllSuccessTest { @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class ProjectFindAllSuccessTest {
@Autowired @Autowired
private ProjectRepository projectRepository; private ProjectRepository projectRepository;
@ -27,7 +29,7 @@ public class ProjectFindAllSuccessTest {
@Test @Test
void findAllProjectsTest() throws Exception { void findAllProjectsTest() throws Exception {
var project = new ProjectEntity(); ProjectEntity project = new ProjectEntity();
project.setId(1); project.setId(1);
project.setComment("comment"); project.setComment("comment");
project.setContractor(1); project.setContractor(1);
@ -36,7 +38,7 @@ public class ProjectFindAllSuccessTest {
project.setLeadingEmployee(1); project.setLeadingEmployee(1);
project.setName("name"); project.setName("name");
project.setStartDate(LocalDate.of(2021, 1, 1)); project.setStartDate(LocalDate.of(2021, 1, 1));
project.setEmployees(List.of(1L,2L,3L)); project.setEmployees(List.of(1L, 2L, 3L));
this.projectRepository.save(project); this.projectRepository.save(project);
this.mockMvc.perform(get("/projects")) this.mockMvc.perform(get("/projects"))

@ -0,0 +1,87 @@
package de.szut.lf8_starter.integration.project;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.*;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class RemoveEmployeeFromProjectIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private RestTemplate restTemplate;
@Autowired
private ProjectRepository projectRepository;
@Test
void removeEmployeeFromProject() throws Exception {
ProjectEntity project = new ProjectEntity();
project.setComment("comment");
project.setContractor(1);
project.setContractorName("contractorName");
project.setEndDate(LocalDate.of(2024, 1, 1));
project.setLeadingEmployee(1);
project.setName("name");
project.setStartDate(LocalDate.of(2021, 1, 1));
project.setEmployees(List.of(1L, 2L, 3L, 312L));
this.projectRepository.save(project);
mockMvc.perform(delete("/projects/{projectId}/employees/{employeeId}", 1, 312)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
ProjectEntity updatedProject = projectRepository.findById(1L).get();
assert !updatedProject.getEmployees().contains(312L);
}
private String getBearerToken() {
String url = "https://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", "password");
map.add("client_id", "employee-management-service");
map.add("username", "user");
map.add("password", "test");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<Map> response = this.restTemplate.exchange(url, HttpMethod.POST, request, Map.class);
return Objects.requireNonNull(response.getBody()).get("access_token").toString();
}
@Test
void removeEmployeeShouldReturn404IfProjectNotFound() throws Exception {
mockMvc.perform(delete("/projects/{projectId}/employees/{employeeId}", 1987234987, 312)
.header(HttpHeaders.AUTHORIZATION, getBearerToken())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
}

@ -0,0 +1,49 @@
package de.szut.lf8_starter.integration.project;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDate;
import java.util.List;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class RemoveProjectActionTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ProjectRepository projectRepository;
@Test
void deleteProjectTest() throws Exception {
ProjectEntity project = new ProjectEntity();
project.setComment("comment");
project.setContractor(1);
project.setContractorName("contractorName");
project.setEndDate(LocalDate.of(2024, 1, 1));
project.setLeadingEmployee(1);
project.setName("name");
project.setStartDate(LocalDate.of(2021, 1, 1));
project.setEmployees(List.of(1L, 2L, 3L));
this.projectRepository.save(project);
this.mockMvc.perform(delete("/projects/" + project.getId()))
.andExpect(status().isNoContent());
}
@Test
void deleteProjectShouldReturnNotFoundResponseWhenProjectIsNotFound() throws Exception {
this.mockMvc.perform(get("/projects/2987")).andExpect(status().isNotFound());
}
}

@ -0,0 +1,143 @@
package de.szut.lf8_starter.integration.project;
import de.szut.lf8_starter.project.ProjectEntity;
import de.szut.lf8_starter.project.ProjectRepository;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class UpdateProjectActionTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ProjectRepository projectRepository;
@Test
void updateProjectShouldUpdateProject() throws Exception {
ProjectEntity project = new ProjectEntity();
project.setId(1);
project.setComment("comment");
project.setContractor(1);
project.setContractorName("contractorName");
project.setEndDate(LocalDate.of(2024, 1, 1));
project.setLeadingEmployee(1);
project.setName("name");
project.setStartDate(LocalDate.of(2021, 1, 1));
project.setEmployees(List.of(1L, 2L, 3L));
this.projectRepository.save(project);
String content = """
{
"name": "updatedName",
"leading_employee": 2,
"employees": [3, 4, 5],
"contractor": 6,
"contractor_name": "Updated Contractor name",
"comment": "new goal of project",
"start_date": "01.01.2021",
"planned_end_date": "01.01.2022"
}
""";
final String contentAsString = this.mockMvc.perform(
put("/projects/1").content(content).contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andExpect(jsonPath("name", is("updatedName")))
.andExpect(jsonPath("leading_employee", is(2)))
.andExpect(jsonPath("employees", is(Arrays.asList(3, 4, 5))))
.andExpect(jsonPath("contractor", is(6)))
.andExpect(jsonPath("contractor_name", is("Updated Contractor name")))
.andExpect(jsonPath("comment", is("new goal of project")))
.andExpect(jsonPath("start_date", is("01.01.2021")))
.andExpect(jsonPath("planned_end_date", is("01.01.2022")))
.andReturn()
.getResponse()
.getContentAsString();
final long id = Long.parseLong(new JSONObject(contentAsString).get("id").toString());
final Optional<ProjectEntity> existingProject = this.projectRepository.findById(id);
assertThat(existingProject.get().getName()).isEqualTo("updatedName");
assertThat(existingProject.get().getLeadingEmployee()).isEqualTo(2);
assertThat(existingProject.get().getContractor()).isEqualTo(6);
assertThat(existingProject.get().getContractorName()).isEqualTo("Updated Contractor name");
assertThat(existingProject.get().getComment()).isEqualTo("new goal of project");
assertThat(existingProject.get().getStartDate()).isEqualTo(LocalDate.of(2021, 1, 1));
assertThat(existingProject.get().getPlannedEndDate()).isEqualTo(LocalDate.of(2022, 1, 1));
}
@Test
void updateProjectShouldUpdateProjectPartially() throws Exception {
ProjectEntity project = new ProjectEntity();
project.setId(1);
project.setName("name");
project.setLeadingEmployee(1);
project.setContractor(1);
project.setComment("comment");
project.setEmployees(List.of(1L, 2L, 3L));
project.setContractorName("contractorName");
project.setStartDate(LocalDate.of(2021, 1, 1));
project.setPlannedEndDate(LocalDate.of(2023, 1, 1));
project.setEndDate(LocalDate.of(2024, 1, 1));
this.projectRepository.save(project);
String content = """
{}
""";
final String contentAsString = this.mockMvc.perform(
put("/projects/1").content(content).contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andExpect(jsonPath("name", is("name")))
.andExpect(jsonPath("leading_employee", is(1)))
.andExpect(jsonPath("employees", is(List.of(1, 2, 3))))
.andExpect(jsonPath("contractor", is(1)))
.andExpect(jsonPath("contractor_name", is("contractorName")))
.andExpect(jsonPath("comment", is("comment")))
.andExpect(jsonPath("start_date", is("01.01.2021")))
.andExpect(jsonPath("planned_end_date", is("01.01.2023")))
.andExpect(jsonPath("end_date", is("01.01.2024")))
.andReturn()
.getResponse()
.getContentAsString();
final long id = Long.parseLong(new JSONObject(contentAsString).get("id").toString());
final Optional<ProjectEntity> existingProject = this.projectRepository.findById(id);
assertThat(existingProject.get().getName()).isEqualTo("name");
assertThat(existingProject.get().getLeadingEmployee()).isEqualTo(1);
assertThat(existingProject.get().getContractor()).isEqualTo(1);
assertThat(existingProject.get().getContractorName()).isEqualTo("contractorName");
assertThat(existingProject.get().getComment()).isEqualTo("comment");
assertThat(existingProject.get().getStartDate()).isEqualTo(LocalDate.of(2021, 1, 1));
assertThat(existingProject.get().getPlannedEndDate()).isEqualTo(LocalDate.of(2023, 1, 1));
assertThat(existingProject.get().getEndDate()).isEqualTo(LocalDate.of(2024, 1, 1));
}
@Test
void updateProjectShouldReturnNotFoundResponseWhenProjectIsNotFound() throws Exception {
this.mockMvc.perform(put("/projects/98723498798").content("{}").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isNotFound());
}
}

@ -0,0 +1,6 @@
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop