Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fiksclient + digisosapiclient: resttemplate til webclient #339

Merged
merged 34 commits into from
Mar 17, 2021
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
027dce8
tester ut spring webflux (reactive) i norgclient
martintveter Mar 10, 2021
b3c4d8b
trenger ikke "it.addAll(headers)"
martintveter Mar 11, 2021
cf68be3
accept json
martintveter Mar 11, 2021
546026b
bruker jetty
martintveter Mar 11, 2021
521bd24
formatting
martintveter Mar 11, 2021
a5f242c
spesifiser servletApi version
martintveter Mar 11, 2021
9764f97
Revert "spesifiser servletApi version"
martintveter Mar 11, 2021
5c4c74b
ping fix
martintveter Mar 11, 2021
0af5d9d
errorhandling. fjerner unødvendig ekstra logging av NorgException i I…
martintveter Mar 11, 2021
3fb156d
asdf
martintveter Mar 11, 2021
db88c68
bump sosialhjelp-common (forelopig snapshot-versjon)
martintveter Mar 12, 2021
64a1bc0
formatting
martintveter Mar 12, 2021
99997a3
coroutines reactor
martintveter Mar 12, 2021
04e3685
webclient bean
martintveter Mar 12, 2021
49049e8
webclient config
martintveter Mar 12, 2021
ee6e4ef
proxy
martintveter Mar 12, 2021
6171419
mock idportenclientconfig for test
martintveter Mar 12, 2021
f4723f0
asdf
martintveter Mar 12, 2021
979fe7c
proxiedWebClient for idportenclient og kommuneinfoclient (og fiksclie…
martintveter Mar 12, 2021
c748bf9
non-snapshot sosialhjelp-common
martintveter Mar 15, 2021
e32711a
skriver om fra resttemplate til webclient for fiksclient.
martintveter Mar 15, 2021
c5dcf58
asdf
martintveter Mar 15, 2021
bc55245
Merge branch 'master' into fiksclient_endre_fra_resttemplate_til_webc…
martintveter Mar 16, 2021
fd59a05
Merge branch 'master' into fiksclient_endre_fra_resttemplate_til_webc…
martintveter Mar 16, 2021
663d6c7
asdf
martintveter Mar 16, 2021
37b21cc
hmhm
martintveter Mar 16, 2021
6770e27
max memory size for fiksWebClient
martintveter Mar 16, 2021
09e74c0
cleanup
martintveter Mar 16, 2021
86f8983
cleanup
martintveter Mar 16, 2021
b6430cd
cleanup
martintveter Mar 16, 2021
0178385
ryddings.
martintveter Mar 16, 2021
53f0e9f
fjern exception fra error-logging i exceptionHandler. Disse loggmeldi…
martintveter Mar 16, 2021
0eb6999
fiksWebClient konfigurert med objectMapper
martintveter Mar 17, 2021
4e335fe
fiksWebClient konfigurert med objectMapper
martintveter Mar 17, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ object Versions {
const val junitJupiter = "5.7.0"
const val mockk = "1.10.3"
const val springmockk = "2.0.0"
const val mockwebserver = "5.0.0-alpha.2"
}

plugins {
Expand Down Expand Up @@ -147,6 +148,7 @@ dependencies {
testImplementation("no.nav.security:token-validation-test-support:${Versions.tokenValidation}")
testImplementation("org.jetbrains.kotlin:kotlin-test:${Versions.kotlin}")
testImplementation("com.ninja-squad:springmockk:${Versions.springmockk}")
testImplementation("com.squareup.okhttp3:mockwebserver3-junit5:${Versions.mockwebserver}")

// spesifikke versjoner oppgradert etter ønske fra snyk
constraints {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package no.nav.sosialhjelp.innsyn.client.digisosapi

import com.fasterxml.jackson.module.kotlin.readValue
import no.nav.sosialhjelp.api.fiks.exceptions.FiksClientException
import no.nav.sosialhjelp.api.fiks.exceptions.FiksException
import no.nav.sosialhjelp.api.fiks.exceptions.FiksServerException
import no.nav.sosialhjelp.innsyn.client.fiks.FiksClientImpl
import no.nav.sosialhjelp.innsyn.client.fiks.VedleggMetadata
Expand All @@ -16,17 +14,17 @@ import no.nav.sosialhjelp.innsyn.utils.IntegrationUtils.HEADER_INTEGRASJON_PASSO
import no.nav.sosialhjelp.innsyn.utils.IntegrationUtils.forwardHeaders
import no.nav.sosialhjelp.innsyn.utils.logger
import no.nav.sosialhjelp.innsyn.utils.objectMapper
import no.nav.sosialhjelp.innsyn.utils.typeRef
import org.springframework.context.annotation.Profile
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpHeaders.AUTHORIZATION
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.stereotype.Component
import org.springframework.util.LinkedMultiValueMap
import org.springframework.web.client.HttpClientErrorException
import org.springframework.web.client.HttpServerErrorException
import org.springframework.web.client.RestTemplate
import org.springframework.web.reactive.function.BodyInserters
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.bodyToMono
import java.util.Collections

/**
Expand All @@ -35,109 +33,106 @@ import java.util.Collections
@Profile("!(prod-sbs|mock)")
@Component
class DigisosApiClientImpl(
clientProperties: ClientProperties,
private val restTemplate: RestTemplate,
private val idPortenService: IdPortenService,
private val fiksClientImpl: FiksClientImpl
private val clientProperties: ClientProperties,
private val fiksWebClient: WebClient,
private val idPortenService: IdPortenService,
private val fiksClientImpl: FiksClientImpl,
) : DigisosApiClient {

private val testbrukerNatalie = System.getenv("TESTBRUKER_NATALIE") ?: "11111111111"

private val baseUrl = clientProperties.fiksDigisosEndpointUrl
private val fiksIntegrasjonIdKommune = clientProperties.fiksIntegrasjonIdKommune
private val fiksIntegrasjonPassordKommune = clientProperties.fiksIntegrasjonPassordKommune

override fun oppdaterDigisosSak(fiksDigisosId: String?, digisosApiWrapper: DigisosApiWrapper): String? {
var id = fiksDigisosId
if (fiksDigisosId == null || fiksDigisosId == "001" || fiksDigisosId == "002" || fiksDigisosId == "003") {
id = opprettDigisosSak()
log.info("Laget ny digisossak: $id")
}
val httpEntity = HttpEntity(objectMapper.writeValueAsString(digisosApiWrapper), headers())
try {
restTemplate.exchange("$baseUrl/digisos/api/v1/11415cd1-e26d-499a-8421-751457dfcbd5/$id", HttpMethod.POST, httpEntity, String::class.java)
log.info("Postet DigisosSak til Fiks")
return id
} catch (e: HttpClientErrorException) {
log.warn(e.responseBodyAsString)
log.warn("Fiks - oppdaterDigisosSak feilet - ${e.statusCode} ${e.statusText}", e)
throw FiksClientException(e.rawStatusCode, e.message, e)
} catch (e: HttpServerErrorException) {
log.warn(e.responseBodyAsString)
log.warn("Fiks - oppdaterDigisosSak feilet - ${e.statusCode} ${e.statusText}", e)
throw FiksServerException(e.rawStatusCode, e.message, e)
} catch (e: Exception) {
log.error(e.message, e)
throw FiksException(e.message, e)
}

return fiksWebClient.post()
.uri("/digisos/api/v1/11415cd1-e26d-499a-8421-751457dfcbd5/$id")
.headers { it.addAll(headers()) }
.body(BodyInserters.fromValue(objectMapper.writeValueAsString(digisosApiWrapper)))
.retrieve()
.onStatus(HttpStatus::is4xxClientError) {
it.createException().map { e ->
log.warn("Fiks - oppdaterDigisosSak feilet - ${e.statusCode} ${e.statusText}", e)
FiksClientException(e.rawStatusCode, e.message, e)
}
}
.onStatus(HttpStatus::is5xxServerError) {
it.createException().map { e ->
log.warn("Fiks - oppdaterDigisosSak feilet - ${e.statusCode} ${e.statusText}", e)
FiksServerException(e.rawStatusCode, e.message, e)
}
}
Comment on lines +56 to +67
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Disse er jo rimelig like, kan de skrives i en?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Jepp! Noe som dette hadde blitt mer konsist

.onErrorMap(WebClientResponseException::class.java) { e ->
    log.warn("Fiks - hentDigisosSak feilet - ${messageUtenFnr(e)}", e)
    if (e.statusCode.is4xxClientError) {
        FiksClientException(e.rawStatusCode, e.message?.feilmeldingUtenFnr, e)
    } else {
        FiksServerException(e.rawStatusCode, e.message?.feilmeldingUtenFnr, e)
    }
}

Tenkte å ta en runde med forenkling av feilhåndtering i webclients etter at alle restemplater er erstattet :)

.bodyToMono<String>()
.block()
.also { log.info("Postet DigisosSak til Fiks") }
}

// Brukes for å laste opp Pdf-er fra test-fagsystem i q-miljø
override fun lastOppNyeFilerTilFiks(files: List<FilForOpplasting>, soknadId: String): List<String> {
val headers = forwardHeaders()
headers.accept = Collections.singletonList(MediaType.APPLICATION_JSON)
headers.set(AUTHORIZATION, BEARER + idPortenService.getToken().token)
headers.set(HEADER_INTEGRASJON_ID, fiksIntegrasjonIdKommune)
headers.set(HEADER_INTEGRASJON_PASSORD, fiksIntegrasjonPassordKommune)
headers.contentType = MediaType.MULTIPART_FORM_DATA

val body = LinkedMultiValueMap<String, Any>()

files.forEachIndexed { fileId, file ->
val vedleggMetadata = VedleggMetadata(file.filnavn, file.mimetype, file.storrelse)
body.add("vedleggSpesifikasjon:$fileId", fiksClientImpl.createHttpEntityOfString(fiksClientImpl.serialiser(vedleggMetadata), "vedleggSpesifikasjon:$fileId"))
body.add("dokument:$fileId", fiksClientImpl.createHttpEntityOfFile(file, "dokument:$fileId"))
}

val requestEntity = HttpEntity(body, headers)
try {
val path = "$baseUrl/digisos/api/v1/11415cd1-e26d-499a-8421-751457dfcbd5/$soknadId/filer"
val response = restTemplate.exchange(path, HttpMethod.POST, requestEntity, String::class.java)

val opplastingResponse: List<FilOpplastingResponse> = objectMapper.readValue(response.body!!)
log.info("Filer sendt til Fiks")
return opplastingResponse.map { filOpplastingResponse -> filOpplastingResponse.dokumentlagerDokumentId }

} catch (e: HttpClientErrorException) {
log.warn(e.responseBodyAsString)
log.warn("Opplasting av filer feilet - ${e.statusCode} ${e.statusText}", e)
throw FiksClientException(e.rawStatusCode, e.message, e)
} catch (e: HttpServerErrorException) {
log.warn(e.responseBodyAsString)
log.warn("Opplasting av filer feilet - ${e.statusCode} ${e.statusText}", e)
throw FiksServerException(e.rawStatusCode, e.message, e)
} catch (e: Exception) {
log.warn("Opplasting av filer feilet", e)
throw FiksException(e.message, e)
}

val opplastingResponseList = fiksWebClient.post()
.uri("/digisos/api/v1/11415cd1-e26d-499a-8421-751457dfcbd5/$soknadId/filer")
.headers { it.addAll(headers()) }
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData(body))
.retrieve()
.onStatus(HttpStatus::is4xxClientError) {
it.createException().map { e ->
log.warn("Fiks - Opplasting av filer feilet - ${e.statusCode} ${e.statusText}", e)
FiksClientException(e.rawStatusCode, e.message, e)
}
}
.onStatus(HttpStatus::is5xxServerError) {
it.createException().map { e ->
log.warn("Fiks - Opplasting av filer feilet - ${e.statusCode} ${e.statusText}", e)
FiksServerException(e.rawStatusCode, e.message, e)
}
}
.bodyToMono(typeRef<List<FilOpplastingResponse>>())
.block()
log.info("Filer sendt til Fiks")
return opplastingResponseList!!.map { it.dokumentlagerDokumentId }
}

fun opprettDigisosSak(): String? {
val httpEntity = HttpEntity("", headers())
try {
val response = restTemplate.exchange("$baseUrl/digisos/api/v1/11415cd1-e26d-499a-8421-751457dfcbd5/ny?sokerFnr=$testbrukerNatalie", HttpMethod.POST, httpEntity, String::class.java)
log.info("Opprettet sak hos Fiks. Digisosid: ${response.body}")
return response.body?.replace("\"", "")
} catch (e: HttpClientErrorException) {
log.warn("Fiks - opprettDigisosSak feilet - ${e.statusCode} ${e.statusText}", e)
throw FiksClientException(e.rawStatusCode, e.message, e)
} catch (e: HttpServerErrorException) {
log.warn("Fiks - opprettDigisosSak feilet - ${e.statusCode} ${e.statusText}", e)
throw FiksServerException(e.rawStatusCode, e.message, e)
} catch (e: Exception) {
log.error(e.message, e)
throw FiksException(e.message, e)
}
val response = fiksWebClient.post()
.uri("/digisos/api/v1/11415cd1-e26d-499a-8421-751457dfcbd5/ny?sokerFnr=$testbrukerNatalie")
.headers { it.addAll(headers()) }
.body(BodyInserters.fromValue(""))
.retrieve()
.onStatus(HttpStatus::is4xxClientError) {
it.createException().map { e ->
log.warn("Fiks - opprettDigisosSak feilet - ${e.statusCode} ${e.statusText}", e)
FiksClientException(e.rawStatusCode, e.message, e)
}
}
.onStatus(HttpStatus::is5xxServerError) {
it.createException().map { e ->
log.warn("Fiks - opprettDigisosSak feilet - ${e.statusCode} ${e.statusText}", e)
FiksServerException(e.rawStatusCode, e.message, e)
}
}
.bodyToMono<String>()
.block()
log.info("Opprettet sak hos Fiks. Digisosid: $response")
return response?.replace("\"", "")
}

private fun headers(): HttpHeaders {
val headers = forwardHeaders()
val accessToken = idPortenService.getToken()
headers.accept = Collections.singletonList(MediaType.ALL)
headers.set(HEADER_INTEGRASJON_ID, fiksIntegrasjonIdKommune)
headers.set(HEADER_INTEGRASJON_PASSORD, fiksIntegrasjonPassordKommune)
headers.set(AUTHORIZATION, BEARER + accessToken.token)
headers.accept = Collections.singletonList(MediaType.APPLICATION_JSON)
headers.set(HEADER_INTEGRASJON_ID, clientProperties.fiksIntegrasjonIdKommune)
headers.set(HEADER_INTEGRASJON_PASSORD, clientProperties.fiksIntegrasjonPassordKommune)
headers.set(AUTHORIZATION, BEARER + idPortenService.getToken().token)
headers.contentType = MediaType.APPLICATION_JSON
return headers
}
Expand All @@ -148,7 +143,7 @@ class DigisosApiClientImpl(
}

data class FilOpplastingResponse(
val filnavn: String,
val dokumentlagerDokumentId: String,
val storrelse: Long
val filnavn: String,
val dokumentlagerDokumentId: String,
val storrelse: Long,
)
Original file line number Diff line number Diff line change
@@ -1,24 +1,19 @@
package no.nav.sosialhjelp.innsyn.client.fiks

import no.nav.sosialhjelp.api.fiks.exceptions.FiksClientException
import no.nav.sosialhjelp.api.fiks.exceptions.FiksException
import no.nav.sosialhjelp.api.fiks.exceptions.FiksServerException
import no.nav.sosialhjelp.innsyn.config.ClientProperties
import no.nav.sosialhjelp.innsyn.utils.IntegrationUtils
import no.nav.sosialhjelp.innsyn.utils.logger
import org.springframework.context.annotation.Profile
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Component
import org.springframework.web.client.HttpClientErrorException
import org.springframework.web.client.HttpServerErrorException
import org.springframework.web.client.RestTemplate
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.bodyToMono
import java.io.ByteArrayInputStream
import java.security.cert.CertificateException
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import java.util.Collections


interface DokumentlagerClient {
Expand All @@ -28,41 +23,40 @@ interface DokumentlagerClient {
@Profile("!mock")
@Component
class DokumentlagerClientImpl(
clientProperties: ClientProperties,
private val restTemplate: RestTemplate
private val clientProperties: ClientProperties,
private val proxiedWebClientBuilder: WebClient.Builder,
private val fiksWebClient: WebClient = proxiedWebClientBuilder
.baseUrl(clientProperties.fiksDigisosEndpointUrl)
.build(),
) : DokumentlagerClient {

private val baseUrl = clientProperties.fiksDigisosEndpointUrl
private val fiksIntegrasjonid = clientProperties.fiksIntegrasjonId
private val fiksIntegrasjonpassord = clientProperties.fiksIntegrasjonpassord

override fun getDokumentlagerPublicKeyX509Certificate(token: String): X509Certificate {
val headers = IntegrationUtils.forwardHeaders()
headers.accept = Collections.singletonList(MediaType.APPLICATION_JSON)
headers.set(HttpHeaders.AUTHORIZATION, token)
headers.set(IntegrationUtils.HEADER_INTEGRASJON_ID, fiksIntegrasjonid)
headers.set(IntegrationUtils.HEADER_INTEGRASJON_PASSORD, fiksIntegrasjonpassord)

try {
val response = restTemplate.exchange("$baseUrl/digisos/api/v1/dokumentlager-public-key", org.springframework.http.HttpMethod.GET, HttpEntity<Nothing>(headers), ByteArray::class.java)
log.info("Hentet public key for dokumentlager")
val publicKey = response.body
try {
val certificateFactory = CertificateFactory.getInstance("X.509")
val publicKey = fiksWebClient.get()
.uri(FiksPaths.PATH_DOKUMENTLAGER_PUBLICKEY)
.headers { it.addAll(IntegrationUtils.fiksHeaders(clientProperties, token)) }
.retrieve()
.onStatus(HttpStatus::is4xxClientError) {
it.createException().map { e ->
log.warn("Fiks - getDokumentlagerPublicKey feilet - ${e.statusCode} ${e.statusText}", e)
FiksClientException(e.rawStatusCode, e.message, e)
}
}
.onStatus(HttpStatus::is5xxServerError) {
it.createException().map { e ->
log.warn("Fiks - getDokumentlagerPublicKey feilet - ${e.statusCode} ${e.statusText}", e)
FiksServerException(e.rawStatusCode, e.message, e)
}
}
.bodyToMono<ByteArray>()
.block()

return certificateFactory.generateCertificate(ByteArrayInputStream(publicKey)) as X509Certificate
log.info("Hentet public key for dokumentlager")

} catch (e: CertificateException) {
throw RuntimeException(e)
}
} catch (e: HttpClientErrorException) {
log.warn("Fiks - getDokumentlagerPublicKey feilet - ${e.statusCode} ${e.statusText}", e)
throw FiksClientException(e.rawStatusCode, e.message, e)
} catch (e: HttpServerErrorException) {
log.warn("Fiks - getDokumentlagerPublicKey feilet - ${e.statusCode} ${e.statusText}", e)
throw FiksServerException(e.rawStatusCode, e.message, e)
} catch (e: Exception) {
throw FiksException(e.message, e)
try {
val certificateFactory = CertificateFactory.getInstance("X.509")
return certificateFactory.generateCertificate(ByteArrayInputStream(publicKey!!)) as X509Certificate
} catch (e: CertificateException) {
throw RuntimeException(e)
}
}

Expand Down
Loading