Workplace Widget 5.10.23

This commit is contained in:
chris
2026-11-08 17:45:04 +00:00
parent 180127e2ae
commit 60d35e2326
98 changed files with 4221 additions and 268 deletions

View File

@@ -0,0 +1,31 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WidgetWorkbench V5.10.19 – CheerpJ Java-11-Diagnose</title>
<style>
body{font:16px/1.55 system-ui,sans-serif;background:#152331;color:#e7eef4;margin:2rem;max-width:1050px}
a{display:inline-block;color:#89d5ff;margin:.2rem .6rem .2rem 0;padding:.25rem .6rem;border:1px solid #516c80;border-radius:6px;text-decoration:none}
a[aria-current="page"]{background:#34536b;border-color:#b0d0eb;color:white}
pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#0d1822;padding:1rem;border-radius:9px;min-height:12rem}
.hint{color:#bacfe0}.section{margin-block:1.25rem}button{font:inherit;color:white;background:#255978;padding:.5rem 1rem;border:1px solid #84beda;border-radius:7px;cursor:pointer}
code{color:#bee8ff}
</style>
<script type="module" src="./cheerpj-native-loader-test.js"></script>
</head>
<body>
<h1>CheerpJ Java 11 – Native-Loader-Diagnose</h1>
<p class="hint">Ohne iTAC-JARs, MES-Anmeldedaten oder Änderungen an proprietären Bibliotheken. Alle Tests laufen fest unter Java 11; jeder Link startet einen einzelnen Test in einer frischen Seite.</p>
<div class="section"><strong>Einzeltests</strong><nav id="modes" aria-label="Diagnosemodi"></nav></div>
<div class="section"><strong>CheerpJ-Release vergleichen (jeweils Java 11)</strong><nav id="runtime-links" aria-label="CheerpJ-Versionen"></nav></div>
<p class="hint"><code>environment</code> JDK/Modul, <code>sysprop</code> Java-Systemeigenschaften,
<code>direct</code> direktes JNI, <code>wwprobe</code> unabhängiger JS-Library-Loader,
<code>jaas</code> JDK-Bibliothek, <code>unix</code> echter UnixSystem-Konstruktor,
<code>bridge</code> Java-Hilfsklasse ohne UnixSystem-Konstruktor.
Ein bestandener Bridge-Test behebt den JDK-Konstruktor nicht.</p>
<pre id="result">Start noch nicht ausgeführt …</pre>
<button id="copy-report" type="button">Diagnosebericht kopieren</button>
<p class="hint">Bei <code>Missing import: JVM_LoadLibrary</code> bitte zusätzlich die ersten relevanten <code>[NATIVE-LOADER]</code>-Zeilen aus der Browserkonsole sichern. Der Bericht enthält keine MES-Anmeldedaten.</p>
</body>
</html>

View File

@@ -0,0 +1,189 @@
// WidgetWorkbench V5.10.19: self-contained, Java-11-only CheerpJ diagnostics.
// No iTAC JARs, MES calls, credentials or modification of JDK/vendor classes.
import wwprobeNativeHandlers from './cheerpj/natives/wwprobe.js';
const out = document.getElementById('result');
const diagnosticModes = ['environment', 'sysprop', 'direct', 'wwprobe', 'jaas', 'unix', 'bridge'];
const params = new URL(location.href).searchParams;
const mode = diagnosticModes.includes(params.get('mode')) ? params.get('mode') : 'environment';
const runtime = params.get('runtime') === '4.3' ? '4.3' : '5.0';
const pathVariant = params.get('path') === 'missing' ? 'missing' : 'normal';
const nativeRoot = '/backend/hmi/cheerpj/natives';
const classJar = '/backend/hmi/cheerpj/jaas-native-loader-smoke.jar';
const bridgeJar = '/backend/hmi/cheerpj/jaas-identity-bridge.jar';
const logs = [];
let resultCode = null;
let resultStatus = 'NOT_RUN';
const log = (...parts) => {
const line = parts.map(value => {
if (value === null) return 'null';
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return String(value);
return '(Objekt: siehe Konsole)';
}).join(' ');
logs.push(line);
out.textContent += line + '\n';
console.info('[WidgetWorkbench/NativeLoaderSmoke]', ...parts);
};
function renderModeLinks() {
const links = document.getElementById('modes');
if (!links) return;
for (const name of diagnosticModes) {
const a = document.createElement('a');
const url = new URL(location.href);
url.searchParams.set('mode', name);
url.searchParams.set('runtime', runtime);
url.searchParams.delete('path');
a.href = url.pathname + url.search;
a.textContent = name;
a.setAttribute('aria-current', name === mode ? 'page' : 'false');
links.appendChild(a);
}
const variants = document.getElementById('runtime-links');
if (!variants) return;
for (const name of ['5.0', '4.3']) {
const a = document.createElement('a');
const url = new URL(location.href);
url.searchParams.set('runtime', name);
a.href = url.pathname + url.search;
a.textContent = 'CheerpJ ' + name;
a.setAttribute('aria-current', name === runtime ? 'page' : 'false');
variants.appendChild(a);
}
}
function report() {
return [
'WidgetWorkbench 5.10.19 - CheerpJ Native Loader Diagnosis',
'CheerpJ runtime: ' + runtime + ' | Java: 11 | mode: ' + mode,
'java.library.path variant: ' + pathVariant,
'Run result: ' + resultStatus + (resultCode !== null ? ' (exit ' + resultCode + ')' : ''),
'No MES account information or internal URLs are recorded.',
'',
...logs,
'',
'NOTE: Java System.out/System.err and JVM_LoadLibrary events appear separately',
'in the browser developer console. Attach only the relevant [NATIVE-LOADER]',
'lines when reporting to the runtime vendor.',
].join('\n');
}
function installCopyButton() {
const btn = document.getElementById('copy-report');
if (!btn) return;
btn.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(report());
btn.textContent = 'Bericht kopiert';
} catch (_) {
const blob = new Blob([report()], { type: 'text/plain;charset=utf-8' });
const obj = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = obj;
a.download = 'cheerpj-native-' + runtime + '-' + mode + '.txt';
a.click();
URL.revokeObjectURL(obj);
btn.textContent = 'Bericht als Datei gespeichert';
}
});
}
async function checkResource(url, { range = false, module = false } = {}) {
const resp = await fetch(url, {
credentials: 'same-origin',
cache: 'no-store',
...(range ? { headers: { Range: 'bytes=0-0' } } : {}),
});
const type = resp.headers.get('content-type') || '(nicht angegeben)';
const ranges = resp.headers.get('accept-ranges') || '(nicht angegeben)';
const contentRange = resp.headers.get('content-range') || '(nicht angegeben)';
log(url, 'HTTP', resp.status, 'Content-Type:', type, 'Accept-Ranges:', ranges,
range ? 'Content-Range: ' + contentRange : '');
if (!resp.ok) throw new Error('Datei nicht abrufbar: ' + url + ' (HTTP ' + resp.status + ')');
if (range && resp.status !== 206) {
throw new Error('Java-JAR unterstützt keinen HTTP-Range-Abruf (HTTP ' + resp.status + '): ' + url);
}
if (range && !/^bytes\s+0-0\/\d+$/i.test(contentRange) && contentRange !== '(nicht angegeben)') {
throw new Error('Ungültige Content-Range für JAR: ' + contentRange);
}
if (module) {
const source = await resp.text();
if (type.toLowerCase().includes('text/html') || !source.includes('export default') ||
!source.includes('Java_com_')) {
throw new Error('JS-Native-Modul fehlt oder Server liefert HTML: ' + url);
}
} else if (resp.body && typeof resp.body.cancel === 'function') {
await resp.body.cancel(); // With Range, never fetch a complete large JAR.
}
}
async function ensureRuntimeLoader() {
if (typeof cheerpjInit === 'function') {
log('CheerpJ-Loader bereits verfügbar.');
return;
}
// Only these two fixed release URLs are permitted, never user-supplied URLs.
const url = 'https://cjrtnc.leaningtech.com/' + runtime + '/loader.js';
log('CheerpJ-Loader:', 'release ' + runtime);
await new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.onload = () => resolve();
script.onerror = () => reject(new Error('CheerpJ-Loader nicht erreichbar: release ' + runtime));
document.head.appendChild(script);
});
if (typeof cheerpjInit !== 'function') throw new Error('cheerpjInit nach Laden nicht verfügbar');
}
async function run() {
resultStatus = 'RUNNING';
log('V5.10.19 | Modus:', mode, '| Java 11 | CheerpJ:', runtime);
log('Dieser Test ist unabhängig von iTAC und GlassFish-Java-Prozessen.');
await checkResource(classJar, { range: true });
if (mode === 'bridge') await checkResource(bridgeJar, { range: true });
if (mode === 'direct' || mode === 'wwprobe') {
await checkResource(nativeRoot + '/wwprobe.js', { module: true });
} else if (mode === 'jaas' || mode === 'unix') {
await checkResource(nativeRoot + '/jaas.js', { module: true });
}
await ensureRuntimeLoader();
const libPath = pathVariant === 'missing'
? '/app/backend/hmi/cheerpj/absichtlich-nicht-vorhanden'
: '/app' + nativeRoot;
const settings = {
version: 11,
status: 'none',
javaProperties: ['java.library.path=' + libPath],
};
if (mode === 'direct') {
settings.natives = wwprobeNativeHandlers;
log('Direkter JNI-Handler registriert. Kein System.loadLibrary.');
} else {
log('Kein direkter Native-Handler registriert; Isolation des Testmodus.');
}
await cheerpjInit(settings);
log('CheerpJ Java 11 initialisiert; Testklasse starten …');
const classpath = '/app' + classJar + (mode === 'bridge' ? ':/app' + bridgeJar : '');
const code = await cheerpjRunMain('com.widgetworkbench.cheerpj.NativeLoaderSmoke', classpath, mode);
resultCode = typeof code === 'number' ? code : null;
resultStatus = code === 0 ? 'PASS' : 'FAIL';
log('Java-Exit-Code:', resultCode === null ? 'nicht numerisch' : resultCode);
log('TESTERGEBNIS:', resultStatus);
if (mode === 'direct' && code === 0) {
log('Direct JNI funktioniert. System.loadLibrary/UnixSystem ist dadurch NICHT repariert.');
} else if (mode === 'bridge' && code === 0) {
log('Java-Bridge funktioniert OHNE UnixSystem-Konstruktor. Kein produktiver Login-Workaround.');
}
log('Für vollständige Java-Fehlerdetails die [NATIVE-LOADER]-Zeilen aus der Browserkonsole hinzufügen.');
}
renderModeLinks();
installCopyButton();
out.textContent = '';
run().catch(error => {
resultStatus = 'ABORT';
// CheerpJ Java Throwable proxies can fail conversion to String(); preserve original.
console.error('[WidgetWorkbench/NativeLoaderSmoke] Original exception:', error);
const reason = error instanceof Error && typeof error.message === 'string'
? error.message : 'Java-/Runtime-Exception; Original in der Browserkonsole';
log('TESTABBRUCH:', reason);
});

