EN · DE · RU · FR · ES

#238: MerlinExecutionPageRest.kt

plugins/org.projectforge.plugins.merlin/src/main/kotlin/org/projectforge/plugins/merlin/rest/MerlinExecutionPageRest.kt Type: Kotlin · Role: Plugin Registration · Source: plugins/org.projectforge.plugins.merlin/src/main/kotlin/org/projectforge/plugins/merlin/rest/MerlinExecutionPageRest.kt 415 lines · 355 code · 34 comments · 26 blank
REST API endpoint for MerlinExecution. Handles HTTP requests and returns JSON responses for the React frontend.

Code Structure

Annotations: Valid, RequestBody, GetMapping, PathVariable, Autowired, return, RequestMapping, RestController, PostMapping, RequestParam

Classes: MerlinExecutionPageRest

Supertype(s): AbstractDynamicPageRest

Functions (12): execute, serialExecution, validate, downloadSerialExecutionTemplate, getForm, createSerialExcelDownloadMenu, createInputElement, hasEditAccess, getUserPref, getFieldId, addUsers, registerColumn

Properties (51): merlinTemplateDao, merlinHandler, merlinRunner, merlinPagesRest, userPrefService, userService, employeeService, executionData, userPref, errors, filename, wordBytes, download, pdfResult, filename, zipFilename, zipByteArray, validationErrors, stats, inputVariables, inputData, filename, excel, logViewerMenuItem, id...

Imports: 30 packages

Package: org.projectforge.plugins.merlin.rest

Source Code (abridged)

package org.projectforge.plugins.merlin.rest

import de.micromata.merlin.excel.ExcelSheet
import de.micromata.merlin.word.templating.VariableType
import jakarta.servlet.http.HttpServletRequest
import jakarta.validation.Valid
import mu.KotlinLogging
import org.projectforge.business.fibu.EmployeeService
import org.projectforge.business.user.UserGroupCache
import org.projectforge.business.user.service.UserPrefService
import org.projectforge.business.user.service.UserService
import org.projectforge.common.FormatterUtils
import org.projectforge.framework.i18n.translate
import org.projectforge.framework.persistence.user.api.ThreadLocalUserContext
import org.projectforge.framework.utils.NumberHelper
import org.projectforge.menu.MenuItem
import org.projectforge.menu.MenuItemTargetType
import org.projectforge.plugins.merlin.*
import org.projectforge.rest.admin.LogViewerPageRest
import org.projectforge.rest.config.Rest
import org.projectforge.rest.config.RestUtils
import org.projectforge.rest.core.AbstractDynamicPageRest
import org.projectforge.rest.core.PagesResolver
import org.projectforge.rest.core.RestResolver
import org.projectforge.rest.dto.FormLayoutData
import org.projectforge.rest.dto.PostData
import org.projectforge.ui.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile

private val log = KotlinLogging.logger {}

@RestController
@RequestMapping("${Rest.URL}/merlinexecution")
class MerlinExecutionPageRest : AbstractDynamicPageRest() {

    @Autowired
    private lateinit var merlinTemplateDao: MerlinTemplateDao

    @Autowired
    private lateinit var merlinHandler: MerlinHandler

    @Autowired
    private lateinit var merlinRunner: MerlinRunner

    @Autowired
    private lateinit var merlinPagesRest: MerlinPagesRest

    @Autowired
    private lateinit var userPrefService: UserPrefService

    @Autowired
    private lateinit var userService: UserService

    @Autowired
    private lateinit var employeeService: EmployeeService

    /**
     * Will be called, if the user wants to change his/her observeStatus.
     */
    @PostMapping("execute")
    fun execute(@Valid @RequestBody postData: PostData<MerlinExecutionData>): ResponseEntity<*> {
        MerlinPlugin.ensureUserLogSubscription()
        val executionData = postData.data
        log.info("User wants to execute '${executionData.name}'...")
        // Save input values as user preference:
        val userPref = getUserPref(executionData.id)
        userPref.inputVariables = executionData.inputVariables
        userPref.pdfFormat = executionData.pdfFormat
        val errors = validate(executionData)
        if (!errors.isNullOrEmpty()) {
            return ResponseEntity(ResponseAction(validationErrors = errors), HttpStatus.NOT_ACCEPTABLE)
        }
        val result = merlinRunner.executeTemplate(executionData.id, executionData.inputVariables)
        var filename = result.first
        val wordBytes = result.second
        var download = wordBytes
        if (executionData.pdfFormat) {
            try {
                val pdfResult = merlinRunner.convertToPdf(wordBytes, filename)
                filename = pdfResult.filename
                download = pdfResult.content
            } catch (ex: Throwable) {
                // Stackoverflow may occur.
                log.error("Error while converting to pdf (falling back to docx): ${ex.message}", ex)
            }
        }
        return RestUtils.downloadFile(filename, download)
    }

    @PostMapping("serialExecution/{id}")
    fun serialExecution(
        @PathVariable("id", required = true) id: Long,
        @RequestParam("file") file: MultipartFile
    ): ResponseEntity<*> {
        MerlinPlugin.ensureUserLogSubscription()
        val filename = file.originalFilename
        log.info {
            "User tries to upload serial execution file: id='$id', filename='$filename', size=${
                FormatterUtils.formatBytes(
                    file.size
                )
            }."
        }
        val result = file.inputStream.use { inputStream ->
            merlinRunner.serialExecuteTemplate(id, filename ?: "untitled.xlsx", inputStream)
                ?: throw IllegalArgumentException("Can't execute serial Excel file.")
        }
        val zipFilename = result.first
        val zipByteArray = result.second
        return RestUtils.downloadFile(zipFilename, zipByteArray)
    }

    private fun validate(data: MerlinExecutionData): List<ValidationError>? {
        val validationErrors = mutableListOf<ValidationError>()
        val stats = merlinHandler.analyze(data.id).statistics
// ... (truncated, total 393 lines)

Git History

868d6abb7 2025 -> 2026
420ce7f24 Merlin fix for export of employee list for serial function.
bf998d85f BankingServicesRest, DataTransferPublicServicesRest, MerlinExecutionPageRest, ButlerServicet: stream.use (streams weren't closed before?)
63081666f Source file headers: 2024-> 2025.
e80642c81 Migration stuff in progress... (all tests of all packages: OK).