'; } t += J2S._getWrapper(this, false); if (Info.addSelectionOptions) t += J2S._getGrabberOptions(this); if (J2S._debugAlert && !J2S._document) alert(t); this._code = J2S._documentWrite(t); }; proto._newCanvas = function(doReplace) { if (this._is2D) this._createCanvas2d(doReplace); else this._GLmol.create(); }; // ////// swingjs.api.HTML5Applet interface proto._getHtml5Canvas = function() { return this._canvas }; proto._getWidth = function() { return (this._canvas ? this._canvas.width : 0) }; proto._getHeight = function() { return (this._canvas ? this._canvas.height : 0) }; proto._getContentLayer = function() { return J2S.$(this, "contentLayer")[0] }; proto.repaintNow = function() { J2S.repaint(this, false) }; // ////// proto._createCanvas2d = function(doReplace) { var container = J2S.$(this, "appletdiv"); // if (doReplace) { if (this._canvas) { try { container[0].removeChild(this._canvas); if (this._canvas.frontLayer) container[0].removeChild(this._canvas.frontLayer); if (this._canvas.rearLayer) container[0].removeChild(this._canvas.rearLayer); if (this._canvas.contentLayer) container[0].removeChild(this._canvas.contentLayer); J2S.unsetMouse(this._mouseInterface); } catch (e) { } } var w = Math.round(container.width()); var h = Math.round(container.height()); var canvas = document.createElement('canvas'); canvas.applet = this; this._canvas = canvas; canvas.style.width = "100%"; canvas.style.height = "100%"; canvas.width = w; canvas.height = h; // w and h used in setScreenDimension canvas.id = this._id + "_canvas2d"; container.append(canvas); J2S._$(canvas.id).css({ "z-index" : J2S.getZ(this, "main") }); if (this._isLayered) { var content = document.createElement("div"); canvas.contentLayer = content; content.id = this._id + "_contentLayer"; container.append(content); J2S._$(content.id).css({ zIndex : J2S.getZ(this, "content"), position : "absolute", left : "0px", top : "0px", width : (this._isSwing ? w : 0) + "px", height : (this._isSwing ? h : 0) + "px", overflow : "hidden" }); if (this._isSwing) { this._mouseInterface = content; content.applet = this; } else { this._mouseInterface = this._getLayer("front", container, w, h, false); } } else { this._mouseInterface = canvas; } J2S.setMouse(this._mouseInterface, this._isSwing); } proto._getLayer = function(name, container, w, h, isOpaque) { var c = document.createElement("canvas"); this._canvas[name + "Layer"] = c; c.style.width = "100%"; c.style.height = "100%"; c.id = this._id + "_" + name + "Layer"; c.width = w; c.height = h; // w and h used in setScreenDimension container.append(c); c.applet = this; J2S._$(c.id).css({ background : (isOpaque ? "rgb(0,0,0,1)" : "rgb(0,0,0,0.001)"), "z-index" : J2S.getZ(this, name), position : "absolute", left : "0px", top : "0px", overflow : "hidden" }); return c; } proto._setupJS = function() { J2S.setWindowVar("j2s.lib", { base : this._j2sPath + "/", alias : ".", console : this._console, monitorZIndex : J2S.getZ(this, "monitorZIndex") }); var isFirst = (__execStack.length == 0); if (isFirst) J2S._addExec([ this, __loadClazz, null, "loadClazz" ]); this._addCoreFiles(); J2S._addExec([ this, this.__startAppletJS, null, "start applet" ]) this._isSigned = true; // access all files via URL hook this._ready = false; this._applet = null; this._canScript = function(script) { return true; }; this._savedOrientations = []; __execTimer && clearTimeout(__execTimer); __execTimer = setTimeout(__nextExecution, __execDelayMS); }; proto.__startAppletJS = function(applet) { if (J2S._version.indexOf("$Date: ") == 0) J2S._version = (J2S._version.substring(7) + " -").split(" -")[0] + " (J2S)"; Clazz.load("java.lang.Class"); J2S._registerApplet(applet._id, applet); if (!applet.__Info.args || applet.__Info.args == "?") { var s = J2S.getURIField("j2sargs", null); if (s !== null) applet.__Info.args = decodeURIComponent(s); } var isApp = applet._isApp = !!applet.__Info.main; try { var clazz = (applet.__Info.main || applet.__Info.code); try { if (clazz.indexOf(".") < 0) { clazz = "_." + clazz; if (isApp) applet.__Info.main = clazz; else applet.__Info.code = clazz; } var cl = Clazz.load(clazz); if (clazz.indexOf("_.") == 0) J2S.setWindowVar(clazz.substring(2), cl); if (isApp && cl.j2sHeadless) applet.__Info.headless = true; } catch (e) { alert("Java class " + clazz + " was not found."); return; } if (isApp && applet.__Info.headless) { cl.main$SA(applet.__Info.args || []); } else { applet.__Info.main var viewerOptions = Clazz.new_(Clazz .load("java.util.Hashtable")); viewerOptions.put = viewerOptions.put$TK$TV; J2S._setAppletParams(applet._availableParams, viewerOptions, applet.__Info, true); viewerOptions.put("name", applet._id);// + "_object"); viewerOptions.put("syncId", J2S._syncId); viewerOptions.put("fullName", applet._id + "__" + J2S._syncId + "__"); if (J2S._isAsync) viewerOptions.put("async", true); if (applet._startupScript) viewerOptions.put("script", applet._startupScript) viewerOptions.put("platform", applet._platform); viewerOptions.put("documentBase", document.location.href); var codePath = applet._j2sPath + "/"; if (codePath.indexOf("://") < 0) { var base = document.location.href.split("#")[0] .split("?")[0].split("/"); if (codePath.indexOf("/") == 0) base = [ base[0], codePath.substring(1) ]; else base[base.length - 1] = codePath; codePath = base.join("/"); } if (applet.__Info.code) codePath += applet.__Info.code.replace(/\./g, "/"); codePath = codePath.substring(0, codePath.lastIndexOf("/") + 1); viewerOptions.put("codePath", codePath); viewerOptions.put("appletReadyCallback", "J2S.readyCallback"); viewerOptions.put("applet", true); if (applet._color) viewerOptions.put("bgcolor", applet._color); if (J2S._syncedApplets.length) viewerOptions .put("synccallback", "J2S._mySyncCallback"); viewerOptions.put("signedApplet", "true"); if (applet._is2D && !isApp) viewerOptions.put("display", applet._id + "_canvas2d"); var w = applet.__Info.width; var h = applet.__Info.height; if (w > 0 && h > 0 && (!applet._canvas || w != applet._canvas.width || h != applet._canvas.height)) { // developer has used static { J2S.thisApplet.__Info.width=...} J2S.$(applet, "appletinfotablediv").width(w).height(h); applet._newCanvas(true); } applet._newApplet(viewerOptions); } } catch (e) { System.out.println((J2S._isAsync ? "normal async abort from " : "") + e + (e.stack ? "\n" + e.stack : "")); return; } //applet._jsSetScreenDimensions(); __nextExecution(); }; if (!proto._restoreState) proto._restoreState = function(clazzName, state) { // applet-dependent } proto._jsSetScreenDimensions = function() { if (!this._appletPanel) return // strangely, if CTRL+/CTRL- are used repeatedly, then the // applet div can be not the same size as the canvas if there // is a border in place. var d = J2S._getElement(this, (this._is2D ? "canvas2d" : "canvas")); this._appletPanel.setScreenDimension$I$I(d.width, d.height); }; proto._show = function(tf) { J2S.$setVisible(J2S.$(this, "appletdiv"), tf); if (tf && !this._isSwing) // SwingJS applets will handle their own // repainting J2S.repaint(this, true); }; proto._canScript = function(script) { return true }; proto._processGesture = function(touches, frameViewer) { (frameViewer || this._appletPanel) .processTwoPointGesture$FAAA(touches); } proto._processEvent = function(type, xym, ev, frameViewer) { // xym is [x,y,modifiers,wheelScroll] // also processes key events (frameViewer || this._appletPanel).processMouseEvent$I$I$I$I$J$O$I( type, xym[0], xym[1], xym[2], System.currentTimeMillis$(), ev, xym[3]); } proto._resize = function() { var s = "__resizeTimeout_" + this._id; // only at end if (J2S[s]) clearTimeout(J2S[s]); var me = this; J2S[s] = setTimeout(function() { J2S.repaint(me, true); J2S[s] = null }, 100); } return proto; }; J2S.repaint = function(applet, asNewThread) { // JmolObjectInterface // asNewThread: true is from RepaintManager.repaintNow() // false is from Repaintmanager.requestRepaintAndWait() // called from apiPlatform Display.repaint() // alert("repaint " + Clazz._getStackTrace()) if (!applet || !applet._appletPanel) return; // asNewThread = false; var container = J2S.$(applet, "appletdiv"); var w = Math.round(container.width()); var h = Math.round(container.height()); if (applet._is2D && !applet._isApp && (applet._canvas.width != w || applet._canvas.height != h)) { applet._newCanvas(true); applet._appletPanel .setDisplay$swingjs_api_js_HTML5Canvas(applet._canvas); } applet._appletPanel.setScreenDimension$I$I(w, h); var f = function() { // if (applet._appletPanel.top) { // System.out.println("j2sApplet invalidate"); // applet._appletPanel.top.invalidate$(); // System.out.println("j2sApplet repaint"); // applet._appletPanel.top.repaint$(); // } }; //if (asNewThread) { //self.setTimeout(f,20); // requestAnimationFrame //} else { f(); //} } /** * loadImage is called for asynchronous image loading. If bytes are not * null, they are from a ZIP file. They are processed sychronously here * using an image data URI. Can all browsers handle MB of data in data URI? * */ J2S.loadImage = function(platform, echoName, path, bytes, fOnload, image) { // JmolObjectInterface var id = "echo_" + echoName + path + (bytes ? "_" + bytes.length : ""); var canvas = J2S.getHiddenCanvas(platform.vwr.html5Applet, id, 0, 0, false, true); if (canvas == null) { if (image == null) { image = new Image(); if (bytes == null) { image.onload = function() { J2S.loadImage(platform, echoName, path, null, fOnload, image) }; image.src = path; return null; } else { System.out .println("Jsmol.js J2S.loadImage using data URI for " + id) } image.src = (typeof bytes == "string" ? bytes : "data:" + Clazz.load("javajs.util.Rdr") .guessMimeTypeForBytes$BA(bytes) + ";base64," + Clazz.load("javajs.util.Base64").getBase64$BA(bytes)); } var width = image.width; var height = image.height; if (echoName == "webgl") { // will be antialiased width /= 2; height /= 2; } canvas = J2S.getHiddenCanvas(platform.vwr.html5Applet, id, width, height, true, false); canvas.imageWidth = width; canvas.imageHeight = height; canvas.id = id; canvas.image = image; J2S.setCanvasImage(canvas, width, height); // return a null canvas and the error in path if there is a problem } else { System.out.println("J2S.loadImage reading cached image for " + id) } return (bytes == null ? fOnload(canvas, path) : canvas); }; J2S._canvasCache = {}; J2S.getHiddenCanvas = function(applet, id, width, height, forceNew, checkOnly) { id = applet._id + "_" + id; var d = J2S._canvasCache[id]; if (checkOnly) return d; if (forceNew || !d || d.width != width || d.height != height) { d = document.createElement('canvas'); // for some reason both these need to be set, or maybe just d.width? d.width = d.style.width = width; d.height = d.style.height = height; d.id = id; J2S._canvasCache[id] = d; } return d; } J2S.setCanvasImage = function(canvas, width, height) { // called from org.J2S.awtjs2d.Platform canvas.buf32 = null; canvas.width = width; canvas.height = height; canvas.getContext("2d").drawImage(canvas.image, 0, 0, canvas.image.width, canvas.image.height, 0, 0, width, height); }; J2S.applyFunc = function(f, a) { // J2SObjectInterface return f(a); } J2S.setDraggable = function(tag, targetOrArray) { // draggable tag object; target is itself // J2S.setDraggable(tag) // J2S.setDraggable(tag, true) // draggable tag object that controls another target, // either given as a DOM element or jQuery selector or function // returning such // J2S.setDraggable(tag, target) // J2S.setDraggable(tag, fTarget) // draggable tag object simply loade=s/reports mouse position as // fDown({x:x,y:y,dx:dx,dy:dy,ev:ev}) should fill x and y with starting // points // fDrag(xy) and fUp(xy) will get {x:x,y:y,dx:dx,dy:dy,ev:ev} to use as // desired // J2S.setDraggable(tag, [fAll]) // J2S.setDraggable(tag, [fDown, fDrag, fUp]) // unbind tag // J2S.setDraggable(tag, false) // draggable frames by their titles. // activation of dragging with a mouse down action // deactivates all other mouse operation in SwingJS // until the mouse is released. // uses jQuery outside events - v1.1 - 3/16/2010 (see j2sJQueryExt.js) // J2S.setDraggable(titlebar, fGetFrameParent), for example, is issued // in swingjs.plaf.JSFrameUI.js var drag, up; var dragBind = function(isBind) { $tag.unbind('mousemoveoutjsmol'); $tag.unbind('touchmoveoutjsmol'); $tag.unbind('mouseupoutjsmol'); $tag.unbind('touchendoutjsmol'); J2S._dmouseOwner = null; tag.isDragging = false; tag._isDragger = false; if (isBind) { $tag.bind('mousemoveoutjsmol touchmoveoutjsmol', function(ev) { drag && drag(ev); }); $tag.bind('mouseupoutjsmol touchendoutjsmol', function(ev) { up && up(ev); }); } }; var $tag = $(tag); tag = $tag[0]; if (tag._isDragger) return; var target, fDown, fDrag, fUp; if (targetOrArray === false) { dragBind(tag, false); return; } if (targetOrArray instanceof Array) { // J2S.setDraggable(tag, [fAll]) // J2S.setDraggable(tag, [fDown, fDrag, fUp]) fDown = targetOrArray[0]; fDrag = targetOrArray[1] || fDown; fUp = targetOrArray[2] || fDown; } else { // J2S.setDraggable(tag) // J2S.setDraggable(tag, true) // J2S.setDraggable(tag, target) // J2S.setDraggable(tag, fTarget) target = (targetOrArray !== true && targetOrArray || tag); // allow for a function to return the target // this allows the target to be created after the call to // J2S.setDraggable() if (!(typeof target == "function")) { var t = target; target = function() { return $(t).parent() } } } tag._isDragger = true; var x, y, dx, dy, pageX0, pageY0, pageX, pageY; var down = function(ev) { J2S._dmouseOwner = tag; J2S._dmouseDrag = drag; tag.isDragging = true; // used by J2S mouse event business pageX = ev.pageX; pageY = ev.pageY; var xy = { x : 0, y : 0, dx : 0, dy : 0, ev : ev }; if (fDown) { fDown(xy, 501); } else if (target) { var o = $(target(501)).position(); xy = { x : o.left, y : o.top }; } pageX0 = xy.x; pageY0 = xy.y; return false; }, drag = function(ev) { // we will move the frame's parent node and take the frame along // with it var ev0 = ev.ev0 || ev; if (ev0.buttons == 0 && ev0.button == 0) tag.isDragging = false; var mode = (tag.isDragging ? 506 : 503); if (!J2S._dmouseOwner || tag.isDragging && J2S._dmouseOwner == tag) { x = pageX0 + (dx = ev.pageX - pageX); y = pageY0 + (dy = ev.pageY - pageY); if (fDrag) { fDrag({ x : x, y : y, dx : dx, dy : dy, ev : ev }, mode); } else if (target) { var frame = target(mode, x, y); if (frame) $(frame).css({ top : y + 'px', left : x + 'px'}) } } }, up = function(ev) { J2S._dmouseDrag = null; if (J2S._dmouseOwner == tag) { tag.isDragging = false; J2S._dmouseOwner = null fUp && fUp({ x : x, y : y, dx : dx, dy : dy, ev : ev }, 502); return false; } else { } }; $tag.bind('mousedown touchstart', function(ev) { return down && down(ev); }); $tag.bind('mousemove touchmove', function(ev) { return drag && drag(ev); }); $tag.bind('mouseup touchend', function(ev) { return up && up(ev); }); dragBind(true); } J2S.setWindowZIndex = function(node, z) { // on frame show or mouse-down, create a stack of frames and sort by // z-order if (!node) return var zbase = J2S._z.rear + 2000; var a = []; var zmin = 1e10 var zmax = -1e10 var $windows = $(".swingjs-window"); $windows.each(function(c, b) { if (b != node) a.push([ +b.style.zIndex, b ]); }); a.sort(function(a, b) { return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0 }) var z0 = zbase; var z0 = zbase; for (var i = 0; i < a.length; i++) { if (!a[i][1].ui || !a[i][1].ui.embeddingNode) a[i][1].style.zIndex = zbase; zbase += 1000; } z = (z > 0 ? zbase : z0); if (!node.ui || !node.ui.embeddingNode) // could be popupMenu, with no ui node.style.zIndex = z; node.style.position = "absolute"; if (J2S._checkLoading) System.out.println("setting z-index to " + z + " for " + node.id); return z; } J2S.say = function(msg) { alert(msg); } J2S.Swing = { // a static class for menus and other resources count : 0, menuInitialized : 0, menuCounter : 0 }; J2S.getSwing = function() { return J2S.Swing } J2S.showInfo = function(applet, tf) { applet._showInfo(tf); } J2S.Loaded = {}; J2S.isResourceLoaded = function(resource, done) { path = J2S.getResourcePath(resource, true); var r = J2S.Loaded[resource]; if (done) J2S.Loaded[resource] = 1; return r; } J2S.getResourcePath = function(path, isJavaPath) { if (!path || path.indexOf("https:/") != 0 && path.indexOf("https:/") != 0 && path.indexOf("file:/") != 0) { var applet = J2S._applets[Clazz.loadClass("java.lang.Thread").currentThread$() .getName$()]; path = (!isJavaPath && applet.__Info.resourcePath || applet.__Info.j2sPath) + "/" + (path || ""); } return path; } J2S._newGrayScaleImage = function(context, image, width, height, grayBuffer) { var c; image || (image = Jmol.$(context.canvas.applet, "image")[0]); if (image == null) { var appId = context.canvas.applet._id; var id = appId + "_imagediv"; c = document.createElement("canvas"); c.id = id; c.style.width = width + "px"; c.style.height = height + "px"; c.width = width; c.height = height; var layer = document.getElementById(appId + "_contentLayer"); image = new Image(); image.canvas = c; image.appId = appId; image.id = appId + "_image"; image.layer = layer; image.w = width; image.h = height; image.onload = function(e) { try { URL.revokeObjectURL(image.src); } catch (e) {} }; var div = document.createElement("div"); image.div = div; div.style.position="absolute"; layer.appendChild(div); div.appendChild(image); } c = image.canvas.getContext("2d"); var imageData = c.getImageData(0, 0, width, height); var buf = imageData.data; var ng = grayBuffer.length; var pt = 0; for (var i = 0; i < ng; i++) { buf[pt++] = buf[pt++] = buf[pt++] = grayBuffer[i]; buf[pt++] = 0xFF; } c.putImageData(imageData, 0, 0); image.canvas.toBlob(function(blob){image.src = URL.createObjectURL(blob)}); return image; } })(J2S); // j2sClazz.js // NOTE: updates to this file should be copies to j2sjmol.js // latest author: Bob Hanson, St. Olaf College, hansonr@stolaf.edu // NOTES by Bob Hanson // Google closure compiler cannot handle Clazz.new or Clazz.super // TODO: still a lot of references to window[...] // BH 2019.05.21 changes Clazz.isClassDefined to Clazz._isClassDefined for compression // BH 2019.05.13 fixes for Math.getExponent, Math.IEEERemainder, Array.equals(Object) // BH 2019.02.16 fixes typo in Integer.parseInt(s,radix) // BH 2019.02.07 fixes radix|10 should be radix||10 // BH 1/29/2019 adds String.join$CharSequence$Iterable, String.join$CharSequence$CharSequenceA // BH 1/13/2019 3.2.4.07 adds Character.to[Title|Lower|Upper]Case(int) // BH 1/8/2019 3.2.4.07 fixes String.prototype.to[Upper|Lower]Case$java_util_Locale - using toLocal[Upper|Lower]Case() // BH 1/3/2019 3.2.4.07 adds ByteBuffer/CharBuffer support, proper CharSet encoding, including GBK (Standard Chinese) // see earlier notes at net.sf.j2s.java.core.srcjs/js/devnotes.txt LoadClazz = function() { if (!window["j2s.clazzloaded"]) window["j2s.clazzloaded"] = false; if (window["j2s.clazzloaded"])return; window["j2s.clazzloaded"] = true; //window["j2s.object.native"] = true; /* http://j2s.sf.net/ *//****************************************************************************** * Copyright (c) 2007 java2script.org and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Zhou Renjian - initial API and implementation *****************************************************************************/ /******* * @author zhou renjian * @create Nov 5, 2005 *******/ /** * Class Clazz. All the methods are static in this class. */ /* static */ /*Class = */ Clazz = { _isQuiet: true, _debugging: false, _loadcore: true, _nooutput: 0, _VERSION_R: "3.2.4.07", //runtime _VERSION_T: "3.2.4.07", //transpiler }; ;(function(Clazz, J2S) { try { Clazz._debugging = (document.location.href.indexOf("j2sdebug") >= 0); Clazz._loadcore = (document.location.href.indexOf("j2snocore") < 0); Clazz._quiet = (document.location.href.indexOf("j2sverbose") < 0); } catch (e) {} try { // will alert in system.out.println with a message Clazz._traceOutput = (document.location.href.indexOf("j2strace=") >= 0 ? decodeURI(document.location.href.split("j2strace=")[1].split("&")[0]) : null); Clazz._traceFilter = (document.location.href.indexOf("j2sfilter=") >= 0 ? decodeURI(document.location.href.split("j2sfilter=")[1].split("&")[0]) : null); } catch (e) {} Clazz.setTVer = function(ver) { if (Clazz._VERSION_T != ver) { System.err.println("transpiler was " + Clazz._VERSION_T + " now " + ver + " for " + lastLoaded); } Clazz._VERSION_T = ver; } var lastLoaded; Clazz.ClassFilesLoaded = []; Clazz.popup = Clazz.log = Clazz.error = window.alert; /* can be set by page JavaScript */ Clazz.defaultAssertionStatus = true; /* can be set by page JavaScript */ Clazz._assertFunction = null; //////// 16 methods called from code created by the transpiler //////// var getArrayClass = function(name){ // "[C" "[[C" var n = 0; while (name.charAt(n) == "[") n++; var type = name.substring(n); var clazz = (type.length == 1 ? primTypes[type].TYPE : Clazz._4Name(type.split(";")[0].substring(1)).$clazz$); return Clazz.array(clazz,-n); } Clazz.array = function(baseClass, paramType, ndims, params, isClone) { var t0 = (_profileNew ? window.performance.now() : 0); var ret = _array.apply(null, arguments); _profileNew && addProfileNew(baseClass, t0 - window.performance.now() - 0.01); return ret; } var _array = function(baseClass, paramType, ndims, params, isClone) { // int[][].class Clazz.array(Integer.TYPE, -2) // new int[] {3, 4, 5} Clazz.array(Integer.TYPE, -1, [3, 4, 5]) // new int[][]{new int[] {3, 4, 5}, {new int[] {3, 4, 5}} // Clazz.array(Integer.TYPE, -2, Clazz.array(Integer.TYPE, -1, [3, 4, 5]), Clazz.array(Integer.TYPE, -1, [3, 4, 5]) ) // new int[3] Clazz.array(Integer.TYPE, [3]) // new int[3][3] Clazz.array(Integer.TYPE, [3, 3]) // new int[3][] Clazz.array(Integer.TYPE, [3, null]) // new char[3] Clazz.array(Character.TYPE, [3]) // new String[3] Clazz.array(java.lang.String, [3]) if (arguments[0] === -1) { // four-parameter option from JU.AU.arrayCopyObject; // truncate array using slice // Clazz.array(-1, array, ifirst, ilast+1) var a = arguments[1]; var b = a.slice(arguments[2], arguments[3]); return copyArrayProps(a, b); } var prim = Clazz._getParamCode(baseClass); var dofill = true; if (arguments.length < 4) { // one-parameter option just for convenience, same as array(String, 0) // two-parameter options for standard new foo[n], // Array.newInstance(class, length), and // Array.newInstance(class, [dim1, dim2, dim3....]) // three-parameter option for (Integer.TYPE, -1, [3, 4, 5]) var cl = arguments[0]; var baseClass = cl.__BASECLASS || cl; var haveDims = (typeof arguments[1] == "number"); var vals = arguments[haveDims ? 2 : 1]; var ndims = (arguments.length == 1 ? 0 : !haveDims ? vals.length : arguments[1] || 0); if (ndims < 0 && arguments.length == 2) { return arrayClass(baseClass, -ndims); } if (ndims == 0) { ndims = -1; vals = []; } if (haveDims && ndims >= -1) { if (ndims == -1) { // new int[] {3, 4, 5}; return _array(baseClass, prim + "A", -1, vals); } // Array.newInstance(int[][].class, 3); return _array(baseClass, prim + "A", (cl.__NDIM || 0) + 1, [ndims]); } params = vals; paramType = prim; for (var i = Math.abs(ndims); --i >= 0;) { paramType += "A"; if (!haveDims && params[i] === null) { params.length--; dofill = false; } } if (haveDims) { // new int[][] { {0, 1, 2}, {3, 4, 5} , {3, 4, 5} , {3, 4, 5} }; return setArray(vals, baseClass, paramType, -ndims); } } if (ndims < 0) { params = [-1, params]; } else { var initValue = null; if (ndims >= 1 && dofill) { switch (prim) { case "B": case "H": // short case "I": case "L": case "F": case "D": initValue = 0; break; case "C": initValue = '\0'; break; case "Z": initValue = false; break; } } params.push(initValue); } params.push(paramType); var nbits = 0; if (ndims != 0) { switch (prim) { case "B": nbits = 8; break; case "H": nbits = 16; break; case "I": case "L": nbits = 32; break; case "F": case "D": nbits = 64; break; } } return newTypedA(baseClass, params, nbits, (dofill ? ndims : -ndims), isClone); } Clazz.assert = function(clazz, obj, tf, msg) { if (!clazz.$_ASSERT_ENABLED_)return; var ok = true; try { ok = tf.apply(obj) if (!ok) msg = msg.apply(obj); } catch (e) { ok = false; } if (!ok) { doDebugger(); if (Clazz._assertFunction) { return Clazz._assertFunction(clazz, obj, msg || Clazz._getStackTrace()); } Clazz.load("java.lang.AssertionError"); if (msg == null) throw Clazz.new_(AssertionError.c$); else throw Clazz.new_(AssertionError.c$$S, [msg]); } } Clazz.clone = function(me) { // BH allows @j2sNative access without super constructor if (me.__ARRAYTYPE) { return appendMap(Clazz.array(me.__BASECLASS, me.__ARRAYTYPE, -1, me, true), me); } me = appendMap(new me.constructor(inheritArgs), me); me.__JSID__ = ++_jsid; return me; } /**sgurin * Implements Java's keyword "instanceof" in JavaScript's way **for exception objects**. * * calls Clazz.instanceOf if e is a Java exception. If not, try to detect known native * exceptions, like native NullPointerExceptions and wrap it into a Java exception and * call Clazz.instanceOf again. if the native exception can't be wrapped, false is returned. * * @param obj the object to be tested * @param clazz the class to be checked * @return whether the object is an instance of the class * @author: sgurin */ Clazz.exceptionOf = function(e, clazz) { if (typeof clazz == "string") clazz = Clazz.load(clazz); if(e.__CLASS_NAME__) return Clazz.instanceOf(e, clazz); if (!e.getMessage) { e.getMessage = function() {return "" + e}; } if (!e.printStackTrace$) { e.printStackTrace$ = function(){System.err.println$S(e + "\n" + this.stack)}; e.printStackTrace$java_io_PrintStream = function(stream){ stream.println$S(e + "\n" + e.stack); }; //alert(e + " try/catch path:" + Clazz._getStackTrace(-10)); } if(clazz == Error) { if (("" + e).indexOf("Error") < 0) return false; System.err.println$O(Clazz._getStackTrace()); return true; // everything here is a Java Exception, not a Java Error } return (clazz == Exception || clazz == Throwable || clazz == NullPointerException && _isNPEExceptionPredicate(e)); }; Clazz.forName = function(name, initialize, loader, isQuiet) { // we need to consider loading a class from the path of the calling class. var cl = null; if (loader) { try { isQuiet = true; var className = loader.baseClass.getName$(); // set in java.lang.Class.getClassLoader$() var i = className.lastIndexOf("."); var name1 = className.substring(0, i + 1) + name; cl = Clazz._4Name(name1, null, null, false, initialize, true); } catch (e) {} } return cl || Clazz._4Name(name, null, null, false, initialize, isQuiet); } Clazz.getClass = function(cl, methodList) { // $Class$ is the java.lang.Class object wrapper // $clazz$ is the unwrapped JavaScript object cl = getClazz(cl) || cl; if (cl.$Class$) return cl.$Class$; java.lang.Class || Clazz.load("java.lang.Class"); var Class_ = cl.$Class$ = new java.lang.Class(); Class_.$clazz$ = cl; // for arrays - a bit of a hack Class_.$methodList$ = methodList; return Class_; } /** * Implements Java's keyword "instanceof" in JavaScript's way. * Also alows for obj to be a class itself * * @param obj the object to be tested * @param clazz the class to be checked * @return whether the object is an instance of the class */ /* public */ Clazz.instanceOf = function (obj, clazz) { // allows obj to be a class already, from arrayX.getClass().isInstance(y) // unwrap java.lang.Class to JavaScript clazz using $clazz$ if (typeof clazz == "string") { clazz = window[clazz]; } if (obj == null || !clazz) return false; // check for object being a java.lang.Class and the other not if (obj.$clazz$ && !clazz.$clazz$) return false; obj.$clazz$ && (obj = obj.$clazz$); clazz.$clazz$ && (clazz = clazz.$clazz$); if (obj == clazz) return true; if (obj.__ARRAYTYPE || clazz.__ARRAYTYPE) return (obj.__ARRAYTYPE == clazz.__ARRAYTYPE || obj.__ARRAYTYPE && clazz.__ARRAYTYPE && obj.__NDIM == clazz.__NDIM && isInstanceOf(obj.__BASECLASS, clazz.__BASECLASS)); return (obj instanceof clazz || isInstanceOf(getClassName(obj, true), clazz, true)); }; /** * Load a class by name or an array representing a nested list of inner classes. * Just finalize this class if from $clinit$. */ Clazz.load = function(cName, from$clinit$) { if (!cName) return null; if (from$clinit$) { // C$.$clinit$ call to finalize all dependencies var cl = cName; delete cl.$clinit$; var ld = cl.$load$; setSuperclass(cl, (ld && ld[0] ? Clazz.load(ld[0]) : null)); ld[1] && addInterface(cl, ld[1]); delete cl.$load$; return; } // allow for nested calling: ["foo",".foo_inner1",".foo_inner2"] if (cName instanceof Array) { var cl1 = null; var name; for (var i = 0; i < cName.length; i++) { var cn = cName[i]; cl1 = Clazz.load(name = (cn.indexOf(".") == 0 ? name + cn : cn)); } return cl1; } // allow for a clazz itself if (cName.__CLASS_NAME__) { var cl2 = cName; cl2.$clinit$ && cl2.$clinit$(); return cl2; } // standard load of class by name if (cName.indexOf("Thread.") == 0) Clazz._4Name("java.lang.Thread", null, null, true) if (cName.indexOf("Thread") == 0) cName = "java.lang." + cName; return Clazz._4Name(cName, null, null, true); } Clazz._newCount = 0; /** * Create a new instance of a class. * Accepts: * a string Clazz.new_("java.util.Hashtable") * a clazz (has .__CLASS_NAME__ and a default contructor) * a specific class constructor such as c$$S * a constructor from a one class (c, anonymous constructor) and a class to create, cl * */ Clazz.new_ = function(c, args, cl) { if (!c) return new Clazz._O(); var haveArgs = !!args; args || (args = [[]]); Clazz._newCount++; var t0 = (_profileNew ? window.performance.now() : 0); if (c.__CLASS_NAME__ && c.c$) c = c.c$; else if (typeof c == "string") return Clazz.new_(Clazz.load(c)); // an inner class will attach arguments to the arguments returned // Integer will be passed as is here, without c.exClazz, or cl var clInner = cl; cl = cl || c.exClazz || c; cl.$clinit$ && cl.$clinit$(); var obj = new (Function.prototype.bind.apply(cl, arguments)); if (args[2] != inheritArgs) { // cl.$init0$ && cl.$init0$.apply(obj); if (haveArgs) { c.apply(obj, args); } clInner && clInner.$init$.apply(obj); } _profileNew && addProfileNew(cl, window.performance.now() - t0); return obj; } Clazz.newClass = function (prefix, name, clazz, clazzSuper, interfacez, type) { if (J2S._debugCore) { var qualifiedName = (prefix ? (prefix.__PKG_NAME__ || prefix.__CLASS_NAME__) + "." : "") + name; checkDeclared(qualifiedName, type); } clazz || (clazz = function () {Clazz.newInstance(this,arguments,0,clazz)}); clazz.__NAME__ = name; // prefix class means this is an inner class, and $this$0 refers to the outer class. // no prefix class but a super class that is an inner class, then $this$0 refers to its $this$0. // there can be a conflict here. prefix.__CLASS_NAME__ && (clazz.$this$0 = prefix.__CLASS_NAME__) || clazzSuper && clazzSuper.$this$0 && (clazz.$this$0 = clazzSuper.$this$0); clazz.$load$ = [clazzSuper, interfacez]; clazz.$isEnum = clazzSuper == 'Enum'; // get qualifed name, and for inner classes, the name to use to refer to this // class in the synthetic reference array b$[]. var qName, bName; if (!prefix) { // e.g. Clazz.declareInterface (null, "ICorePlugin", org.eclipse.ui.IPlugin); qName = name; Clazz.setGlobal(name, clazz); } else if (prefix.__PKG_NAME__) { // e.g. Clazz.declareInterface (org.eclipse.ui, "ICorePlugin", org.eclipse.ui.IPlugin); qName = prefix.__PKG_NAME__ + "." + name; prefix[name] = clazz; if (prefix === java.lang) { Clazz.setGlobal(name, clazz); } } else { // is an inner class qName = prefix.__CLASS_NAME__ + "." + name; bName = prefix.__CLASS_NAME__ + "$" + name; prefix[name] = clazz; } finalizeClazz(clazz, qName, bName, type, false); // for (var i = minimalObjNames.length; --i >= 0;) { // var name = minimalObjNames[i]; // clazz[name] = objMethods[name]; // } Clazz.setGlobal(qName, clazz); return clazz; }; Clazz.newEnumConst = function(vals, c, enumName, enumOrdinal, args, cl) { var clazzEnum = c.exClazz; var e = clazzEnum.$init$$ || (clazzEnum.$init$$ = clazzEnum.$init$); clazzEnum.$init$ = function() {e.apply(this); this.name = this.$name = enumName; this.ordinal = enumOrdinal;this.$isEnumConst = true;} vals.push(clazzEnum[enumName] = clazzEnum.prototype[enumName] = Clazz.new_(c, args, cl)); } Clazz.newInstance = function (objThis, args, isInner, clazz) { if (args && ( args[0] == inheritArgs || args[1] == inheritArgs || args[2] == inheritArgs )) { // Just declaring a class, not creating an instance or doing field preparation. // That is, we are just generating the prototypes for this method using new superClass() return; } if (objThis.__VAL0__) { // Integer, Long, Byte, Float, Double // .instantialize(val) objThis.valueOf = function () { return this; }; } objThis.__JSID__ = ++_jsid; if (!isInner) { clazz && clazz.$clinit$ && clazz.$clinit$(); clazz && clazz.$init0$ && clazz.$init0$.apply(objThis); if ((!args || args.length == 0) && objThis.c$) { // allow for direct default call "new foo()" to run with its default constructor objThis.c$.apply(objThis); args && (args[2] = Clazz.inheritArgs) } return; } // args[0] = outerObject // args[1] = b$ array // args[2-n] = actual arguments var outerObj = shiftArray(args, 0, 1); var finalVars = shiftArray(args, 0, 1); var haveFinals = (finalVars || outerObj && outerObj.$finals$); if (!outerObj || !objThis) return; var clazz1 = getClazz(outerObj); if (clazz1 == outerObj) { outerObj = objThis; } if (haveFinals) { // f$ is short for the once-chosen "$finals$" var of$ = outerObj.$finals$; objThis.$finals$ = (finalVars ? (of$ ? appendMap(appendMap({}, of$), finalVars) : finalVars) : of$ ? of$ : null); } // BH: For efficiency: Save the b$ array with the OUTER class as $b$, // as its keys are properties of it and can be used again. var b = outerObj.$b$; var isNew = false; var innerName = getClassName(objThis, true); if (!b) { b = outerObj.b$; // Inner class of an inner class must inherit all outer object references. Note that this // can cause conflicts. For example, b$["java.awt.Component"] could refer to the wrong // object if I did this wrong. // if (!b) { // the outer class is not itself an inner class - start a new map b = {}; isNew = true; } else if (b["$ " + innerName]) { // this inner class is already in the map pointing to a different object. Clone the map. b = appendMap({},b); isNew = true; } // add all superclass references for outer object addB$Keys(clazz1, isNew, b, outerObj, objThis); } var clazz2 = (clazz.superclazz == clazz1 ? null : clazz.superclazz || null); if (clazz2) { // we have an inner object that subclasses a different object // clone the map and overwrite with the correct values b = appendMap({},b); addB$Keys(clazz2, true, b, objThis, objThis); } else if (isNew) { // it is new, save this map with the OUTER object as $b$ // 12018.12.20 but only if it is clean outerObj.$b$ = b; } // final objective: save this map for the inner object // add a flag to disallow any other same-class use of this map. b["$ " + innerName] = 1; objThis.b$ = b; clazz.$this$0 && (objThis.this$0 = b[clazz.$this$0]); clazz.$clinit$ && clazz.$clinit$(); clazz.$init0$ && clazz.$init0$.apply(objThis); }; var addB$Keys = function(clazz, isNew, b, outerObj, objThis) { var cl = clazz; do { var key = getClassName(cl, true); if (!isNew && b[key]) break; b[key] = outerObj; if (key.indexOf("java.lang.") == 0) b[key.substring(10)] = outerObj; if (cl.implementz) { var impl = cl.implementz; for (var i = impl.length; --i >= 0;) { var key = getClassName(impl[i], true); if (isNew || !b[key]) { b[key] = outerObj; if (key.indexOf("java.lang.") == 0) b[key.substring(10)] = outerObj; } } } } while ((cl = cl.superclazz)); }; /** // arg1 is the package name // arg2 is the full class name in quotes // arg3 is the class definition function, C$, which is called in Clazz.new_(). // arg4 is the superclass // arg5 is the superinterface(s) // arg6 is the type: anonymous(1), local(2), or absent */ Clazz.newInterface = function (prefix, name, _null1, _null2, interfacez, _0) { return Clazz.newClass(prefix, name, function(){}, null, interfacez, 0); }; // An interesting idea, but too complicated, and probably not that effective anyway. //var lambdaCache = {}; //Clazz.newLambda = function(fc, m, lambdaType) { // var key = (fc.__CLASS_NAME__ || fc) + "." + (m||0) + "." + lambdaType; // var ret = lambdaCache[key]; // if (ret) // return ret; // // creates a new functional interface // // fc is either an executable method from i -> fc() or a class or object from Class::meth // // m is the method name // // lambdaType is 'S', 'F', 'C', or 'P' (Supplier, Function, Consumer, or Predicate) // // note that we should be taking into account Boolean,Int,Double,Long here, and // // we are not fully elaborating the classes. For example getClass() does not work here. // var fAction; // if (m) { // Lambda_M // var g = fc[m]; // var f = g||fc.prototype[m]; // fAction = function(t) {return f.apply(f == g ? fc : t,[t])}; // } else { // Lambda_E, Lambda_S, Lambda_C, Lambda_T // fAction = fc; // } // switch(lambdaType) { // case 'S': // ret = {get$: fAction, // __CLASS_NAME__:"java_util_function_Supplier" // }; // // this is a rough-in // ret.getAsBoolean$ = ret.getAsDouble$ = ret.getAsInt$ = ret.getAsLong$ = ret.get$; // break; // case 'C': // ret = {accept$: fAction, // andThen$java_util_function_Function: function(after) { // if (!after) throw new NullPointerException(); // return function(t,u) { fAction(t,u); after.accept$(t,u);} // }, // __CLASS_NAME__:"java_util_function_Consumer" // }; // break; // case 'F': // ret = { // apply$: fAction, // andThen$java_util_function_Function: function(after) { // if (!after) throw new NullPointerException(); // return function(t,u) { return after.apply$(fAction(t,u));} // }, // compose$java_util_function_Function: function(before) { // if (!before) throw new NullPointerException(); // return function(t,u) { return fAction(before.apply$(t,u));} // }, // identity$: function(t) { return t}, // __CLASS_NAME__:"java_util_function_Function" // }; // break; // case 'P': // ret = {test$: fAction, // and$java_util_function_predicate: function(other) { // if (!other) throw new NullPointerException(); // return function(t,u) { return fAction(t,u) && other.test$(t,u);} // }, // or$java_util_function_predicate: function(other) { // if (!other) throw new NullPointerException(); // return function(t,u) { return fAction(t,u) || other.test$(t,u);} // }, // negate$: function() { // return function(t,u) { return !fAction(t,u) } // }, // isEqual$O: function(target) { // return function(t) { return (target == null) == (t == null) // && (t == null || t.equals$O(target));} // }, // __CLASS_NAME__:"java_util_function_Predicate" // }; // break; // } // // return lambdaCache[key] = ret; //}; var __allowOverwriteClass = true; Clazz.newMeth = function (clazzThis, funName, funBody, modifiers) { if (!__allowOverwriteClass && clazzThis.prototype[funName]) return; // modifiers: 1: static, 2: native, p3 -- private holder if (arguments.length == 1) { return Clazz.newMeth(clazzThis, 'c$', function(){ Clazz.super_(clazzThis, this,1); clazzThis.$init$.apply(this); }, 1); } if (funName.constructor == Array) { // If funName is an array, we are setting aliases for generic calls. // For example: ['compareTo$S', 'compareTo$TK', 'compareTo$TA'] // where K and A are generic types that are from a class or class assignment. for (var i = funName.length; --i >= 0;) Clazz.newMeth(clazzThis, funName[i], funBody, modifiers); return; } var isStatic = (modifiers == 1 || modifiers == 2); var isPrivate = (typeof modifiers == "object"); if (isPrivate) clazzThis.$P$ = modifiers; Clazz.saemCount0++; funBody.exName = funName; // mark it as one of our methods funBody.exClazz = clazzThis; // make it traceable funBody.isPrivate = isPrivate; var f; if (isStatic || funName == "c$") clazzThis[funName] = funBody; if (clazzThis.$isInterface) clazzThis.$hasJava8Defaults = true; if (isPrivate && modifiers) modifiers[funName] = funBody; else clazzThis.prototype[funName] = funBody; return funBody; // allow static calls as though they were not static }; Clazz.newPackage = function (pkgName) { Clazz._Loader && Clazz._Loader.doTODO(); if (Clazz.lastPackageName == pkgName || !pkgName) return Clazz.lastPackage; var pkgFrags = pkgName.split (/\./); var pkg = Clazz._allPackage; for (var i = 0; i < pkgFrags.length; i++) { var a = pkgFrags[i]; if (!pkg[a]) { pkg[a] = { __PKG_NAME__ : (pkg.__PKG_NAME__ ? pkg.__PKG_NAME__ + "." + a : a) } if (i == 0) { // window[a] = ... Clazz.setGlobal(a, pkg[a]); } } pkg = pkg[a] } Clazz.lastPackageName = pkgName; return Clazz.lastPackage = pkg; }; Clazz.super_ = function(cl, obj, andInit) { if (cl.superclazz && cl.superclazz.c$) { // added [] here to account for the possibility of vararg default constructor cl.superclazz.c$.apply(obj, [[]]); } if (andInit) { cl.$init$.apply(obj); } } ///////////////////////////////////////////////////////////////////// var aas = "AAA"; /** * Create an array class placeholder for reflection */ var arrayClass = function(baseClass, ndim) { ndim || (ndim = 1); var stub = Clazz._getParamCode(baseClass); while (aas.length < ndim) aas += aas; var aaa = aas.substring(0, ndim); var o = {}; o.arrayType = 1; o.__BASECLASS = baseClass; o.__NDIM = ndim; o.__CLASS_NAME__ = o.__ARRAYTYPE = stub + aaa; o.__COMPONENTTYPE = (o.__NDIM == 1 ? baseClass : null); var oclass = Clazz.getClass(o); oclass.getComponentType$ = function() { return o.__COMPONENTTYPE || (o.__COMPONENTTYPE = arrayClass(baseClass, ndim - 1)); }; oclass.getName$ = function() {return o.__NAME || (o__NAME = (function() { switch (stub) { case "O": stub = "Object"; break; case "S": stub = "String"; break; case "H": stub = "S"; break; default: if (stub.length > 1) stub = baseClass.__CLASS_NAME__; break; } if (stub.indexOf(".") >= 0) stub = "L" + stub + ";"; else if (stub.length > 1) stub = "Ljava.lang." + stub + ";"; return aaa.replace(/A/g,"[") + stub; })())}; return oclass; } var _globals = ["j2s.clazzloaded"];//, "j2s.object.native"]; Clazz.setGlobal = function(a, v) { _globals.push(a); window[a] = v; } Clazz.getGlobals = function() { return _globals.sort().join("\n"); } Clazz.setConsoleDiv = function(d) { window["j2s.lib"] && (window["j2s.lib"].console = d); }; //var supportsNativeObject = window["j2s.object.native"]; // true //Clazz.duplicatedMethods = {}; //Clazz._preps = {}; // prepareFields functions based on class name // BH Clazz.getProfile monitors exactly what is being delegated with SAEM, // which could be a bottle-neck for function calling. // This is critical for performance optimization. var __signatures = ""; var profilet0; var _profileNew = null; var _jsid0 = 0; Clazz.startProfiling = function(doProfile) { _profileNew = {}; if (typeof doProfile == "number") { _jsid0 = _jsid; setTimeout(function() { var s = "total wall time: " + doProfile + " sec\n" + Clazz.getProfile(); console.log(s); System.out.println(s)}, doProfile * 1000); } else if (doProfile === false) { _jsid = 0; _profileNew = null; } return (_profileNew ? "use Clazz.getProfile() to show results" : "profiling stopped and cleared") } var tabN = function(n) { n = ("" + n).split(".")[0]; return "..........".substring(n.length) + n + "\t" }; Clazz.getProfile = function() { var s = "run Clazz.startProfiling() first"; if (_profileNew) { s += "\n\n Total new objects: " + (_jsid - _jsid0) + "\n"; s += "\ncount \texec(ms)\n"; s += "--------\t--------\t------------------------------\n"; totalcount = 0; totaltime = 0; var rows = []; for (var key in _profileNew) { var count = _profileNew[key][0]; var tnano = _profileNew[key][1]; totalcount += count; totaltime += Math.abs(tnano); rows.push(tabN(count) + tabN(Math.round(tnano)) + "\t" +key + "\n"); } rows.sort(); rows.reverse(); s += rows.join(""); s+= tabN(totalcount)+tabN(Math.round(totaltime)) + "\n"; } _profileNew = null; return s; //+ __signatures; } var addProfileNew = function(c, t) { var s = c.__CLASS_NAME__ || c.__PARAMCODE; if (t < 0) s += "[]"; var p = _profileNew[s]; p || (p = _profileNew[s] = [0,0]); p[0]++; p[1]+=t; } ///////////////////// method creation //////////////////////////////// var doDebugger = function() { debugger } var _declared = {}; var checkDeclared = function(name, type) { if (J2S._debugName && name.toLowerCase() == J2S._debugName)doDebugger(); // if (_declared[name] != null && _declared[name] == type) { // var s = (type === 0 ? "interface" : "class") +" " + name + " is defined twice. A prior core file has probably needed to load a class that is in the current core file. Check to make sure that package.js declares the first class read in jarClassPath or that BuildCompress has included all necessary files." // System.out.println(s); // if (J2S._debugCore) doDebugger(); // } _declared[name] = type; } /* public */ Clazz._isClassDefined = function(clazzName) { if (!clazzName) return false; /* consider null or empty name as non-defined class */ if (Clazz.allClasses[clazzName]) return true; var pkgFrags = clazzName.split (/\./); var pkg = null; for (var i = 0; i < pkgFrags.length; i++) if (!(pkg = (pkg ? pkg[pkgFrags[i]] : Clazz._allPackage[pkgFrags[0]]))) { return false; } return (pkg && (Clazz.allClasses[clazzName] = pkg)); }; ///////////////////////// private supporting method creation ////////////////////// var copyArrayProps = function(a, b) { b.__BYTESIZE = a.__BYTESIZE; b.__ARRAYTYPE = a.__ARRAYTYPE; b.__BASECLASS = a.__BASECLASS; b.__NDIM = a.__NDIM; b.getClass$ = a.getClass$; b.equals$O = a.equals$O; b.hashCode$ = a.hashCode$; return b; } var setArray = function(vals, baseClass, paramType, ndims) { ndims = Math.abs(ndims); vals.getClass$ = function () { return arrayClass(this.__BASECLASS, this.__NDIM) }; vals.hashCode$ = function() {return this.toString().hashCode$()} vals.equals$O = function (a) { if (!a || a.__ARRAYTYPE != this.__ARRAYTYPE || a.length != this.length) return false; if (a.length == 0) return true; if (typeof a[0] == "object") { for (var i = a.length; --i >= 0;) if ((a[i] == null) != (this[i] == null) || a[i] != null && (a[i].equals$O && !a[i].equals$O(this[i]) || a.equals && !a[i].equals(this[i]) || a[i] !== this[i])) return false; } else { for (var i = a.length; --i >= 0;) if (a[i] !== this[i]) return false; } return true; }; vals.__ARRAYTYPE = paramType; // referenced in java.lang.Class vals.__BASECLASS = baseClass; vals.__NDIM = ndims; return vals; } /** * in-place shift of an array by k elements, starting with element i0, * resetting its length in case it is arguments (which does not have the * .shift() method. Returns a[i0] */ var shiftArray = function(a, i0, k) { if (a == null || k > a.length) return null; k || (k == 1); i0 || (i0 == 0); var arg = a[i0]; for (var i = i0, n = a.length - k; i < n; i++) a[i] = a[i + k]; a.length -= k; return arg; }; var getParamCode = Clazz._getParamCode = function(cl) { cl.$clazz$ && (cl = cl.$clazz$); return cl.__PARAMCODE || (cl.__PARAMCODE = cl.__CLASS_NAME__.replace(/java\.lang\./, "").replace(/\./g, '_')); } var newTypedA = function(baseClass, args, nBits, ndims, isClone) { var dim = args[0]; if (typeof dim == "string") dim = dim.charCodeAt(0); // int[] a = new int['\3'] ??? var last = args.length - 1; var paramType = args[last]; var val = args[last - 1]; if (ndims > 1) { // array of arrays var xargs = new Array(last--); for (var i = 0; i <= last; i++) xargs[i] = args[i + 1]; // SAA -> SA xargs[last] = paramType.substring(0, paramType.length - 1); var arr = new Array(dim); for (var i = 0; i < dim; i++) arr[i] = newTypedA(baseClass, xargs, nBits, ndims - 1); // Call recursively } else { // Clazz.newIntA(new int[5][] val = null // Clazz.newA(5 ,null, "SA") new String[5] val = null // Clazz.newA(-1, ["A","B"], "SA") new String[] val = {"A", "B"} // Clazz.newA(3, 5, 0, "IAA") new int[3][5] (second pass, so now args = [5, 0, "IA"]) if (val == null) { nBits = 0; } else if (nBits > 0 && dim < 0) { // make sure this is not a character for (var i = val.length; --i >= 0;) val[i].charAt && (val[i] = val[i].$c()); dim = val; // because we can initialize an array using new Int32Array([...]) } if (nBits > 0) ndims = 1; var atype; switch (nBits) { case 8: var arr = new Int8Array(dim); break; case 16: var arr = new Int16Array(dim); break; case 32: var arr = new Int32Array(dim); break; case 64: var arr = new Float64Array(dim); break; default: nBits = 0; var arr; if (isClone) { arr = new Array(dim = val.length); } else { arr = (dim < 0 ? val : new Array(dim)); if (dim > 0 && val != null) for (var i = dim; --i >= 0;) arr[i] = val; } break; } arr.__BYTESIZE = arr.BYTES_PER_ELEMENT || (nBits >> 3); } return setArray(arr, baseClass, paramType, ndims); } /** * Return the class name of the given class or object. * * @param clazzHost given class or object * @return class name */ var getClassName = function(obj, fAsClassName) { if (obj == null) return "NullObject"; if (obj._NULL_) return obj.clazzName; switch(typeof obj) { case "number": return "n"; case "boolean": return "b"; case "string": // Always treat the constant string as String object. // This will be compatiable with Java String instance. return "String"; case "function": if (obj.__CLASS_NAME__) return (fAsClassName ? obj.__CLASS_NAME__ : "Class"); // user defined class name var s = obj.toString(); var idx0 = s.indexOf("function"); if (idx0 < 0) return (s.charAt(0) == '[' ? extractClassName(s) : s.replace(/[^a-zA-Z0-9]/g, '')); var idx1 = idx0 + 8; var idx2 = s.indexOf ("(", idx1); if (idx2 < 0) return "Object"; s = s.substring (idx1, idx2); if (s.indexOf("Array") >= 0) return "Array"; s = s.replace (/^\s+/, "").replace (/\s+$/, ""); return (s == "anonymous" || s == "" ? "Function" : s); case "object": if (obj.__CLASS_NAME__) // user defined class name return obj.__CLASS_NAME__; if (!obj.constructor) return "Object"; // For HTML Element in IE if (!obj.constructor.__CLASS_NAME__) { if (obj.__VAL0__) return "Number"; if (obj instanceof Boolean) return "Boolean"; if (obj instanceof Array || obj.__BYTESIZE) return "Array"; var s = obj.toString(); // "[object Int32Array]" if (s.charAt(0) == '[') return extractClassName(s); } return getClassName(obj.constructor, true); } // some new, unidentified class return "Object"; }; var extractClassName = function(clazzStr) { // [object Int32Array] var clazzName = clazzStr.substring (1, clazzStr.length - 1); return (clazzName.indexOf("Array") >= 0 ? "Array" // BH -- for Float64Array and Int32Array : clazzName.indexOf ("object ") >= 0 ? clazzName.substring (7) // IE : clazzName); } /** * Expand the shortened list of class names. * For example: * JU.Log, $.Display, $.Decorations * will be expanded to * JU.Log, JU.Display, JU.Decorations * where "$." stands for the previous class name's package. * * This method will be used to unwrap the required/optional classes list and * the ignored classes list. */ /* private */ var unwrapArray = function (arr) { if (!arr || arr.length == 0) return []; var last = null; for (var i = 0; i < arr.length; i++) { var ai = arr[i]; if (typeof ai != "string") continue; if (ai.charAt(0) == '$') { if (ai.charAt(1) == '.') { if (!last) continue; var idx = last.lastIndexOf("."); if (idx != -1) { var prefix = last.substring (0, idx); arr[i] = prefix + ai.substring(1); } } else { arr[i] = "org.eclipse.s" + ai.substring (1); } } last = arr[i]; } return arr; }; /** * Return the JavaScript clazz of the given class or object. * * @param clazzHost given class or object * @return class name */ var getClazz = function (clazzHost) { if (!clazzHost) return Clazz._O; // null/undefined is always treated as Object if (typeof clazzHost == "function") return clazzHost; var clazzName; if (clazzHost._NULL_) { clazzName = clazzHost.clazzName; } else { switch (typeof clazzHost) { case "string": return String; case "object": if (!clazzHost.__CLASS_NAME__) return (clazzHost.constructor || Clazz._O); clazzName = clazzHost.__CLASS_NAME__; break; default: return clazzHost.constructor; } } return evalType(clazzName, true); }; var appendMap = function(a, b) { if (b) for (var s in b) { a[s] = b[s]; } return a; } var hashCode = 0; var _jsid = 0; //if (supportsNativeObject) { // true Clazz._O = function () {}; Clazz._O.__CLASS_NAME__ = "Object"; Clazz._O.__PARAMCODE = "O"; Clazz._O.getClass$ = function () { return Clazz._O; }; //} else { // Clazz._O = Object; //} /* * these methods are not part of Java. * var objMethods = { equals : function (o) { return this === o; }, hashCode : function () { return this.__CLASS_NAME__.hashCode (); }, toString : function () { return "class " + this.__CLASS_NAME__; } }; objMethods.equals$O = objMethods.equals; */ // set object methods for Clazz._O and Array var addProto = function(proto, name, func) { func.exClazz = Clazz._O; func.exName = name; return proto[name] = func; }; //var minimalObjNames = [ "equals$", "equals$O", "hashCode$" /*"toString",*/ ]; ;(function(proto) { // for (var i = minimalObjNames.length, name; --i >= 0;) { // name = minimalObjNames[i]; // objMethods[name].exClazz = Clazz._O; // objMethods[name].exName = name; // Clazz._O[name = objNames[i]] = Array[name] = objMethods[name]; // } // addProto(proto, "isInstance", function(c) { // return Clazz.instanceOf(this, c); // }), // // addProto(proto, "equals", function (obj) { // return this == obj; // }); addProto(proto, "equals$O", function (obj) { return this == obj; }); addProto(proto, "hashCode$", function () { return this._$hashcode || (this._$hashcode = ++hashCode) }); addProto(proto, "getClass$", function () { return Clazz.getClass(this); }); addProto(proto, "clone$", function () { return Clazz.clone(this); }); /* * Methods for thread in Object */ addProto(proto, "finalize$", function () {}); addProto(proto, "notify$", function () {}); addProto(proto, "notifyAll$", function () {}); addProto(proto, "wait$", function () {alert("Object.wait was called!" + arguments.callee.caller.toString())}); addProto(proto, "toString$", Object.prototype.toString); addProto(proto, "toString", function () { return (this.__CLASS_NAME__ ? "[" + this.__CLASS_NAME__ + " object]" : this.toString$.apply(this, arguments)); }); })(Clazz._O.prototype); var extendObjectMethodNames = [ // all "equals$O", "getClass$", "clone$", "finalize$", "notify$", "notifyAll$", "wait$", // not Number, Array "hashCode$", // not String "toString" ]; var EXT_NO_TOSTRING = 1; // length - 1 var EXT_NO_HASHCODE = 2; // length - 2 var extendObject = function(clazz, ext) { var op =Clazz._O.prototype; var cp = clazz.prototype; for (var i = extendObjectMethodNames.length - (ext || 0); --i >= 0;) { var p = extendObjectMethodNames[i]; cp[p] = op[p]; } } //var checkObjectMethods = function (hostSuper, funName) { // for (var k = objNames.length; --k >= 0;) // if (funName == objNames[k] && objMethods[funName] === hostSuper[funName]) // return true; // return false; //}; var excludeSuper = function(o) { return o == "b$" || o == "$this$0" || o == "$init$" || o == "$init0$" || o == "$clinit$" || o == "$load$" || o == "$Class$" || o == "prototype" || o == "__CLASS_NAME__" || o == "__CLASS_NAME$__" || o == "superclazz" || o == "implementz" || o.startsWith("c$") } var copyStatics = function(clazzFrom, clazzThis, isInterface) { for (var o in clazzFrom) { if (clazzThis[o] == undefined && !excludeSuper(o)) { clazzThis[o] = clazzFrom[o]; if (isInterface) clazzThis.prototype[o] = clazzFrom[o]; } } if (isInterface) { for (var o in clazzFrom.prototype) { if (clazzThis.prototype[o] == undefined && !excludeSuper(o)) { clazzThis.prototype[o] = clazzFrom.prototype[o]; } } __allowOverwriteClass = false; if (clazzFrom.$defaults$) clazzFrom.$defaults$(clazzThis); __allowOverwriteClass = true; } } var finalizeClazz = function(clazz, qname, bname, type, isNumber) { clazz.$isInterface = (type == 0); qname && (clazz.__CLASS_NAME__ = clazz.prototype.__CLASS_NAME__ = qname); bname && (clazz.__CLASS_NAME$__ = clazz.prototype.__CLASS_NAME$__ = bname); // inner static classes use $ not "." (type == 1) && (clazz.__ANON = clazz.prototype.__ANON = 1); (type == 2) && (clazz.__LOCAL = clazz.prototype.__LOCAL = 1); if (!isNumber && type != 0) Clazz.newMeth(clazz, '$init0$', function(){var c;if ((c=clazz.superclazz) && (c = c.$init0$))c.apply(this);}, 1); if (isNumber || type != 0) extendPrototype(clazz); }; var extendPrototype = function(clazz, isPrimitive, addAll) { clazz.isInstance = function(o) { return Clazz.instanceOf(o, this) }; var cp = clazz.prototype; var op = Clazz._O.prototype; for (var i = 0; i < extendObjectMethodNames.length; i++) { var p = extendObjectMethodNames[i]; if (!cp[p] || cp[p].exClazz == Clazz._O) addProto(cp, p, op[p]); } } Clazz.saemCount0 = 0 // methods defined 5400 (Ripple.js) Clazz.saemCount1 = 0 // delegates created 937 Clazz.saemCount2 = 0 // delegates bound 397 Clazz.saemCount3 = 0 // isInstanceOfs started Clazz.saemCount4 = 0 // isInstanceOfs checked var NullObject = function () {}; var evalType = function (typeStr, isQualified) { if (typeStr == null) return null; if (isQualified && window[typeStr]) return window[typeStr]; var idx = typeStr.lastIndexOf("."); if (idx >= 0) { var pkgName = typeStr.substring (0, idx); var pkg = Clazz.newPackage(pkgName); var clazzName = typeStr.substring (idx + 1); return pkg[clazzName]; } if (isQualified) return window[typeStr]; switch (typeStr) { case "string": return String; case "number": return Number; case "object": return Clazz._O; case "boolean": return Boolean; case "function": return Function; case "void": case "undefined": case "unknown": return typeStr; case "NullObject": return NullObject; default: return window[typeStr]; } }; var equalsOrExtendsLevel = function (clazzThis, clazzAncestor) { while (true) { if (clazzThis == null) return false; if (clazzThis === clazzAncestor) return true; if (clazzThis && clazzThis.implementz) { var impls = clazzThis.implementz; for (var i = impls.length; --i >= 0;) if (equalsOrExtendsLevel(impls[i], clazzAncestor)) return true; } clazzThis = clazzThis.superclazz; } return false; }; var isInstanceOf = function (clazzTarget, clazzBase, isTgtStr, isBaseStr) { if (clazzTarget === clazzBase) return true; clazzBase.$clinit$ && clazzBase.$clinit$(); if (isTgtStr && ("void" == clazzTarget || "unknown" == clazzTarget)) return false; if (isBaseStr && ("void" == clazzBase || "unknown" == clazzBase)) return false; if (clazzTarget === (isTgtStr ? "NullObject" : NullObject)) { switch (clazzBase) { case "n": case "b": return false; case Number: case Boolean: case NullObject: break; default: return true; } } isTgtStr && (clazzTarget = evalType(clazzTarget)); isBaseStr && (clazzBase = evalType(clazzBase)); return (clazzBase && clazzTarget && ( clazzTarget == clazzBase || clazzBase === Object || clazzBase === Clazz._O || equalsOrExtendsLevel(clazzTarget, clazzBase) )); }; /////////////////////////// Exception handling //////////////////////////// /* * Use to mark that the Throwable instance is created or not. * * Called from java.lang.Throwable, as defined in JSmolJavaExt.js * * The underscore is important - it tells the JSmol ANT task to NOT * turn this into Clazz_initializingException, because coreBottom2.js does * not include that call, and so Google Closure Compiler does not minify it. * */ /* public */ Clazz._initializingException = false; /** * MethodException will be used as a signal to notify that the method is * not found in the current clazz hierarchy. */ /* private */ var MethodException = function () { this.toString = function () { return "j2s MethodException"; }; }; var _isNPEExceptionPredicate; ;(function() { /* sgurin: native exception detection mechanism. Only NullPointerException detected and wrapped to java excepions */ /** private utility method for creating a general regexp that can be used later * for detecting a certain kind of native exceptions. use with error messages like "blabla IDENTIFIER blabla" * @param msg String - the error message * @param spliterName String, must be contained once in msg * spliterRegex String, a string with the regexp literal for identifying the spitter in exception further error messages. */ // reproduce NullPointerException for knowing how to detect them, and create detector function Clazz._isNPEExceptionPredicate var $$o$$ = null; try { $$o$$.hello(); } catch (e) { var _ex_reg = function(msg, spliterName, spliterRegex) { if(!spliterRegex) spliterRegex="[^\\s]+"; var idx = msg.indexOf (spliterName), str = msg.substring (0, idx) + spliterRegex + msg.substring(idx + spliterName.length), regexp = new RegExp("^"+str+"$"); return regexp; }; if(/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {// opera throws an exception with fixed messages like "Statement on line 23: Cannot convert undefined or null to Object Backtrace: Line....long text... " var idx1 = e.message.indexOf(":"), idx2 = e.message.indexOf(":", idx1+2); var _NPEMsgFragment = e.message.substr(idx1+1, idx2-idx1-20); _isNPEExceptionPredicate = function(e) { return e.message.indexOf(_NPEMsgFragment)!=-1; }; } else if(navigator.userAgent.toLowerCase().indexOf("webkit")!=-1) { //webkit, google chrome prints the property name accessed. var _exceptionNPERegExp = _ex_reg(e.message, "hello"); _isNPEExceptionPredicate = function(e) { return _exceptionNPERegExp.test(e.message); }; } else {// ie, firefox and others print the name of the object accessed: var _exceptionNPERegExp = _ex_reg(e.message, "$$o$$"); _isNPEExceptionPredicate = function(e) { return _exceptionNPERegExp.test(e.message); }; } }; })(); var getArgs = function(c) { var s = ""; var args = c.arguments; for (var j = 0; j < args.length; j++) { var sa = (args[j] instanceof Object ? args[j].toString() : "" + args[j]); if (sa.length > 60) sa = sa.substring(0, 60) + "..."; s += " args[" + j + "]=" + sa.replace(/\s+/g," ") + "\n"; } return s; } var getSig = function(c, withParams) { var sig = (c.toString ? c.toString().substring(0, c.toString().indexOf("{")) : ""); sig = " " + (c.exName ? c.exClazz.__CLASS_NAME__ + "." + c.exName + sig.replace(/function /,""): sig) + "\n"; if (withParams) sig += getArgs(c); return sig; } Clazz._showStack = function(n) { if (!Clazz._stack) return; n && n < Clazz._stack.length || (n = Clazz._stack.length); if (!n) return; for (var i = 0; i < n; i++) { console.log("" + i + ":" + getSig(Clazz._stack[i], true)); } return ""; } Clazz._getStackTrace = function(n) { Clazz._stack = []; // need to limit this, as JavaScript call stack may be recursive var haven = !!n haven || (n = 25); var showParams = (n < 0); if (showParams) n = -n; // updateNode and updateParents cause infinite loop here var estack = []; try { Clazz.failnow(); } catch (e) { estack = e.stack.split("\n").reverse(); estack.pop(); } var s = "\n"; try { var c = arguments.callee; for (var i = 0; i < n; i++) { if (!(c = c.caller)) break; var sig = getSig(c, false); if (s.indexOf(sig) >= 0) { s += "..."; break; } else { Clazz._stack.push(c); s += "" + i + sig; s += estack.pop() + "\n\n"; } if (c == c.caller) { s += "\n"; break; } if (showParams) { s += getArgs(c); } } } catch(e){} if (!haven) s += estack.join("\n"); if (Clazz._stack.length) { s += "\nsee Clazz._stack"; console.log("Clazz.stack = \n" + estack.join("\n")); console.log("Use Clazz._showStack() or Clazz._showStack(n) to show parameters"); } return s; } ////////////////////////////////// package loading /////////////////////// /* * all root packages. e.g. java.*, org.*, com.* */ Clazz._allPackage = {}; /** * Will be used to keep value of whether the class is defined or not. */ Clazz.allClasses = {}; Clazz.lastPackageName = null; Clazz.lastPackage = null; var unloadedClasses = []; /** * used specifically for declaring prototypes using * subclass.prototype = new superclass(inheritArgs) * without running a constructor or doing field preparation. * */ var inheritArgs = new (function(){return {"$J2SNOCREATE$":true}})(); //var _prepOnly = new (function(){return {"$J2SPREPONLY$":true}})(); /** * Inherit class with "extends" keyword and also copy those static members. * Example, as in Java, if NAME is a static member of ClassA, and ClassB * extends ClassA then ClassB.NAME can be accessed in some ways. * * @param clazzThis child class to be extended * @param clazzSuper super class which is inherited from */ var setSuperclass = function(clazzThis, clazzSuper){ clazzThis.superclazz = clazzSuper || Clazz._O; if (clazzSuper) { copyStatics(clazzSuper, clazzThis, false); var p = clazzThis.prototype; if (clazzSuper == Number) { clazzThis.prototype = new Number(); } else { clazzThis.prototype = new clazzSuper ([inheritArgs]); if (clazzSuper == Error) { var pp = Throwable.prototype; for (o in pp) { if (!pp.exClazz || pp.exClazz != Clazz._O) clazzThis.prototype[o] = pp[o]; } } } for (o in p) { if (!p[o].exClazz || p[o].exClazz != Clazz._O) clazzThis.prototype[o] = p[o]; } } clazzThis.prototype.__CLASS_NAME__ = clazzThis.__CLASS_NAME__; }; /** * Implementation of Java's keyword "implements". * As in JavaScript there are on "implements" keyword implemented, a property * of "implementz" is added to the class to record the interfaces the class * is implemented. * * @param clazzThis the class to implement * @param interfacez Array of interfaces */ var addInterface = function (clazzThis, interfacez) { if (interfacez instanceof Array) { for (var i = interfacez.length; --i >= 0;) { var iface = interfacez[i]; if (iface instanceof Array) { var cl; for (var j = 0; j < iface.length; j++) cl = Clazz.load(iface[j]); iface = cl; } addInterface(clazzThis, iface); } return; } // not an array... if (typeof interfacez == "string") { var str = interfacez; if (!(interfacez = Clazz.load(interfacez))) { alert("Missing interface: " + str); return; } } (clazzThis.implementz || (clazzThis.implementz = [])).push(interfacez); copyStatics(interfacez, clazzThis, true); }; ////////////////////////// default package declarations //////////////////////// /* * Check whether given package's classpath is setup or not. * Only "java" and "org.eclipse.swt" are accepted in argument. */ /* private */ var needPackage = function(pkg) { // note that false != null and true != null return (window[pkg + ".registered"] != null && !classpathMap["@" + pkg]); } // Make sure that packageClasspath ("java", base, true); // is called before any _Loader#loadClass is called. if (needPackage("java")) _Loader.loadPackage("java"); Clazz.newPackage("java.io"); Clazz.newPackage("java.lang.reflect"); Clazz.newPackage("java.util"); // NOTE: Any changes to this list must also be // accounted for in net.sf.j2s.core.astvisitors.Java2ScriptVisitor.knownClasses Clazz.newInterface(java.io,"Externalizable"); Clazz.newInterface(java.io,"Flushable"); Clazz.newInterface(java.io,"Serializable"); Clazz.newInterface(java.lang,"Cloneable"); Clazz.newInterface(java.lang,"Appendable"); Clazz.newInterface(java.lang,"Comparable"); Clazz.newInterface(java.lang,"Runnable"); (function(){var P$=java.lang,I$=[[0,'java.util.stream.StreamSupport','java.util.Spliterators','java.lang.CharSequence$lambda1','java.lang.CharSequence$lambda2']],$I$=function(i){return I$[i]||(I$[i]=Clazz.load(I$[0][i]))}; var C$=Clazz.newInterface(P$, "CharSequence"); C$.$defaults$ = function(C$){ Clazz.newMeth(C$, 'chars$', function () { return $I$(1).intStream$java_util_function_Supplier$I$Z(((P$.CharSequence$lambda1|| (function(){var C$=Clazz.newClass(P$, "CharSequence$lambda1", function(){Clazz.newInstance(this, arguments[0],1,C$);}, null, 'java.util.function.Supplier', 1); C$.$clinit$ = function() {Clazz.load(C$, 1); } Clazz.newMeth(C$, '$init$', function () { }, 1); /*lambda_E*/ Clazz.newMeth(C$, 'get$', function () { return($I$(2).spliterator$java_util_PrimitiveIterator_OfInt$J$I(Clazz.new_(CharSequence$1CharIterator.$init$, [this, null]), this.b$['CharSequence'].length$(), 16));}); })() ), Clazz.new_($I$(3).$init$, [this, null])), 16464, false); }); Clazz.newMeth(C$, 'codePoints$', function () { return $I$(1).intStream$java_util_function_Supplier$I$Z(((P$.CharSequence$lambda2|| (function(){var C$=Clazz.newClass(P$, "CharSequence$lambda2", function(){Clazz.newInstance(this, arguments[0],1,C$);}, null, 'java.util.function.Supplier', 1); C$.$clinit$ = function() {Clazz.load(C$, 1); } Clazz.newMeth(C$, '$init$', function () { }, 1); /*lambda_E*/ Clazz.newMeth(C$, 'get$', function () { return($I$(2).spliteratorUnknownSize$java_util_PrimitiveIterator_OfInt$I(Clazz.new_(CharSequence$1CodePointIterator.$init$, [this, null]), 16));}); })() ), Clazz.new_($I$(4).$init$, [this, null])), 16, false); }); };; (function(){var C$=Clazz.newClass(P$, "CharSequence$1CharIterator", function(){ Clazz.newInstance(this, arguments[0],true,C$); }, null, [['java.util.PrimitiveIterator','java.util.PrimitiveIterator.OfInt']], 2); C$.$clinit$ = function() {Clazz.load(C$, 1); } Clazz.newMeth(C$, '$init0$', function () { var c;if((c = C$.superclazz) && (c = c.$init0$))c.apply(this); this.cur = 0; }, 1); Clazz.newMeth(C$, '$init$', function () { this.cur = 0; }, 1); Clazz.newMeth(C$, 'hasNext$', function () { return this.cur < this.b$['CharSequence'].length$(); }); Clazz.newMeth(C$, 'nextInt$', function () { if (this.hasNext$()) { return this.b$['CharSequence'].charAt$I.apply(this.b$['CharSequence'], [this.cur++]).$c(); } else { throw Clazz.new_(Clazz.load('java.util.NoSuchElementException')); }}); Clazz.newMeth(C$, ['forEachRemaining$java_util_function_IntConsumer','forEachRemaining$TT_CONS'], function (block) { for (; this.cur < this.b$['CharSequence'].length$(); this.cur++) { block.accept$(this.b$['CharSequence'].charAt$I(this.cur).$c()); } }); Clazz.newMeth(C$); })() ; (function(){var C$=Clazz.newClass(P$, "CharSequence$1CodePointIterator", function(){ Clazz.newInstance(this, arguments[0],true,C$); }, null, [['java.util.PrimitiveIterator','java.util.PrimitiveIterator.OfInt']], 2); C$.$clinit$ = function() {Clazz.load(C$, 1); } Clazz.newMeth(C$, '$init0$', function () { var c;if((c = C$.superclazz) && (c = c.$init0$))c.apply(this); this.cur = 0; }, 1); Clazz.newMeth(C$, '$init$', function () { this.cur = 0; }, 1); Clazz.newMeth(C$, ['forEachRemaining$java_util_function_IntConsumer','forEachRemaining$TT_CONS'], function (block) { var length = this.b$['CharSequence'].length$(); var i = this.cur; try { while (i < length){ var c1 = this.b$['CharSequence'].charAt$I(i++); if (!Character.isHighSurrogate$C(c1) || i >= length ) { block.accept$(c1.$c()); } else { var c2 = this.b$['CharSequence'].charAt$I(i); if (Character.isLowSurrogate$C(c2)) { i++; block.accept$(Character.toCodePoint$C$C(c1, c2)); } else { block.accept$(c1.$c()); }}} } finally { this.cur=i; } }); Clazz.newMeth(C$, 'hasNext$', function () { return this.cur < this.b$['CharSequence'].length$(); }); Clazz.newMeth(C$, 'nextInt$', function () { var length = this.b$['CharSequence'].length$(); if (this.cur >= length) { throw Clazz.new_(Clazz.load('java.util.NoSuchElementException')); }var c1 = this.b$['CharSequence'].charAt$I.apply(this.b$['CharSequence'], [this.cur++]); if (Character.isHighSurrogate$C(c1) && this.cur < length ) { var c2 = this.b$['CharSequence'].charAt$I.apply(this.b$['CharSequence'], [this.cur]); if (Character.isLowSurrogate$C(c2)) { this.cur++; return Character.toCodePoint$C$C(c1, c2); }}return c1.$c(); }); Clazz.newMeth(C$); })() })(); //(function(){var P$=java.lang,I$=[['java.util.stream.StreamSupport','java.util.Spliterators','java.lang.CharSequence$1CharIterator','java.lang.CharSequence$1CodePointIterator']],$incl$=function(i){return I$[i]=Clazz.load(I$[0][i-1])}; //var C$=Clazz.newInterface(java.lang, "CharSequence"); //C$.$defaults = function(C$) { //var me; // //Clazz.newMeth(C$, 'chars$', function () { //me = this; //return (I$[1]||$incl$(1)).intStream$java_util_function_Supplier$I$Z((( //(function(){var C$=Clazz.newClass(P$, "CharSequence$lambda1", function(){Clazz.newInstance(this, arguments[0],1,C$);}, null, 'java.util.function.Supplier', 1); // //C$.$clinit$ = function() {Clazz.load(C$, 1); //} // //Clazz.newMeth(C$, '$init$', function () { // this.b$ = {CharSequence: me}; //}, 1); ///*lambdaE*/ //Clazz.newMeth(C$, 'get$', function () { //return (I$[2]||$incl$(2)) //.spliterator$java_util_PrimitiveIterator_OfInt$J$I( // Clazz.new_((I$[3]||$incl$(3)), [this, null]), // this.b$['CharSequence'].length$(), 16); //}); //})() //), Clazz.new_(CharSequence$lambda1.$init$, [this, null])), 16464, false); //}); // //Clazz.newMeth(C$, 'codePoints$', function () { //me = this; //return (I$[1]||$incl$(1)).intStream$java_util_function_Supplier$I$Z((( //(function(){var C$=Clazz.newClass(P$, "CharSequence$lambda2", function(){Clazz.newInstance(this, arguments[0],1,C$);}, null, 'java.util.function.Supplier', 1); // //C$.$clinit$ = function() {Clazz.load(C$, 1); //} // //Clazz.newMeth(C$, '$init$', function () { // this.b$ = {CharSequence: me}; //}, 1); ///*lambdaE*/ //Clazz.newMeth(C$, 'get$', function () { //return (I$[2]||$incl$(2)).spliteratorUnknownSize$java_util_PrimitiveIterator_OfInt$I(Clazz.new_((I$[4]||$incl$(4)), [this, null]), 16); //}); //})() //), Clazz.new_(CharSequence$lambda2.$init$, [this, null])), 16, false); //}); //; //(function(){var C$=Clazz.newClass(P$, "CharSequence$1CharIterator", function(){ //Clazz.newInstance(this, arguments[0],true,C$); //}, null, [['java.util.PrimitiveIterator','java.util.PrimitiveIterator.OfInt']], 2); // //C$.$clinit$ = function() {Clazz.load(C$, 1); //} // //Clazz.newMeth(C$, '$init0$', function () { //var c;if((c = C$.superclazz) && (c = c.$init0$))c.apply(this); //this.cur = 0; //}, 1); // //Clazz.newMeth(C$, '$init$', function () { //this.cur = 0; //}, 1); // //Clazz.newMeth(C$, 'hasNext$', function () { //return this.cur < this.b$['CharSequence'].length$.apply(this.b$['CharSequence'], []); //}); // //Clazz.newMeth(C$, 'nextInt$', function () { //if (this.hasNext$()) { //return this.b$['CharSequence'].charAt$I.apply(this.b$['CharSequence'], [this.cur++]).$c(); //} else { //throw Clazz.new_(Clazz.load('java.util.NoSuchElementException')); //}}); // //Clazz.newMeth(C$, ['forEachRemaining$java_util_function_IntConsumer','forEachRemaining$TT_CONS'], function (block) { //for (; this.cur < this.b$['CharSequence'].length$.apply(this.b$['CharSequence'], []); this.cur++) { //block.accept$(this.b$['CharSequence'].charAt$I.apply(this.b$['CharSequence'], [this.cur]).$c()); //} //}); // //Clazz.newMeth(C$); //})() //; //(function(){var C$=Clazz.newClass(P$, "CharSequence$1CodePointIterator", function(){ //Clazz.newInstance(this, arguments[0],true,C$); //}, null, [['java.util.PrimitiveIterator','java.util.PrimitiveIterator.OfInt']], 2); // //C$.$clinit$ = function() {Clazz.load(C$, 1); //} // //Clazz.newMeth(C$, '$init0$', function () { //var c;if((c = C$.superclazz) && (c = c.$init0$))c.apply(this); //this.cur = 0; //}, 1); // //Clazz.newMeth(C$, '$init$', function () { //this.cur = 0; //}, 1); // //Clazz.newMeth(C$, ['forEachRemaining$java_util_function_IntConsumer','forEachRemaining$TT_CONS'], function (block) { //var length = this.b$['CharSequence'].length$.apply(this.b$['CharSequence'], []); //var i = this.cur; //try { //while (i < length){ //var c1 = this.b$['CharSequence'].charAt$I.apply(this.b$['CharSequence'], [i++]); //if (!Character.isHighSurrogate$C(c1) || i >= length ) { //block.accept$(c1.$c()); //} else { //var c2 = this.b$['CharSequence'].charAt$I.apply(this.b$['CharSequence'], [i]); //if (Character.isLowSurrogate$C(c2)) { //i++; //block.accept$(Character.toCodePoint$C$C(c1, c2)); //} else { //block.accept$(c1.$c()); //}}} //} finally { //this.cur=i; //} //}); // //Clazz.newMeth(C$, 'hasNext$', function () { //return this.cur < this.b$['CharSequence'].length$.apply(this.b$['CharSequence'], []); //}); // //Clazz.newMeth(C$, 'nextInt$', function () { //var length = this.b$['CharSequence'].length$.apply(this.b$['CharSequence'], []); //if (this.cur >= length) { //throw Clazz.new_(Clazz.load('java.util.NoSuchElementException')); //}var c1 = this.b$['CharSequence'].charAt$I.apply(this.b$['CharSequence'], [this.cur++]); //if (Character.isHighSurrogate$C(c1) && this.cur < length ) { //var c2 = this.b$['CharSequence'].charAt$I.apply(this.b$['CharSequence'], [this.cur]); //if (Character.isLowSurrogate$C(c2)) { //this.cur++; //return Character.toCodePoint$C$C(c1, c2); //}}return c1.$c(); //}); // //Clazz.newMeth(C$); //})() //}; // //})(); // //////// (int) conversions ////////// // deprecated Clazz.doubleToInt = Clazz.floatToInt = function (x) { // asm.js-style conversion return x|0; }; ///////////////////////////////// Array additions ////////////////////////////// // // BH: these are necessary for integer processing, especially // // var arraySlice = function(istart, iend) { // could be Safari or could be fake istart || (istart = 0); iend || (iend = this.length); var b = new this.constructor(this.buffer.slice(istart * this.__BYTESIZE, iend * this.__BYTESIZE)); b.__BYTESIZE = a.__BYTESIZE; b.__ARRAYTYPE = a.__ARRAYTYPE; }; var setAType = function (IntXArray, nBytes, atype) { if (!IntXArray) alert("SwingJS will not work in this Browser") if (!IntXArray.prototype.sort) IntXArray.prototype.sort = Array.prototype.sort if (!IntXArray.prototype.slice) IntXArray.prototype.slice = function() {return arraySlice.apply(this, arguments)}; IntXArray.prototype.clone$ = function() { var a = this.slice(); a.__BYTESIZE = 1; a.__ARRAYTYPE = this.__ARRAYTYPE; return a; }; } setAType(Int8Array, 1, "BA"); setAType(Int16Array, 2, "HA"); setAType(Int32Array, 4, "IA"); setAType(Float64Array, 8, "DA"); java.lang.Object = Clazz._O; Clazz._declared = {} Clazz._setDeclared = function(name, func) { Clazz.allClasses[name] = func; Clazz.setGlobal(name, func); } //////////////////////////// hotspot and unloading //////////////////// // not implemented in SwingJS //////////////////////////// class loader ///////////////////////////// /****************************************************************************** * Copyright (c) 2007 java2script.org and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Zhou Renjian - initial API and implementation *****************************************************************************/ /******* * @author zhou renjian * @create July 10, 2006 *******/ // see notes in j2s/classLoader.txt //if (window["ClazzNode"] == null) { /** * TODO: * Make optimization over class dependency tree. */ /** * Static class loader class */ Clazz._Loader = Clazz.ClazzLoader = function () {}; ;(function(Clazz, _Loader) { ClassLoader = java.lang.ClassLoader = _Loader; _Loader.__CLASS_NAME__ = "ClassLoader"; Clazz.allClasses["java.lang.ClassLoader"] = _Loader; _Loader.sysLoader = null; _Loader.getSystemClassLoader$ = function() { return (_Loader.sysLoader ? _Loader.sysLoader : (_Loader.sysLoader = new Class().getClassLoader$())); }; var assertionStatus = {}; _Loader.getClassAssertionStatus$ = function(clazz) { var ret; var clazzName = clazz.__CLASS_NAME__ + "."; for (var c in assertionStatus) { if (clazzName.indexOf(c) == 0) { ret = assertionStatus[c]; break; } } return (ret === false ? false : ret || Clazz.defaultAssertionStatus); } _Loader.prototype.hashCode$ = function(){return 1}; _Loader.prototype.setDefaultAssertionStatus$Z = function(tf) { Clazz.defaultAssertionStatus = tf; }; _Loader.prototype.clearAssertionStatus$ = function() { assertionStatus = {}; Clazz.defaultAssertionStatus = false; } _Loader.prototype.setClassAssertionStatus$S$Z = _Loader.prototype.setPackageAssertionStatus$S$Z = function(clazzName, tf) { if (Clazz.allClasses[clazzName])Clazz.allClasses[clazzName].$_ASSERT_ENABLED_ = tf; assertionStatus[clazzName + "."] = tf; }; _Loader.prototype.loadClass$S = function(clazzName) { return Clazz.forName(clazzName); } _Loader._checkLoad = J2S._checkLoad; _Loader._TODO = []; _Loader.doTODO = function() { while (_Loader._TODO.length) { var f = _Loader._TODO.shift(); f(); } } var loaders = []; /* public */ _Loader.requireLoaderByBase = function (base) { for (var i = 0; i < loaders.length; i++) { if (loaders[i].$_$base == base) { return loaders[i]; } } var loader = new _Loader (); loader.$_$base = base; loaders.push(loader); return loader; }; /** * * Try to be compatible with Clazz system. * In original design _Loader and Clazz are independent! * -- zhourenjian @ December 23, 2006 */ var isClassdefined; var definedClasses; if (self.Clazz && Clazz._isClassDefined) { isClassDefined = Clazz._isClassDefined; } else { definedClasses = {}; isClassDefined = function (clazzName) { return definedClasses[clazzName] == true; }; } /* private */ var classpathMap = Clazz.classpathMap = {}; /* public */ _Loader.loadPackageClasspath = function (pkg, base, isIndex, fSuccess, mode, pt) { var map = classpathMap; mode || (mode = 0); fSuccess || (fSuccess = null); pt || (pt = 0); /* * In some situation, maybe, * _Loader.packageClasspath ("java", ..., true); * is called after other _Loader#packageClasspath, e.g. * * _Loader.packageClasspath ("org.eclipse.swt", "...", true); * _Loader.packageClasspath ("java", "...", true); * * which is not recommended. But _Loader should try to adjust orders * which requires "java" to be declared before normal _Loader * #packageClasspath call before that line! And later that line * should never initialize "java/package.js" again! */ var isPkgDeclared = (isIndex && map["@" + pkg]); if (mode == 0 && isIndex && !map["@java"] && pkg.indexOf ("java") != 0 && needPackage("java")) { _Loader.loadPackage("java", fSuccess ? function(_package){_Loader.loadPackageClasspath(pkg, base, isIndex, fSuccess, 1)} : null); if (fSuccess) return; } if (pkg instanceof Array) { unwrapArray(pkg); if (fSuccess) { if (pt < pkg.length) _Loader.loadPackageClasspath(pkg[pt], base, isIndex, function(_loadPackageClassPath){_Loader.loadPackageClasspath(pkg, base, isIndex, fSuccess, 1, pt + 1)}, 1); else fSuccess(); } else { for (var i = 0; i < pkg.length; i++) _Loader.loadPackageClasspath(pkg[i], base, isIndex, null); } return; } switch (pkg) { case "java.*": pkg = "java"; // fall through case "java": if (base) { // support ajax for default var key = "@net.sf.j2s.ajax"; if (!map[key]) map[key] = base; key = "@net.sf.j2s"; if (!map[key]) map[key] = base; } break; case "swt": pkg = "org.eclipse.swt"; break; case "ajax": pkg = "net.sf.j2s.ajax"; break; case "j2s": pkg = "net.sf.j2s"; break; default: if (pkg.lastIndexOf(".*") == pkg.length - 2) pkg = pkg.substring(0, pkg.length - 2); break; } if (base) // critical for multiple applets map["@" + pkg] = base; if (isIndex && !isPkgDeclared && !window[pkg + ".registered"]) { //pkgRefCount++; if (pkg == "java") pkg = "core" // JSmol -- moves java/package.js to core/package.js _Loader.loadClass(pkg + ".package", function () { //if (--pkgRefCount == 0) //runtimeLoaded(); //fSuccess && fSuccess(); }, true, true, 1); return; } fSuccess && fSuccess(); }; /** * BH: allows user/developer to load classes even though wrapping and Google * Closure Compiler has not been run on the class. * * * */ Clazz.loadClass = function (name, onLoaded, async) { if (!self.Class) { Class = Clazz; Class.forName = Clazz.forName; // maybe more here } if (!name) return null; if (!async) return Clazz.load(name); _Loader.loadClass(name, function() { var cl = Clazz.allClasses[name]; cl && cl.$load$ && cl.$load$(); onLoaded(cl); }, true, async, 1); return true; } /** * Load the given class ant its related classes. */ /* public */ _Loader.loadClass = _Loader.prototype.loadClass = function (name, onLoaded, forced, async, mode) { mode || (mode = 0); // BH: not implemented (async == null) && (async = false); if (typeof onLoaded == "boolean") return evalType(name); //System.out.println("loadClass " + name) var path = _Loader.getClasspathFor(name); lastLoaded = name; Clazz.ClassFilesLoaded.push(name.replace(/\./g,"/") + ".js"); Clazz.loadScript(path);//(n, n.path, n.requiredBy, false, onLoaded ? function(_loadClass){ isLoadingEntryClass = bSave; onLoaded()}: null); } /* private */ _Loader.loadPackage = function(pkg, fSuccess) { fSuccess || (fSuccess = null); window[pkg + ".registered"] = false; _Loader.loadPackageClasspath(pkg, (_Loader.J2SLibBase || (_Loader.J2SLibBase = (_Loader.getJ2SLibBase() || "j2s/"))), true, fSuccess); }; /** * Register classes to a given *.z.js path, so only a single *.z.js is loaded * for all those classes. */ /* public */ _Loader.jarClasspath = function (jar, clazzes) { if (!(clazzes instanceof Array)) clazzes = [clazzes]; unwrapArray(clazzes); if (J2S._debugCore) jar = jar.replace(/\.z\./, ".") for (var i = clazzes.length; --i >= 0;) { clazzes[i] = clazzes[i].replace(/\//g,".").replace(/\.js$/g,"") classpathMap["#" + clazzes[i]] = jar; } classpathMap["$" + jar] = clazzes; }; _Loader.setClasspathFor = function(clazzes) { // Clazz._Loader.setClasspathFor("edu/colorado/phet/idealgas/model/PressureSensingBox.ChangeListener"); if (!(clazzes instanceof Array)) clazzes = [clazzes]; for (var i = clazzes.length; --i >= 0;) { path = clazzes[i]; var jar = _Loader.getJ2SLibBase() + path.split(".")[0]+".js"; path = path.replace(/\//g,"."); classpathMap["#" + path] = jar; var a = classpathMap["$" + jar] || (classpathMap["$" + jar] = []); a.push(path); } } /** * Usually be used in .../package.js. All given packages will be registered * to the same classpath of given prefix package. */ /* public */ _Loader.registerPackages = function (prefix, pkgs) { //_Loader.checkInteractive (); var base = _Loader.getClasspathFor (prefix + ".*", true); for (var i = 0; i < pkgs.length; i++) { if (window["Clazz"]) { Clazz.newPackage(prefix + "." + pkgs[i]); } _Loader.loadPackageClasspath (prefix + "." + pkgs[i], base); } }; /** * Return the *.js path of the given class. Maybe the class is contained * in a *.z.js jar file. * @param clazz Given class that the path is to be calculated for. May * be java.package, or java.lang.String * @param forRoot Optional argument, if true, the return path will be root * of the given classs' package root path. * @param ext Optional argument, if given, it will replace the default ".js" * extension. */ /* public */ _Loader.getClasspathFor = function (clazz, forRoot, ext) { var path = classpathMap["#" + clazz]; if (!path || forRoot || ext) { var base; var idx; if (path) { clazz = clazz.replace(/\./g, "/"); if ((idx = path.lastIndexOf(clazz)) >= 0 || (idx = clazz.lastIndexOf("/")) >= 0 && (idx = path.lastIndexOf(clazz.substring(0, idx))) >= 0) base = path.substring(0, idx); } else { idx = clazz.length + 2; while ((idx = clazz.lastIndexOf(".", idx - 2)) >= 0) if ((base = classpathMap["@" + clazz.substring(0, idx)])) break; if (!forRoot) clazz = clazz.replace (/\./g, "/"); } if (base == null) { var bins = "binaryFolders"; base = (window["Clazz"] && Clazz[bins] && Clazz[bins].length ? Clazz[bins][0] : _Loader[bins] && _Loader[bins].length ? _Loader[bins][0] : "j2s"); } path = (base.lastIndexOf("/") == base.length - 1 ? base : base + "/") + (forRoot ? "" : clazz.lastIndexOf("/*") == clazz.length - 2 ? clazz.substring(0, idx + 1) : clazz + (!ext ? ".js" : ext.charAt(0) != '.' ? "." + ext : ext)); } return path;//_Loader.multipleSites(path); }; /** * page-customizable callbacks * */ /* public */ _Loader.onScriptLoading = function (file){Clazz._quiet || System.out.println("Classloader.onscriptloading " + file);}; /* public */ _Loader.onScriptLoaded = function (file, isError, data){}; /* public */ _Loader.onScriptInitialized = function (file){}; // not implemented /* public */ _Loader.onScriptCompleted = function (file){}; // not implemented /* public */ _Loader.onClassUnloaded = function (clazz){}; // not implemented /* private */ var isClassExcluded = function (clazz) { return excludeClassMap["@" + clazz]; }; /* Used to keep ignored classes */ /* private */ var excludeClassMap = {}; Clazz._lastEvalError = null; /* private */ var evaluate = function(file, js) { try { eval(js + ";//# sourceURL="+file); } catch (e) { var s = "[Java2Script] The required class file \n\n" + file + (js.indexOf("data: no") ? "\nwas not found.\n" : "\ncould not be loaded. Script error: " + e.message + " \n\ndata:\n\n" + js) + "\n\n" + (e.stack ? e.stack : Clazz._getStackTrace()); Clazz._lastEvalError = s; if (Clazz._isQuiet) return; Clazz.alert(s); throw e; } } Clazz._4Name = function(clazzName, applet, state, asClazz, initialize, isQuiet) { if (clazzName.indexOf("[") == 0) return getArrayClass(clazzName); if (clazzName.indexOf(".") < 0) clazzName = "java.lang." + clazzName; var isok = Clazz._isClassDefined(clazzName); if (isok && asClazz) { var cl1 = Clazz.allClasses[clazzName]; cl1.$clinit$ && cl1.$clinit$(); return cl1; } if (!isok) { var name2 = null; if (clazzName.indexOf("$") >= 0) { // BH we allow Java's java.swing.JTable.$BooleanRenderer as a stand-in for java.swing.JTable.BooleanRenderer // when the static nested class is created using declareType name2 = clazzName.replace(/\$/g,"."); if (Clazz._isClassDefined(name2)) { clazzName = name2; } else { name2 = null; } } if (name2 == null) { var f = (J2S._isAsync && applet ? applet._restoreState(clazzName, state) : null); if (f == 1) return null; // must be already being created if (_Loader.setLoadingMode(f ? _Loader.MODE_SCRIPT : "xhr.sync")) { _Loader.loadClass(clazzName, f, false, true, 1); return null; // this will surely throw an error, but that is OK } //alert ("Using Java reflection: " + clazzName + " for " + applet._id + " \n"+ Clazz._getStackTrace()); _Loader.loadClass(clazzName); } } var cl = evalType(clazzName); if (!cl){ if (isQuiet || Clazz._isQuiet) return null; alert(clazzName + " could not be loaded"); doDebugger(); } Clazz.allClasses[clazzName] = cl; if (initialize !== false) cl.$clinit$ && cl.$clinit$(); return (asClazz ? cl : Clazz.getClass(cl)); }; /** * BH: possibly useful for debugging */ Clazz.currentPath= ""; Clazz.loadScript = function(file) { Clazz.currentPath = file; //loadedScripts[file] = true; // also remove from queue //removeArrayItem(classQueue, file); var file0 = file; if (Clazz._debugging) { file = file.replace(/\.z\.js/,".js"); } var data = ""; try{ _Loader.onScriptLoading(file); data = J2S.getFileData(file); evaluate(file, data); _Loader.onScriptLoaded(file, null, data); }catch(e) { _Loader.onScriptLoaded(file, e, data); var s = ""+e; if (data.indexOf("Error") >= 0) s = data; if (s.indexOf("missing ] after element list")>= 0) s = "File not found"; if (file.indexOf("/j2s/core/") >= 0) { System.out.println(s + " loading " + file); } else { alert(s + " loading file " + file + "\n\n" + e.stack); doDebugger() } } } /** * Used in package /* public */ var runtimeKeyClass = _Loader.runtimeKeyClass = "java.lang.String"; /* private */ var J2sLibBase; /** * Return J2SLib base path from existed SCRIPT src attribute. */ /* public */ _Loader.getJ2SLibBase = function () { var o = window["j2s.lib"]; return (o ? o.base + (o.alias == "." ? "" : (o.alias ? o.alias : (o.version ? o.version : "1.0.0")) + "/") : null); }; /** * Indicate whether _Loader is loading script synchronously or * asynchronously. */ /* private */ var isAsynchronousLoading = true; /* private */ var isUsingXMLHttpRequest = false; /* private */ var loadingTimeLag = -1; _Loader.MODE_SCRIPT = 4; _Loader.MODE_XHR = 2; _Loader.MODE_SYNC = 1; /** * String mode: * asynchronous modes: * async(...).script, async(...).xhr, async(...).xmlhttprequest, * script.async(...), xhr.async(...), xmlhttprequest.async(...), * script * * synchronous modes: * sync(...).xhr, sync(...).xmlhttprequest, * xhr.sync(...), xmlhttprequest.sync(...), * xmlhttprequest, xhr * * Integer mode: * Script 4; XHR 2; SYNC bit 1; */ /* public */ _Loader.setLoadingMode = function (mode, timeLag) { var async = true; var ajax = true; if (typeof mode == "string") { mode = mode.toLowerCase(); if (mode.indexOf("script") >= 0) ajax = false; else async = (mode.indexOf("async") >=0); async = false; // BH } else { if (mode & _Loader.MODE_SCRIPT) ajax = false; else async = !(mode & _Loader.MODE_SYNC); } isUsingXMLHttpRequest = ajax; isAsynchronousLoading = async; loadingTimeLag = (async && timeLag >= 0 ? timeLag: -1); return async; }; /* * Load those key *.z.js. This *.z.js will be surely loaded before other * queued *.js. */ /* public */ _Loader.loadZJar = function (zjarPath, keyClass) { // used only by package.js for core.z.js var f = null; var isArr = (keyClass instanceof Array); if (isArr) keyClass = keyClass[keyClass.length - 1]; // else // f = (keyClass == runtimeKeyClass ? runtimeLoaded : null); _Loader.jarClasspath(zjarPath, isArr ? keyClass : [keyClass]); // BH note: runtimeKeyClass is java.lang.String _Loader.loadClass(keyClass, null, true); }; Clazz.binaryFolders = _Loader.binaryFolders = [ _Loader.getJ2SLibBase() ]; })(Clazz, Clazz._Loader); //} /****************************************************************************** * Copyright (c) 2007 java2script.org and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Zhou Renjian - initial API and implementation *****************************************************************************/ /******* * @author zhou renjian * @create Jan 11, 2007 *******/ Clazz._LoaderProgressMonitor = {}; ;(function(CLPM, J2S) { var fadeOutTimer = null; var fadeAlpha = 0; var monitorEl = null; var lastScrollTop = 0; var bindingParent = null; CLPM.DEFAULT_OPACITY = (J2S && J2S._j2sLoadMonitorOpacity ? J2S._j2sLoadMonitorOpacity : 55); /* public */ CLPM.hideMonitor = function () { monitorEl.style.display = "none"; } /* public */ CLPM.showStatus = function (msg, fading) { if (!monitorEl) { createHandle (); if (!attached) { attached = true; //Clazz.addEvent (window, "unload", cleanup); // window.attachEvent ("onunload", cleanup); } } clearChildren(monitorEl); if (msg == null) { if (fading) { fadeOut(); } else { CLPM.hideMonitor(); } return; } monitorEl.appendChild(document.createTextNode ("" + msg)); if (monitorEl.style.display == "none") { monitorEl.style.display = ""; } setAlpha(CLPM.DEFAULT_OPACITY); var offTop = getFixedOffsetTop(); if (lastScrollTop != offTop) { lastScrollTop = offTop; monitorEl.style.bottom = (lastScrollTop + 4) + "px"; } if (fading) { fadeOut(); } }; /* private static */ var clearChildren = function (el) { if (!el) return; for (var i = el.childNodes.length; --i >= 0;) { var child = el.childNodes[i]; if (!child) continue; if (child.childNodes && child.childNodes.length) clearChildren (child); try { el.removeChild (child); } catch (e) {}; } }; /* private */ var setAlpha = function (alpha) { if (fadeOutTimer && alpha == CLPM.DEFAULT_OPACITY) { window.clearTimeout (fadeOutTimer); fadeOutTimer = null; } fadeAlpha = alpha; //monitorEl.style.filter = "Alpha(Opacity=" + alpha + ")"; monitorEl.style.opacity = alpha / 100.0; }; /* private */ var hidingOnMouseOver = function () { CLPM.hideMonitor(); }; /* private */ var attached = false; /* private */ var cleanup = function () { //if (monitorEl) { // monitorEl.onmouseover = null; //} monitorEl = null; bindingParent = null; //Clazz.removeEvent (window, "unload", cleanup); //window.detachEvent ("onunload", cleanup); attached = false; }; /* private */ var createHandle = function () { var div = document.createElement ("DIV"); div.id = "_Loader-status"; div.style.cssText = "position:absolute;bottom:4px;left:4px;padding:2px 8px;" + "z-index:" + (window["j2s.lib"].monitorZIndex || 10000) + ";background-color:#8e0000;color:yellow;" + "font-family:Arial, sans-serif;font-size:10pt;white-space:nowrap;"; div.onmouseover = hidingOnMouseOver; monitorEl = div; if (bindingParent) { bindingParent.appendChild(div); } else { document.body.appendChild(div); } return div; }; /* private */ var fadeOut = function () { if (monitorEl.style.display == "none") return; if (fadeAlpha == CLPM.DEFAULT_OPACITY) { fadeOutTimer = window.setTimeout(function () { fadeOut(); }, 750); fadeAlpha -= 5; } else if (fadeAlpha - 10 >= 0) { setAlpha(fadeAlpha - 10); fadeOutTimer = window.setTimeout(function () { fadeOut(); }, 40); } else { monitorEl.style.display = "none"; } }; /* private */ var getFixedOffsetTop = function (){ if (bindingParent) { var b = bindingParent; return b.scrollTop; } var dua = navigator.userAgent; var b = document.body; var p = b.parentNode; var pcHeight = p.clientHeight; var bcScrollTop = b.scrollTop + b.offsetTop; var pcScrollTop = p.scrollTop + p.offsetTop; return (dua.indexOf("Opera") < 0 && document.all ? (pcHeight == 0 ? bcScrollTop : pcScrollTop) : dua.indexOf("Gecko") < 0 ? (pcHeight == p.offsetHeight && pcHeight == p.scrollHeight ? bcScrollTop : pcScrollTop) : bcScrollTop); }; /* not used in Jmol if (window["ClazzLoader"]) { _Loader.onScriptLoading = function(file) { CLPM.showStatus("Loading " + file + "..."); }; _Loader.onScriptLoaded = function(file, isError) { CLPM.showStatus(file + (isError ? " loading failed." : " loaded."), true); }; _Loader.onGlobalLoaded = function(file) { CLPM.showStatus("Application loaded.", true); }; _Loader.onClassUnloaded = function(clazz) { CLPM.showStatus("Class " + clazz + " is unloaded.", true); }; } */ })(Clazz._LoaderProgressMonitor, J2S); //} /****************************************************************************** * Copyright (c) 2007 java2script.org and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Zhou Renjian - initial API and implementation *****************************************************************************/ /******* * @author zhou renjian * @create Nov 5, 2005 *******/ Clazz.Console = {}; ;(function(Con) { /** * Setting maxTotalLines to -1 will not limit the console result */ Con.maxTotalLines = 10000; Con.setMaxTotalLines = function (lines) { Con.maxTotalLines = (lines > 0 ? lines : 999999); } Con.maxLatency = 40; Con.setMaxLatency = function (latency) { Con.maxLatency = (latency > 0 ? latency : 40); }; Con.pinning = false; Con.enablePinning = function (enabled) { Con.pinning = enabled; }; Con.linesCount = 0; Con.metLineBreak = false; /* * Give an extension point so external script can create and bind the console * themself. * * TODO: provide more template of binding console window to browser. */ /* protected */ Con.createConsoleWindow = function (parentEl) { var console = document.createElement ("DIV"); console.style.cssText = "font-family:monospace, Arial, sans-serif;"; document.body.appendChild (console); return console; }; var c160 = String.fromCharCode(160); //nbsp; c160 += c160+c160+c160; Con.consoleOutput = function (s, color) { var o = window["j2s.lib"]; var con = (o && o.console); if (!con) { return false; // BH this just means we have turned off all console action } if (con == window.console) { if (color == "red") con.err(s); else con.log(s); return; } if (con && typeof con == "string") con = document.getElementById(con) if (Con.linesCount > Con.maxTotalLines) { for (var i = 0; i < Con.linesCount - Con.maxTotalLines; i++) { if (con && con.childNodes.length > 0) { con.removeChild (con.childNodes[0]); } } Con.linesCount = Con.maxTotalLines; } var willMeetLineBreak = false; s = (typeof s == "undefined" ? "" : s == null ? "null" : "" + s); s = s.replace (/\t/g, c160); if (s.length > 0) switch (s.charAt(s.length - 1)) { case '\n': case '\r': s = (s.length > 1 ? s.substring (0, s.length - (s.charAt(s.length - 2) == '\r' ? 2 : 1)) : ""); willMeetLineBreak = true; break; } var lines = null; s = s.replace (/\t/g, c160); lines = s.split(/\r\n|\r|\n/g); for (var i = 0, last = lines.length - 1; i <= last; i++) { var lastLineEl = null; if (Con.metLineBreak || Con.linesCount == 0 || con.childNodes.length < 1) { lastLineEl = document.createElement ("DIV"); con.appendChild (lastLineEl); lastLineEl.style.whiteSpace = "nowrap"; Con.linesCount++; } else { try { lastLineEl = con.childNodes[con.childNodes.length - 1]; } catch (e) { lastLineEl = document.createElement ("DIV"); con.appendChild (lastLineEl); lastLineEl.style.whiteSpace = "nowrap"; Con.linesCount++; } } var el = document.createElement ("SPAN"); lastLineEl.appendChild (el); el.style.whiteSpace = "nowrap"; if (color) el.style.color = color; var l = lines[i] if (l.length == 0) l = c160; el.appendChild(document.createTextNode(l)); if (!Con.pinning) con.scrollTop += 100; Con.metLineBreak = (i != last || willMeetLineBreak); } var cssClazzName = con.parentNode.className; if (!Con.pinning && cssClazzName && cssClazzName.indexOf ("composite") != -1) { con.parentNode.scrollTop = con.parentNode.scrollHeight; } Con.lastOutputTime = new Date ().getTime (); }; /* * Clear all contents inside the console. */ /* public */ Con.clear = function () { try { Con.metLineBreak = true; var o = window["j2s.lib"]; var console = o && o.console; if (!console || !(console = document.getElementById (console))) return; console.innerHTML = ""; Con.linesCount = 0; } catch(e){}; }; /* public */ Clazz.alert = function (s) { Con.consoleOutput (s + "\r\n"); }; })(Clazz.Console); Clazz._setDeclared("java.lang.System", java.lang.System = System = { props : null, //new java.util.Properties (), $props : {}, arraycopy$O$I$O$I$I : function (src, srcPos, dest, destPos, length) { if (src !== dest || srcPos > destPos) { for (var i = length; --i >= 0;) dest[destPos++] = src[srcPos++]; } else { destPos += length; srcPos += length; for (var i = length; --i >= 0;) src[--destPos] = src[--srcPos]; } }, currentTimeMillis$ : function () { return new Date ().getTime (); }, exit$ : function() { swingjs.JSToolkit && swingjs.JSToolkit.exit$() }, gc$ : function() {}, // bh getProperties$ : function () { return System.props; }, getProperty$S$S : function (key, def) { if (System.props) return System.props.getProperty$S$S (key, def); var v = System.$props[key]; if (typeof v != "undefined") return v; if (key.indexOf(".") > 0) { v = null; switch (key) { case "java.awt.printerjob": v = "swingjs.JSPrinterJob"; break; case "java.class.version": v = "50"; break; case "user.home": v = "https://."; break; case "java.vendor": v = "SwingJS/OpenJDK"; break; case "java.version": v = "1.6-1.8"; break; case "file.separator": case "path.separator": v = "/"; break; case "line.separator": v = (navigator.userAgent.indexOf("Windows") >= 0 ? "\r\n" : "\n"); break; case "os.name": case "os.version": v = navigator.userAgent; break; case "javax.xml.datatype.DatatypeFactory": v = "org.apache.xerces.jaxp.datatype"; break; case "javax.xml.bind.JAXBContextFactory": v = "swingjs.xml.JSJAXBContextFactory"; break; } if (v) return System.$props[key] = v; } return (arguments.length == 1 ? null : def == null ? key : def); // BH }, getSecurityManager$ : function() { return null }, // bh identityHashCode$O : function(obj){return obj==null ? 0 : obj._$hashcode || (obj._$hashcode = ++hashCode)}, lineSeparator$ : function() { return '\n' }, // bh nanoTime$: function() { return Math.round(window.performance.now() * 1e6) }, setProperties$java_util_Properties : function (props) { System.props = props; }, setProperty$S$S : function (key, val) { if (!System.props) return System.$props[key] = val; // BH System.props.setProperty (key, val); } }); ;(function(Con, Sys) { Sys.getProperty$S = Sys.getProperty$S$S; Sys.exit$I = Sys.exit$; Sys.out = new Clazz._O (); Sys.out.__CLASS_NAME__ = "java.io.PrintStream"; Sys.out.print = Sys.out.print$O = Sys.out.print$Z = Sys.out.print$I = Sys.out.println$J = Sys.out.print$S = Sys.out.print$C = Sys.out.print = function (s) { Con.consoleOutput (s); }; Sys.out.printf = Sys.out.printf$S$OA = Sys.out.format = Sys.out.format$S$OA = function (f, args) { Sys.out.print(String.format$S$OA.apply(null, arguments)); } Sys.out.flush$ = function() {} Sys.out.println = Sys.out.println$ = Sys.out.println$O = Sys.out.println$Z = Sys.out.println$I = Sys.out.println$J = Sys.out.println$S = Sys.out.println$C = function(s) { s = (typeof s == "undefined" ? "" : "" + s); if (Clazz._nooutput || Clazz._traceFilter && s.indexOf(Clazz._traceFilter) < 0) return; if (!Clazz._traceFilter && Clazz._traceOutput && s && (s.indexOf(Clazz._traceOutput) >= 0 || '"' + s + '"' == Clazz._traceOutput)) { alert(s + "\n\n" + Clazz._getStackTrace()); doDebugger(); } Con.consoleOutput(typeof s == "undefined" ? "\r\n" : s == null ? s = "null\r\n" : s + "\r\n"); }; Sys.out.println$F = Sys.out.println$D = function(f) {var s = "" + f; Sys.out.println(s.indexOf(".") < 0 && s.indexOf("Inf") < 0 ? s + ".0" : s)}; Sys.out.write$BA$I$I = function (buf, offset, len) { Sys.out.print(String.instantialize(buf).substring(offset, offset+len)); }; Sys.err = new Clazz._O (); Sys.err.__CLASS_NAME__ = "java.io.PrintStream"; Sys.err.print = Sys.err.print$S = function (s) { Con.consoleOutput (s, "red"); }; Sys.err.printf = Sys.err.printf$S$OA = Sys.err.format = Sys.err.format$S$OA = Sys.err.format = function (f, args) { Sys.out.print(String.format$S$OA.apply(null, arguments)); } Sys.err.println = Sys.err.println$O = Sys.err.println$Z = Sys.err.println$I = Sys.err.println$S = Sys.err.println$C = Sys.err.println = function (s) { if (Clazz._traceOutput && s && ("" + s).indexOf(Clazz._traceOutput) >= 0) { alert(s + "\n\n" + Clazz._getStackTrace()); doDebugger(); } Con.consoleOutput (typeof s == "undefined" ? "\r\n" : s == null ? s = "null\r\n" : s + "\r\n", "red"); }; Sys.err.println$F = Sys.err.println$D = function(f) {var s = "" + f; Sys.err.println(s.indexOf(".") < 0 && s.indexOf("Inf") < 0 ? s + ".0" : s)}; Sys.err.write$BA$I$I = function (buf, offset, len) { Sys.err.print(String.instantialize(buf).substring(offset, offset+len)); }; Sys.err.flush$ = function() {} })(Clazz.Console, System); Clazz._Loader.registerPackages("java", [ "io", "lang", "lang.reflect", "util" ]); if (!window["java.registered"]) window["java.registered"] = false; (function (ClazzLoader) { if (window["java.packaged"]) return; window["java.packaged"] = true; }) (Clazz._Loader); window["java.registered"] = true; ///////////////// special definitions of standard Java class methods /////////// var C$, m$ = Clazz.newMeth; Clazz._setDeclared("java.lang.Math", java.lang.Math = Math); Math.rint || (Math.rint = function(a) { var b; return Math.round(a) + ((b = a % 1) != 0.5 && b != -0.5 ? 0 : (b = Math.round(a % 2)) > 0 ? b - 2 : b); }); Math.log10||(Math.log10=function(a){return Math.log(a)/Math.E}); Math.hypot||(Math.hypot=function(x,y){return Math.sqrt(Math.pow(x,2)+Math.pow(y,2))}); Math.toDegrees||(Math.toDegrees=function(angrad){return angrad*180.0/Math.PI;}); Math.toRadians||(Math.toRadians=function(angdeg){return angdeg/180.0*Math.PI}); Math.copySign||(Math.copySign=function(mag,sign){return((sign>0?1:-1)*Math.abs(mag))}); //could use Math.sign(), but this was used to preserve cross-brower compatability (not in Internet Explorer) Math.signum||(Math.signum=function(d){return(d==0.0||isNaN(d))?d:d < 0 ? -1 : 1}); Math.scalb||(Math.scalb=function(d,scaleFactor){return d*Math.pow(2,scaleFactor)}); //var a64 = null, a32 = null, i32 = null, i64 = null; Math.nextAfter|| (Math.nextAfter=function(start,direction){ if (isNaN(start) || isNaN(direction)) return NaN; if (direction == start) return start; if (start == Double.MAX_VALUE && direction == Double.POSITIVE_INFINITY) return Double.POSITIVE_INFINITY; if (start == -Double.MAX_VALUE && direction == Double.NEGATIVE_INFINITY) return Double.NEGATIVE_INFINITY; if (start == Double.POSITIVE_INFINITY && direction == Double.NEGATIVE_INFINITY) return Double.MAX_VALUE; if (start == Double.NEGATIVE_INFINITY && direction == Double.POSITIVE_INFINITY) return -Double.MAX_VALUE; if (start == 0) return (direction > 0 ? Double.MIN_VALUE : -Double.MIN_VALUE); if (!a64) { a64 = new Float64Array(1); i64 = new Uint32Array(a64.buffer); } a64[0] = start; var i0 = i64[0]; var i1 = i64[1]; var carry; if ((direction > start) == (start >= 0)) { i64[0]++; carry = (i64[0] == 0 ? 1 : 0); } else { i64[0]--; carry = (i64[0] == 4294967295 ? -1 : 0); } if (carry) i64[1]+=carry; return a64[0]; }); Math.nextAfter$D$D = Math.nextAfter; Math.nextAfter$F$D =function(start,direction){ if (isNaN(start) || isNaN(direction)) return NaN; if (direction == start) return start; if (start == Float.MAX_VALUE && direction == Float.POSITIVE_INFINITY) return Float.POSITIVE_INFINITY; if (start == -Float.MAX_VALUE && direction == Float.NEGATIVE_INFINITY) return Float.NEGATIVE_INFINITY; if (start == Float.POSITIVE_INFINITY && direction == Float.NEGATIVE_INFINITY) return Float.MAX_VALUE; if (start == Float.NEGATIVE_INFINITY && direction == Float.POSITIVE_INFINITY) return -Float.MAX_VALUE; if (start == 0 && direction < 0) return -Float.MIN_VALUE; if (start == 0) return (direction > 0 ? Float.MIN_VALUE : -Float.MIN_VALUE); if (!i32) { a32 = new Float32Array(1); i32 = new Int32Array(a32.buffer); } a32[0] = start; i32[0] += ((direction > start) == (start >= 0) ? 1 : -1); return a32[0]; }; Math.nextUp||(Math.nextUp=function(d){ return Math.nextAfter(d, Double.POSITIVE_INFINITY); }); Math.nextUP$D=Math.nextUp; Math.nextUp$F = function(f){ return Math.nextAfter$F$D(f, Double.NEGATIVE_INFINITY); }; Math.nextDown||(Math.nextDown=function(d){ return Math.nextAfter(d, Double.NEGATIVE_INFINITY); }); Math.nextDown$D=Math.nextDown; Math.nextDown$F = function(f){ return Math.nextAfter$F$D(f, Double.NEGATIVE_INFINITY); }; Math.ulp||(Math.ulp=function(d){ if (isNaN(d)) { return Double.NaN; } if (isInfinite(d)) { return Double.POSITIVE_INFINITY; } if (d == Double.MAX_VALUE || d == -Double.MAX_VALUE) { return Math.pow(2, 971); } return Math.nextUp(Math.abs(d)); }); Math.ulp$D = Math.ulp; Math.ulp$F = function(f){ if (isNaN(f)) { return Float.NaN; } if (isInfinite(f)) { return Float.POSITIVE_INFINITY; } if (f == Float.MAX_VALUE || f == -Float.MAX_VALUE) { return Math.pow(2, 104); } return Math.nextUp$F(Math.abs(f)); }; Math.getExponent = Math.getExponent$D = function(d) { if (!a64) { a64 = new Float64Array(1); i64 = new Uint32Array(a64.buffer); } a64[0] = d; return ((i64[1] & 0x7ff00000) >> 20) - 1023; }; Math.getExponent$F=function(f){ return ((Float.floatToRawIntBits$F(f) & 0x7f800000) >> 23) - 127; } Math.IEEEremainder||(Math.IEEEremainder=function (x, y) { if (Double.isNaN$D(x) || Double.isNaN$D(y) || Double.isInfinite$D(x) || y == 0) return NaN; if (!Double.isInfinite$D(x) && Double.isInfinite$D(y)) return x; var modxy = x % y; if (modxy == 0) return modxy; var rem = modxy - Math.abs(y) * Math.signum(x); if (Math.abs(rem) == Math.abs(modxy)) { var div = x / y; return (Math.abs(Math.round(div)) > Math.abs(div) ? rem : modxy); } return (Math.abs(rem) < Math.abs(modxy) ? rem : modxy); }); Clazz._setDeclared("java.lang.Number", java.lang.Number=Number); Number.prototype._numberToString=Number.prototype.toString; extendObject(Array, EXT_NO_HASHCODE); extendObject(Number, EXT_NO_HASHCODE); Number.__CLASS_NAME__="Number"; addInterface(Number,java.io.Serializable); //extendPrototype(Number, true, false); Number.prototype.compareTo$ = Number.prototype.compareTo$Number = Number.prototype.compareTo$TT = function(x) { var a = this.valueOf(), b = x.valueOf(); return (a < b ? -1 : a == b ? 0 : 1) }; var $b$ = new Int8Array(1); var $s$ = new Int16Array(1); var $i$ = new Int32Array(1); // short forms, for the actual numbers in JavaScript m$(Number,["byteValue"],function(){return ($b$[0] = this, $b$[0]);}); m$(Number,["shortValue"],function(){return ($s$[0] = this, $s$[0]);}); m$(Number,["intValue"],function(){return ($i$[0] = this, $i$[0]);}); m$(Number,["longValue"],function(){return (this|0);}); // Object values m$(Number,["byteValue$"],function(){return this.valueOf().byteValue();}); m$(Number,["shortValue$"],function(){return this.valueOf().shortValue();}); m$(Number,["intValue$"],function(){return this.valueOf().intValue();}); m$(Number,["longValue$"],function(){return this.valueOf().longValue();}); m$(Number,["floatValue$", "doubleValue$", "hashCode$"],function(){return this.valueOf();}); Clazz._setDeclared("java.lang.Integer", java.lang.Integer=Integer=function(){ if (typeof arguments[0] != "object")this.c$(arguments[0]); }); var primTypes = {}; var setJ2STypeclass = function(cl, type, paramCode) { // TODO -- should be a proper Java.lang.Class primTypes[paramCode] = cl; cl.TYPE = { isPrimitive: function() { return true }, type:type, __PARAMCODE:paramCode, __PRIMITIVE:1 // referenced in java.lang.Class }; cl.TYPE.toString = cl.TYPE.getName$ = cl.TYPE.getTypeName$ = cl.TYPE.getCanonicalName$ = cl.TYPE.getSimpleName$ = function() {return type} } var decorateAsNumber = function (clazz, qClazzName, type, PARAMCODE) { clazz.prototype.valueOf=function(){return 0;}; clazz.prototype.__VAL0__ = 1; finalizeClazz(clazz, qClazzName, null, 0, true); extendPrototype(clazz, true, true); setSuperclass(clazz, Number); addInterface(clazz, Comparable); setJ2STypeclass(clazz, type, PARAMCODE); return clazz; }; decorateAsNumber(Integer, "Integer", "int", "I"); Integer.toString=Integer.toString$I=Integer.toString$I$I=Integer.prototype.toString=function(i,radix){ switch(arguments.length) { case 2: return i.toString(radix); case 1: return "" +i; case 0: return (this===Integer ? "class java.lang.Integer" : ""+this.valueOf()); } }; m$(Integer, ["c$", "c$$S", "c$$I"], function(v){ v == null && (v = 0); if (typeof v != "number") v = Integer.parseIntRadix$S$I(v, 10); v = v.intValue(); this.valueOf=function(){return v;}; }, 1); Integer.MIN_VALUE=Integer.prototype.MIN_VALUE=-0x80000000; Integer.MAX_VALUE=Integer.prototype.MAX_VALUE=0x7fffffff; //Integer.TYPE=Integer.prototype.TYPE=Integer; m$(Integer,"highestOneBit$I", function(i) { i |= (i >> 1); i |= (i >> 2); i |= (i >> 4); i |= (i >> 8); i |= (i >> 16); return i - (i >>> 1); }, 1); m$(Integer,"lowestOneBit$I", function(i) { return i & -i;}, 1); m$(Integer,"rotateLeft$I$I", function(i, distance) { return (i << distance) | (i >>> -distance); }, 1); m$(Integer,"rotateRight$I$I", function(i, distance) { return (i >>> distance) | (i << -distance); }, 1); m$(Integer,"reverse$I", function(i) { i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555; i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333; i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f; i = (i << 24) | ((i & 0xff00) << 8) | ((i >>> 8) & 0xff00) | (i >>> 24); return i;}, 1); Integer.reverseBytes = m$(Integer,"reverseBytes$I", function(i) { return ((i >>> 24) ) | ((i >> 8) & 0xFF00) | ((i << 8) & 0xFF0000) | ((i << 24)); }, 1); m$(Integer,"signum$I", function(i){ return i < 0 ? -1 : i > 0 ? 1 : 0; }, 1); m$(Integer,"bitCount$I", function(i) { i = i - ((i >>> 1) & 0x55555555); i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); i = (i + (i >>> 4)) & 0x0f0f0f0f; i = i + (i >>> 8); i = i + (i >>> 16); return i & 0x3f; }, 1); m$(Integer,"numberOfLeadingZeros$I", function(i) { if (i == 0) return 32; var n = 1; if (i >>> 16 == 0) { n += 16; i <<= 16; } if (i >>> 24 == 0) { n += 8; i <<= 8; } if (i >>> 28 == 0) { n += 4; i <<= 4; } if (i >>> 30 == 0) { n += 2; i <<= 2; } n -= i >>> 31; return n; }, 1); m$(Integer,"numberOfTrailingZeros$I", function(i) { if (i == 0) return 32; var n = 31; var y = i <<16; if (y != 0) { n = n -16; i = y; } y = i << 8; if (y != 0) { n = n - 8; i = y; } y = i << 4; if (y != 0) { n = n - 4; i = y; } y = i << 2; if (y != 0) { n = n - 2; i = y; } return n - ((i << 1) >>> 31); }, 1); var radixChar = "0123456789abcdefghijklmnopqrstuvwxyz"; m$(Integer,"parseIntRadix$S$I", function(s,radix){ var v = parseInt(s, radix); if (isNaN(v)){ throw Clazz.new_(NumberFormatException.c$$S, ["parsing " + s + " radix " + radix]); } return v; }, 1); m$(Integer,["parseInt$S","parseInt$S$I"], function(s,radix){ return Integer.parseIntRadix$S$I(s, radix || 10); }, 1); m$(Integer,["valueOf$S","valueOf$I"], function(s, radix){ return Clazz.new_(Integer.c$, [s]); }, 1); m$(Integer,["valueOf$S$I"], function(s, radix){ return Integer.parseIntRadix$S$I(s, radix || 10); }, 1); m$(Integer,"equals$O", function(s){ return (s instanceof Integer) && s.valueOf()==this.valueOf(); }); Integer.toHexString$I=function(d){ if (d < 0) { var b = d & 0xFFFFFF; var c = ((d>>24)&0xFF); return c._numberToString(16) + (b = "000000" + b._numberToString(16)).substring(b.length - 6); } return d._numberToString(16); }; Integer.toOctalString$I=function(d){return d._numberToString(8);}; Integer.toBinaryString$I=function(d){return d._numberToString(2);}; m$(Integer,"decodeRaw$S", function(n){ if (n.indexOf(".") >= 0)n = ""; var i = (n.startsWith("-") ? 1 : 0); n = n.replace(/\#/, "0x").toLowerCase(); var radix=(n.startsWith("0x", i) ? 16 : n.startsWith("0", i) ? 8 : 10); // The general problem with parseInt is that is not strict -- ParseInt("10whatever") == 10. // Number is strict, but Number("055") does not work, though ParseInt("055", 8) does. // need to make sure negative numbers are negative if (n == "") return NaN n = Number(n) & 0xFFFFFFFF; return (radix == 8 ? parseInt(n, 8) : n); }, 1); m$(Integer,"decode$S", function(n){ if (isNaN(n = Integer.decodeRaw$S(n)) || n < Integer.MIN_VALUE|| n > Integer.MAX_VALUE) throw Clazz.new_(NumberFormatException.c$$S,["Invalid Integer"]); return Clazz.new_(Integer.c$, [n]); }, 1); m$(Integer,"hashCode$", function(){ return this.valueOf(); }); // Note that Long is problematic in JavaScript Clazz._setDeclared("java.lang.Long", java.lang.Long=Long=function(){ if (typeof arguments[0] != "object")this.c$(arguments[0]); }); decorateAsNumber(Long, "Long", "long", "L"); Long.toString=Long.toString$J=Long.toString$J$I = Long.prototype.toString=function(i, radix){ switch(arguments.length) { case 2: return i.toString(radix); case 1: return "" +i; case 0: return (this===Long ? "class java.lang.Long" : ""+this.valueOf()); } }; m$(Long, ["c$", "c$$S", "c$$J"], function(v){ v == null && (v = 0); v = (typeof v == "number" ? Math.round(v) : Integer.parseIntRadix$S$I(v, 10)); this.valueOf=function(){return v;}; }, 1); //Long.MIN_VALUE=Long.prototype.MIN_VALUE=-0x8000000000000000; //Long.MAX_VALUE=Long.prototype.MAX_VALUE=0x7fffffffffffffff; //Long.TYPE=Long.prototype.TYPE=Long; m$(Long,["parseLong$S", "parseLong$S$I"], function(s,radix){ return Integer.parseIntRadix$S$I(s, radix || 10); }, 1); m$(Long,["valueOf$S","valueOf$J","valueOf$S$I"], function(s, radix){ return Clazz.new_(Long.c$, [s, radix||10]); }, 1); m$(Long,"equals$O", function(s){ return (s instanceof Long) && s.valueOf()==this.valueOf(); }, 1); Long.toHexString$J=function(i){ return i.toString(16); }; Long.toOctalString$J=function(i){ return i.toString(8); }; Long.toBinaryString$J=function(i){ return i.toString(2); }; m$(Long,"decode$S", function(n){ if (isNaN(n = Integer.decodeRaw$S(n))) throw Clazz.new_(NumberFormatException.c$$S, ["Invalid Long"]); return Clazz.new_(Long.c$, [n]); }, 1); Long.sum$J$J = Integer.sum$I$I; m$(Long,"signum$J", function(i){ return i < 0 ? -1 : i > 0 ? 1 : 0; }, 1); Clazz._setDeclared("java.lang.Short", java.lang.Short = Short = function(){ if (typeof arguments[0] != "object")this.c$(arguments[0]); }); decorateAsNumber(Short, "Short", "short", "H"); m$(Short, ["c$", "c$$S", "c$$H"], function (v,radix) { v == null && (v = 0); if (typeof v != "number") v = Integer.parseIntRadix$S$I(v, radix||10); v = v.shortValue(); this.valueOf = function () {return v;}; }, 1); Short.toString = Short.toString$H = Short.toString$H$I = Short.prototype.toString = function (i,radix) { switch(arguments.length) { case 2: return i.toString(radix); case 1: return "" +i; case 0: return (this===Short ? "class java.lang.Short" : ""+this.valueOf()); } }; Short.MIN_VALUE = Short.prototype.MIN_VALUE = -32768; Short.MAX_VALUE = Short.prototype.MAX_VALUE = 32767; //Short.TYPE = Short.prototype.TYPE = Short; m$(Short, "parseShortRadix$S$I",function (s, radix) { return Integer.parseIntRadix$S$I(s, radix).shortValue(); }, 1); m$(Short, "parseShort$S",function (s) { return Short.parseShortRadix$S$I(s, 10); }, 1); m$(Short, ["valueOf$S","valueOf$H","valueOf$S$I"], function (s,radix) { return Clazz.new_(Short.c$, [s,radix||10]); }, 1); m$(Short, "equals$O", function (s) { return (s instanceof Short) && s.valueOf() == this.valueOf(); }); Short.toHexString$H = function (i) { return i.toString(16); }; Short.toOctalString$H = function (i) { return i.toString(8); }; Short.toBinaryString$H = function (i) { return i.toString (2); }; m$(Short, "decode$S", function(n){ if (isNaN(n = Integer.decodeRaw$S(n)) || n < -32768|| n > 32767) throw Clazz.new_(NumberFormatException.c$$S, ["Invalid Short"]); return Clazz.new_(Short.c$, [n]); }, 1); Clazz._setDeclared("java.lang.Byte", java.lang.Byte=Byte=function(){ if (typeof arguments[0] != "object")this.c$(arguments[0]); }); decorateAsNumber(Byte,"Byte", "byte", "B"); m$(Byte, ["c$", "c$$S", "c$$B"], function(v,radix){ if (typeof v != "number") v = Integer.parseIntRadix$S$I(v, radix||10); v = v.byteValue(); this.valueOf=function(){return v;}; this.byteValue = function(){return v}; }, 1); Byte.toString=Byte.toString$B=Byte.toString$B$I=Byte.prototype.toString=function(i,radix){ switch(arguments.length) { case 2: return i.toString(radix); case 1: return "" +i; case 0: return (this===Byte ? "class java.lang.Byte" : ""+this.valueOf()); } }; Byte.serialVersionUID=Byte.prototype.serialVersionUID=-7183698231559129828; Byte.MIN_VALUE=Byte.prototype.MIN_VALUE=-128; Byte.MAX_VALUE=Byte.prototype.MAX_VALUE=127; Byte.SIZE=Byte.prototype.SIZE=8; //Byte.TYPE=Byte.prototype.TYPE=Byte; m$(Byte,"parseByteRadix$S$I", function(s,radix){ return Integer.parseIntRadix$S$I(s, radix).byteValue$(); }, 1); m$(Byte,"parseByte$S", function(s){ return Byte.parseByteRadix$S$I(s,10); }, 1); m$(Byte, ["valueOf$S","valueOf$B","valueOf$S$I"], function (s,radix) { return Clazz.new_(Byte.c$, [s, radix||10]); }, 1); m$(Byte,"equals$O", function(s){ return (s instanceof Byte) && s.valueOf()==this.valueOf(); }); Byte.toHexString$B=function(i){return i.toString(16);}; Byte.toOctalString$B=function(i){return i.toString(8);}; Byte.toBinaryString$B=function(i){return i.toString(2);}; m$(Byte,"decode$S", function(n){ if (isNaN(n = Integer.decodeRaw$S(n)) || n < -128|| n > 127) throw Clazz.new_(NumberFormatException.c$$S, ["Invalid Byte"]); return Clazz.new_(Byte.c$, [n]); }, 1); Clazz._floatToString = function(f) { var check57 = (Math.abs(f) >= 1e-6 && Math.abs(f) < 1e-3); if (check57) f/=1e7; var s = (""+f).replace('e','E'); if (s.indexOf(".") < 0 && s.indexOf("Inf") < 0 && s.indexOf("NaN") < 0) { if(s.indexOf('E') < 0) s += ".0"; else { s = s.replace('E', '.0E'); } } if (check57) { s = s.substring(0, s.length - 2) + (parseInt(s.substring(s.length - 2)) - 7); s = s.replace(".0000000000000001",".0"); } return s; } Clazz._setDeclared("java.lang.Float", java.lang.Float=Float=function(){ if (typeof arguments[0] != "object")this.c$(arguments[0]); }); decorateAsNumber(Float,"Float", "float", "F"); m$(Float, ["c$", "c$$S", "c$$F", "c$$D"], function(v){ v == null && (v = 0); if (typeof v != "number") v = Number(v); this.valueOf=function(){return v;} }, 1); Float.toString=Float.toString$F=Float.prototype.toString=function(){ if(arguments.length!=0){ return Clazz._floatToString(arguments[0]); }else if(this===Float){ return"class java.lang.Float"; } return Clazz._floatToString(this.valueOf()); }; var a32, i32; Float.floatToIntBits$F = function(f) { if (isNaN(f)) return return Float.floatToRawIntBits$F(f); } Float.floatToRawIntBits$F = function(f) { i32 || (a32 = new Float32Array(1), i32 = new Int32Array(a32.buffer)); a32[0] = f; return i32[0]; } Float.intBitsToFloat$I = function(i) { i32 || (a32 = new Float32Array(1), i32 = new Int32Array(a32.buffer)); i32[0] = i; return a32[0]; } Float.serialVersionUID=Float.prototype.serialVersionUID=-2671257302660747028; Float.MIN_VALUE=Float.prototype.MIN_VALUE=1.4e-45; Float.MAX_VALUE=Float.prototype.MAX_VALUE=3.4028235e+38; Float.NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY; Float.POSITIVE_INFINITY=Number.POSITIVE_INFINITY; Float.NaN=Number.NaN; //Float.TYPE=Float.prototype.TYPE=Float; m$(Float,"parseFloat$S", function(s){ if(s==null){ throw Clazz.new_(NumberFormatException.c$$S, ["null"]); } if (typeof s == "number")return s; // important -- typeof NaN is "number" and is OK here var floatVal=Number(s); if(isNaN(floatVal)){ throw Clazz.new_(NumberFormatException.c$$S, ["Not a Number : "+s]); } return floatVal; }, 1); m$(Float,["valueOf$S","valueOf$F"], function(s){ return Clazz.new_(Float.c$, [s]); }, 1); Float.isNaN$F = m$(Float,"isNaN$", function(num){ return isNaN(arguments.length == 1 ? num : this.valueOf()); }); Float.isInfinite$F = m$(Float,"isInfinite$", function(num){ return !Number.isFinite(arguments.length == 1 ? num : this.valueOf()); }); m$(Float,"equals$O", function(s){ return (s instanceof Float) && s.valueOf()==this.valueOf(); }); Clazz._setDeclared("java.lang.Double", java.lang.Double=Double=function(){ if (typeof arguments[0] != "object")this.c$(arguments[0]); }); decorateAsNumber(Double,"Double", "double", "D"); Double.toString=Double.toString$D=Double.prototype.toString=function(){ if(arguments.length!=0){ return Clazz._floatToString(arguments[0]); }else if(this===Double){ return"class java.lang.Double"; } return Clazz._floatToString(this.valueOf()); }; m$(Double, ["c$", "c$$S", "c$$D"], function(v){ v == null && (v = 0); if (typeof v != "number") v = Double.parseDouble$S(v); this.valueOf=function(){return v;}; }, 1); Double.serialVersionUID=Double.prototype.serialVersionUID=-9172774392245257468; Double.MIN_VALUE=Double.prototype.MIN_VALUE=4.9e-324; Double.MAX_VALUE=Double.prototype.MAX_VALUE=1.7976931348623157e+308; Double.NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY; Double.POSITIVE_INFINITY=Number.POSITIVE_INFINITY; Double.NaN=Number.NaN; //Double.TYPE=Double.prototype.TYPE=Double; Double.isNaN$D = m$(Double,"isNaN$", function(num){ return isNaN(arguments.length == 1 ? num : this.valueOf()); }); Float.prototype.hashCode$ = Double.prototype.hashCode$ = function() {("" + this.valueOf()).hashCode$()} Double.isInfinite$D = m$(Double,"isInfinite$", function(num){ return!Number.isFinite(arguments.length == 1 ? num : this.valueOf()); }); m$(Double,"parseDouble$S", function(s){ if(s==null){ throw Clazz.new_(NumberFormatException.c$$S, ["null"]); } if (typeof s == "number")return s; // important -- typeof NaN is "number" and is OK here var doubleVal=Number(s); if(isNaN(doubleVal)){ throw Clazz.new_(NumberFormatException.c$$S, ["Not a Number : "+s]); } return doubleVal; }, 1); m$(Double,["valueOf$S","valueOf$D"], function(v){ return Clazz.new_(Double.c$, [v]); }, 1); Double.prototype.equals = m$(Double,"equals$O", function(s){ return (s instanceof Double) && s.valueOf()==this.valueOf(); }); Clazz._setDeclared("java.lang.Boolean", Boolean = java.lang.Boolean = Boolean || function(){ if (typeof arguments[0] != "object")this.c$(arguments[0]); }); extendObject(Boolean); Boolean.__CLASS_NAME__="Boolean"; addInterface(Boolean,[java.io.Serializable,java.lang.Comparable]); setJ2STypeclass(Boolean, "boolean", "Z"); //extendPrototype(Boolean, true, false); Boolean.serialVersionUID=Boolean.prototype.serialVersionUID=-3665804199014368530; m$(Boolean, ["c$", "c$$S", "c$$Z"], function(s){ var b = ((typeof s == "string" ? Boolean.toBoolean(s) : s) ? true : false); this.valueOf=function(){return b;}; }, 1); m$(Boolean,["booleanValue","booleanValue$"], function(){ return this.valueOf(); }); m$(Boolean,"compare$Z$Z", function(a,b){return(a == b ? 0 : a ? 1 : -1);}, 1); m$(Boolean,["compareTo$Boolean","compareTo$TT"], function(b){ return(b.valueOf() == this.valueOf() ? 0 : this.valueOf() ? 1 : -1); }); Boolean.prototype.equals = m$(Boolean,"equals$O", function(obj){ return obj instanceof Boolean && this.booleanValue()==obj.booleanValue(); }); m$(Boolean,"getBoolean$S", function(name){ var result=false; try{ result=Boolean.toBoolean(System.getProperty$S(name)); }catch(e){ if(Clazz.instanceOf(e,IllegalArgumentException)){ }else if(Clazz.instanceOf(e,NullPointerException)){ }else{ throw e; } } return result; }, 1); m$(Boolean,"hashCode$", function(){ return this.valueOf()?1231:1237;}); m$(Boolean,"hashCode$Z", function(b){ return b?1231:1237;}, 1); m$(Boolean,"logicalAnd$Z$Z", function(a,b){return(a && b);}, 1); m$(Boolean,"logicalOr$Z$Z", function(a,b){return(a || b);}, 1); m$(Boolean,"logicalXor$Z$Z", function(a,b){return !!(a ^ b);}, 1); m$(Boolean,"parseBoolean$S", function(s){return Boolean.toBoolean(s);}, 1); m$(Boolean,"toString",function(){return this.valueOf()?"true":"false";}); m$(Boolean,"toString$Z",function(b){return "" + b;}, 1); m$(Boolean,"valueOf$S",function(s){ return("true".equalsIgnoreCase$S(s)?Boolean.TRUE:Boolean.FALSE);}, 1); m$(Boolean,"valueOf$Z",function(b){ return(b?Boolean.TRUE:Boolean.FALSE);}, 1); //the need is to have new Boolean(string), but that won't work with native Boolean //so instead we have to do a lexical switch from "new Boolean" to "Boolean.from" //note no $ here m$(Boolean,"toBoolean", function(name){ return(typeof name == "string" ? name.equalsIgnoreCase$S("true") : !!name); }, 1); m$(Boolean,"from", function(name){ return Boolean.toBoolean(name) ? Boolean.TRUE : Boolean.FALSE; }, 1); Boolean.TRUE=Boolean.prototype.TRUE=Clazz.new_(Boolean.c$, [true]); Boolean.FALSE=Boolean.prototype.FALSE=Clazz.new_(Boolean.c$, [false]); Clazz._Encoding={ UTF8:"utf-8", UTF16:"utf-16", ASCII:"ascii" }; (function(Encoding) { Encoding.guessEncoding=function(str){ return (str.charCodeAt(0)==0xEF&&str.charCodeAt(1)==0xBB&&str.charCodeAt(2)==0xBF ? Encoding.UTF8 : str.charCodeAt(0)==0xFF&&str.charCodeAt(1)==0xFE ? Encoding.UTF16 : Encoding.ASCII); }; Encoding.guessEncodingArray=function(a, offset){ return (a[offset]==0xEF&&a[offset + 1]==0xBB&&a[offset + 2]==0xBF ? Encoding.UTF8 : a[offset + 0]==0xFF&&a[offset + 1]==0xFE ? Encoding.UTF16 : Encoding.ASCII); }; Encoding.readUTF8Array=function(a, offset, length){ if (arguments.length == 1) { offset = 0; length = a.length; } var encoding=Encoding.guessEncodingArray(a); var startIdx=0; if(encoding==Encoding.UTF8){ startIdx=3; }else if(encoding==Encoding.UTF16){ startIdx=2; } var arrs=new Array(); for(var i=offset + startIdx, endIdx = offset + length; i < endIdx; i++){ var charCode=a[i]; if(charCode<0x80){ arrs[arrs.length]=String.fromCharCode(charCode); }else if(charCode>0xc0&&charCode<0xe0){ var c1=charCode&0x1f; var c2=a[++i]&0x3f; var c=(c1<<6)+c2; arrs[arrs.length]=String.fromCharCode(c); }else if(charCode>=0xe0){ var c1=charCode&0x0f; var c2=a[++i]&0x3f; var c3=a[++i]&0x3f; var c=(c1<<12)+(c2<<6)+c3; arrs[arrs.length]=String.fromCharCode(c); } } return arrs.join(''); }; Encoding.convert2UTF8=function(str){ var encoding=this.guessEncoding(str); var startIdx=0; if(encoding==Encoding.UTF8){ return str; }else if(encoding==Encoding.UTF16){ startIdx=2; } var offset=0; var arrs=new Array(offset+str.length-startIdx); for(var i=startIdx;i>6); var c2=0x80+(charCode&0x003f); arrs[offset+i-startIdx]=String.fromCharCode(c1)+String.fromCharCode(c2); }else{ var c1=0xe0+((charCode&0xf000)>>12); var c2=0x80+((charCode&0x0fc0)>>6); var c3=0x80+(charCode&0x003f); arrs[offset+i-startIdx]=String.fromCharCode(c1)+String.fromCharCode(c2)+String.fromCharCode(c3); } } return arrs.join(''); }; if(!String.__PARAMCODE){ String.__PARAMCODE = "S"; Clazz._setDeclared("java.lang.String", java.lang.String=String); extendObject(String, EXT_NO_TOSTRING); addInterface(String,[java.io.Serializable,CharSequence,Comparable]); String.serialVersionUID=String.prototype.serialVersionUID=-6849794470754667710; var formatterClass; String.format$S$OA = function(format, args) { if (!formatterClass) formatterClass = Clazz._4Name("java.util.Formatter", null, null, true); var f = new formatterClass(); return f.format$S$OA.apply(f,arguments).toString(); }; String.CASE_INSENSITIVE_ORDER = { compare$: function(s1, s2){ if(s1==null || s2 == null) throw new NullPointerException(); if(s1==s2) return 0; var s1=s1.toUpperCase(); var s2=s2.toUpperCase(); if(s1==s2) return 0; var s1=s1.toLowerCase(); var s2=s2.toLowerCase(); return (s1==s2 ? 0 : s1 > s2 ? 1 : -1); } } String.CASE_INSENSITIVE_ORDER.compare$S$S = String.CASE_INSENSITIVE_ORDER.compare$; CharSequence.$defaults$(String); ;(function(sp) { sp.compareToIgnoreCase$S = function(str) { return String.CASE_INSENSITIVE_ORDER.compare$S$S(this, str);} sp.generateExpFunction$S=function(str){ var arr=[]; var orders=[]; var idx=0; arr[0]=""; var i=0; for(;i= 0) c1 = "\\" + c1; } else { c1=c1.replace(/([\\\$\.\*\+\|\?\^\{\}\(\)\[\]])/g,function($0,$1){ return "\\"+$1; }); } return this.replace(new RegExp(c1,"gm"),c2); }; sp.replaceAll$S$S=sp.replaceAll$CharSequence$CharSequence=function(exp,str){ var regExp=new RegExp(exp,"gm"); return this.replace(regExp,str); }; sp.replaceFirst$S$S=function(exp,str){ var regExp=new RegExp(exp,"m"); return this.replace(regExp,str); }; sp.matches$S=function(exp){ if(exp!=null){ exp="^("+exp+")$"; } var regExp=new RegExp(exp,"gm"); var m=this.match(regExp); return m!=null&&m.length!=0; }; sp.regionMatches$I$S$I$I=function(toffset,other,ooffset,len){ return this.regionMatches$Z$I$S$I$I(false,toffset,other,ooffset,len); } sp.regionMatches$Z$I$S$I$I=function(ignoreCase,toffset,other,ooffset,len){ var to=toffset; var po=ooffset; if((ooffset<0)||(toffset<0)||(toffset>this.length-len)|| (ooffset>other.length-len)){ return false; } var s1=this.substring(toffset,toffset+len); var s2=other.substring(ooffset,ooffset+len); if(ignoreCase){ s1=s1.toLowerCase(); s2=s2.toLowerCase(); } return s1==s2; }; sp.split$S=sp.split$S$I=function(regex,limit){ var arr; if (!limit && regex == " ") { arr = this.split(" "); } else if(limit && limit > 0){ if(limit == 1){ arr = [this]; } else { var regExp=new RegExp("("+regex+")","gm"); var count=1; var s=this.replace(regExp,function($0,$1){ count++; if(count==limit){ return"@@_@@"; } else if(count>limit){ return $0; }else{ return $0; } }); regExp=new RegExp(regex,"gm"); arr=this.split(regExp); if(arr.length>limit){ arr[limit-1]=s.substring(s.indexOf("@@_@@")+5); arr.length=limit; } } }else{ var regExp=new RegExp(regex,"gm"); arr = this.split(regExp); } while (arr[arr.length - 1] === "") arr.pop(); return Clazz.array(String, -1, arr); }; var sn=function(s, prefix,toffset){ var to=toffset; var po=0; var pc=prefix.length; if((toffset<0)||(toffset>s.length-pc)){ return false; } while(--pc>=0){ if(s.charAt(to++)!=prefix.charAt(po++)){ return false; } } return true; }; sp.startsWith$S=sp.startsWith$S$I=function(prefix){ if(arguments.length==1){ return sn(this,arguments[0],0); }else if(arguments.length==2){ return sn(this,arguments[0],arguments[1]); }else{ return false; } }; sp.endsWith$S=function(suffix){ return sn(this, suffix,this.length-suffix.length); }; sp.equals$O = function(anObject){ return this.valueOf()==anObject; }; sp.equalsIgnoreCase$S=function(anotherString){ return(anotherString==null)?false:(this==anotherString ||this.toLowerCase()==anotherString.toLowerCase()); }; sp.hash=0; sp.hashCode$=function(){ var h=this.hash; if(h==0){ var off=0; var len=this.length; for(var i=0;is.length){ throw new StringIndexOutOfBoundsException(srcEnd); } if(srcBegin>srcEnd){ throw new StringIndexOutOfBoundsException(srcEnd-srcBegin); } if(dst==null){ throw new NullPointerException(); } for(var i=0;i255){ arrs[ii]=0x1a; arrs[ii+1]=c&0xff; arrs[ii+2]=(c&0xff00)>>8; ii+=2; }else{ arrs[ii]=c; } ii++; } return Clazz.array(Byte.TYPE, -1, arrs); }; sp.contains$S = function(a) {return this.indexOf(a) >= 0} // bh added sp.compareTo$ = sp.compareTo$S = sp.compareTo$TT = function(a){return this > a ? 1 : this < a ? -1 : 0} // bh added sp.toCharArray$=function(){ var result=new Array(this.length); for(var i=0;i cs.length$() && this.indexOf(cs.toString()) > -1); }; sp.contentEquals$CharSequence=function(cs){ if(cs==null) throw new NullPointerException(); if(this == cs) return true; if(this.length!=cs.length$()) return false; var v=cs.getValue(); var n=this.length; while(n-- >= 0){ if(this.charCodeAt(n)!=v[n]){ return false; } } return true; }; sp.concat$S = function(s){ if(s==null){ throw new NullPointerException(); } return this.concat(s); }; sp.isEmpty$ = function() { return this.valueOf().length == 0; } sp.indexOf$S = sp.indexOf$S$I = sp.indexOf; sp.lastIndexOf$S = sp.lastIndexOf; sp.indexOf$I = function(c){ return this.indexOf(typeof c == "string" ? c : String.fromCodePoint(c)); }; sp.indexOf$I$I = function(c, first) { return this.indexOf(typeof c == "string" ? c : String.fromCodePoint(c), first); } sp.lastIndexOf$S = sp.lastIndexOf$S$I = sp.lastIndexOf; sp.lastIndexOf$I = function(c){ return this.lastIndexOf(typeof c == "string" ? c : String.fromCodePoint(c)); }; sp.lastIndexOf$I$I = function(c, last) { return this.lastIndexOf(typeof c == "string" ? c : String.fromCodePoint(c), last); } sp.intern$=function(){ return this.valueOf(); }; String.copyValueOf$S=String.copyValueOf$S$I$I=sp.copyValueOf=function(){ if(arguments.length==1){ return String.instantialize(arguments[0]); }else{ return String.instantialize(arguments[0],arguments[1],arguments[2]); } }; sp.$c = function(){return this.charCodeAt(0)}; // covers for same functions in JavaScript sp.codePointAt$I = (sp.codePointAt || sp.charCodeAt); // MSIE only sp.charCodeAt$I = sp.charCodeAt; sp.charAt$I = sp.charAt; sp.substring$I = sp.substring$I$I = sp.subSequence$I$I = sp.substring; sp.replace$C$C = sp.replace$CharSequence$CharSequence = sp.replace$; sp.toUpperCase$ = sp.toUpperCase; sp.toLowerCase$ = sp.toLowerCase; sp.trim$ = sp.trim; sp.toLowerCase$java_util_Locale = sp.toLocaleLowerCase ? function(loc) {loc = loc.toString(); var s = this.valueOf(); return (loc ? s.toLocaleLowerCase(loc.replace(/_/g,'-')) : s.toLocaleLowerCase()) } : sp.toLowerCase; sp.toUpperCase$java_util_Locale = sp.toLocaleUpperCase ? function(loc) {loc = loc.toString(); var s = this.valueOf(); return (loc ? s.toLocaleUpperCase(loc.replace(/_/g,'-')) : s.toLocaleUpperCase()) } : sp.toUpperCase; sp.length$ = function() {return this.length}; //sp.chars$ = CharSequence.prototype.chars$; //sp.codePoints$ = CharSequence.prototype.codePoints$; // toString is always unqualified, and it is unnecessary for String })(String.prototype); /* String(byte[] bytes) String(char[] value) String(StringBuffer buffer) String(StringBuilder builder) String(String original) String(byte[] ascii, int hibyte) String(byte[] bytes, Charset charset) String(byte[] bytes, String charsetName) String(byte[] bytes, int offset, int length) String(char[] value, int offset, int count) String(int[] codePoints, int offset, int count) String(byte[] bytes, int offset, int length, Charset charset) String(byte[] bytes, int offset, int length, String charsetName) String(byte[] ascii, int hibyte, int offset, int count) */ String.instantialize=function(){ switch (arguments.length) { case 0: return new String(); case 1: // String(byte[] bytes) // String(char[] value) // String(StringBuffer buffer) // String(StringBuilder builder) // String(String original) var x=arguments[0]; if (x.__BYTESIZE || x instanceof Array){ return (x.length == 0 ? "" : typeof x[0]=="number" ? Encoding.readUTF8Array(x) : x.join('')); } return x.toString(); case 2: // String(byte[] ascii, int hibyte) // String(byte[] bytes, Charset charset) // String(byte[] bytes, String charsetName) var x=arguments[0]; var hibyte=arguments[1]; return (typeof hibyte=="number" ? String.instantialize(x,hibyte,0,x.length) : String.instantialize(x,0,x.length,hibyte)); case 3: // String(byte[] bytes, int offset, int length) // String(char[] value, int offset, int count) // String(int[] codePoints, int offset, int count) var bytes=arguments[0]; var offset=arguments[1]; var length=arguments[2]; if(arguments[2]instanceof Array){ // ??? bytes=arguments[2]; offset=arguments[0]; length=arguments[1]; } var arr=new Array(length); if(offset<0||length+offset>bytes.length){ throw new IndexOutOfBoundsException(); } if(length>0){ var isChar=(bytes[offset].length!=null); if(isChar){ for(var i=0;i= 0) return Encoding.readUTF8Array(bytes,offset,length); cs = Clazz.loadClass("java.nio.charset.Charset").forName$S(cs); if (!cs) throw new java.io.UnsupportedEncodingException(); } return cs.decode$BA$I$I(bytes, offset, length).toString(); } var count=arguments[3]; var offset=arguments[2]; var hibyte=arguments[1]; var value=new Array(count); if(hibyte==0){ for(var i=count;i-->0;){ value[i]=String.fromCharCode(bytes[i+offset]&0xff); } }else{ hibyte<<=8; for(var i=count;i-->0;){ value[i]=String.fromCharCode(hibyte|(bytes[i+offset]&0xff)); } } return value.join(''); default: // ???? var s=""; for(var i=0;i= 0x1c && c <= 0x20 || c >= 0x9 && c <= 0xd || c == 0x1680 || c >= 0x2000 && c != 0x2007 && (c <= 0x200b || c == 0x2028 || c == 0x2029 || c == 0x3000)); }, 1); m$(C$,"isSurrogate$C", function(c) { c = c.charCodeAt(0); return c >= 0xd800 && c < 0xe000; }, 1); m$(C$,"isHighSurrogate$C", function(c) { c = c.charCodeAt(0); return c >= 0xd800 && c < 0xdc00; }, 1); m$(C$,"isLowSurrogate$C", function(c) { c = c.charCodeAt(0); return c >= 0xdc00 && c < 0xe000; }, 1); m$(C$,["digit$C$I","digit$I$I"], function(c,radix){ var i = (typeof c == "string" ? c.charCodeAt(0) : c); if(radix >= 2 && radix <= 36){ if(i < 128){ var result = -1; if(48 <= i && i <= 57){ result = i - 48; }else if(97 <= i && i <= 122){ result = i - 87; }else if(65 <= i && i <= 90){ result=i-(55); } return (result < radix ? result : -1); } } return -1; }, 1); m$(C$,"toString", function(c){ if (arguments.length == 0) { if(this===Character){ return"class java.lang.Character"; } var buf=[this.value]; return String.valueOf$(buf); } return String.valueOf$(c); }, 1); m$(C$,"charCount$I", function(codePoint){ return codePoint >= 0x010000 ? 2 : 1; }, 1); Integer.compare$I$I = Byte.compare$B$B = Short.compare$H$H = Long.compare$J$J = Float.compare$F$F = Double.compare$D$D = function(a,b) { return (a < b ? -1 : a == b ? 0 : 1) }; Integer.prototype.objectValue$ = Byte.prototype.objectValue$ = Short.prototype.objectValue$ = Long.prototype.objectValue$ = Float.prototype.objectValue$ = Double.prototype.objectValue$ = function() {return this.valueOf()}; Boolean.prototype.objectValue$ = Character.prototype.objectValue$ = function() { return this.value }; Character.prototype.intValue$ = function() { return this.value.codePointAt(0) }; Integer.min$I$I = Long.min$J$J = Float.min$F$F = Double.min$D$D = function(a,b) { return Math.min(a,b); }; Integer.max$I$I = Long.max$J$J = Float.max$F$F = Double.max$D$D = function(a,b) { return Math.max(a,b); }; Integer.sum$I$I = Long.sum$J$J = Float.sum$F$F = Double.sum$D$D = function(a,b) { return a + b; }; // TODO: Only asking for problems declaring Date. This is not necessary // NOTE THAT java.util.Date, like java.lang.Math, is unqualified by the transpiler -- this is NOT necessary Clazz._setDeclared("java.util.Date", java.util.Date=Date); //Date.TYPE="java.util.Date"; Date.__CLASS_NAME__="Date"; addInterface(Date,[java.io.Serializable,java.lang.Comparable]); m$(java.util.Date, ["c$", "c$$S", "c$$J"], function(t) { this.setTime$J(typeof t == "string" ? Date.parse(t) : t ? t : System.currentTimeMillis$()) }, 1); m$(java.util.Date, ["getClass$", "getClass"], function () { return Clazz.getClass(this); }, 1); m$(java.util.Date,["clone$","clone"], function(){ return new Date(this.getTime()); }); m$(java.util.Date,["before", "before$java_util_Date"], function(when){ return this.getTime()when.getTime(); }); m$(java.util.Date,["equals","equals$O"], function(obj){ return Clazz.instanceOf(obj,java.util.Date)&&this.getTime()==(obj).getTime(); }); m$(java.util.Date,["compareTo","compareTo$java_util_Date","compareTo$","compareTo$TT","compareTo$O"], function(anotherDate){ var thisTime=this.getTime(); var anotherTime=anotherDate.getTime(); return(thisTime>32)); }); var notImplemented = function(why) {return function() {System.err.println(why + " has not been implemented.")}}; ;(function(dp){ dp.from$java_time_Instant = notImplemented("Date.from(java.time.Instant)"); dp.setInstant$ = notImplemented("Date.toInstant()"); dp.getDate$ = dp.getDate; dp.getDay$ = dp.getDay; dp.getHours$ = dp.getHours; dp.getMinutes$ = dp.getMinutes; dp.getMonth$ = dp.getMonth; dp.getSeconds$ = dp.getSeconds; dp.getTime$ = dp.getTime; dp.getTimeZoneOffset$ = dp.getTimeZoneOffset; dp.getYear$ = dp.getYear; dp.parse$S = dp.parse; dp.setDate$I = dp.setDate; dp.setHours$I = dp.setHours; dp.setMinutes$I = dp.setMinutes; dp.setMonth$I = dp.setMonth; dp.setSeconds$I = dp.setSeconds; dp.setTime$J = dp.setTime; dp.setYear$I = dp.setYear; dp.toGMTString$ = dp.toGMTString; dp.toLocaleString$ = dp.toLocaleString = dp.toLocaleDateString; dp.UTC$ = dp.UTC; })(Date.prototype); /* Java8 classes have default methods Clazz.newInterface(java.util,"Iterator"); Clazz.newInterface(java.util,"ListIterator",java.util.Iterator); Clazz.newInterface(java.util,"Enumeration"); Clazz.newInterface(java.util,"Collection",Iterable); Clazz.newInterface(java.util,"Set",java.util.Collection); Clazz.newInterface(java.util,"Map"); Clazz.newInterface(java.util.Map,"Entry"); Clazz.newInterface(java.util,"List",java.util.Collection); Clazz.newInterface(java.util,"Queue",java.util.Collection); Clazz.newInterface(java.util,"RandomAccess"); */ var C$ = Clazz.newClass(java.lang, "Throwable", function () { Clazz.newInstance(this, arguments); }, null, java.io.Serializable); m$(C$, 'c$', function () { this.fillInStackTrace$(); this.detailMessage = this.stack; this.cause = this; }, 1); m$(C$, 'c$$S', function (message) { this.fillInStackTrace$(); this.cause = this; this.detailMessage = message; }, 1); m$(C$, 'c$$S$Throwable', function (message, cause) { this.fillInStackTrace$(); this.detailMessage = message; this.cause = cause; }, 1); m$(C$, 'c$$Throwable', function (cause) { this.fillInStackTrace$(); this.detailMessage = (cause == null ? this.stack : cause.toString ()); this.cause = cause; }, 1); m$(C$, 'getMessage$', function () {return this.message || this.detailMessage}); m$(C$, 'getLocalizedMessage$', function () { return this.getMessage$(); }); m$(C$, 'getCause$', function () { return (this.cause === this ? null : this.cause); }); m$(C$, 'initCause$Throwable', function (cause) { if (this.cause !== this) throw Clazz.new_(IllegalStateException.c$$S,["Can't overwrite cause"]); if (cause === this) throw Clazz.new_(IllegalArgumentException.c$$S,["Self-causation not permitted"]); this.cause = cause; return this; }); m$(C$, 'toString', function () { var s = this.getClass$().getName$(); var message = this.getLocalizedMessage$(); return (message != null) ? (s + ": " + message) : s; }); m$(C$, 'getStackTrace$', function () { return this.stackTrace; }); m$(C$, 'printStackTrace$', function () { printStackTrace(this, System.err.println$O); }); var printStackTrace = function(e, f) { f("" + e); if (!e.stackTrace){ f(e.stack); return; } for (var i = 0; i < e.stackTrace.length; i++) { var t = e.stackTrace[i]; if (t.nativeClazz == null || isInstanceOf(t.nativeClazz, Throwable) < 0) { f(t); } } // from a JavaScript error e.stack && f(e.stack); } m$(C$, ['printStackTrace$java_io_PrintStream','printStackTrace$java_io_PrintWriter'], function (stream) { printStackTrace(this, stream.println$O); }); Clazz.newMeth(C$, 'fillInStackTrace$', function () { this.stackTrace = Clazz.array(StackTraceElement); try { var caller = arguments.callee.caller; var superCaller = null; var callerList = []; var index = 0; while (index < 20 && caller != null) { index++; var clazzName = null; var nativeClazz = null; superCaller = caller; if (superCaller.exClazz != null) { nativeClazz = superCaller.exClazz; } var st =Clazz.new_(StackTraceElement.c$, [ ((nativeClazz != null && nativeClazz.__CLASS_NAME__.length != 0) ? nativeClazz.__CLASS_NAME__ : "anonymous"), ((superCaller.exName == null) ? "anonymous" : superCaller.exName), null, -1]); st.nativeClazz = nativeClazz; this.stackTrace.push(st); for (var i = 0; i < callerList.length; i++) { if (callerList[i] == superCaller) { // ... stack Information lost as recursive invocation existed ... var st =Clazz.new_(StackTraceElement.c$, ["lost", "missing", null, -3]); st.nativeClazz = null; this.stackTrace.push(st); index = 100; break; } } if (superCaller != null) { callerList.push(superCaller); } caller = (superCaller && superCaller.arguments && superCaller.arguments.callee) ? superCaller.arguments.callee.caller : null; } } catch (e) {}; Clazz.initializingException = false; return this; }); Clazz.newMeth(C$, 'setStackTrace$StackTraceElementA', function (stackTrace) { var defensiveCopy = stackTrace.clone$(); for (var i = 0; i < defensiveCopy.length; i++) if (defensiveCopy[i] == null) throw Clazz.new_(NullPointerException.c$$S,["stackTrace[" + i + "]"]); this.stackTrace = defensiveCopy; }); C$=Clazz.newClass(java.lang,"StackTraceElement",function(){ this.declaringClass=null; this.methodName=null; this.fileName=null; this.lineNumber=0; },null,java.io.Serializable); m$(C$, "c$",function(cls,method,file,line){ if(cls==null||method==null){ throw new NullPointerException(); }this.declaringClass=cls; this.methodName=method; this.fileName=file; this.lineNumber=line; },1); m$(C$,"equals$O", function(obj){ if(!(Clazz.instanceOf(obj,StackTraceElement))){ return false; }var castObj=obj; if((this.methodName==null)||(castObj.methodName==null)){ return false; }if(!this.getMethodName$().equals(castObj.getMethodName$())){ return false; }if(!this.getClassName$().equals(castObj.getClassName$())){ return false; }var localFileName=this.getFileName$(); if(localFileName==null){ if(castObj.getFileName$()!=null){ return false; }}else{ if(!localFileName.equals(castObj.getFileName$())){ return false; }}if(this.getLineNumber$()!=castObj.getLineNumber$()){ return false; }return true; }); m$(C$,"getClassName$", function(){ return(this.declaringClass==null)?"":this.declaringClass; }); m$(C$,"getFileName$", function(){ return this.fileName; }); m$(C$,"getLineNumber$", function(){ return this.lineNumber; }); m$(C$,"getMethodName$", function(){ return(this.methodName==null)?"":this.methodName; }); m$(C$,"hashCode$", function(){ if(this.methodName==null){ return 0; }return this.methodName.hashCode$()^this.declaringClass.hashCode(); }); m$(C$,"isNativeMethod$", function(){ return this.lineNumber==-2; }); m$(C$,"toString", function(){ var s = this.getClassName$() + "." + this.getMethodName$(); if(this.isNativeMethod$()){ s += "(Native Method)"; }else{ var fName=this.getFileName$(); if(fName==null){ s += "(Unknown Source)"; }else{ var lineNum=this.getLineNumber$(); s += '(' + fName; if(lineNum>=0){ s += ':' + lineNum; } s += ')'; }}return s; }); TypeError.prototype.getMessage$ || (TypeError.prototype.getMessage$ = TypeError.prototype.getLocalizedMessage$ = function(){ return (this.stack ? this.stack : this.message || this.toString()) + (this.getStackTrace ? this.getStackTrace$() : Clazz._getStackTrace())}); TypeError.prototype.printStackTrace$ = function(){System.out.println(this + "\n" + this.stack)}; TypeError.prototype.printStackTrace$java_io_PrintStream = function(stream){stream.println$S(this + "\n" + this.stack);}; Clazz.Error = Error; var declareType = function(prefix, name, clazzSuper, interfacez) { var cl = Clazz.newClass(prefix, name, null, clazzSuper, interfacez); if (clazzSuper) setSuperclass(cl, clazzSuper); return cl; }; // at least allow Error() by itself to work as before Clazz._Error || (Clazz._Error = Error); //setSuperclass(Clazz._Error, Throwable); var setEx = function(C$) { C$.$clinit$ = function() {Clazz.load(C$, 1);} m$(C$, "c$", function() { C$.superclazz.c$.apply(this, []);}, 1); m$(C$, "c$$S", function(detailMessage){C$.superclazz.c$$S.apply(this,[detailMessage]);},1); return C$; } ;(function() { var C$ = Clazz.newClass(java.lang, "Error", function (){ var err = Clazz._Error(); return err; }, Throwable); //setSuperclass(java.lang.Error, Throwable); //setSuperclass(Clazz._Error, Throwable); setEx(C$); })(); var newEx = function(prefix, name, clazzSuper) { return setEx(declareType(prefix, name, clazzSuper)); } C$ = newEx(java.lang,"Exception",Throwable); m$(C$, "c$", function(){}, 1); newEx(java.lang,"RuntimeException",Exception); newEx(java.lang,"IllegalArgumentException",RuntimeException); newEx(java.lang,"LinkageError",Error); newEx(java.lang,"VirtualMachineError",Error); newEx(java.lang,"IncompatibleClassChangeError",LinkageError); newEx(java.lang,"AbstractMethodError",IncompatibleClassChangeError); newEx(java.lang,"ArithmeticException",RuntimeException); newEx(java.lang,"ArrayStoreException",RuntimeException); newEx(java.lang,"ClassCircularityError",LinkageError); newEx(java.lang,"ClassFormatError",LinkageError); newEx(java.lang,"CloneNotSupportedException",Exception); newEx(java.lang,"IllegalAccessError",IncompatibleClassChangeError); newEx(java.lang,"IllegalAccessException",Exception); newEx(java.lang,"IllegalMonitorStateException",RuntimeException); newEx(java.lang,"IllegalStateException",RuntimeException); newEx(java.lang,"IllegalThreadStateException",IllegalArgumentException); newEx(java.lang,"IndexOutOfBoundsException",RuntimeException); newEx(java.lang,"InstantiationError",IncompatibleClassChangeError); newEx(java.lang,"InstantiationException",Exception); newEx(java.lang,"InternalError",VirtualMachineError); newEx(java.lang,"InterruptedException",Exception); newEx(java.lang,"NegativeArraySizeException",RuntimeException); newEx(java.lang,"NoClassDefFoundError",LinkageError); newEx(java.lang,"NoSuchFieldError",IncompatibleClassChangeError); newEx(java.lang,"NoSuchFieldException",Exception); newEx(java.lang,"NoSuchMethodException",Exception); newEx(java.lang,"NoSuchMethodError",IncompatibleClassChangeError); newEx(java.lang,"NullPointerException",RuntimeException); newEx(java.lang,"NumberFormatException",IllegalArgumentException); newEx(java.lang,"OutOfMemoryError",VirtualMachineError); newEx(java.lang,"SecurityException",RuntimeException); newEx(java.lang,"StackOverflowError",VirtualMachineError); newEx(java.lang,"ThreadDeath",Error); newEx(java.lang,"UnknownError",VirtualMachineError); newEx(java.lang,"UnsatisfiedLinkError",LinkageError); newEx(java.lang,"UnsupportedClassVersionError",ClassFormatError); newEx(java.lang,"UnsupportedOperationException",RuntimeException); newEx(java.lang,"VerifyError",LinkageError); newEx(java.lang,"ClassCastException",RuntimeException); C$=Clazz.newClass(java.lang,"ClassNotFoundException",function(){this.ex=null;},Exception); m$(C$, "c$$S$Throwable", function(detailMessage,exception){ C$.superclazz.c$$S$Throwable.apply(this, arguments); this.ex=exception; }, 1); m$(C$,"getException$", function(){ return this.ex; }); m$(C$,"getCause$", function(){ return this.ex; }); C$=newEx(java.lang,"StringIndexOutOfBoundsException",IndexOutOfBoundsException); m$(C$, "c$$I", function(index){ C$.superclazz.c$$S.apply(this,["String index out of range: "+index]); }, 1); C$=Clazz.newClass(java.lang.reflect,"InvocationTargetException",function(){this.target=null;},Exception); m$(C$, "c$$Throwable", function(exception){ C$.superclazz.c$$Throwable.apply(this, arguments); this.target=exception; }, 1); m$(C$, "c$$Throwable$S", function(exception,detailMessage){ C$.superclazz.c$$S$Throwable.apply(this,[detailMessage,exception]); this.target=exception; }, 1); m$(C$,"getTargetException$", function(){ return this.target; }); m$(C$,"getCause$", function(){ return this.target; }); ;(function(){ var C$=Clazz.newClass(java.lang.reflect,"UndeclaredThrowableException",function(){this.undeclaredThrowable=null;},RuntimeException); m$(C$, "c$$Throwable", function(exception){ Clazz.super_(C$, this); C$.superclazz.c$$Throwable.apply(this, arguments); this.undeclaredThrowable=exception; this.initCause(exception); },1); m$(C$, "c$$Throwable$S", function(exception,detailMessage){ C$.superclazz.c$$S.apply(this,[detailMessage]); this.undeclaredThrowable=exception; this.initCause(exception); },1); m$(C$,"getUndeclaredThrowable$", function(){ return this.undeclaredThrowable; }); m$(C$,"getCause$", function(){ return this.undeclaredThrowable; }); })(); newEx(java.io,"IOException",Exception); newEx(java.io,"CharConversionException",java.io.IOException); newEx(java.io,"EOFException",java.io.IOException); newEx(java.io,"FileNotFoundException",java.io.IOException); newEx(java.io,"ObjectStreamException",java.io.IOException); newEx(java.io,"SyncFailedException",java.io.IOException); newEx(java.io,"UnsupportedEncodingException",java.io.IOException); newEx(java.io,"UTFDataFormatException",java.io.IOException); newEx(java.io,"InvalidObjectException",java.io.ObjectStreamException); newEx(java.io,"NotActiveException",java.io.ObjectStreamException); newEx(java.io,"NotSerializableException",java.io.ObjectStreamException); newEx(java.io,"StreamCorruptedException",java.io.ObjectStreamException); C$=Clazz.newClass(java.io,"InterruptedIOException",function(){ this.bytesTransferred=0; },java.io.IOException); C$=Clazz.newClass(java.io,"InvalidClassException",function(){ this.classname=null; },java.io.ObjectStreamException); m$(C$, "c$$S$S", function(className,detailMessage){ C$.superclazz.c$$S.apply(this,[detailMessage]); this.classname=className; },1); m$(C$,"getMessage$", function(){ var msg=C$.superclazz.getMessage$.apply(this, []); if(this.classname!=null){ msg=this.classname+';' + ' '+msg; }return msg; }); C$=Clazz.newClass(java.io,"OptionalDataException",function(){ this.eof=false; this.length=0; },java.io.ObjectStreamException); C$=Clazz.newClass(java.io,"WriteAbortedException",function(){ this.detail=null; },java.io.ObjectStreamException); m$(C$, "c$$S$Throwable", function(detailMessage, rootCause){ C$.superclazz.c$$S.apply(this,[detailMessage]); this.detail=rootCause; this.initCause(rootCause); }, 1); m$(C$,"getMessage$", function(){ var msg=C$.superclazz.getMessage.apply(this); return (this.detail ? msg + "; "+this.detail.toString() : msg); }); m$(C$,"getCause$", function(){ return this.detail; }); newEx(java.util,"EmptyStackException",RuntimeException); newEx(java.util,"NoSuchElementException",RuntimeException); newEx(java.util,"TooManyListenersException",Exception); ;(function(){ var C$=newEx(java.util,"ConcurrentModificationException",RuntimeException); m$(C$, "c$", function(detailMessage, rootCause){ Clazz.super_(C$, this); }, 1); })(); ;(function(){ var C$=Clazz.newClass(java.util,"MissingResourceException",function(){ this.className=null; this.key=null; },RuntimeException); C$.$clinit$ = function() { Clazz.load(C$, 1); } m$(C$, "c$$S$S$S", function(detailMessage,className,resourceName){ Clazz.super_(C$, this); C$.superclazz.c$$S.apply(this,[detailMessage]); this.className=className; this.key=resourceName; }, 1); m$(C$,"getClassName$", function(){ return this.className; }); m$(C$,"getKey$", function(){ return this.key; }); })(); declareType(java.lang,"Void"); setJ2STypeclass(java.lang.Void, "void", "V"); //java.lang.Void.TYPE=java.lang.Void; //java.lang.V Clazz.newInterface(java.lang.reflect,"GenericDeclaration"); Clazz.newInterface(java.lang.reflect,"AnnotatedElement"); C$=declareType(java.lang.reflect,"AccessibleObject",null,java.lang.reflect.AnnotatedElement); m$(C$, "c$",function(){ }, 1); m$(C$,"isAccessible$", function(){ return true; }); m$(C$,"setAccessible$reflect_AccessibleObjectA$Z", function(objects,flag){ return; },1); m$(C$,"setAccessible$Z", function(flag){ return; }); m$(C$,"isAnnotationPresent$Class", function(annotationType){ return false; }); m$(C$,"getDeclaredAnnotations$", function(){ return new Array(0); }); m$(C$,"getAnnotations$", function(){ return new Array(0); }); m$(C$,"getAnnotation$Class", function(annotationType){ return null; }); m$(C$,"marshallArguments$ClassA$OA", function(parameterTypes,args){ return null; }, 1); m$(C$,"invokeV$O$OA", function(receiver,args){ return; }); m$(C$,"invokeL$O$OA", function(receiver,args){ return null; }); m$(C$,"invokeI$O$OA", function(receiver,args){ return 0; }); m$(C$,"invokeJ$O$OA", function(receiver,args){ return 0; }); m$(C$,"invokeF$O$OA", function(receiver,args){ return 0.0; }); m$(C$,"invokeD$O$OA", function(receiver,args){ return 0.0; }); C$.emptyArgs=C$.prototype.emptyArgs=new Array(0); Clazz.newInterface(java.lang.reflect,"InvocationHandler"); C$=Clazz.newInterface(java.lang.reflect,"Member"); C$=declareType(java.lang.reflect,"Modifier"); m$(C$, "c$", function(){}, 1); m$(C$,"isAbstract$I", function(modifiers){ return((modifiers&1024)!=0); }, 1); m$(C$,"isFinal$I", function(modifiers){ return((modifiers&16)!=0); }, 1); m$(C$,"isInterface$I", function(modifiers){ return((modifiers&512)!=0); }, 1); m$(C$,"isNative$I", function(modifiers){ return((modifiers&256)!=0); }, 1); m$(C$,"isPrivate$I", function(modifiers){ return((modifiers&2)!=0); }, 1); m$(C$,"isProtected$I", function(modifiers){ return((modifiers&4)!=0); }, 1); m$(C$,"isPublic$I", function(modifiers){ return((modifiers&1)!=0); }, 1); m$(C$,"isStatic$I", function(modifiers){ return((modifiers&8)!=0); }, 1); m$(C$,"isStrict$I", function(modifiers){ return((modifiers&2048)!=0); }, 1); m$(C$,"isSynchronized$I", function(modifiers){ return((modifiers&32)!=0); }, 1); m$(C$,"isTransient$I", function(modifiers){ return((modifiers&128)!=0); }, 1); m$(C$,"isVolatile$I", function(modifiers){ return((modifiers&64)!=0); }, 1); m$(C$,"toString", function(modifiers){ var sb=new Array(0); if(java.lang.reflect.Modifier.isPublic(modifiers))sb[sb.length]="public"; if(java.lang.reflect.Modifier.isProtected(modifiers))sb[sb.length]="protected"; if(java.lang.reflect.Modifier.isPrivate(modifiers))sb[sb.length]="private"; if(java.lang.reflect.Modifier.isAbstract(modifiers))sb[sb.length]="abstract"; if(java.lang.reflect.Modifier.isStatic(modifiers))sb[sb.length]="static"; if(java.lang.reflect.Modifier.isFinal(modifiers))sb[sb.length]="final"; if(java.lang.reflect.Modifier.isTransient(modifiers))sb[sb.length]="transient"; if(java.lang.reflect.Modifier.isVolatile(modifiers))sb[sb.length]="volatile"; if(java.lang.reflect.Modifier.isSynchronized(modifiers))sb[sb.length]="synchronized"; if(java.lang.reflect.Modifier.isNative(modifiers))sb[sb.length]="native"; if(java.lang.reflect.Modifier.isStrict(modifiers))sb[sb.length]="strictfp"; if(java.lang.reflect.Modifier.isInterface(modifiers))sb[sb.length]="interface"; if(sb.length>0){ return sb.join(" "); }return""; }, 1); var newMethodNotFoundException = function (clazz, method) { var message = "Method " + getClassName(clazz, true) + (method ? "." + method : "") + " was not found"; System.out.println(message); console.log(message); throw Clazz.new_(java.lang.NoSuchMethodException.c$$S, [message]); }; // Constructor, Field, Method all moved back to their original class js; no need to have those here // if (needPackage("core")) // _Loader.loadPackage("core"); //Clazz._Loader.loadZJar(Clazz._Loader.getJ2SLibBase() + "core/coreswingjs.z.js", "swingjs.JSUtil"); //if (!J2S._isAsync) { if (!Clazz._loadcore || J2S._coreFiles.length == 0) { if (!Clazz._quiet)System.out.println("Clazz: No core files to load -- check Info.core"); } else { J2S.onClazzLoaded && J2S.onClazzLoaded(1, "Clazz loaded; loading J2S._coreFiles " + J2S._coreFiles.length); for (var i = 0; i < J2S._coreFiles.length; i++) { Clazz.loadScript(J2S._coreFiles[i]); } J2S.onClazzLoaded && J2S.onClazzLoaded(2, "Clazz loaded; core files loaded"); } })(Clazz, J2S); }; // called by external application // SwingJSApplet.js // BH 8/1/2018 $-qualified Java methods // generic SwingJS Applet // BH 3/14/2018 8:42:33 PM adds applet._window for JSObject // BH 12/18/2016 8:09:56 AM added SwingJS.Loaded and SwingJS.isLoaded // BH 7/24/2015 9:09:39 AM allows setting Info.resourcePath // BH 4/28/2015 10:15:32 PM adds getAppletHtml // BH 4/2/2015 5:17:44 PM adds SwingJS.getJavaResource(path) // BH 3/27/2015 6:34:49 AM just a shell if(typeof(jQuery)=="undefined") alert ("Note -- jQuery is required for SwingJS, but it's not defined.") if (typeof(SwingJS) == "undefined") { SwingJS = {}; (function (SwingJS, $, J2S) { SwingJS.getApplet = function(id, Info, checkOnly) { return SwingJS._Applet._get(id, Info, checkOnly); } // optional Info here SwingJS.getAppletHtml = function(applet, Info) { if (Info) { var d = SwingJS._document; SwingJS._document = null; applet = SwingJS.getApplet(applet, Info); SwingJS._document = d; } return applet._code; } SwingJS._Applet = function(id, Info, checkOnly){ window[id] = this; this._appletType = "SwingJS._Applet" + (Info.isSigned ? " (signed)" : ""); this._isJava = true; this._availableParams = null; // all allowed this._window = window; if (checkOnly) return this; this._isSigned = Info.isSigned; this._readyFunction = Info.readyFunction; this._ready = false; this._isJava = true; this._isInfoVisible = false; this._applet = null; this._memoryLimit = Info.memoryLimit || 512; this._canScript = function(script) {return true;}; this._savedOrientations = []; this._initialize = function(jarPath, jarFile) { var doReport = false; SwingJS._jarFile && (jarFile = SwingJS._jarFile); if(this._jarFile) { var f = this._jarFile; if(f.indexOf("/") >= 0) { alert ("This web page URL is requesting that the applet used be " + f + ". This is a possible security risk, particularly if the applet is signed, because signed applets can read and write files on your local machine or network."); var ok = prompt("Do you want to use applet " + f + "? ", "yes or no") if(ok == "yes") { jarPath = f.substring(0, f.lastIndexOf("/")); jarFile = f.substring(f.lastIndexOf("/") + 1); } else { doReport = true; } } else { jarFile = f; } this_isSigned = Info.isSigned = (jarFile.indexOf("Signed") >= 0); } this._jarPath = Info.jarPath = jarPath || "."; this._jarFile = Info.jarFile = jarFile; if (doReport) alert ("The web page URL was ignored. Continuing using " + this._jarFile + ' in directory "' + this._jarPath + '"'); // could do something like this: J2S.controls == undefined || J2S.controls._onloadResetForms(); } this._create(id, Info); return this; } ;(function(Applet, proto) { Applet._get = function(id, Info, checkOnly) { checkOnly || (checkOnly = false); Info || (Info = {}); var DefaultInfo = { code: null,//"swingjs.test.TanSugd3S", uncompressed: true, //color: "#FFFFFF", // applet object background color width: 300, height: 300, serverURL: "http://your.server.here/jsmol.php", console: null, // div for where the JavaScript console will be. readyFunction: null, use: "HTML5",//other options include JAVA jarPath: "java", jarFile: "[code].jar", j2sPath: "j2s", disableJ2SLoadMonitor: false, disableInitialConsole: false, debug: false }; J2S._addDefaultInfo(Info, DefaultInfo); Info.jarFile && Info.code && Info.jarFile.replace(/\[code\]/,Info.code); J2S._debugAlert = Info.debug; Info.serverURL && (J2S._serverUrl = Info.serverURL); var javaAllowed = false; var applet = null; var List = Info.use.toUpperCase().split("#")[0].split(" "); for (var i = 0; i < List.length; i++) { switch (List[i]) { case "JAVA": javaAllowed = true; if (J2S.featureDetection.supportsJava()) applet = new Applet(id, Info, checkOnly); break; case "HTML5": if (J2S.featureDetection.allowHTML5){ applet = Applet._getCanvas(id, Info, checkOnly); } else { List.push("JAVA"); } break; } if (applet != null) break; } if (applet == null) { if (checkOnly || !javaAllowed) applet = {_appletType : "none" }; else if (javaAllowed) applet = new Applet(id, Info); } // keyed to both its string id and itself return (checkOnly ? applet : J2S._registerApplet(id, applet)); } Applet._getCanvas = function(id, Info, checkOnly) { Info._isLayered = true; Info._isSwing = true; Info._platform = ""; J2S._Canvas2D.prototype = J2S._jsSetPrototype(new Applet(id, Info, true)); return new J2S._Canvas2D(id, Info, Info.code, checkOnly); }; /* AngelH, mar2007: By (re)setting these variables in the webpage before calling J2S.getApplet(), a custom message can be provided (e.g. localized for user's language) when no Java is installed. */ Applet._noJavaMsg = "Either you do not have Java applets enabled in your web
browser or your browser is blocking this applet.
\ Check the warning message from your browser and/or enable Java applets in
\ your web browser preferences, or install the Java Runtime Environment from
www.java.com"; Applet._setCommonMethods = function(p) { p._showInfo = proto._showInfo; /// p._search = proto._search; p._getName = proto._getName; p.readyCallback = proto.readyCallback; } Applet._createApplet = function(applet, Info, params) { applet._initialize(Info.jarPath, Info.jarFile); var jarFile = applet._jarFile; var jnlp = "" if (J2S._isFile) { jarFile = jarFile.replace(/0\.jar/,".jar"); } // size is set to 100% of containers' size, but only if resizable. // Note that resizability in MSIE requires: // var w = (applet._containerWidth.indexOf("px") >= 0 ? applet._containerWidth : "100%"); var h = (applet._containerHeight.indexOf("px") >= 0 ? applet._containerHeight : "100%"); var widthAndHeight = " style=\"width:" + w + ";height:" + h + "\" "; var attributes = "name='" + applet._id + "_object' id='" + applet._id + "_object' " + "\n" + widthAndHeight + jnlp + "\n" params.codebase = applet._jarPath; params.codePath = params.codebase + "/"; if (params.codePath.indexOf("://") < 0) { var base = document.location.href.split("#")[0].split("?")[0].split("/"); base[base.length - 1] = params.codePath; params.codePath = base.join("/"); } params.archive = jarFile; params.mayscript = 'true'; params.java_arguments = "-Xmx" + Math.round(Info.memoryLimit || applet._memoryLimit) + "m"; params.permissions = (applet._isSigned ? "all-permissions" : "sandbox"); params.documentLocation = document.location.href; params.documentBase = document.location.href.split("#")[0].split("?")[0]; params.jarPath = Info.jarPath; J2S._syncedApplets.length && (params.synccallback = "J2S._mySyncCallback"); applet._startupScript && (params.script = applet._startupScript); var t = "\n"; for (var i in params) if(params[i]) t += " \n"; if (J2S.featureDetection.useIEObject || J2S.featureDetection.useHtml4Object) { t = "" : " type='application/x-java-applet'>") + t + "