View File

@@ -1,7 +1,20 @@
<!doctype html>
<html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>CheerpJ-Frame | WidgetWorkbench</title>
<style>html,body,#display{width:100%;height:100%;margin:0;padding:0;overflow:hidden;background:#14212e}body{display:flex;flex-direction:column;color:#a9e8f0;font:13px system-ui}#display{flex:1;min-height:0}#state{height:0;overflow:hidden} body.cheerpj-original-mode{display:block;overflow:auto}body.cheerpj-original-mode #display{width:1280px;height:1024px;min-width:1280px;min-height:1024px;flex:none} .fail{height:auto!important;max-height:80px!important;background:#510d1b;color:#fff;padding:8px;white-space:normal}</style>
<script src="https://cjrtnc.leaningtech.com/4.3/loader.js" defer></script>
<style>html,body,#display{width:100%;height:100%;margin:0;padding:0;overflow:hidden;background:#14212e}body{display:flex;flex-direction:column;color:#a9e8f0;font:13px system-ui}#display{flex:1;min-height:0}#state{height:0;overflow:hidden} body.cheerpj-original-mode{display:block;overflow:auto}body.cheerpj-original-mode #display{width:1280px;height:1024px;min-width:1280px;min-height:1024px;flex:none} body.cheerpj-standalone #state{height:auto;min-height:22px;overflow:visible;padding:5px 10px;font-size:12px;color:#c2e8ee;background:#1a3441;box-sizing:border-box;white-space:normal} .fail{height:auto!important;max-height:80px!important;background:#510d1b;color:#fff;padding:8px;white-space:normal}#window-diagnostics{position:fixed;right:10px;bottom:10px;z-index:2147483000;max-width:min(92vw,650px);max-height:70vh;overflow:auto;background:rgba(14,28,38,.98);color:#dbf7fa;border:1px solid #4d8a9b;border-radius:8px;box-shadow:0 5px 18px #0009;font:12px ui-monospace,monospace}
#window-diagnostics summary{cursor:pointer;padding:8px 12px;font-weight:bold;user-select:none}
#window-diagnostics pre{white-space:pre-wrap;word-break:break-word;max-height:57vh;overflow:auto;margin:0;padding:10px 12px;border-top:1px solid #365762}
</style>
<script>
/* Fixed allowlist: runtime fallback is selected by the user, never by a remote URL. */
(function () {
const requested = new URLSearchParams(location.search).get('runtime');
const runtime = requested === '4.3' ? '4.3' : '5.0';
const loader = document.createElement('script');
loader.src = 'https://cjrtnc.leaningtech.com/' + runtime + '/loader.js';
loader.defer = true;
document.head.appendChild(loader);
})();
</script>
<script type="module" src="./cheerpj-runner.js"></script>
</head><body><div id="state" aria-live="polite"></div><div id="display"></div></body></html>
</head><body><div id="state" aria-live="polite"></div><div id="display"></div><details id="window-diagnostics" hidden><summary>Fensterdiagnose (Java 11)</summary><pre id="window-diagnostics-output" aria-live="polite">Noch keine Fensterdaten.</pre></details></body></html>

