This is an automated email from the ASF dual-hosted git repository.

jamesnetherton pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel-quarkus.git


The following commit(s) were added to refs/heads/main by this push:
     new 855afd72734 Add a Camel Dev UI expression evaluator page
855afd72734 is described below

commit 855afd72734437068973d354e461e382cec4607c
Author: James Netherton <[email protected]>
AuthorDate: Thu Dec 3 07:05:53 2026 +0000

    Add a Camel Dev UI expression evaluator page
    
    Wraps the Camel eval-language dev console in a Dev UI page that
    evaluates an expression or predicate in any language available in the
    application, against a sample message with optional body, headers and
    variables. Results, and parse or evaluation errors, are shown on the
    page. When Simple is selected, a side panel lists its functions from the
    Camel catalog, grouped and searchable, and inserts one at the cursor
    when clicked.
    
    Expressions run with full application privileges, so the page and its
    JSON-RPC service are registered in dev mode only. The service does not
    log submitted expressions, inputs or results.
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .../devui/CamelCoreDevConsoleProcessor.java        |  38 ++
 .../dev-ui/qwc-camel-core-expression-evaluator.js  | 499 +++++++++++++++++++++
 ...melQuarkusCoreDevUIExpressionEvaluatorTest.java | 174 +++++++
 .../quarkus/devui/CamelCoreDevUIRecorder.java      |   5 +
 .../CamelExpressionEvaluatorDevUIService.java      | 208 +++++++++
 5 files changed, 924 insertions(+)

diff --git 
a/extensions-core/core/deployment/src/main/java/org/apache/camel/quarkus/core/deployment/devui/CamelCoreDevConsoleProcessor.java
 
b/extensions-core/core/deployment/src/main/java/org/apache/camel/quarkus/core/deployment/devui/CamelCoreDevConsoleProcessor.java
index ecad1a7a707..21f2cbe4725 100644
--- 
a/extensions-core/core/deployment/src/main/java/org/apache/camel/quarkus/core/deployment/devui/CamelCoreDevConsoleProcessor.java
+++ 
b/extensions-core/core/deployment/src/main/java/org/apache/camel/quarkus/core/deployment/devui/CamelCoreDevConsoleProcessor.java
@@ -16,11 +16,14 @@
  */
 package org.apache.camel.quarkus.core.deployment.devui;
 
+import java.nio.file.Path;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.stream.Collectors;
 
 import io.quarkus.deployment.IsDevelopment;
 import io.quarkus.deployment.annotations.BuildProducer;
@@ -31,11 +34,14 @@ import io.quarkus.deployment.annotations.Record;
 import io.quarkus.devjsonrpc.spi.JsonRPCProvidersBuildItem;
 import io.quarkus.devui.spi.page.CardPageBuildItem;
 import io.quarkus.devui.spi.page.Page;
+import org.apache.camel.quarkus.core.deployment.spi.CamelServiceBuildItem;
 import org.apache.camel.quarkus.devui.CamelCoreDevUIRecorder;
 import org.apache.camel.quarkus.devui.CamelCoreDevUIService;
