Compare commits

..
14 Commits
34 changed files with 617 additions and 424 deletions
+2 -3
View File
@@ -158,10 +158,9 @@ volumes:
path: /var/lib/drone/cache/.ansible
trigger:
# target:
# - production
target:
- production
event:
include:
- promote
- rollback
- custom
+3 -3
View File
@@ -543,9 +543,9 @@ ij_html_space_inside_empty_tag = false
ij_html_text_wrap = normal
[{*.kt,*.kts}]
indent_size = 4
tab_width = 4
ij_continuation_indent_size = 8
indent_size = 2
tab_width = 2
ij_continuation_indent_size = 4
ij_kotlin_align_in_columns_case_branch = false
ij_kotlin_align_multiline_binary_operation = false
ij_kotlin_align_multiline_extends_list = false
@@ -8,9 +8,6 @@ val libs = the<LibrariesForLibs>()
dependencies {
implementation(libs.kotlin.logging)
implementation(libs.kotlin.reactor)
implementation(libs.kotlin.coroutines)
implementation(libs.kotlin.coroutines.reactor)
implementation(kotlin("reflect"))
}
@@ -9,6 +9,7 @@ val libs = the<LibrariesForLibs>()
dependencies {
implementation(platform(libs.spring.cloud))
implementation(libs.bundles.spring.boot.server)
implementation(libs.spring.openapi)
implementation(libs.httpclient)
implementation(libs.prometheus)
+4 -15
View File
@@ -1,7 +1,6 @@
[versions]
spring-boot = "3.1.2"
spring-doc = "2.1.0"
spring-doc-webflux = "1.7.0"
spring-cloud = "2022.0.4"
spring-grpc = "2.14.0.RELEASE"
grpc = "1.57.0"
@@ -18,8 +17,6 @@ keycloak = "22.0.1"
kotlin-logging = "3.0.5"
kotlin-reflect = "1.9.0"
kotlin-lombok = "1.9.0"
kotlin-reactor = "1.2.2"
kotlin-coroutines = "1.7.3"
plugin-nebula-release = "17.2.2"
plugin-lombok = "8.0.1"
plugin-gradle-versions = "0.46.0"
@@ -34,12 +31,10 @@ spring-boot-web = { module = "org.springframework.boot:spring-boot-starter-web"
spring-boot-log4j = { module = "org.springframework.boot:spring-boot-starter-log4j2" }
spring-boot-thymeleaf = { module = "org.springframework.boot:spring-boot-starter-thymeleaf" }
spring-boot-mongo = { module = "org.springframework.boot:spring-boot-starter-data-mongodb" }
spring-boot-mongo-reactive = { module = "org.springframework.boot:spring-boot-starter-data-mongodb-reactive" }
spring-boot-validation = { module = "org.springframework.boot:spring-boot-starter-validation" }
spring-boot-test = { module = "org.springframework.boot:spring-boot-starter-test" }
spring-boot-security = { module = "org.springframework.boot:spring-boot-starter-security" }
spring-boot-oauth2-resource-server = { module = "org.springframework.boot:spring-boot-starter-oauth2-resource-server" }
spring-boot-webflux = { module = "org.springframework.boot:spring-boot-starter-webflux" }
spring-boot-config = { module = "org.springframework.boot:spring-boot-configuration-processor", version.ref = "spring-boot" }
spring-cloud = { module = "org.springframework.cloud:spring-cloud-dependencies", version.ref = "spring-cloud" }
spring-cloud-starter = { module = "org.springframework.cloud:spring-cloud-starter" }
@@ -49,9 +44,8 @@ spring-cloud-config-server = { module = "org.springframework.cloud:spring-cloud-
spring-boot-starter = { module = "org.springframework.boot:spring-boot-starter" }
spring-grpc = { module = "net.devh:grpc-spring-boot-starter", version.ref = "spring-grpc" }
spring-ui = { module = "org.springdoc:springdoc-openapi-starter-webmvc-ui", version.ref = "spring-doc" }
spring-openapi-starter = { module = "org.springdoc:springdoc-openapi-starter-common", version.ref = "spring-doc" }
spring-openapi-webmvc = { module = "org.springdoc:springdoc-openapi-starter-webmvc-api", version.ref = "spring-doc" }
spring-openapi-webflux = { module = "org.springdoc:springdoc-openapi-webflux-ui", version.ref = "spring-doc-webflux" }
spring-sec = { module = "org.springdoc:springdoc-openapi-starter-common", version.ref = "spring-doc" }
spring-openapi = { module = "org.springdoc:springdoc-openapi-starter-webmvc-api", version.ref = "spring-doc" }
keycloak-core = { module = "org.keycloak:keycloak-core", version.ref = "keycloak" }
keycloak-policy-enforcer = { module = "org.keycloak:keycloak-policy-enforcer", version.ref = "keycloak" }
grpc-api = { module = "io.grpc:grpc-api", version.ref = "grpc" }
@@ -84,9 +78,6 @@ mockito-inline = "org.mockito:mockito-inline:5.2.0"
mockito-junit = { module = "org.mockito:mockito-junit-jupiter", version.ref = "mockito" }
kotlin-logging = { module = "io.github.microutils:kotlin-logging-jvm", version.ref = "kotlin-logging" }
kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin-reflect" }
kotlin-reactor = { module = "io.projectreactor.kotlin:reactor-kotlin-extensions", version.ref = "kotlin-reactor" }
kotlin-coroutines = { module = "org.jetbrains.kotlinx:kotlin-coroutines-core", version.ref = "kotlin-coroutines" }
kotlin-coroutines-reactor = { module = "org.jetbrains.kotlinx:kotlin-coroutines-reactor", version.ref = "kotlin-coroutines" }
plugin-nebula-release = { module = "com.netflix.nebula:nebula-release-plugin", version.ref = "plugin-nebula-release" }
plugin-springboot = { module = "org.springframework.boot:spring-boot-gradle-plugin", version.ref = "spring-boot" }
plugin-lombok = { module = "io.freefair.gradle:lombok-plugin", version.ref = "plugin-lombok" }
@@ -121,14 +112,12 @@ spring-boot = [
spring-boot-server = [
"spring-boot-actuator",
"spring-boot-log4j",
"spring-boot-mongo-reactive",
"spring-boot-mongo",
"spring-boot-thymeleaf",
"spring-boot-validation",
"spring-boot-web",
"spring-boot-webflux",
"spring-cloud-starter",
"spring-openapi-starter",
"spring-openapi-webflux",
"spring-sec",
"spring-ui",
]
spring-boot-security = [
+1 -1
View File
@@ -8,7 +8,7 @@ dependencies {
jib {
from {
image = "amazoncorretto:" + properties["projectSourceCompatibility"]
image = "amazoncorretto:" + properties["projectSourceCompatibility"] + "-alpine"
platforms {
platform {
architecture = "amd64"
+3
View File
@@ -0,0 +1,3 @@
apiVersion: v2
name: wahlrecht
version: 0.2.4
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+4
View File
@@ -0,0 +1,4 @@
# Wahlrecht API
This chart installs the Wahlrecht API
into the Kubernetes cluster.
@@ -3,13 +3,11 @@ package de.twomartens.wahlrecht
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.data.mongodb.config.EnableMongoAuditing
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories
import org.springframework.scheduling.annotation.EnableScheduling
@EnableMongoAuditing
@EnableScheduling
@SpringBootApplication
@EnableReactiveMongoRepositories
open class MainApplication
fun main(args: Array<String>) {
@@ -0,0 +1,13 @@
package de.twomartens.wahlrecht.configuration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.filter.ForwardedHeaderFilter
@Configuration
open class FilterConfiguration {
@Bean
open fun forwardedFilter(): ForwardedHeaderFilter {
return ForwardedHeaderFilter()
}
}
@@ -8,13 +8,13 @@ import java.time.Clock
@Configuration
open class InterceptorConfiguration {
@Bean
open fun loggingInterceptorRest(clock: Clock): LoggingInterceptorRest {
return LoggingInterceptorRest(clock)
}
@Bean
open fun loggingInterceptorRest(clock: Clock): LoggingInterceptorRest {
return LoggingInterceptorRest(clock)
}
@Bean
open fun headerInterceptorRest(): HeaderInterceptorRest {
return HeaderInterceptorRest()
}
@Bean
open fun headerInterceptorRest(): HeaderInterceptorRest {
return HeaderInterceptorRest()
}
}
@@ -6,7 +6,6 @@ import io.swagger.v3.oas.annotations.security.OAuthFlows
import io.swagger.v3.oas.annotations.security.SecurityScheme
import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.info.Info
import io.swagger.v3.oas.models.servers.Server
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@@ -36,7 +35,5 @@ open class OpenApiConfiguration {
.version(apiVersion)
.description(apiDescription)
)
.addServersItem(Server().url("http://localhost:12000"))
.addServersItem(Server().url("https://api.2martens.de"))
}
}
@@ -18,7 +18,6 @@ import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
@RestController
@RequestMapping(value = ["/wahlrecht/v1"])
@@ -48,12 +47,12 @@ class CalculationController(private val service: CalculationService) {
@SecurityRequirement(name = "oauth2")
fun calculateResult(
@RequestBody electionResult: ElectionResult
): ResponseEntity<Mono<ElectedCandidates>> {
): ResponseEntity<ElectedCandidates> {
val result = electedCandidatesMapper.mapToExternal(
service.determineElectedCandidates(electionResultMapper.mapToInternal(electionResult))
)
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(Mono.just(result))
.body(result)
}
}
@@ -14,11 +14,10 @@ import io.swagger.v3.oas.annotations.tags.Tag
import org.mapstruct.factory.Mappers
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.http.ResponseEntity.created
import org.springframework.http.ResponseEntity.ok
import org.springframework.web.bind.annotation.*
import org.springframework.web.util.UriComponentsBuilder
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.util.function.Tuples
@RestController
@RequestMapping(value = ["/wahlrecht/v1"])
@@ -28,7 +27,7 @@ class ElectionController(private val service: ElectionService) {
@SecurityRequirement(name = "oauth2")
@SecurityRequirement(name = "bearerAuth")
@GetMapping(value = ["/elections"])
@GetMapping(value = ["/elections"], produces = [MediaType.APPLICATION_JSON_VALUE])
@Operation(
summary = "Returns all stored elections",
responses = [ApiResponse(
@@ -44,12 +43,13 @@ class ElectionController(private val service: ElectionService) {
)]
)]
)
fun getElections(): Flux<Election> {
val elections = service.getElections()
.map {
mapper.mapToExternal(it)
}
return elections
fun getElections(): ResponseEntity<Collection<Election>> {
val elections = service.elections.asSequence()
.map { mapper.mapToExternal(it.value) }
.toList()
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(elections)
}
@Operation(
@@ -64,11 +64,10 @@ class ElectionController(private val service: ElectionService) {
@SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2")
fun getElectionByName(
@PathVariable @Parameter(description = "the election name", example = "Bezirkswahl 2019") electionName: String
): ResponseEntity<Mono<Election>> {
val election = service.findElectionByName(electionName)
.map { mapper.mapToExternal(it) }
return ResponseEntity.ok()
@PathVariable @Parameter(description = "the election name", example = "Bezirkswahl 2019") electionName: String?
): ResponseEntity<Election> {
val election = mapper.mapToExternal(service.elections[electionName]!!)
return ok()
.contentType(MediaType.APPLICATION_JSON)
.body(election)
}
@@ -87,22 +86,14 @@ class ElectionController(private val service: ElectionService) {
@PutMapping("/election")
@SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2")
fun putElection(@RequestBody election: Election, uriComponentsBuilder: UriComponentsBuilder): Mono<ResponseEntity<Election>> {
return service.storeElection(mapper.mapToDB(election))
.map { tuple ->
Tuples.of(tuple.t1, mapper.mapToExternal(tuple.t2))
}
.map { tuple ->
if (tuple.t1) {
ResponseEntity.created(uriComponentsBuilder.path("/elections/{electionName}")
.buildAndExpand(tuple.t2.name).toUri())
.contentType(MediaType.APPLICATION_JSON)
.body(tuple.t2)
} else {
ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(tuple.t2)
}
}
fun putElection(@RequestBody election: Election?, uriComponentsBuilder: UriComponentsBuilder):
ResponseEntity<Void> {
val createdNew = service.storeElection(mapper.mapToDB(election!!))
return if (createdNew) {
created(uriComponentsBuilder.path("/elections/{electionName}")
.buildAndExpand(election.name).toUri())
.build()
}
else ok().build()
}
}
@@ -16,10 +16,10 @@ import lombok.extern.slf4j.Slf4j
import org.mapstruct.factory.Mappers
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.http.ResponseEntity.created
import org.springframework.http.ResponseEntity.ok
import org.springframework.web.bind.annotation.*
import org.springframework.web.util.UriComponentsBuilder
import reactor.core.publisher.Mono
import reactor.util.function.Tuples
@Slf4j
@RestController
@@ -27,72 +27,57 @@ import reactor.util.function.Tuples
@RequestMapping(value = ["/wahlrecht/v1"])
@Tag(name = "ElectionResults", description = "all requests relating to election results")
class ElectionResultController(private val service: ElectionResultService) {
private val mapper = Mappers.getMapper(ElectionResultMapper::class.java)
private val mapper = Mappers.getMapper(ElectionResultMapper::class.java)
@Operation(
summary = "Returns election result for given election name",
responses = [ApiResponse(
responseCode = "200",
description = "Returns stored election result for given election name",
content = [Content(mediaType = "application/json", schema = Schema(implementation = ElectionResult::class))]
), ApiResponse(
responseCode = "404",
description = "No election result found",
content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorMessage::class))]
)]
)
@GetMapping(
value = ["/electionResult/{electionName}"],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
@SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2")
fun getElectionByName(
@PathVariable @Parameter(description = "the election name", example = "Bezirkswahl 2019") electionName: String
): Mono<ResponseEntity<ElectionResult>> {
return service.getElectionResult(electionName)
.map {
mapper.mapToExternal(it)
}
.map {
ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(it)
}
}
@Operation(
summary = "Returns election result for given election name",
responses = [ApiResponse(
responseCode = "200",
description = "Returns stored election result for given election name",
content = [Content(mediaType = "application/json", schema = Schema(implementation = ElectionResult::class))]
), ApiResponse(
responseCode = "404",
description = "No election result found",
content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorMessage::class))]
)]
)
@GetMapping(
value = ["/electionResults/{electionName}"],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
@SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2")
fun getElectionResultByElectionName(
@PathVariable @Parameter(description = "the election name", example = "Bezirkswahl 2019") electionName: String
): ResponseEntity<ElectionResult> {
val result = mapper.mapToExternal(service.getElectionResult(electionName))
return ok()
.contentType(MediaType.APPLICATION_JSON)
.body(result)
}
@Operation(
summary = "Stores a new election",
responses = [ApiResponse(
responseCode = "201",
description = "Election was created"
), ApiResponse(responseCode = "200", description = "Election was modified"), ApiResponse(
responseCode = "401",
description = "Unauthorized",
content = [Content(mediaType = "plain/text")]
)]
)
@PutMapping("/electionResult")
@SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2")
fun putElection(@RequestBody electionResult: ElectionResult,
uriComponentsBuilder: UriComponentsBuilder): Mono<ResponseEntity<ElectionResult>> {
val storedElection = service.storeResult(mapper.mapToDB(electionResult))
return storedElection
.map { tuple ->
Tuples.of(tuple.t1, mapper.mapToExternal(tuple.t2))
@Operation(
summary = "Stores a new election",
responses = [ApiResponse(
responseCode = "201",
description = "Election was created"
), ApiResponse(responseCode = "200", description = "Election was modified"), ApiResponse(
responseCode = "401",
description = "Unauthorized",
content = [Content(mediaType = "plain/text")]
)]
)
@PutMapping("/electionResult")
@SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2")
fun putElection(@RequestBody electionResult: ElectionResult?,
uriComponentsBuilder: UriComponentsBuilder): ResponseEntity<Void> {
val createdNew = service.storeResult(mapper.mapToDB(electionResult!!))
return if (createdNew) {
created(uriComponentsBuilder.path("/electionResult/{electionName}")
.buildAndExpand(electionResult.electionName).toUri())
.build()
}
.map { tuple ->
if (tuple.t1) {
ResponseEntity.created(uriComponentsBuilder.path("/electionResult/{electionName}")
.buildAndExpand(tuple.t2.electionName).toUri())
.contentType(MediaType.APPLICATION_JSON)
.body(tuple.t2)
} else {
ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(tuple.t2)
}
}
}
else ok().build()
}
}
@@ -20,9 +20,6 @@ import org.springframework.http.ResponseEntity.ok
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.*
import org.springframework.web.util.UriComponentsBuilder
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.util.function.Tuples
@Controller
@RequestMapping(value = ["/wahlrecht/v1"])
@@ -45,23 +42,26 @@ class PartyController(private val service: PartyService) {
content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorMessage::class))]
)]
)
@GetMapping(value = ["/parties/by-election-name/{electionName}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@GetMapping(value = ["/parties/{electionName}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2")
fun getPartiesByElectionName(
@PathVariable @Parameter(description = "the election name", example = "Bezirkswahl 2019") electionName: String
): ResponseEntity<Flux<PartyInElection>> {
val parties = service.getPartiesByElectionName(electionName)
.map { election: de.twomartens.wahlrecht.model.db.PartyInElection ->
mapper.mapToExternal(election)
): ResponseEntity<Collection<PartyInElection>> {
val parties = service.getPartiesByElectionName(electionName).stream()
.map { election: de.twomartens.wahlrecht.model.db.PartyInElection? ->
mapper.mapToExternal(
election!!
)
}
.toList()
return ok()
.contentType(MediaType.APPLICATION_JSON)
.body(parties)
}
@Operation(
summary = "Returns party stored for given election name and abbreviation",
summary = "Returns stored party for given election name and party abbreviation",
responses = [ApiResponse(
responseCode = "200",
description = "Returns stored party",
@@ -81,11 +81,10 @@ class PartyController(private val service: PartyService) {
fun getPartyByElectionNameAndAbbreviation(
@PathVariable @Parameter(description = "the election name", example = "Bezirkswahl 2019") electionName: String,
@PathVariable @Parameter(description = "the party abbreviation", example = "SPD") abbreviation: String
): ResponseEntity<Mono<PartyInElection>> {
val party = service.getPartyByElectionNameAndAbbreviation(electionName, abbreviation)
.map { stored: de.twomartens.wahlrecht.model.db.PartyInElection ->
mapper.mapToExternal(stored)
}
): ResponseEntity<PartyInElection> {
val party = mapper.mapToExternal(
service.getPartyByElectionNameAndAbbreviation(electionName, abbreviation)
)
return ok()
.contentType(MediaType.APPLICATION_JSON)
.body(party)
@@ -104,24 +103,13 @@ class PartyController(private val service: PartyService) {
@PutMapping("/party")
@SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2")
fun putParty(@RequestBody party: PartyInElection,
uriComponentsBuilder: UriComponentsBuilder): Mono<ResponseEntity<PartyInElection>> {
val storedParty = service.storeParty(mapper.mapToDB(party))
return storedParty
.map { tuple ->
Tuples.of(tuple.t1, mapper.mapToExternal(tuple.t2))
}
.map { tuple ->
if (tuple.t1) {
created(uriComponentsBuilder.path("/parties/{electionName}/{abbreviation}")
.buildAndExpand(tuple.t2.electionName, tuple.t2.abbreviation).toUri())
.contentType(MediaType.APPLICATION_JSON)
.body(tuple.t2)
} else {
ok()
.contentType(MediaType.APPLICATION_JSON)
.body(tuple.t2)
}
}
fun putParty(@RequestBody party: PartyInElection?,
uriComponentsBuilder: UriComponentsBuilder): ResponseEntity<Void> {
val createdNew = service.storeParty(mapper.mapToDB(party!!))
return if (createdNew) {
created(uriComponentsBuilder.path("/parties/{electionName}/{abbreviation}")
.buildAndExpand(party.electionName, party.abbreviation).toUri())
.build()
} else ok().build()
}
}
@@ -7,30 +7,27 @@ import org.springframework.data.annotation.Id
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.mongodb.core.index.CompoundIndex
import org.springframework.data.mongodb.core.mapping.Document
import org.springframework.data.mongodb.core.mapping.DocumentReference
import java.time.Instant
@Document
@EqualsAndHashCode
@CompoundIndex(def = "{'name': 1, 'partyAbbreviation': 1, 'electionName': 1}")
class Nomination {
@EqualsAndHashCode.Exclude
@Id
var id: ObjectId? = null
@EqualsAndHashCode.Exclude
@Id
var id: ObjectId? = null
@EqualsAndHashCode.Exclude
@CreatedDate
var created: Instant? = null
@EqualsAndHashCode.Exclude
@CreatedDate
var created: Instant? = null
@EqualsAndHashCode.Exclude
@LastModifiedDate
var lastModified: Instant? = null
@EqualsAndHashCode.Exclude
@LastModifiedDate
var lastModified: Instant? = null
var name: String = ""
var partyAbbreviation: String = ""
var electionName: String = ""
@DocumentReference
var candidates: Collection<Candidate> = emptyList()
var supportVotesOnNomination = false
var name: String = ""
var partyAbbreviation: String = ""
var electionName: String = ""
var candidates: Collection<Candidate> = emptyList()
var supportVotesOnNomination = false
}
@@ -1,31 +1,6 @@
package de.twomartens.wahlrecht.repository
import de.twomartens.wahlrecht.model.db.Candidate
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import org.springframework.data.mongodb.repository.MongoRepository
interface CandidateRepository : ReactiveMongoRepository<Candidate, String> {
fun findByName(name: String): Mono<Candidate>
fun findAndModify(new: Candidate): Mono<Candidate> {
val existing = findByName(new.name)
return existing.hasElement().flatMap { hasElement ->
if (hasElement) {
existing.flatMap { old ->
old.profession = new.profession
save(old)
}
} else {
save(new)
}
}
}
fun findAllAndModify(new: Collection<Candidate>): Flux<Candidate> {
val existing = new.map {
findAndModify(it)
}
return Flux.merge(existing)
}
}
interface CandidateRepository : MongoRepository<Candidate, String>
@@ -1,27 +1,6 @@
package de.twomartens.wahlrecht.repository
import de.twomartens.wahlrecht.model.db.Constituency
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import reactor.core.publisher.Mono
import org.springframework.data.mongodb.repository.MongoRepository
interface ConstituencyRepository : ReactiveMongoRepository<Constituency, String> {
fun findByElectionNameAndNumber(electionName: String, number: Int): Mono<Constituency>
fun findAndModify(new: Constituency): Mono<Constituency> {
val existing = findByElectionNameAndNumber(
new.electionName,
new.number)
return existing.hasElement().flatMap { hasElement ->
if (hasElement) {
existing.flatMap { old ->
old.name = new.name
old.numberOfSeats = new.numberOfSeats
save(old)
}
} else {
save(new)
}
}
}
}
interface ConstituencyRepository : MongoRepository<Constituency, String>
@@ -1,27 +1,6 @@
package de.twomartens.wahlrecht.repository
import de.twomartens.wahlrecht.model.db.Election
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import reactor.core.publisher.Mono
import reactor.util.function.Tuple2
import org.springframework.data.mongodb.repository.MongoRepository
interface ElectionRepository : ReactiveMongoRepository<Election, String> {
fun findByName(name: String): Mono<Election>
fun findAndModify(new: Election): Mono<Tuple2<Boolean, Election>> {
val electionName = new.name
val existing = findByName(electionName)
return existing.hasElement().flatMap { hasElement ->
if (hasElement) {
existing.flatMap { old ->
old.constituencies = new.constituencies
old.totalNumberOfSeats = new.totalNumberOfSeats
old.votingThreshold = new.votingThreshold
Mono.just(false).zipWith(save(old))
}
} else {
Mono.just(true).zipWith(save(new))
}
}
}
}
interface ElectionRepository : MongoRepository<Election, String>
@@ -1,25 +1,6 @@
package de.twomartens.wahlrecht.repository
import de.twomartens.wahlrecht.model.db.ElectionResult
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import reactor.core.publisher.Mono
import reactor.util.function.Tuple2
import org.springframework.data.mongodb.repository.MongoRepository
interface ElectionResultRepository : ReactiveMongoRepository<ElectionResult, String> {
fun findByElectionName(electionName: String): Mono<ElectionResult>
fun findAndModify(new: ElectionResult): Mono<Tuple2<Boolean, ElectionResult>> {
val existing = findByElectionName(new.electionName)
return existing.hasElement().flatMap { hasElement ->
if (hasElement) {
existing.flatMap { old ->
old.overallResults = new.overallResults
old.constituencyResults = new.constituencyResults
Mono.just(false).zipWith(save(old))
}
} else {
Mono.just(true).zipWith(save(new))
}
}
}
}
interface ElectionResultRepository : MongoRepository<ElectionResult, String>
@@ -1,31 +1,6 @@
package de.twomartens.wahlrecht.repository
import de.twomartens.wahlrecht.model.db.Nomination
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import org.springframework.data.mongodb.repository.MongoRepository
interface NominationRepository : ReactiveMongoRepository<Nomination, String> {
fun findByElectionNameAndPartyAbbreviationAndName(electionName: String,
abbreviation: String,
name: String): Mono<Nomination>
fun findAndModify(new: Nomination): Mono<Nomination> {
val existing = findByElectionNameAndPartyAbbreviationAndName(
new.electionName,
new.partyAbbreviation,
new.name
)
return existing.hasElement().flatMap { hasElement ->
if (hasElement) {
existing.publishOn(Schedulers.boundedElastic()).publishOn(Schedulers.boundedElastic()).flatMap { old ->
old.supportVotesOnNomination = new.supportVotesOnNomination
old.candidates = new.candidates
save(old)
}
} else {
save(new)
}
}
}
}
interface NominationRepository : MongoRepository<Nomination, String>
@@ -1,30 +1,10 @@
package de.twomartens.wahlrecht.repository
import de.twomartens.wahlrecht.model.db.PartyInElection
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.util.function.Tuple2
import org.springframework.data.mongodb.repository.MongoRepository
interface PartyRepository : ReactiveMongoRepository<PartyInElection, String> {
interface PartyRepository : MongoRepository<PartyInElection, String> {
fun findByElectionName(name: String): Collection<PartyInElection>
fun findByElectionName(name: String): Flux<PartyInElection>
fun findByElectionNameAndAbbreviation(electionName: String, abbreviation: String): Mono<PartyInElection>
fun findAndModify(party: PartyInElection): Mono<Tuple2<Boolean, PartyInElection>> {
val existing = findByElectionNameAndAbbreviation(party.electionName, party.abbreviation)
return existing.hasElement().flatMap { hasElement ->
if (hasElement) {
existing.flatMap { old ->
old.name = party.name
old.overallNomination = party.overallNomination
old.constituencyNominations = party.constituencyNominations
Mono.just(false).zipWith(save(old))
}
} else {
Mono.just(true).zipWith(save(party))
}
}
}
fun findByElectionNameAndAbbreviation(electionName: String, abbreviation: String): PartyInElection?
}
@@ -17,9 +17,9 @@ class CalculationService(
log.info("Calculate election result for election {}", electionResult.electionName)
val stopWatch = StopWatch()
stopWatch.start("determineElectedCandidates")
val election = electionService.getElectionInternal(electionResult.electionName).block()
val election = electionService.getElectionInternal(electionResult.electionName)
val seatResult = calculateOverallSeatDistribution(
election!!,
election,
electionResult.overallResults
)
val constituencyResults: MutableMap<Int, ElectedResult> = HashMap()
@@ -192,8 +192,8 @@ class CalculationService(
.toMap()
.toMutableMap()
val nominationId = votingResult.nominationId
val nomination = nominationService.getNominationInternal(nominationId).block()
if (nomination!!.supportsVotesOnNomination()) {
val nomination = nominationService.getNominationInternal(nominationId)
if (nomination.supportsVotesOnNomination()) {
val seatsByNomination = calculateSeatsByNominationOrder(votingResult, numberOfSeats)
seatsByVoteOrder = numberOfSeats - seatsByNomination
val candidates = nomination.getCandidates()
@@ -3,17 +3,33 @@ package de.twomartens.wahlrecht.service
import de.twomartens.wahlrecht.model.db.Candidate
import de.twomartens.wahlrecht.repository.CandidateRepository
import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
@Service
class CandidateService(private val repository: CandidateRepository) {
private val candidates: MutableMap<String, Candidate> by lazy {
fetchCandidates()
}
fun storeCandidate(candidate: Candidate): Mono<Candidate> {
return repository.findAndModify(candidate)
}
fun storeCandidate(candidate: Candidate): Candidate {
var result = candidate
val existing = candidates[candidate.name]
val needsUpdate = candidate != existing
if (!needsUpdate && existing != null) {
return existing
}
if (existing != null) {
existing.profession = candidate.profession
result = existing
}
result = repository.save(result)
candidates[candidate.name] = candidate
return result
}
fun storeCandidates(candidates: Collection<Candidate>): Flux<Candidate> {
return Flux.merge(candidates.map { storeCandidate(it) })
}
private fun fetchCandidates(): MutableMap<String, Candidate> {
return repository.findAll().asSequence()
.map { Pair(it.name, it) }
.toMap()
.toMutableMap()
}
}
@@ -1,14 +1,40 @@
package de.twomartens.wahlrecht.service
import de.twomartens.wahlrecht.model.db.Constituency
import de.twomartens.wahlrecht.model.internal.ConstituencyId
import de.twomartens.wahlrecht.repository.ConstituencyRepository
import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
@Service
class ConstituencyService(private val repository: ConstituencyRepository) {
private val constituencies: MutableMap<ConstituencyId, Constituency> by lazy {
fetchConstituencies()
}
fun storeConstituencies(constituencies: Collection<Constituency>): Flux<Constituency> {
return Flux.merge(constituencies.map { repository.findAndModify(it) })
}
fun storeConstituency(constituency: Constituency): Constituency {
var result = constituency
val constituencyId = ConstituencyId(
constituency.electionName,
constituency.number
)
val existing = constituencies[constituencyId]
if (constituency == existing) {
return existing
}
if (existing != null) {
existing.numberOfSeats = constituency.numberOfSeats
existing.name = constituency.name
result = existing
}
val stored = repository.save(result)
constituencies[constituencyId] = stored
return stored
}
private fun fetchConstituencies(): MutableMap<ConstituencyId, Constituency> {
return repository.findAll().asSequence()
.map { Pair(ConstituencyId(electionName = it.electionName, number = it.number), it) }
.toMap()
.toMutableMap()
}
}
@@ -5,20 +5,45 @@ import de.twomartens.wahlrecht.repository.ElectionResultRepository
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.web.server.ResponseStatusException
import reactor.core.publisher.Mono
import reactor.util.function.Tuple2
@Service
class ElectionResultService(private val repository: ElectionResultRepository) {
private val electionResults: MutableMap<String, ElectionResult> by lazy {
fetchResults()
}
fun getElectionResult(electionName: String): ElectionResult {
return electionResults[electionName]
?: throw ResponseStatusException(
HttpStatus.NOT_FOUND,
"no election result found for $electionName"
)
}
fun getElectionResult(electionName: String): Mono<ElectionResult> {
return repository.findByElectionName(electionName)
.switchIfEmpty(Mono.error(
ResponseStatusException(HttpStatus.NOT_FOUND, "no election result found for $electionName")
))
}
fun storeResult(electionResult: ElectionResult): Boolean {
var result = electionResult
fun storeResult(new: ElectionResult): Mono<Tuple2<Boolean, ElectionResult>> {
return repository.findAndModify(new)
}
val id = result.electionName
val existing = electionResults[id]
val needsUpdate = result != existing
if (!needsUpdate) {
return false
}
var createdNew = true
if (existing != null) {
existing.overallResults = result.overallResults
existing.constituencyResults = result.constituencyResults
result = existing
createdNew = false
}
val stored = repository.save(result)
electionResults[id] = stored
return createdNew
}
private fun fetchResults(): MutableMap<String, ElectionResult> {
return repository.findAll().asSequence()
.map { Pair(it.electionName, it) }
.toMap()
.toMutableMap()
}
}
@@ -1,35 +1,60 @@
package de.twomartens.wahlrecht.service
import de.twomartens.wahlrecht.mapper.v1.ElectionMapper
import de.twomartens.wahlrecht.model.db.Constituency
import de.twomartens.wahlrecht.model.db.Election
import de.twomartens.wahlrecht.repository.ElectionRepository
import org.mapstruct.factory.Mappers
import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.util.function.Tuple2
@Service
class ElectionService(
private val electionRepository: ElectionRepository
private val electionRepository: ElectionRepository,
private val constituencyService: ConstituencyService
) {
private val electionMapper = Mappers.getMapper(ElectionMapper::class.java)
fun getElections(): Flux<Election> {
return electionRepository.findAll()
}
fun findElectionByName(electionName: String): Mono<Election> {
return electionRepository.findByName(electionName)
}
fun getElectionInternal(electionName: String): Mono<de.twomartens.wahlrecht.model.internal.Election> {
return findElectionByName(electionName).map {
electionMapper.mapToInternal(it)
private val electionMapper = Mappers.getMapper(ElectionMapper::class.java)
private val _elections: MutableMap<String, Election> by lazy {
fetchElections()
}
}
fun storeElection(new: Election): Mono<Tuple2<Boolean, Election>> {
return electionRepository.findAndModify(new)
}
val elections: Map<String, Election> = _elections
private fun getElection(electionName: String): Election? {
return elections[electionName]
}
fun getElectionInternal(electionName: String): de.twomartens.wahlrecht.model.internal.Election {
return electionMapper.mapToInternal(getElection(electionName)!!)
}
fun storeElection(election: Election): Boolean {
var result = election
var createdNew = true
val electionName = election.name
val existing = elections[electionName]
if (election == existing) {
return false
}
val constituencies: MutableCollection<Constituency> = mutableListOf()
result.constituencies
.forEach { constituencies.add(constituencyService.storeConstituency(it)) }
if (existing != null) {
existing.day = election.day
existing.totalNumberOfSeats = election.totalNumberOfSeats
existing.votingThreshold = election.votingThreshold
result = existing
createdNew = false
}
result.constituencies = constituencies
val stored = electionRepository.save(result)
_elections[electionName] = stored
return createdNew
}
private fun fetchElections(): MutableMap<String, Election> {
return electionRepository.findAll().asSequence()
.map { Pair(it.name, it) }
.toMap()
.toMutableMap()
}
}
@@ -1,41 +1,69 @@
package de.twomartens.wahlrecht.service
import de.twomartens.wahlrecht.mapper.v1.NominationMapper
import de.twomartens.wahlrecht.model.db.Candidate
import de.twomartens.wahlrecht.model.db.Nomination
import de.twomartens.wahlrecht.model.internal.NominationId
import de.twomartens.wahlrecht.repository.NominationRepository
import org.mapstruct.factory.Mappers
import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
@Service
class NominationService(
private val repository: NominationRepository
private val repository: NominationRepository,
private val candidateService: CandidateService
) {
private val mapper = Mappers.getMapper(NominationMapper::class.java)
fun getNominationInternal(id: NominationId): Mono<de.twomartens.wahlrecht.model.internal.Nomination> {
return getNomination(id).map {
mapper.mapToInternal(it)
private val mapper = Mappers.getMapper(NominationMapper::class.java)
private val nominations: MutableMap<NominationId, Nomination> by lazy {
fetchNominations()
}
}
fun storeNomination(new: Nomination?): Mono<Nomination> {
if (new == null) return Mono.empty()
fun getNominationInternal(id: NominationId): de.twomartens.wahlrecht.model.internal.Nomination {
return mapper.mapToInternal(getNomination(id)!!)
}
return repository.findAndModify(new)
}
fun storeNomination(nomination: Nomination?): Nomination? {
if (nomination == null) return null
val nominationId = NominationId(
nomination.electionName,
nomination.partyAbbreviation,
nomination.name
)
val existing = nominations[nominationId]
val needsUpdate = nomination != existing
if (!needsUpdate) {
return existing
}
var result: Nomination = nomination
val candidates: MutableCollection<Candidate> = ArrayList()
result.candidates
.forEach { candidates.add(candidateService.storeCandidate(it)) }
if (existing != null) {
result = existing
}
result.candidates = candidates
result = repository.save(nomination)
nominations[nominationId] = result
return result
}
fun storeNominations(new: Collection<Nomination>): Flux<Nomination> {
return Flux.merge(new.map { storeNomination(it) })
}
private fun getNomination(id: NominationId): Nomination? {
return nominations[id]
}
private fun getNomination(id: NominationId): Mono<Nomination> {
return repository.findByElectionNameAndPartyAbbreviationAndName(
id.electionName,
id.partyAbbreviation,
id.name
)
}
private fun fetchNominations(): MutableMap<NominationId, Nomination> {
return repository.findAll().asSequence()
.map {
Pair(
NominationId(
electionName = it.electionName,
partyAbbreviation = it.partyAbbreviation,
name = it.name
),
it
)
}
.toMap()
.toMutableMap()
}
}
@@ -1,32 +1,73 @@
package de.twomartens.wahlrecht.service
import de.twomartens.wahlrecht.model.db.Nomination
import de.twomartens.wahlrecht.model.db.PartyInElection
import de.twomartens.wahlrecht.model.internal.PartyId
import de.twomartens.wahlrecht.repository.PartyRepository
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.web.server.ResponseStatusException
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.util.function.Tuple2
@Service
class PartyService(
private val partyRepository: PartyRepository
private val partyRepository: PartyRepository,
private val nominationService: NominationService
) {
fun getPartiesByElectionName(electionName: String): Flux<PartyInElection> {
return partyRepository.findByElectionName(electionName)
.switchIfEmpty(Flux.error(
ResponseStatusException(HttpStatus.NOT_FOUND, "no party found for $electionName")
))
}
private val parties: MutableMap<PartyId, PartyInElection> by lazy {
fetchParties()
}
fun getPartyByElectionNameAndAbbreviation(electionName: String,
abbreviation: String): Mono<PartyInElection> {
abbreviation: String): PartyInElection {
return partyRepository.findByElectionNameAndAbbreviation(electionName, abbreviation)
?: throw ResponseStatusException(HttpStatus.NOT_FOUND,
"no party found for $electionName and $abbreviation")
}
fun storeParty(new: PartyInElection): Mono<Tuple2<Boolean, PartyInElection>> {
return partyRepository.findAndModify(new)
}
fun getPartiesByElectionName(electionName: String): Collection<PartyInElection> {
val parties = partyRepository.findByElectionName(electionName)
if (parties.isEmpty()) {
throw ResponseStatusException(HttpStatus.NOT_FOUND, "no party found for $electionName")
}
return parties
}
fun storeParty(partyInElection: PartyInElection): Boolean {
var result = partyInElection
var createdNew = true
val partyId = PartyId(
partyInElection.electionName,
partyInElection.abbreviation
)
val existing = parties[partyId]
val needsUpdate = partyInElection != existing
if (!needsUpdate) {
return false
}
val constituencyNominations: MutableMap<Int, Nomination> = mutableMapOf()
result.constituencyNominations
.forEach { constituencyNominations[it.key] = nominationService.storeNomination(it.value)!! }
if (existing != null) {
existing.name = partyInElection.name
if (constituencyNominations.isEmpty()) {
constituencyNominations.putAll(existing.constituencyNominations)
}
result = existing
createdNew = false
}
partyInElection.constituencyNominations = constituencyNominations
partyInElection.overallNomination = nominationService.storeNomination(partyInElection.overallNomination)!!
result = partyRepository.save(result)
parties[partyId] = result
return createdNew
}
private fun fetchParties(): MutableMap<PartyId, PartyInElection> {
val allParties = partyRepository.findAll()
return allParties.asSequence()
.map { Pair(PartyId(electionName = it.electionName, abbreviation = it.abbreviation), it) }
.toMap()
.toMutableMap()
}
}
@@ -6,4 +6,4 @@ spring:
config:
import:
- "classpath:config/wahlrecht.yaml"
- "optional:configserver:http://localhost:8888/config"
- "optional:configserver:${CONFIGSERVER_SCHEME:http}://${CONFIGSERVER_HOST:configserver}:${CONFIGSERVER_PORT:8888}${CONFIGSERVER_PREFIX:/config}"
@@ -1,7 +1,7 @@
spring:
config:
import:
- "configserver:http://configserver:8888/config"
- "configserver:${CONFIGSERVER_SCHEME:http}://${CONFIGSERVER_HOST:configserver}:${CONFIGSERVER_PORT:8888}${CONFIGSERVER_PREFIX:/config}"
kafka:
bootstrap-servers:
- kafka:9092
- ${KAFKA_HOST:kafka}:${KAFKA_PORT:9092}
@@ -1,6 +1,7 @@
server:
port: 12000
shutdown: graceful
forward-headers-strategy: framework
### technical configurations ###
management:
@@ -37,7 +38,7 @@ spring:
oauth2:
resourceserver:
jwt:
jwk-set-uri: https://id.2martens.de/realms/2martens/protocol/openid-connect/certs
jwk-set-uri: ${KEYCLOAK_URL:https://id.2martens.de}/realms/${KEYCLOAK_REALM:2martens}/protocol/openid-connect/certs
application:
name: wahlrecht