View File

@@ -1,14 +1,115 @@
/* WidgetWorkbench CheerpJ 4.3 runner.
import jaasNativeHandlers from './cheerpj/natives/jaas.js';
/* WidgetWorkbench CheerpJ 5.0 runner (4.3 selectable as a compatibility fallback).
* CheerpJ Core has no documented runJNLP(url) API: parse the manifest and run JAR(s).
* Deliberately SAME-ORIGIN only. Do not turn this into an open server-side URL proxy.
*/
const screen=document.getElementById('display');
const notice=document.getElementById('state');
const BRIDGE_JAR='/app/backend/hmi/cheerpj/workplace-resize-bridge-v2.jar';
const BRIDGE_JAR='/app/backend/hmi/cheerpj/workplace-window-monitor-v4.jar';
const CREDENTIAL_BRIDGE_JAR='/app/backend/hmi/cheerpj/workplace-credential-bridge.jar';
const CREDENTIAL_BRIDGE_URL='/backend/hmi/cheerpj/workplace-credential-bridge.jar';
let credentialWaiter=null;
// JS implementation for OpenJDK UnixSystem.getUnixInfo. Register the handler via
// cheerpjInit({natives}) AND keep the JS native library for System.loadLibrary.
// Note: registration cannot repair a missing CheerpJ JVM_LoadLibrary import.
const JAAS_JS_URL='/backend/hmi/cheerpj/natives/jaas.js';
const JAAS_NATIVE_PATH='/app/backend/hmi/cheerpj/natives';
const JAAS_BRIDGE_JAR='/app/backend/hmi/cheerpj/jaas-identity-bridge.jar';
// JSON-P 1.1 provider required by iTAC ParameterType; NOT included in Workplace.jnlp.
// Maven packages this dependency as a static WAR resource.
const JSONP_PROVIDER_URL='/backend/hmi/cheerpj-libs/javax.json-1.1.4.jar';
const JSONP_PROVIDER_JAR='/app'+JSONP_PROVIDER_URL;
const WORKPLACE_MANIFEST='/backend/api/hmi/v1/cheerpj/workplace/manifest.jnlp';
// Writable, browser-local CheerpJ directory; never a GlassFish/server filesystem path.
const WORKPLACE_TMP_DIR='/files/itac-workplace/tmp';
// CheerpJ /files is writable. A flat and finally root fallback handle engines
// that cannot create nested directories or previously conflicting user files.
const WORKPLACE_TMP_CANDIDATES=[WORKPLACE_TMP_DIR,'/files/itac-workplace-tmp','/files'];
let busy=false;
// Collect the last boot stage so a CheerpJ WASM exit code can be tied to the
// Java startup phase. No credentials, JNLP arguments or MES URLs are logged.
let bootStage='not-started';
function boot(stage){
bootStage=stage;
console.info('[WidgetWorkbench/CheerpJ] '+stage);
}
// CheerpJ can reject library-mode calls with a Java Throwable proxy. Such
// objects do NOT necessarily implement JS Symbol.toPrimitive/toString, so
// String(error), a template literal or `'' + error` can replace the original
// JAAS exception with "Cannot convert object to primitive value".
function primitiveText(value){
switch(typeof value){
case 'string': return value;
case 'number': case 'boolean': case 'bigint': return String(value);
default: return null;
}
}
async function describeThrowable(error,depth=0,seen=new Set()){
const direct=primitiveText(error);
if(direct!==null)return direct;
if(error===null||error===undefined)return 'Unbekannte JavaScript-Ausnahme';
if(depth>2||seen.has(error))return 'Weitere Exception (rekursiv)';
seen.add(error);
let className=null, message=null, stack=null, cause=null;
try{
const getClass=error.getClass;
if(typeof getClass==='function'){
const cls=await getClass.call(error);
if(cls && typeof cls.getName==='function')className=primitiveText(await cls.getName());
}
}catch(_ignored){ /* Java proxy may not expose class metadata. */ }
try{if(!className)className=primitiveText(error.name);}catch(_ignored){}
try{
const getMessage=error.getMessage;
if(typeof getMessage==='function')message=primitiveText(await getMessage.call(error));
}catch(_ignored){ /* Read the original exception below without replacing it. */ }
try{if(!message)message=primitiveText(error.message);}catch(_ignored){}
try{
if(!message && typeof error.toString==='function'){
message=primitiveText(await error.toString());
}
}catch(_ignored){}
try{stack=primitiveText(error.stack);}catch(_ignored){}
try{
if(typeof error.getCause==='function')cause=await error.getCause();
else cause=error.cause;
}catch(_ignored){}
let result=[className,message].filter(Boolean).join(': ');
if(!result && stack)result=stack;
if(!result)result='CheerpJ-Java-Exception (nicht als JavaScript-String lesbar)';
if(cause!==null&&cause!==undefined&&cause!==error)
result+=' | Ursache: '+await describeThrowable(cause,depth+1,seen);
return result.slice(0,900);
}
async function describeFailure(error){
// Keep the original object accessible in DevTools, not only a reformatted copy.
console.error('[WidgetWorkbench/CheerpJ] Failure in '+bootStage+' (original):',error);
const reason=await describeThrowable(error);
return 'CheerpJ-Start fehlgeschlagen in Phase "'+bootStage+'": '+reason+
'. Details in der Browser-Konsole (WidgetWorkbench/CheerpJ).';
}
// Optional browser-JVM probe: ?diagnose=jaas. Only exercised on demand.
// Does not replace the real iTAC authentication or modify vendor JARs.
async function probeJaasRuntime(lib){
boot('JAAS: UnixSystem-Klasse laden');
const UnixSystem=await lib.com.sun.security.auth.module.UnixSystem;
boot('JAAS: UnixSystem-Konstruktor (System.loadLibrary)');
const instance=await new UnixSystem();
boot('JAAS: UnixSystem.getUsername()');
const user=await instance.getUsername();
let identityOk=user==='cheerpj-client';
// CheerpJ generally passes Java String by value, but guard versions that
// expose a Java proxy instead of coercing that object with String(user).
if(!identityOk && user!=null){
try{if(typeof user.equals==='function')identityOk=(await user.equals('cheerpj-client'))===true;}
catch(_ignored){}
}
console.info('[WidgetWorkbench/CheerpJ] UnixSystem konstruiert; synthetische Benutzeridentität gültig:',identityOk);
if(!identityOk)throw Error('JAAS-Runtimeprüfung: unerwartete virtuelle Benutzeridentität');
boot('JAAS-Laufzeittest erfolgreich (UnixSystem)');
}
const trusted=(raw,base=location.href)=>{
const u=new URL(raw,base);
if(u.origin!==location.origin)throw Error('JNLP und alle JARs müssen von derselben Origin wie WidgetWorkbench kommen.');
@@ -69,74 +170,108 @@ function readManifest(xml,jnlpUrl){
* Only the immutable, locally packaged Bridge JAR is loaded; no vendor JAR is modified.
* When the JVM has not created MesSuiteFrame yet, retry for a bounded startup window.
*/
async function ensureWorkplaceTempDirectory() {
// /app is read-only and /str is read-only to Java. CheerpJ's /files mount
// supports Java writes (IndexedDB, per-browser origin). Create via Java NIO,
// not JavaScript, because JS cannot write directly into /files.
if (typeof window.cheerpjRunLibrary !== 'function')
throw Error('CheerpJ Library Mode für die Temp-Verzeichnisanlage nicht verfügbar.');
const lib=await window.cheerpjRunLibrary('');
async function ensureWorkplaceTempDirectory(lib) {
// Use Java NIO through CheerpJ Library Mode. Checking Files.isDirectory()
// with `=== true` is not reliable across CheerpJ versions: the reported
// value can be a bridge wrapper, even when the directory is writable.
// The real requirement for java.io.tmpdir is that Java can create a file.
if (!lib)throw Error('CheerpJ Library Mode für das Temp-Verzeichnis nicht verfügbar.');
const Paths=await lib.java.nio.file.Paths;
const Files=await lib.java.nio.file.Files;
const path=await Paths.get(WORKPLACE_TMP_DIR);
try {
await Files.createDirectories(path, []);
if (await Files.isDirectory(path, []) !== true)
throw Error('Pfad ist kein Verzeichnis.');
// Checking the directory alone is not enough: verify actual write access.
const probe=await Files.createTempFile(path,'hmi-tmp-check-','.tmp',[]);
await Files.deleteIfExists(probe);
} catch(error) {
throw Error('CheerpJ-Temp-Verzeichnis '+WORKPLACE_TMP_DIR+' nicht verfügbar: '+
(error instanceof Error ? error.message : String(error)));
}
}
async function attachWorkplaceResize(container, classPath, mode) {
if (typeof window.cheerpjRunLibrary !== 'function')
throw Error('CheerpJ Library Mode für die ResizeBridge nicht verfügbar.');
const lib=await window.cheerpjRunLibrary(classPath);
const bridge=await lib.com.widgetworkbench.cheerpj.WorkplaceResizeBridge;
let closed=false, inFlight=false, pending=false, lastSize='', retry=0;
let retryTimer=null;
const desired=()=>{
if(mode==='original')return [1280,1024];
const size=container.getBoundingClientRect();
return [Math.max(200,Math.floor(size.width)),Math.max(150,Math.floor(size.height))];
};
async function update(){
if(closed||inFlight){pending=true;return;}
const [width,height]=desired(), size=width+'x'+height;
if(size===lastSize && retry>=24)return;
inFlight=true;
const System=await lib.java.lang.System;
const errors=[];
for(const candidate of WORKPLACE_TMP_CANDIDATES){
try{
const found=await bridge.resize(width,height);
// The frame appears asynchronously while cheerpjRunMain is active.
if(Number(found)>0){lastSize=size;retry=24;}
const dir=await Paths.get(candidate);
if(candidate!=='/files')await Files.createDirectories(dir,[]);
// A successful write/delete is stronger proof than isDirectory() and
// works independently of Java boolean conversion in the JS bridge.
const probe=await Files.createTempFile(dir,'hmi-tmp-check-','.tmp',[]);
try{
const deleted=await Files.deleteIfExists(probe);
if(deleted===false)throw Error('Schreibtestdatei konnte nicht entfernt werden.');
}catch(cleanupError){
throw Error('Temporäre Testdatei konnte nicht gelöscht werden: '+await describeThrowable(cleanupError));
}
// Bootstrap with java.io.tmpdir=/files (always an existing mount point),
// then configure the tested directory before invoking Workplace main().
await System.setProperty('java.io.tmpdir',candidate);
return candidate;
}catch(error){
console.warn('Workplace resize bridge:',error);
retry=24;
}finally{
inFlight=false;
if(pending&&!closed){pending=false;void update();}
errors.push(candidate+': '+await describeThrowable(error));
}
}
const observer=typeof ResizeObserver!=='undefined' ? new ResizeObserver(()=>{retry=24;void update();}) : null;
observer?.observe(container);
// Retry initialization until first Workplace JFrame is shown, stop after 24 attempts.
retryTimer=setInterval(()=>{
if(closed||retry>=24){clearInterval(retryTimer);return;}
retry++;
void update();
},750);
void update();
return {stop(){closed=true;observer?.disconnect();if(retryTimer)clearInterval(retryTimer);},refresh:()=>update()};
throw Error('CheerpJ-Temp-Verzeichnis nicht beschreibbar ('+errors.join(' | ')+').');
}
// V5.10.21: Do NOT concurrently call a CheerpJ Library Mode method from
// JS timers. CheerpJ may reject the second invocation with:
// "Java code still running, check for a missing 'await'".
// The Java bridge starts ONE daemon monitor before main(), which handles
// resize and window inspection entirely inside the JVM/AWT thread domain.
// No further JS -> CheerpJ library-mode calls are made while main() runs.
async function attachWorkplaceRuntimeMonitor(container, lib, windowMode, displayMode) {
if(!lib)throw Error('CheerpJ Library Mode für Fensterüberwachung nicht verfügbar.');
const bridge=await lib.com.widgetworkbench.cheerpj.WorkplaceResizeBridge;
if(typeof bridge.startRuntimeMonitor!=='function')
throw Error('Workplace Window Monitor v4 fehlt: startRuntimeMonitor nicht vorhanden. JAR V5.10.22 prüfen.');
const panel=document.getElementById('window-diagnostics');
const output=document.getElementById('window-diagnostics-output');
const bounds=container.getBoundingClientRect();
const width=displayMode==='original'?1280:Math.max(200,Math.floor(bounds.width));
const height=displayMode==='original'?1024:Math.max(150,Math.floor(bounds.height));
// This is the LAST library-mode method call before cheerpjRunMain().
// startRuntimeMonitor returns immediately; Java then polls independently.
const started=await bridge.startRuntimeMonitor(width,height,windowMode);
if(Number(started)!==1&&Number(started)!==2)
throw Error('Workplace Window Monitor wurde nicht gestartet (Code '+(primitiveText(started)??'?')+').');
if(windowMode!=='off'){
if(panel)panel.hidden=false;
if(output)output.textContent='Java-11-Fensterdiagnose aktiv ('+windowMode+').\n'
+'Ausgabe in der Browser-Konsole: [WidgetWorkbench/WindowGeometry]\n'
+'Die Abfragen laufen im Java-Hintergrundthread, ohne parallele CheerpJ-Library-Aufrufe.\n'
+'MES_LOGIN: NOT_SEEN / CREATED_HIDDEN / VISIBLE_ONSCREEN / VISIBLE_OFFSCREEN.\n'
+'MES_LOGIN_OWNER zeigt das iTAC-Besitzerfenster; COMPONENT_TREE erfasst JInternalFrame/MyDoggy.\n'
+'Eine JAAS UnsatisfiedLinkError kann die Dialogerzeugung verhindern und wird hier NICHT umgangen.';
}
console.info('[WidgetWorkbench/WindowGeometry] Java-interner Monitor gestartet; '
+width+'x'+height+'; Modus='+windowMode+'; keine JS-Library-Polling-Aufrufe.');
return {stop(){ /* Monitor lebt als Java-Daemon bis zum Ende der JVM. */ }};
}
// Request secrets only after the JVM has initialized and immediately before
// main(). No URL/query parameters, storage or server-side password endpoint.
async function requestBrowserCredentials(requestId){
if(window.parent===window)return null; // standalone window has no trusted parent
return new Promise(resolve=>{
const waiter={requestId,resolve};credentialWaiter=waiter;
const timeout=setTimeout(()=>{
if(credentialWaiter===waiter){credentialWaiter=null;resolve(null);}
},5000);
waiter.finish=value=>{
clearTimeout(timeout);
if(credentialWaiter===waiter)credentialWaiter=null;
resolve(value);
};
window.parent.postMessage({type:'hmi-cheerpj-credential-request',requestId},location.origin);
});
}
function credentialNativeHandlers(requestId){
return {
...jaasNativeHandlers,
// Direct JNI, not System.loadLibrary(). Results contain codes only.
async Java_com_widgetworkbench_cheerpj_WorkplaceCredentialBridge_nativeReport(_lib,_self,code){
const result=Number(code);
const labels={1:'MES_LOGIN_SUCCESS',2:'MES_LOGIN_REJECTED',3:'ALREADY_AUTHENTICATED',4:'EXPIRED',5:'BRIDGE_ERROR'};
console.info('[WidgetWorkbench/WorkplaceAuth]',labels[result]||'UNKNOWN_RESULT');
if(window.parent!==window)window.parent.postMessage({type:'hmi-cheerpj-auth-result',requestId,code:result},location.origin);
}
};
}
function status(requestId,state,message){
const text=String(message).slice(0,350);
notice.textContent=text;notice.className=state==='error'?'fail':'';
parent.postMessage({type:'hmi-cheerpj-state',requestId,state,message:text},location.origin);
if(window.parent!==window)parent.postMessage({type:'hmi-cheerpj-state',requestId,state,message:text},location.origin);
}
async function start(e,data){
const id=data.requestId;
@@ -148,6 +283,11 @@ async function start(e,data){
if(![8,11,17].includes(version))throw Error('Ungültige Java-Version.');
const isWorkplace=data.workplace===true && url.pathname===WORKPLACE_MANIFEST;
const displayMode=data.displayMode==='original'?'original':'fit';
const params=new URL(location.href).searchParams;
const rawWindowMode=data.windowMode ?? params.get('windows');
const windowMode=isWorkplace && ['off','diagnose','rescue'].includes(rawWindowMode)
? rawWindowMode : (isWorkplace ? 'diagnose' : 'off');
boot('JNLP-Abruf');
status(id,'loading','JNLP wird gelesen …');
const r=await fetch(url.href,{credentials:'same-origin',redirect:'follow',cache:'no-store'});
if(!r.ok||!r.url||trusted(r.url).origin!==location.origin)throw Error('JNLP nicht abrufbar (HTTP '+r.status+').');
@@ -158,45 +298,165 @@ async function start(e,data){
if(typeof window.cheerpjInit!=='function'){
await new Promise((resolve,reject)=>{let count=0;const timer=setInterval(()=>{if(typeof window.cheerpjInit==='function'){clearInterval(timer);resolve();}else if(++count>150){clearInterval(timer);reject(Error('CheerpJ CDN nicht erreichbar oder durch CSP blockiert.'));}},100);});
}
// Keep a single JVM library context for tmp, optional JAAS diagnostics and
// ResizeBridge: CheerpJ allows only one library thread in this configuration.
const cp=manifest.paths.join(':')+(isWorkplace
? ':'+JSONP_PROVIDER_JAR+':'+JAAS_BRIDGE_JAR+':'+CREDENTIAL_BRIDGE_JAR+':'+BRIDGE_JAR : '');
const diag=new URL(location.href).searchParams.get('diagnose');
// Explicitly verify native JavaScript is delivered before VM initialization;
// a successful HTTP response alone does NOT guarantee System.loadLibrary works.
if(isWorkplace){
boot('JAAS-JavaScript abrufen');
const nativeResponse=await fetch(JAAS_JS_URL,{credentials:'same-origin',cache:'no-store'});
if(!nativeResponse.ok)throw Error('JAAS-Kompatibilitätsmodul fehlt (HTTP '+nativeResponse.status+').');
if(typeof jaasNativeHandlers?.Java_com_sun_security_auth_module_UnixSystem_getUnixInfo!=='function')
throw Error('JAAS-JavaScript enthält keine gültige UnixSystem-JNI-Implementierung.');
}
// JNLP URL query parameters are not Java system properties.
// CheerpJ 4.3 supplies -D equivalents through javaProperties.
// CheerpJ supplies -D equivalents through javaProperties.
const javaProperties=isWorkplace && manifest.clusterNodes
? ['itac.artes.clusternodes='+manifest.clusterNodes] : [];
if(isWorkplace)javaProperties.push('java.io.tmpdir='+WORKPLACE_TMP_DIR);
await window.cheerpjInit({version,status:'none',javaProperties});
// /files exists already when the Java VM initializes; choose the actual
// writable subdirectory after probing, before launching the application.
if(isWorkplace){
status(id,'loading','Virtuelles Workplace-Temp-Verzeichnis wird vorbereitet …');
await ensureWorkplaceTempDirectory();
javaProperties.push('java.io.tmpdir=/files');
// Must be present at VM initialization: UnixSystem() calls loadLibrary("jaas")
// before running its private native method getUnixInfo().
javaProperties.push('java.library.path='+JAAS_NATIVE_PATH);
}
boot('CheerpJ-Initialisierung');
await window.cheerpjInit({version,status:'none',javaProperties,
...(isWorkplace ? {natives:credentialNativeHandlers(id)} : {})});
boot('CheerpJ initialisiert');
let sharedLib=null;
if(isWorkplace){
boot('Gemeinsamen Java-Library-Kontext starten');
sharedLib=await window.cheerpjRunLibrary(cp);
status(id,'loading','Virtuelles Workplace-Temp-Verzeichnis wird vorbereitet …');
boot('Temp-Verzeichnis prüfen');
const tempDir=await ensureWorkplaceTempDirectory(sharedLib);
if(tempDir!==WORKPLACE_TMP_DIR)manifest.warnings.push('Temp-Ausweichverzeichnis: '+tempDir+'.');
}
boot('Java-Anzeigefläche vorbereiten');
if(isWorkplace && displayMode==='original'){
document.body.classList.add('cheerpj-original-mode');
window.cheerpjCreateDisplay(1280,1024,screen);
}else{
window.cheerpjCreateDisplay(-1,-1,screen);
}
let resizeBridge=null;
let cp=manifest.paths.join(':');
let windowMonitor=null;
if(isWorkplace){
cp+=':'+BRIDGE_JAR;
// Range probe catches a missing WAR-bundled provider (or server-side
// Range misconfiguration) before Java reports opaque ExceptionInInitializerError.
boot('JSON-P-JAR prüfen');
const jsonpProbe=await fetch(JSONP_PROVIDER_URL,{
credentials:'same-origin',cache:'no-store',headers:{Range:'bytes=0-0'}
});
if(jsonpProbe.status!==206){
throw Error('JSON-P-Provider im WAR fehlt oder unterstützt kein HTTP Range '
+'(HTTP '+jsonpProbe.status+'). Maven-Build und '
+'hmi/cheerpj-libs/javax.json-1.1.4.jar prüfen.');
}
// Validate the helper JAR before Java main(); the native JS module has
// already been registered via cheerpjInit({natives}) above.
boot('JAAS-Bridge-JAR prüfen');
const bridgeProbe=await fetch(JAAS_BRIDGE_JAR.slice(4),{
credentials:'same-origin',cache:'no-store',headers:{Range:'bytes=0-0'}
});
if(bridgeProbe.status!==206)throw Error('JAAS-Java-Hilfsklasse nicht als JAR abrufbar '
+'(HTTP '+bridgeProbe.status+'). hmi/cheerpj/jaas-identity-bridge.jar prüfen.');
// The vendor JNLP contains javax.json API but not its implementation.
// Keep proprietary JARs untouched; helpers are part of the shared cp.
if(diag==='jaas' || diag==='jaas-only'){
try{
await probeJaasRuntime(sharedLib);
}catch(error){
console.error('[WidgetWorkbench/CheerpJ] JAAS-Laufzeittest Original-Exception:',error);
const msg=await describeThrowable(error);
throw Error('JAAS-Laufzeittest fehlgeschlagen. '+msg+'; '
+'falls JVM_LoadLibrary oder no jaas in java.library.path gemeldet wird, '
+'liegt das Problem bereits beim nativen Library-Loader der CheerpJ-JVM.',
{cause:error});
}
if(diag==='jaas-only'){
boot('JAAS-Laufzeittest erfolgreich – kein Workplace-Start');
status(id,'finished','JAAS UnixSystem erfolgreich initialisiert. Workplace nicht gestartet (Diagnosemodus).');
return;
}
}
if(data.browserCredentials===true){
boot('Einmalige Browser-Anmeldung vorbereiten');
const credentials=await requestBrowserCredentials(id);
if(credentials){
// Probe only when a one-time offer was made. Server must support Range.
const credentialProbe=await fetch(CREDENTIAL_BRIDGE_URL,{
credentials:'same-origin',cache:'no-store',headers:{Range:'bytes=0-0'}
});
if(credentialProbe.status!==206){
status(id,'loading','Workplace-Anmeldebridge ist nicht verfügbar; normaler Login bleibt aktiv.');
}else{
try{
const authBridge=await sharedLib.com.widgetworkbench.cheerpj.WorkplaceCredentialBridge;
const accepted=await authBridge.offer(credentials.username,credentials.password,credentials.client);
if(Number(accepted)!==1)throw Error('Einmalige Anmeldung wurde von der Java-Bridge abgelehnt.');
// No success claim until the Java nativeReport callback reports code 1.
console.info('[WidgetWorkbench/WorkplaceAuth] One-shot offer accepted; waiting for PersonService');
}catch(error){
console.warn('[WidgetWorkbench/WorkplaceAuth] Übergabe fehlgeschlagen (Zugangsdaten und Exception werden nicht protokolliert).');
status(id,'loading','Workplace-Übergabe fehlgeschlagen; manueller MES-Login bleibt möglich.');
}
}
}else{
console.info('[WidgetWorkbench/WorkplaceAuth] Keine Browser-Zugangsdaten angeboten; normaler MES-Login.');
}
}
boot('Java-internen Swing-Fenstermonitor starten ('+windowMode+')');
try{
resizeBridge=await attachWorkplaceResize(screen,cp,displayMode);
windowMonitor=await attachWorkplaceRuntimeMonitor(screen,sharedLib,windowMode,displayMode);
}catch(error){
console.warn('Optional Workplace ResizeBridge unavailable:',error);
manifest.warnings.push('ResizeBridge konnte nicht gestartet werden; Anzeige bleibt nutzbar, interne Größe möglicherweise fix.');
console.warn('[WidgetWorkbench/WindowGeometry] Java-interner Monitor nicht verfügbar:',error);
manifest.warnings.push('Fenstermonitor nicht verfügbar; Workplace-Start wird fortgesetzt.');
}
}
boot('iTAC Workplace main(): '+(manifest.main?'Startklasse vorhanden':'JAR-Start'));
status(id,'running','Java-Anwendungsstart wird versucht. '+manifest.warnings.join(' '));
try{
const exitCode=manifest.main
? await window.cheerpjRunMain(manifest.main,cp,...manifest.args)
: await window.cheerpjRunJar(manifest.paths[0],...manifest.args);
boot('Java main() beendet');
status(id,'finished','Anwendung beendet (Exit-Code '+exitCode+').');
}finally{resizeBridge?.stop();}
}catch(error){status(id,'error',error instanceof Error?error.message:String(error));}
}finally{windowMonitor?.stop();}
}catch(error){status(id,'error',await describeFailure(error));}
}
window.addEventListener('message',event=>{
if(event.source!==window.parent||event.origin!==location.origin)return;
const data=event.data;
if(!data||data.type!=='hmi-cheerpj-launch'||typeof data.requestId!=='string'||data.requestId.length>150)return;
void start(event,data);
if(!data||typeof data.requestId!=='string'||data.requestId.length>150)return;
if(data.type==='hmi-cheerpj-credentials'||data.type==='hmi-cheerpj-credentials-unavailable'){
const waiter=credentialWaiter;
if(!waiter||waiter.requestId!==data.requestId)return;
if(data.type==='hmi-cheerpj-credentials-unavailable'){waiter.finish(null);return;}
if(typeof data.username!=='string'||!data.username||data.username.length>120
||typeof data.password!=='string'||!data.password||data.password.length>1024
||typeof data.client!=='string'||!data.client||data.client.length>120)return;
waiter.finish({username:data.username,password:data.password,client:data.client});
return;
}
if(data.type==='hmi-cheerpj-launch')void start(event,data);
});
// Direct, full-window workplace mode. This URL is deliberately limited to the
// fixed authenticated MES JNLP bridge. No arbitrary JNLP or Java class name
// can be supplied through query parameters.
if(new URL(location.href).searchParams.get('standalone')==='workplace'){
document.body.classList.add('cheerpj-standalone');
void start(null,{
requestId:'standalone-workplace',
jnlpUrl:new URL(WORKPLACE_MANIFEST,location.href).href,
javaVersion:11,
workplace:true,
displayMode:'fit',
windowMode:new URL(location.href).searchParams.get('windows')
});
}

Binary file not shown.

View File

@@ -0,0 +1,27 @@
/*
* Virtual OpenJDK 11 `jaas` library for CheerpJ Workplace.
* JDK UnixSystem() calls System.loadLibrary("jaas") followed by native
* getUnixInfo(). This module supplies only that native method and delegates
* protected-field initialization to our unsigned, non-vendor Java helper.
*
* Not an authentication provider: users must still authenticate to iTAC MES.
* This handler is registered with cheerpjInit({natives}) in addition to being
* exported as a System.loadLibrary("jaas") module. Registering the method
* does not itself make JVM_LoadLibrary available in the CheerpJ runtime.
*/
export default {
async Java_com_sun_security_auth_module_UnixSystem_getUnixInfo(lib, self) {
if (!lib || !self) {
throw new Error('CheerpJ JAAS bridge: missing native context');
}
const helper = await lib.com.widgetworkbench.cheerpj.JaasIdentityBridge;
if (!helper || typeof helper.populate !== 'function') {
throw new Error('CheerpJ JAAS bridge JAR is not on the Workplace classpath');
}
console.info('[WidgetWorkbench/JAAS] UnixSystem.getUnixInfo native invoked');
const username = await helper.populate(self);
if (username !== 'cheerpj-client') {
throw new Error('CheerpJ JAAS bridge returned an unexpected identity');
}
},
};

View File

@@ -0,0 +1,10 @@
// Self-contained native-library-loader diagnostic; no MES authentication or system identity.
// Loaded EITHER by System.loadLibrary("wwprobe") from java.library.path OR
// injected directly through cheerpjInit({natives}) in the isolated direct test.
// The direct path does not repair JVM_LoadLibrary and does not affect JAAS.
export default {
async Java_com_widgetworkbench_cheerpj_NativeLoaderSmoke_ping() {
console.info('[WidgetWorkbench/NativeLoaderSmoke] wwprobe.js JNI callback reached');
return 42;
}
};