+import org.apache.camel.quarkus.devui.CamelExpressionEvaluatorDevUIService;
 
 @BuildSteps(onlyIf = IsDevelopment.class)
 public class CamelCoreDevConsoleProcessor {
+    private static final String LANGUAGE_SERVICE_PATH = 
"META-INF/services/org/apache/camel/language";
 
     @BuildStep
     void createDevUICards(BuildProducer<CardPageBuildItem> cardsProducer) {
@@ -79,6 +85,12 @@ public class CamelCoreDevConsoleProcessor {
                 .componentLink("qwc-camel-core-events.js")
                 .metadata(CamelDevUIConstants.CONSOLE_ID_METADATA_KEY, 
"event"));
 
+        cardPageBuildItem.addPage(Page.webComponentPageBuilder()
+                .title("Expression Evaluator")
+                .icon("font-awesome-solid:flask")
+                .componentLink("qwc-camel-core-expression-evaluator.js")
+                .metadata(CamelDevUIConstants.CONSOLE_ID_METADATA_KEY, 
CamelDevUIConstants.CONSOLE_ID_NONE));
+
         cardPageBuildItem.addPage(Page.webComponentPageBuilder()
                 .title("Inflight Exchanges")
                 .icon("font-awesome-solid:plane")
@@ -125,6 +137,32 @@ public class CamelCoreDevConsoleProcessor {
         return new JsonRPCProvidersBuildItem(CamelCoreDevUIService.class);
     }
 
+    @BuildStep
+    JsonRPCProvidersBuildItem createJsonRPCServiceForExpressionEvaluator() {
+        return new 
JsonRPCProvidersBuildItem(CamelExpressionEvaluatorDevUIService.class);
+    }
+
+    @BuildStep
+    @Record(ExecutionTime.STATIC_INIT)
+    void recordExpressionEvaluatorLanguages(
+            CamelCoreDevUIRecorder recorder,
+            List<CamelServiceBuildItem> camelServices) {
+        List<String> languageNames = camelServices.stream()
+                .map(CamelServiceBuildItem::getPath)
+                .filter(CamelCoreDevConsoleProcessor::isLanguageService)
+                .map(path -> path.getFileName().toString())
+                .distinct()
+                .sorted()
+                .collect(Collectors.toCollection(ArrayList::new));
+        recorder.setExpressionEvaluatorLanguages(languageNames);
+    }
+
+    private static boolean isLanguageService(Path path) {
+        // The path may belong to a jar file system, so compare its string 
form rather than Path instances
+        Path parent = path.getParent();
+        return parent != null && 
LANGUAGE_SERVICE_PATH.equals(parent.toString().replace('\\', '/'));
+    }
+
     @BuildStep
     @Record(ExecutionTime.STATIC_INIT)
     void recordAllowedConsoleMetadata(
diff --git 
a/extensions-core/core/deployment/src/main/resources/dev-ui/qwc-camel-core-expression-evaluator.js
 
b/extensions-core/core/deployment/src/main/resources/dev-ui/qwc-camel-core-expression-evaluator.js
new file mode 100644
index 00000000000..be9088a6e8b
--- /dev/null
+++ 
b/extensions-core/core/deployment/src/main/resources/dev-ui/qwc-camel-core-expression-evaluator.js
@@ -0,0 +1,499 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+import {css, html, QwcHotReloadElement} from 'qwc-hot-reload-element';
+import {JsonRpc} from 'jsonrpc';
+import '@vaadin/button';
+import '@vaadin/details';
+import '@vaadin/icon';
+import '@vaadin/select';
+import '@vaadin/text-area';
+import '@vaadin/text-field';
+import '@qomponent/qui-badge';
+
+const MODES = [
+    {label: 'Expression', value: 'expression'},
+    {label: 'Predicate', value: 'predicate'},
+];
+
+/**
+ * Evaluates an expression or predicate against a sample message using the 
Camel eval-language dev console.
+ * Everything typed into the form stays in this component's memory only.
+ */
+export class QwcCamelCoreExpressionEvaluator extends QwcHotReloadElement {
+    jsonRpc = new JsonRpc(this);
+
+    static styles = css`
+        :host {
+            display: flex;
+            height: 100%;
+            gap: var(--lumo-space-m);
+            padding: var(--lumo-space-m);
+            box-sizing: border-box;
+        }
+
+        .main {
+            flex: 1;
+            min-width: 0;
+            display: flex;
+            flex-direction: column;
+            gap: var(--lumo-space-s);
+            overflow: auto;
+        }
+
+        .toolbar {
+            display: flex;
+            flex-wrap: wrap;
+            align-items: baseline;
+            gap: var(--lumo-space-s);
+        }
+
+        .expression, .body {
+            width: 100%;
+            font-family: var(--lumo-font-family-monospace, monospace);
+        }
+
+        .expression {
+            min-height: 6em;
+        }
+
+        .entries {
+            display: flex;
+            flex-direction: column;
+            gap: var(--lumo-space-xs);
+        }
+
+        .entry {
+            display: flex;
+            gap: var(--lumo-space-xs);
+            align-items: baseline;
+        }
+
+        .entry vaadin-text-field {
+            flex: 1;
+        }
+
+        .hint {
+            color: var(--lumo-secondary-text-color);
+            font-size: var(--lumo-font-size-s);
+        }
+
+        .section-title {
+            font-weight: bold;
+            margin-top: var(--lumo-space-s);
+        }
+
+        .result {
+            border: 1px solid var(--lumo-contrast-20pct);
+            border-radius: var(--lumo-border-radius-m);
+            padding: var(--lumo-space-s) var(--lumo-space-m);
+        }
+
+        .result.failed {
+            border-color: var(--lumo-error-color);
+            background: var(--lumo-error-color-10pct);
+        }
+
+        .result pre {
+            margin: var(--lumo-space-xs) 0;
+            white-space: pre-wrap;
+            word-break: break-word;
+            font-family: var(--lumo-font-family-monospace, monospace);
+            font-size: var(--lumo-font-size-s);
+        }
+
+        .null {
+            color: var(--lumo-secondary-text-color);
+            font-style: italic;
+        }
+
+        .error-type {
+            color: var(--lumo-error-text-color);
+            font-weight: bold;
+        }
+
+        .functions {
+            width: 20em;
+            flex-shrink: 0;
+            display: flex;
+            flex-direction: column;
+            gap: var(--lumo-space-xs);
+            overflow: auto;
+            border-left: 1px solid var(--lumo-contrast-10pct);
+            padding-left: var(--lumo-space-m);
+        }
+
+        .functions ul {
+            list-style: none;
+            margin: 0;
+            padding: 0;
+        }
+
+        .functions li {
+            cursor: pointer;
+            padding: var(--lumo-space-xs);
+            border-radius: var(--lumo-border-radius-s);
+        }
+
+        .functions li:hover {
+            background: var(--lumo-contrast-5pct);
+        }
+
+        .functions li code {
+            font-size: var(--lumo-font-size-s);
+            word-break: break-all;
+        }
+
+        .function-name {
+            color: var(--lumo-secondary-text-color);
+            font-size: var(--lumo-font-size-xs);
+        }
+
+        .capitalized {
+            text-transform: capitalize;
+        }
+    `;
+
+    static properties = {
+        _info: {state: true},
+        _simpleFunctions: {state: true},
+        _language: {state: true},
+        _mode: {state: true},
+        _expression: {state: true},
+        _body: {state: true},
+        _headers: {state: true},
+        _variables: {state: true},
+        _resultType: {state: true},
+        _result: {state: true},
+        _evaluating: {state: true},
+        _functionFilter: {state: true},
+    };
+
+    constructor() {
+        super();
+        this._info = null;
+        this._simpleFunctions = null;
+        this._language = 'simple';
+        this._mode = 'expression';
+        this._expression = '';
+        this._body = '';
+        this._headers = [];
+        this._variables = [];
+        this._resultType = '';
+        this._result = null;
+        this._evaluating = false;
+        this._functionFilter = '';
+    }
+
+    connectedCallback() {
+        super.connectedCallback();
+        this.hotReload();
+    }
+
+    hotReload() {
+        this.jsonRpc.getEvaluatorInfo().then(response => {
+            this._info = JSON.parse(response.result);
+            const languages = this._info.languages || [];
+            if (languages.length > 0 && !languages.includes(this._language)) {
+                this._language = languages.includes('simple') ? 'simple' : 
languages[0];
+            }
+        });
+        this.jsonRpc.getSimpleFunctions().then(response => {
+            this._simpleFunctions = JSON.parse(response.result);
+        });
+    }
+
+    render() {
+        if (!this._info) {
+            return html`<div class="main">Loading...</div>`;
+        }
+        return html`
+            <div class="main">
+                <div class="toolbar">
+                    <vaadin-select
+                            label="Language"
+                            .items="${(this._info.languages || []).map(l => 
({label: l, value: l}))}"
+                            .value="${this._language}"
+                            @value-changed="${e => 
this._setLanguage(e.detail.value)}">
+                    </vaadin-select>
+                    <vaadin-select
+                            label="Evaluate as"
+                            .items="${MODES}"
+                            .value="${this._mode}"
+                            @value-changed="${e => 
this._setMode(e.detail.value)}">
+                    </vaadin-select>
+                    <vaadin-text-field
+                            label="Result type"
+                            placeholder="java.lang.String"
+                            .value="${this._resultType}"
+                            ?disabled=${this._mode === 'predicate'}
+                            @value-changed="${e => this._resultType = 
e.detail.value}">
+                    </vaadin-text-field>
+                    <vaadin-button
+                            theme="primary"
+                            ?disabled=${this._evaluating || 
!this._expression.trim()}
+                            @click="${this._evaluate}">
+                        <vaadin-icon icon="font-awesome-solid:play" 
slot="prefix"></vaadin-icon>
+                        Evaluate
+                    </vaadin-button>
+                </div>
+                <vaadin-text-area
+                        class="expression"
+                        label="${this._mode === 'predicate' ? 'Predicate' : 
'Expression'}"
+                        helper-text="Press Ctrl+Enter (Cmd+Enter on macOS) to 
evaluate"
+                        .value="${this._expression}"
+                        @value-changed="${e => this._expression = 
e.detail.value}"
+                        @keydown="${this._onExpressionKeyDown}">
+                </vaadin-text-area>
+                ${this._renderResult()}
+                <vaadin-details summary="Sample message" opened>
+                    <div class="hint">
+                        The expression is evaluated against this message. Set 
the body, headers and variables that
+                        the expression reads, for example with 
<code>\${body}</code>, <code>\${header.name}</code> or
+                        <code>\${variable.name}</code>.
+                    </div>
+                    <vaadin-text-area
+                            class="body"
+                            label="Body"
+                            .value="${this._body}"
+                            @value-changed="${e => this._body = 
e.detail.value}">
+                    </vaadin-text-area>
+                    ${this._renderEntries('Headers', '_headers')}
+                    ${this._renderEntries('Variables', '_variables')}
+                </vaadin-details>
+            </div>
+            ${this._renderSimpleFunctions()}
+        `;
+    }
+
+    _renderEntries(title, property) {
+        const entries = this[property];
+        return html`
+            <div class="section-title">${title}</div>
+            <div class="entries">
+                ${entries.map((entry, index) => html`
+                    <div class="entry">
+                        <vaadin-text-field
+                                placeholder="Name"
+                                .value="${entry.key}"
+                                @value-changed="${e => 
this._updateEntry(property, index, 'key', e.detail.value)}">
+                        </vaadin-text-field>
+                        <vaadin-text-field
+                                placeholder="Value"
+                                .value="${entry.value}"
+                                @value-changed="${e => 
this._updateEntry(property, index, 'value', e.detail.value)}">
+                        </vaadin-text-field>
+                        <vaadin-button
+                                theme="tertiary icon"
+                                aria-label="Remove"
+                                @click="${() => this._removeEntry(property, 
index)}">
+                            <vaadin-icon 
icon="font-awesome-solid:trash"></vaadin-icon>
+                        </vaadin-button>
+                    </div>
+                `)}
+                <div>
+                    <vaadin-button theme="tertiary small" @click="${() => 
this._addEntry(property)}">
+                        <vaadin-icon icon="font-awesome-solid:plus" 
slot="prefix"></vaadin-icon>
+                        Add
+                    </vaadin-button>
+                </div>
+            </div>
+        `;
+    }
+
+    _renderResult() {
+        const result = this._result;
+        if (!result) {
+            return '';
+        }
+        if (result.status === 'success') {
+            if (result.predicate && (result.result === 'true' || result.result 
=== 'false')) {
+                return html`
+                    <div class="result">
+                        Result:
+                        <qui-badge level="${result.result === 'true' ? 
'success' : 'contrast'}"><span>${result.result}</span></qui-badge>
+                    </div>`;
+            }
+            return html`
+                <div class="result">
+                    Result:
+                    ${result.result === undefined || result.result === null
+                        ? html`<pre class="null">null</pre>`
+                        : html`<pre>${result.result}</pre>`}
+                </div>`;
+        }
+        const exception = result.exception || {};
+        const stackTrace = this._unescape(exception.stackTrace);
+        return html`
+            <div class="result failed">
+                <span class="error-type">${exception.type || 'Error'}</span>
+                <pre>${exception.message ?? result.message ?? 'The expression 
could not be evaluated'}</pre>
+                ${stackTrace ? html`
+                    <vaadin-details summary="Stack trace">
+                        <pre>${stackTrace}</pre>
+                    </vaadin-details>` : ''}
+            </div>`;
+    }
+
+    _renderSimpleFunctions() {
+        if (this._language !== 'simple' || !this._simpleFunctions) {
+            return '';
+        }
+        const filter = this._functionFilter.toLowerCase();
+        const matches = text => text && text.toLowerCase().includes(filter);
+        const functions = (this._simpleFunctions.functions || []).filter(fn => 
!filter
+            || matches(fn.syntax) || matches(fn.displayName) || 
matches(fn.description));
+        const custom = (this._simpleFunctions.customFunctions || [])
+            .filter(name => !filter || matches(name))
+            .map(name => ({syntax: '${' + name + '}', displayName: name}));
+
+        // Group in catalog order, with the custom functions first
+        const groups = new Map();
+        if (custom.length > 0) {
+            groups.set('custom', custom);
+        }
+        functions.forEach(fn => {
+            const group = fn.group || 'other';
+            if (!groups.has(group)) {
+                groups.set(group, []);
+            }
+            groups.get(group).push(fn);
+        });
+
+        return html`
+            <div class="functions">
+                <vaadin-text-field
+                        placeholder="Search functions"
+                        clear-button-visible
+                        .value="${this._functionFilter}"
+                        @value-changed="${e => this._functionFilter = 
e.detail.value}">
+                    <vaadin-icon slot="prefix" 
icon="font-awesome-solid:magnifying-glass"></vaadin-icon>
+                </vaadin-text-field>
+                ${this._simpleFunctions.error ? html`<span 
class="null">${this._simpleFunctions.error}</span>` : ''}
+                ${[...groups.entries()].map(([group, items]) => html`
+                    <div class="section-title capitalized">
+                        ${group} <qui-badge small 
pill><span>${items.length}</span></qui-badge>
+                    </div>
+                    <ul>${items.map(fn => html`
+                        <li title="${fn.description ?? ''}" @click="${() => 
this._insertAtCursor(fn.syntax)}">
+                            <code>${fn.syntax}</code>
+                            ${fn.displayName && fn.displayName !== fn.syntax
+                                ? html`<div 
class="function-name">${fn.displayName}</div>` : ''}
+                        </li>`)}
+                    </ul>
+                `)}
+            </div>
+        `;
+    }
+
+    _insertAtCursor(text) {
+        const textArea = 
this.shadowRoot.querySelector('vaadin-text-area.expression');
+        const input = textArea?.inputElement;
+        const value = this._expression;
+        const start = input ? input.selectionStart : value.length;
+        const end = input ? input.selectionEnd : value.length;
+        this._expression = value.slice(0, start) + text + value.slice(end);
+        this.updateComplete.then(() => {
+            if (input) {
+                input.focus();
+                input.setSelectionRange(start + text.length, start + 
text.length);
+            }
+        });
+    }
+
+    _setLanguage(language) {
+        if (language !== this._language) {
+            this._language = language;
+            this._result = null;
+        }
+    }
+
+    _setMode(mode) {
+        if (mode !== this._mode) {
+            this._mode = mode;
+            this._result = null;
+        }
+    }
+
+    _onExpressionKeyDown(e) {
+        if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
+            e.preventDefault();
+            this._evaluate();
+        }
+    }
+
+    _evaluate() {
+        if (this._evaluating || !this._expression.trim()) {
+            return;
+        }
+        this._evaluating = true;
+        const predicate = this._mode === 'predicate';
+        this.jsonRpc.evaluateExpression({
+            'language': this._language,
+            'expression': this._expression,
+            'predicate': predicate,
+            'body': this._body,
+            'headers': this._toMap(this._headers),
+            'variables': this._toMap(this._variables),
+            'resultType': predicate ? '' : this._resultType,
+        }).then(response => {
+            this._result = {...JSON.parse(response.result), predicate};
+        }).catch(error => {
+            this._result = {
+                status: 'failed',
+                exception: {message: error?.error?.message ?? 'The evaluation 
request failed'},
+            };
+        }).finally(() => {
+            this._evaluating = false;
+        });
+    }
+
+    _toMap(entries) {
+        const map = {};
+        entries.filter(entry => entry.key.trim()).forEach(entry => 
map[entry.key.trim()] = entry.value);
+        return map;
+    }
+
+    _addEntry(property) {
+        this[property] = [...this[property], {key: '', value: ''}];
+    }
+
+    _removeEntry(property, index) {
+        this[property] = this[property].filter((_, i) => i !== index);
+    }
+
+    _updateEntry(property, index, field, value) {
+        const entries = [...this[property]];
+        entries[index] = {...entries[index], [field]: value};
+        this[property] = entries;
+    }
+
+    _unescape(value) {
+        if (!value) {
+            return '';
+        }
+        // The console JSON-escapes the stack trace text, so decode each 
escape sequence in a single pass
+        const escapes = {'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': 
'\t'};
+        return value.replace(/\\(u[0-9a-fA-F]{4}|[\s\S])/g, (match, escape) => 
{
+            if (escape.length === 5) {
+                return String.fromCharCode(parseInt(escape.slice(1), 16));
+            }
+            return escapes[escape] ?? escape;
+        });
+    }
+}
+
+customElements.define('qwc-camel-core-expression-evaluator', 
QwcCamelCoreExpressionEvaluator);
diff --git 
a/extensions-core/core/deployment/src/test/java/org/apache/camel/quarkus/core/deployment/devui/CamelQuarkusCoreDevUIExpressionEvaluatorTest.java
 
