Skip to content

Commit

Permalink
chore: clean up mail service and other backend code; removed unused c…
Browse files Browse the repository at this point in the history
…ode (#2786)

Clean up mail service and other backend code; removed unused code.

Solves PZ-5698
  • Loading branch information
edgarvonk authored Feb 27, 2025
1 parent d13833d commit acbb55b
Show file tree
Hide file tree
Showing 13 changed files with 63 additions and 131 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public MailGegevens convert(final RESTMailGegevens restMailGegevens) {
final String afzender = configuratieService.readGemeenteNaam();
return new MailGegevens(
new MailAdres(restMailGegevens.verzender, afzender),
new MailAdres(restMailGegevens.ontvanger),
new MailAdres(restMailGegevens.ontvanger, null),
restMailGegevens.replyTo == null ? null : new MailAdres(restMailGegevens.replyTo, afzender),
restMailGegevens.onderwerp,
restMailGegevens.body,
Expand Down
4 changes: 2 additions & 2 deletions src/main/kotlin/net/atos/client/zgw/shared/ZGWApiService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,8 @@ class ZGWApiService @Inject constructor(
*/
fun createZaakInformatieobjectForZaak(
zaak: Zaak,
enkelvoudigInformatieObjectCreateLockRequest: EnkelvoudigInformatieObjectCreateLockRequest?,
titel: String?,
enkelvoudigInformatieObjectCreateLockRequest: EnkelvoudigInformatieObjectCreateLockRequest,
titel: String,
beschrijving: String?,
omschrijvingVoorwaardenGebruiksrechten: String?
): ZaakInformatieobject {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ class PlanItemsRESTService @Inject constructor(
private var restMailGegevensConverter: RESTMailGegevensConverter,
private var zaakService: ZaakService
) {

companion object {
private const val REDEN_OPSCHORTING = "Aanvullende informatie opgevraagd"
private const val REDEN_PAST_FATALE_DATUM = "Aanvullende informatie opgevraagd"
Expand Down Expand Up @@ -174,9 +173,9 @@ class PlanItemsRESTService @Inject constructor(
MailGegevens(
TaakVariabelenService.readMailFrom(taakdata)
.map { MailAdres(it, afzender) }
.orElseGet { mailService.gemeenteMailAdres },
.orElseGet { mailService.getGemeenteMailAdres() },
TaakVariabelenService.readMailTo(taakdata)
.map { MailAdres(it) }
.map { MailAdres(it, null) }
.orElse(null),
TaakVariabelenService.readMailReplyTo(taakdata)
.map { MailAdres(it, afzender) }
Expand Down
87 changes: 37 additions & 50 deletions src/main/kotlin/net/atos/zac/mail/MailService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import com.itextpdf.kernel.pdf.PdfDocument
import com.itextpdf.kernel.pdf.PdfWriter
import com.itextpdf.layout.Document
import com.itextpdf.layout.element.IBlockElement
import com.itextpdf.layout.element.IElement
import com.itextpdf.layout.element.Paragraph
import jakarta.annotation.PostConstruct
import jakarta.annotation.Resource
Expand Down Expand Up @@ -53,8 +52,6 @@ import java.io.IOException
import java.time.LocalDate
import java.util.Base64
import java.util.Optional
import java.util.UUID
import java.util.function.Consumer
import java.util.logging.Level
import java.util.logging.Logger

Expand All @@ -73,7 +70,6 @@ class MailService @Inject constructor(
@ConfigProperty(name = "SMTP_USERNAME")
private val smtpUsername: Optional<String> = Optional.empty(),
) {

companion object {
private val LOG = Logger.getLogger(MailService::class.java.name)

Expand All @@ -94,24 +90,11 @@ class MailService @Inject constructor(
private const val JAVAMAIL_SMTP_AUTH_KEY = "mail.smtp.auth"
}

@PostConstruct
@Suppress("UnusedPrivateMember")
private fun initPasswordAuthentication() {
// If there's no SMTP_USERNAME environment variable set, we consider this as a case, where SMTP server
// has no authentication. In this case we disable SMTP authentication in the mail session to prevent sending
// the default dummy credentials configured in src/main/resources/wildfly/configure-wildfly.cli
//
// Without the dummy credentials, the SMTP mail session is not properly configured, and:
// - Weld fails to instantiate the mail session and satisfy the @Resource dependency above
// - mail Transport below throws AuthenticationFailedException because of insufficient configuration
if (!smtpUsername.isPresent) {
mailSession.properties.setProperty(JAVAMAIL_SMTP_AUTH_KEY, "false")
LOG.warning { "SMTP authentication disabled" }
}
}

val gemeenteMailAdres
get() = MailAdres(configuratieService.readGemeenteMail(), configuratieService.readGemeenteNaam())
fun getGemeenteMailAdres() =
MailAdres(
configuratieService.readGemeenteMail(),
configuratieService.readGemeenteNaam()
)

fun sendMail(mailGegevens: MailGegevens, bronnen: Bronnen): String {
val subject = StringUtils.abbreviate(
Expand All @@ -121,9 +104,7 @@ class MailService @Inject constructor(
val body = resolveVariabelen(mailGegevens.body, bronnen)
val attachments = getAttachments(mailGegevens.attachments)
val fromAddress = mailGegevens.from.toAddress()
val replyToAddress = mailGegevens.replyTo?.toAddress().let {
if (fromAddress == it) null else it
}
val replyToAddress = mailGegevens.replyTo?.toAddress()?.takeIf { fromAddress != it }
val message = MailMessageBuilder(
fromAddress = fromAddress,
toAddress = mailGegevens.to.toAddress(),
Expand All @@ -132,7 +113,6 @@ class MailService @Inject constructor(
body = body,
attachments = attachments
).build(mailSession)

try {
Transport.send(message)
LOG.fine("Sent mail to ${mailGegevens.to} with subject '$subject'.")
Expand All @@ -153,6 +133,22 @@ class MailService @Inject constructor(
return body
}

@PostConstruct
@Suppress("UnusedPrivateMember")
private fun initPasswordAuthentication() {
// If there's no SMTP_USERNAME environment variable set, we consider this as a case, where SMTP server
// has no authentication. In this case we disable SMTP authentication in the mail session to prevent sending
// the default dummy credentials configured in src/main/resources/wildfly/configure-wildfly.cli
//
// Without the dummy credentials, the SMTP mail session is not properly configured, and:
// - Weld fails to instantiate the mail session and satisfy the @Resource dependency above
// - mail Transport below throws AuthenticationFailedException because of insufficient configuration
if (!smtpUsername.isPresent) {
mailSession.properties.setProperty(JAVAMAIL_SMTP_AUTH_KEY, "false")
LOG.warning { "SMTP authentication disabled" }
}
}

@Suppress("LongParameterList")
private fun createZaakDocumentFromMail(
verzender: String,
Expand All @@ -179,7 +175,6 @@ class MailService @Inject constructor(
vertrouwelijkheidaanduiding = VertrouwelijkheidaanduidingEnum.OPENBAAR
verzenddatum = LocalDate.now()
}

zgwApiService.createZaakInformatieobjectForZaak(
zaak,
enkelvoudigInformatieobjectWithInhoud,
Expand All @@ -203,49 +198,41 @@ class MailService @Inject constructor(
PdfDocument(pdfWriter).use { pdfDoc ->
Document(pdfDoc).use { document ->
val font = PdfFontFactory.createFont(StandardFonts.COURIER)

document.add(
Paragraph().apply {
setFont(font).setFontSize(FONT_SIZE).setFontColor(ColorConstants.BLACK)
add("$MAIL_VERZENDER: $verzender \n\n")
add("$MAIL_ONTVANGER: $ontvanger \n\n")
if (attachments.isNotEmpty()) {
val content = attachments.joinToString(",") { attachment: Attachment ->
attachment.filename
}
val content = attachments.joinToString(",") { it.filename }
add("$MAIL_BIJLAGE: $content \n\n")
}
add("$MAIL_ONDERWERP: $subject \n\n")
add("$MAIL_BERICHT \n")
}
)

val cleaner = HtmlCleaner()
val rootTagNode = cleaner.clean(body)
val cleanerProperties = cleaner.properties.apply {
isOmitXmlDeclaration = true
}
val html = PrettyXmlSerializer(cleanerProperties).getAsString(rootTagNode)

val emailBodyParagraph = Paragraph()
HtmlConverter.convertToElements(html).forEach(
Consumer { element: IElement? ->
emailBodyParagraph.add(element as IBlockElement?)
// the individual (HTML paragraph) block elements are not separated
// with new lines, so we add them explicitly here
emailBodyParagraph.add("\n")
}
)
HtmlConverter.convertToElements(html).forEach {
emailBodyParagraph.add(it as IBlockElement)
// the individual (HTML paragraph) block elements are not separated
// with new lines, so we add them explicitly here
emailBodyParagraph.add("\n")
}
document.add(emailBodyParagraph)
}
}
}
} catch (e: PdfException) {
LOG.log(Level.SEVERE, "Failed to create pdf document", e)
} catch (e: IOException) {
LOG.log(Level.SEVERE, "Failed to create pdf document", e)
} catch (pdfException: PdfException) {
LOG.log(Level.SEVERE, "Failed to create PDF document", pdfException)
} catch (ioException: IOException) {
LOG.log(Level.SEVERE, "Failed to create PDF document", ioException)
}

return byteArrayOutputStream.toByteArray()
}

Expand All @@ -255,13 +242,13 @@ class MailService @Inject constructor(
.first { it.omschrijving == ConfiguratieService.INFORMATIEOBJECTTYPE_OMSCHRIJVING_EMAIL }

private fun getAttachments(bijlagenString: Array<String>): List<Attachment> =
bijlagenString.map { UUIDUtil.uuid(it) }.map { uuid: UUID ->
bijlagenString.map(UUIDUtil::uuid).map { uuid ->
val enkelvoudigInformatieobject = drcClientService.readEnkelvoudigInformatieobject(uuid)
val byteArrayInputStream = drcClientService.downloadEnkelvoudigInformatieobject(uuid)
Attachment(
enkelvoudigInformatieobject.formaat,
enkelvoudigInformatieobject.bestandsnaam,
String(Base64.getEncoder().encode(byteArrayInputStream.readAllBytes()))
contentType = enkelvoudigInformatieobject.formaat,
filename = enkelvoudigInformatieobject.bestandsnaam,
base64Content = String(Base64.getEncoder().encode(byteArrayInputStream.readAllBytes()))
)
}

Expand Down
6 changes: 3 additions & 3 deletions src/main/kotlin/net/atos/zac/mail/model/Attachment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ package net.atos.zac.mail.model
import jakarta.json.bind.annotation.JsonbProperty

data class Attachment(
@field:JsonbProperty("ContentType") var contentType: String,
@field:JsonbProperty("Filename") var filename: String,
@field:JsonbProperty("Base64Content") var base64Content: String
@field:JsonbProperty("ContentType") val contentType: String,
@field:JsonbProperty("Filename") val filename: String,
@field:JsonbProperty("Base64Content") val base64Content: String
)
22 changes: 4 additions & 18 deletions src/main/kotlin/net/atos/zac/mail/model/Bronnen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,10 @@ class Bronnen private constructor(
private var document: EnkelvoudigInformatieObject? = null
private var taskInfo: TaskInfo? = null

fun add(zaak: Zaak): Builder {
this.zaak = zaak
return this
}

fun add(document: EnkelvoudigInformatieObject): Builder {
this.document = document
return this
}

fun add(taskInfo: TaskInfo): Builder {
this.taskInfo = taskInfo
return this
}

fun build(): Bronnen {
return Bronnen(zaak, document, taskInfo)
}
fun add(zaak: Zaak) = apply { this.zaak = zaak }
fun add(document: EnkelvoudigInformatieObject) = apply { this.document = document }
fun add(taskInfo: TaskInfo) = apply { this.taskInfo = taskInfo }
fun build() = Bronnen(zaak, document, taskInfo)
}
}

Expand Down
19 changes: 0 additions & 19 deletions src/main/kotlin/net/atos/zac/mail/model/EMail.kt

This file was deleted.

17 changes: 0 additions & 17 deletions src/main/kotlin/net/atos/zac/mail/model/EMails.kt

This file was deleted.

12 changes: 4 additions & 8 deletions src/main/kotlin/net/atos/zac/mail/model/MailAdres.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,15 @@ import jakarta.mail.Address
import jakarta.mail.internet.InternetAddress
import net.atos.zac.util.ValidationUtil

class MailAdres(
@field:JsonbProperty("Email") var email: String,
@field:JsonbProperty("Name") var name: String?
data class MailAdres(
@field:JsonbProperty("Email") val email: String,
@field:JsonbProperty("Name") val name: String?
) {
init {
require(ValidationUtil.isValidEmail(email)) { "Email '$email' is not valid" }
}

constructor(email: String) : this(email, null)

fun toAddress(): Address = InternetAddress(email, name)

override fun toString(): String {
return "$email ($name)"
}
override fun toString() = "$email ($name)"
}
11 changes: 7 additions & 4 deletions src/main/kotlin/net/atos/zac/signalering/SignaleringService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -256,9 +256,7 @@ class SignaleringService @Inject constructor(

fun sendSignalering(signalering: Signalering) {
ValidationUtil.valideerObject(signalering)
signaleringenMailHelper.getTargetMail(signalering)?.let {
val from = mailService.gemeenteMailAdres
val to = formatTo(it)
signaleringenMailHelper.getTargetMail(signalering)?.let { mail ->
val mailTemplate = signaleringenMailHelper.getMailTemplate(signalering)
val bronnenBuilder = Bronnen.Builder()
when (signalering.subjecttype) {
Expand All @@ -283,7 +281,12 @@ class SignaleringService @Inject constructor(
else -> {}
}
mailService.sendMail(
MailGegevens(from, to, mailTemplate.onderwerp, mailTemplate.body),
MailGegevens(
mailService.getGemeenteMailAdres(),
formatTo(mail),
mailTemplate.onderwerp,
mailTemplate.body
),
bronnenBuilder.build()
)
}
Expand Down
3 changes: 0 additions & 3 deletions src/test/kotlin/net/atos/zac/mail/MailServiceTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -109,14 +109,11 @@ class MailServiceTest : BehaviorSpec({
zaak, any(), resolvedSubject, resolvedSubject, "geen"
)
} returns zaakInformatieobject

mockkObject(MailService.Companion)
every { MailService.Companion.mailSession.properties } returns Properties()

mockkStatic(Transport::class)
val transportSendRequest = slot<Message>()
every { Transport.send(capture(transportSendRequest)) } just runs

every { configuratieService.readBronOrganisatie() } returns "123443210"

When("the send mail function is invoked") {
Expand Down
4 changes: 2 additions & 2 deletions src/test/kotlin/net/atos/zac/mail/model/MailAdresTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ class MailAdresTest : BehaviorSpec({

Given("a valid email address") {
When("constructing and object") {
MailAdres("[email protected]")
MailAdres("[email protected]", "dummyName")
Then("it should succeed") {}
}
}

Given("an invalid email address") {
When("constructing and object") {
val exception = shouldThrow<IllegalArgumentException> {
MailAdres("fake email")
MailAdres("fake email", null)
}

Then("it should error") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ class SignaleringServiceTest : BehaviorSpec({
val mailBody = "dummyMailBody"
val mailGegevensSlot = slot<MailGegevens>()
every { signaleringenMailHelper.getTargetMail(signalering) } returns signaleringMail
every { mailService.gemeenteMailAdres } returns gemeenteMailAdres
every { mailService.getGemeenteMailAdres() } returns gemeenteMailAdres
every { signaleringenMailHelper.getMailTemplate(signalering) } returns mailTemplate
every { flowableTaskService.readTask(task.id) } returns task
every { zrcClientService.readZaak(zaak.uuid) } returns zaak
Expand Down

0 comments on commit acbb55b

Please sign in to comment.