\n" + Applet._noJavaMsg + "

\n"; } else { // use applet tag t = "\n" + t + "
\n" + Applet._noJavaMsg + "
\n"; } if (applet._deferApplet) applet._javaCode = t, t=""; t = J2S._getWrapper(applet, true) + t + J2S._getWrapper(applet, false) + (Info.addSelectionOptions ? J2S._getGrabberOptions(applet) : ""); if (J2S._debugAlert) alert (t); applet._code = J2S._documentWrite(t); } proto._newApplet = function(viewerOptions) { this._viewerOptions = viewerOptions; // for now assigning this._applet here instead of in readyCallback Clazz.loadClass("swingjs.JSAppletViewer"); this._appletPanel = Clazz.new_(swingjs.JSAppletViewer.c$$java_util_Hashtable, [viewerOptions]); this._appletPanel.start$(); } proto._addCoreFiles = function() { if (this.__Info.core != "NONE" && this.__Info.core != "none" && !J2S._debugCode) J2S._addCoreFile((this.__Info.core || "swingjs"), this._j2sPath, this.__Info.preloadCore); // if (J2S._debugCode) { // // no min package for that // J2S._addExec([this, null, "swingjs.JSAppletViewer", "load " + this.__Info.code]); // // } } proto._create = function(id, Info){ J2S._setObject(this, id, Info); var params = { syncId: J2S._syncId, progressbar: "true", progresscolor: "blue", boxbgcolor: this._color || "black", boxfgcolor: "white", boxmessage: "Downloading Applet ...", //script: (this._color ? "background \"" + this._color +"\"": ""), code: Info.appletClass + ".class" }; J2S._setAppletParams(this._availableParams, params, Info); function sterilizeInline(model) { model = model.replace(/\r|\n|\r\n/g, (model.indexOf("|") >= 0 ? "\\/n" : "|")).replace(/'/g, "'"); if(J2S._debugAlert) alert ("inline model:\n" + model); return model; } params.loadInline = (Info.inlineModel ? sterilizeInline(Info.inlineModel) : ""); params.appletReadyCallback = "J2S.readyCallback"; if (J2S._syncedApplets.length) params.synccallback = "J2S._mySyncCallback"; params.java_arguments = "-Xmx" + Math.round(Info.memoryLimit || this._memoryLimit) + "m"; this._initialize(Info.jarPath, Info.jarFile); Applet._createApplet(this, Info, params); } proto._restoreState = function(clazzName, state) { // applet-dependent } proto.readyCallback = function(id, fullid, isReady) { if (!isReady) return; // ignore -- page is closing J2S._setDestroy(this); this._ready = true; this._showInfo(true); this._showInfo(false); J2S.Cache.setDragDrop(this); this._readyFunction && this._readyFunction(this); J2S._setReady(this); var app = this._2dapplet; if (app && app._isEmbedded && app._ready && app.__Info.visible) this._show2d(true); } proto._showInfo = function(tf) { if(this._isJNLP)return; if(tf && this._2dapplet) this._2dapplet._show(false); J2S.$html(J2S.$(this, "infoheaderspan"), this._infoHeader); if (this._info) J2S.$html(J2S.$(this, "infodiv"), this._info); if ((!this._isInfoVisible) == (!tf)) return; this._isInfoVisible = tf; // 1px does not work for MSIE if (this._isJava) { var x = (tf ? 2 : "100%"); J2S.$setSize(J2S.$(this, "appletdiv"), x, x); } J2S.$setVisible(J2S.$(this, "infotablediv"), tf); J2S.$setVisible(J2S.$(this, "infoheaderdiv"), tf); this._show(!tf); } proto._show = function(tf) { var x = (!tf ? 2 : "100%"); J2S.$setSize(J2S.$(this, "object"), x, x); if (!this._isJava) J2S.$setVisible(J2S.$(this, "appletdiv"), tf); } proto._clearConsole = function () { if (this._console == this._id + "_infodiv") this.info = ""; if (!self.Clazz)return; J2S._setConsoleDiv(this._console); Clazz.Console.clear(); } proto._resizeApplet = function(size) { // See _jmolGetAppletSize() for the formats accepted as size [same used by jmolApplet()] // Special case: an empty value for width or height is accepted, meaning no change in that dimension. /* * private functions */ function _getAppletSize(size, units) { /* Accepts single number, 2-value array, or object with width and height as mroperties, each one can be one of: percent (text string ending %), decimal 0 to 1 (percent/100), number, or text string (interpreted as nr.) [width, height] array of strings is returned, with units added if specified. Percent is relative to container div or element (which should have explicitly set size). */ var width, height; if(( typeof size) == "object" && size != null) { width = size[0]||size.width; height = size[1]||size.height; } else { width = height = size; } return [J2S.fixDim(width, units), J2S.fixDim(height, units)]; } var sz = _getAppletSize(size, "px"); var d = J2S._getElement(this, "appletinfotablediv"); d.style.width = sz[0]; d.style.height = sz[1]; this._containerWidth = sz[0]; this._containerHeight = sz[1]; if (this._is2D) J2S.repaint(this, true); } proto._cover = function (doCover) { // from using getAppletHtml() this._newCanvas(false); this._showInfo(false); this._init(); }; })(SwingJS._Applet, SwingJS._Applet.prototype); })(SwingJS, jQuery, J2S); } // SwingJS undefined
This is System.out. clear it
Add ?j2snocore to URL to see full class list; ?j2sdebug to use uncompressed j2s/core files
get _j2sClassList.txt