b/extensions-core/core/deployment/src/test/java/org/apache/camel/quarkus/core/deployment/devui/CamelQuarkusCoreDevUIExpressionEvaluatorTest.java
new file mode 100644
index 00000000000..c851d43927c
--- /dev/null
+++ 
b/extensions-core/core/deployment/src/test/java/org/apache/camel/quarkus/core/deployment/devui/CamelQuarkusCoreDevUIExpressionEvaluatorTest.java
@@ -0,0 +1,174 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+package org.apache.camel.quarkus.core.deployment.devui;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import io.quarkus.arc.Unremovable;
+import io.quarkus.devui.tests.DevUIJsonRPCTest;
+import io.quarkus.test.QuarkusDevModeTest;
+import io.vertx.core.json.Json;
+import io.vertx.core.json.JsonObject;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Named;
+import org.jboss.shrinkwrap.api.asset.StringAsset;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class CamelQuarkusCoreDevUIExpressionEvaluatorTest extends 
DevUIJsonRPCTest {
+    @RegisterExtension
+    static final QuarkusDevModeTest CONFIG = new QuarkusDevModeTest()
+            .withApplicationRoot(jar -> jar
+                    .addClass(Greeter.class)
+                    .addAsResource(new StringAsset("greeting=Hello from 
config\n"), "application.properties"));
+
+    public CamelQuarkusCoreDevUIExpressionEvaluatorTest() {
+        super("org.apache.camel.quarkus.camel-quarkus-core");
+    }
+
+    @Test
+    void evaluatorInfoListsLanguages() throws Exception {
+        JsonObject info = (JsonObject) 
Json.decodeValue(executeJsonRPCMethod(String.class, "getEvaluatorInfo"));
+        List<?> languages = info.getJsonArray("languages").getList();
+        // bean comes from camel-bean, on the test classpath
+        assertTrue(languages.containsAll(List.of("bean", "constant", "header", 
"simple")), languages::toString);
+    }
+
+    @Test
+    void simpleExpressionWithMessage() throws Exception {
+        JsonObject result = evaluate("simple", "${body} ${header.FOO} 
${variable.bar}", false,
+                "Hello", Map.of("foo", "header-value"), Map.of("bar", 
"variable-value"), "");
+        assertSuccess("Hello header-value variable-value", result);
+    }
+
+    @Test
+    void simplePredicate() throws Exception {
+        assertSuccess("true", evaluate("simple", "${header.count} > 5", true, 
"", Map.of("count", "10"), Map.of(), ""));
+        assertSuccess("false", evaluate("simple", "${header.count} > 5", true, 
"", Map.of("count", "1"), Map.of(), ""));
+    }
+
+    @Test
+    void simpleSyntaxError() throws Exception {
+        JsonObject result = evaluate("simple", "${unknownFunctionXyz}", false, 
"", Map.of(), Map.of(), "");
+        assertEquals("failed", result.getString("status"), result::encode);
+        JsonObject exception = result.getJsonObject("exception");
+        
assertTrue(exception.getString("type").endsWith("IllegalSyntaxException"), 
result::encode);
+        
assertTrue(exception.getString("message").contains("unknownFunctionXyz"), 
result::encode);
+    }
+
+    @Test
+    void simpleEvaluationError() throws Exception {
+        JsonObject result = evaluate("simple", "${bean:missingBean}", false, 
"", Map.of(), Map.of(), "");
+        assertEquals("failed", result.getString("status"), result::encode);
+        
assertTrue(result.getJsonObject("exception").getString("message").contains("missingBean"),
 result::encode);
+    }
+
+    @Test
+    void evaluationHasNoRouteContext() throws Exception {
+        JsonObject routeId = evaluate("simple", "${routeId}", false, "", 
Map.of(), Map.of(), "");
+        assertEquals("success", routeId.getString("status"), routeId::encode);
+        assertFalse(routeId.containsKey("result"), routeId::encode);
+
+        assertSuccess("camel-1", evaluate("simple", "${camelId}", false, "", 
Map.of(), Map.of(), ""));
+    }
+
+    @Test
+    void simpleRunsWithApplicationPrivileges() throws Exception {
+        assertSuccess("Hello World", evaluate("simple", 
"${bean:greeter?method=hello}", false,
+                "World", Map.of(), Map.of(), ""));
+        assertSuccess("WORLD", evaluate("simple", "${body.toUpperCase()}", 
false, "World", Map.of(), Map.of(), ""));
+        assertSuccess("Hello from config", evaluate("simple", "{{greeting}}", 
false, "", Map.of(), Map.of(), ""));
+    }
+
+    @Test
+    void otherLanguages() throws Exception {
+        assertSuccess("fixed", evaluate("constant", "fixed", false, "", 
Map.of(), Map.of(), ""));
+        assertSuccess("header-value", evaluate("header", "foo", false, "", 
Map.of("foo", "header-value"), Map.of(), ""));
+    }
+
+    @Test
+    void resultTypeIsAccepted() throws Exception {
+        assertSuccess("Hello", evaluate("simple", "${body}", false, "Hello", 
Map.of(), Map.of(), "java.lang.String"));
+    }
+
+    @Test
+    void unknownLanguageFails() throws Exception {
+        JsonObject result = evaluate("groovy", "anything", false, "", 
Map.of(), Map.of(), "");
+        assertEquals("failed", result.getString("status"), result::encode);
+        
assertTrue(result.getJsonObject("exception").getString("type").endsWith("NoSuchLanguageException"),
 result::encode);
+    }
+
+    @Test
+    void blankExpressionIsRejected() throws Exception {
+        JsonObject result = evaluate("simple", " ", false, "", Map.of(), 
Map.of(), "");
+        assertEquals("failed", result.getString("status"), result::encode);
+    }
+
+    @Test
+    void evalLanguageConsoleIsNotReachableThroughGenericBridge() throws 
Exception {
+        String result = executeJsonRPCMethod(String.class, "getConsoleJSON",
+                Map.of("id", "eval-language", "options", Map.of("template", 
"${camelId}")));
+        assertEquals("{}", result);
+    }
+
+    @Test
+    void simpleFunctionsComeFromCatalog() throws Exception {
+        JsonObject json = (JsonObject) 
Json.decodeValue(executeJsonRPCMethod(String.class, "getSimpleFunctions"));
+        assertFalse(json.containsKey("error"), json::encode);
+        JsonObject bodyAs = json.getJsonArray("functions").stream()
+                .map(JsonObject.class::cast)
+                .filter(fn -> "${bodyAs(type)}".equals(fn.getString("syntax")))
+                .findFirst()
+                .orElseThrow(() -> new AssertionError("${bodyAs(type)} not 
found in " + json.encode()));
+        assertEquals("core", bodyAs.getString("group"));
+        assertFalse(bodyAs.getString("description").isBlank());
+        assertTrue(json.getJsonArray("customFunctions").isEmpty(), 
json::encode);
+    }
+
+    private JsonObject evaluate(String language, String expression, boolean 
predicate, String body,
+            Map<String, String> headers, Map<String, String> variables, String 
resultType) throws Exception {
+        Map<String, Object> params = new HashMap<>();
+        params.put("language", language);
+        params.put("expression", expression);
+        params.put("predicate", predicate);
+        params.put("body", body);
+        params.put("headers", headers);
+        params.put("variables", variables);
+        params.put("resultType", resultType);
+        return (JsonObject) 
Json.decodeValue(executeJsonRPCMethod(String.class, "evaluateExpression", 
params));
+    }
+
+    private static void assertSuccess(String expected, JsonObject result) {
+        assertEquals("success", result.getString("status"), result::encode);
+        assertEquals(expected, result.getString("result"), result::encode);
+    }
+
+    @Named("greeter")
+    @ApplicationScoped
+    @Unremovable
+    public static class Greeter {
+        public String hello(String name) {
+            return "Hello " + name;
+        }
+    }
+}
diff --git 
a/extensions-core/core/runtime/src/main/java/org/apache/camel/quarkus/devui/CamelCoreDevUIRecorder.java
 
b/extensions-core/core/runtime/src/main/java/org/apache/camel/quarkus/devui/CamelCoreDevUIRecorder.java
index 6af0b5348c5..c49993803b7 100644
--- 
a/extensions-core/core/runtime/src/main/java/org/apache/camel/quarkus/devui/CamelCoreDevUIRecorder.java
+++ 
b/extensions-core/core/runtime/src/main/java/org/apache/camel/quarkus/devui/CamelCoreDevUIRecorder.java
@@ -16,6 +16,7 @@
  */
 package org.apache.camel.quarkus.devui;
 
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
@@ -30,4 +31,8 @@ public class CamelCoreDevUIRecorder {
     public void setAllowedConsoleOptions(Map<String, String> optionSpecs) {
         CamelCoreDevUIService.setAllowedConsoleOptions(optionSpecs);
     }
+
+    public void setExpressionEvaluatorLanguages(List<String> languages) {
+        CamelExpressionEvaluatorDevUIService.setLanguages(languages);
+    }
 }
diff --git 
a/extensions-core/core/runtime/src/main/java/org/apache/camel/quarkus/devui/CamelExpressionEvaluatorDevUIService.java
 
b/extensions-core/core/runtime/src/main/java/org/apache/camel/quarkus/devui/CamelExpressionEvaluatorDevUIService.java
new file mode 100644
index 00000000000..b19647fc0f4
--- /dev/null
+++ 
b/extensions-core/core/runtime/src/main/java/org/apache/camel/quarkus/devui/CamelExpressionEvaluatorDevUIService.java
@@ -0,0 +1,208 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+package org.apache.camel.quarkus.devui;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import io.quarkus.arc.Arc;
+import io.quarkus.arc.ArcContainer;
+import io.smallrye.common.annotation.Blocking;
+import jakarta.enterprise.context.ApplicationScoped;
+import org.apache.camel.CamelContext;
+import org.apache.camel.catalog.RuntimeCamelCatalog;
+import org.apache.camel.catalog.impl.AbstractCamelCatalog;
+import org.apache.camel.console.DevConsole;
+import org.apache.camel.console.DevConsoleRegistry;
+import org.apache.camel.support.PluginHelper;
+import org.apache.camel.util.CaseInsensitiveMap;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
+
+/**
+ * Dev UI service backing the expression evaluator page. It wraps the Camel 
{@code eval-language} dev console.
+ * <p>
+ * Evaluating an expression runs code with full application privileges, so 
this service is registered only in dev mode.
+ * It has no logger and never throws, since submitted expressions, inputs and 
results may contain secrets, and the
+ * Dev UI JSON-RPC layer logs exceptions thrown by its methods.
+ */
+@ApplicationScoped
+public class CamelExpressionEvaluatorDevUIService {
+    static final String EVAL_LANGUAGE_CONSOLE_ID = "eval-language";
+
+    private static volatile List<String> LANGUAGES = Collections.emptyList();
+
+    static void setLanguages(List<String> languages) {
+        LANGUAGES = List.copyOf(languages);
+    }
+
+    /**
+     * Gets the languages available in the application.
+     *
+     * @return JSON String with the key {@code languages}
+     */
+    @Blocking
+    public String getEvaluatorInfo() {
+        JsonObject info = new JsonObject();
+        info.put("languages", new JsonArray(LANGUAGES));
+        return info.toJson();
+    }
+
+    /**
+     * Gets the Simple language functions: the built-in ones from the Camel 
catalog, with their syntax and description, and
+     * the names of the custom functions registered in the application.
+     *
+     * @return JSON String with the keys {@code functions} and {@code 
customFunctions}
+     */
+    @Blocking
+    public String getSimpleFunctions() {
+        JsonObject response = new JsonObject();
+        JsonArray functions = new JsonArray();
+        JsonArray customFunctions = new JsonArray();
+        response.put("functions", functions);
+        response.put("customFunctions", customFunctions);
+
+        try {
+            CamelContext camelContext = getCamelContext();
+            if (camelContext == null) {
+                return response.toJson();
+            }
+
+            RuntimeCamelCatalog catalog = 
camelContext.getCamelContextExtension()
+                    .getContextPlugin(RuntimeCamelCatalog.class);
+            // The language schemas are part of the full catalog 
implementation, not the RuntimeCamelCatalog interface
+            String json = catalog instanceof AbstractCamelCatalog fullCatalog 
? fullCatalog.languageJSonSchema("simple") : null;
+            if (json != null && Jsoner.deserialize(json) instanceof JsonObject 
schema
+                    && schema.get("functions") instanceof JsonObject 
catalogFunctions) {
+                for (Map.Entry<String, Object> entry : 
catalogFunctions.entrySet()) {
+                    if (entry.getValue() instanceof JsonObject function && 
!function.getBooleanOrDefault("deprecated", false)) {
+                        JsonObject item = new JsonObject();
+                        item.put("syntax", 
function.getStringOrDefault("prefix", "${") + entry.getKey()
+                                + function.getStringOrDefault("suffix", "}"));
+                        item.put("displayName", 
function.getString("displayName"));
+                        item.put("group", function.getString("group"));
+                        item.put("description", 
function.getString("description"));
+                        item.put("javaType", function.getString("javaType"));
+                        functions.add(item);
+                    }
+                }
+            }
+
+            List<String> custom = new ArrayList<>(
+                    
PluginHelper.getSimpleFunctionRegistry(camelContext).getCustomFunctionNames());
+            Collections.sort(custom);
+            customFunctions.addAll(custom);
+        } catch (Exception e) {
+            response.put("error", "Could not read the Simple functions: " + 
e.getMessage());
+        }
+        return response.toJson();
+    }
+
+    /**
+     * Evaluates an expression or predicate against a sample message, using 
the Camel {@code eval-language} dev console.
+     *
+     * @param  language   The language name
+     * @param  expression The expression or predicate text
+     * @param  predicate  Whether to evaluate as a predicate
+     * @param  body       Optional message body
+     * @param  headers    Optional message headers
+     * @param  variables  Optional exchange variables
+     * @param  resultType Optional class name of the result type, passed to 
the language as in a route
+     * @return            JSON String representation of the eval-language 
console response
+     */
+    @Blocking
+    public String evaluateExpression(
+            String language,
+            String expression,
+            boolean predicate,
+            String body,
+            Map<String, String> headers,
+            Map<String, String> variables,
+            String resultType) {
+        try {
+            if (expression == null || expression.isBlank()) {
+                return failure("IllegalArgumentException", "The expression 
must not be blank");
+            }
+
+            DevConsole console = getEvalLanguageConsole();
+            if (console == null) {
+                return failure("IllegalStateException", "The Camel 
eval-language dev console is not available");
+            }
+
+            Map<String, Object> options = new HashMap<>();
+            options.put("language", language);
+            options.put("template", expression);
+            options.put("predicate", predicate);
+            if (body != null && !body.isEmpty()) {
+                options.put("body", body);
+            }
+            if (headers != null && !headers.isEmpty()) {
+                // Match how message headers behave in a route, where header 
names are case-insensitive
+                options.put("headers", new CaseInsensitiveMap(headers));
+            }
+            if (variables != null && !variables.isEmpty()) {
+                options.put("variables", new HashMap<>(variables));
+            }
+            if (resultType != null && !resultType.isBlank()) {
+                options.put("resultType", resultType.strip());
+            }
+
+            Object result = console.call(DevConsole.MediaType.JSON, options);
+            if (result instanceof JsonObject json) {
+                return json.toJson();
+            }
+            return failure("IllegalStateException", "The Camel eval-language 
dev console returned no result");
+        } catch (Exception e) {
+            return failure(e.getClass().getName(), e.getMessage());
+        }
+    }
+
+    private static CamelContext getCamelContext() {
+        ArcContainer container = Arc.container();
+        if (container == null) {
+            // The app is likely performing a dev mode hot reload, thus the 
container may be temporarily unavailable
+            return null;
+        }
+        return container.select(CamelContext.class).get();
+    }
+
+    private static DevConsole getEvalLanguageConsole() {
+        CamelContext camelContext = getCamelContext();
+        if (camelContext == null) {
+            return null;
+        }
+        DevConsoleRegistry registry = 
camelContext.getCamelContextExtension().getContextPlugin(DevConsoleRegistry.class);
+        if (registry == null) {
+            return null;
+        }
+        return registry.getConsole(EVAL_LANGUAGE_CONSOLE_ID).orElse(null);
+    }
+
+    private static String failure(String type, String message) {
+        JsonObject exception = new JsonObject();
+        exception.put("type", type);
+        exception.put("message", message);
+        JsonObject response = new JsonObject();
+        response.put("status", "failed");
+        response.put("exception", exception);
+        return response.toJson();
+    }
+}

Reply via email to