summaryrefslogtreecommitdiff
path: root/js/src
diff options
context:
space:
mode:
Diffstat (limited to 'js/src')
-rw-r--r--js/src/Glacier2/Glacier2.js4
-rw-r--r--js/src/Ice/ACM.js175
-rw-r--r--js/src/Ice/Address.js16
-rw-r--r--js/src/Ice/ArrayUtil.js86
-rw-r--r--js/src/Ice/AsyncResult.js145
-rw-r--r--js/src/Ice/AsyncResultBase.js71
-rw-r--r--js/src/Ice/AsyncStatus.js4
-rw-r--r--js/src/Ice/Base64.js396
-rw-r--r--js/src/Ice/BasicStream.js3016
-rw-r--r--js/src/Ice/BatchRequestQueue.js67
-rw-r--r--js/src/Ice/Buffer.js438
-rw-r--r--js/src/Ice/Class.js55
-rw-r--r--js/src/Ice/Communicator.js171
-rw-r--r--js/src/Ice/CompactIdRegistry.js4
-rw-r--r--js/src/Ice/ConnectRequestHandler.js180
-rw-r--r--js/src/Ice/ConnectionI.js846
-rw-r--r--js/src/Ice/ConnectionRequestHandler.js44
-rw-r--r--js/src/Ice/Debug.js21
-rw-r--r--js/src/Ice/DefaultsAndOverrides.js208
-rw-r--r--js/src/Ice/EndpointFactoryManager.js123
-rw-r--r--js/src/Ice/EndpointI.js46
-rw-r--r--js/src/Ice/EnumBase.js125
-rw-r--r--js/src/Ice/ExUtil.js8
-rw-r--r--js/src/Ice/Exception.js222
-rw-r--r--js/src/Ice/FormatType.js2
-rw-r--r--js/src/Ice/HashMap.js252
-rw-r--r--js/src/Ice/HashUtil.js34
-rw-r--r--js/src/Ice/IPEndpointI.js132
-rw-r--r--js/src/Ice/Ice.js12
-rw-r--r--js/src/Ice/IdentityUtil.js75
-rw-r--r--js/src/Ice/ImplicitContextI.js92
-rw-r--r--js/src/Ice/IncomingAsync.js452
-rw-r--r--js/src/Ice/Initialize.js26
-rw-r--r--js/src/Ice/Instance.js408
-rw-r--r--js/src/Ice/LocatorInfo.js300
-rw-r--r--js/src/Ice/LocatorManager.js42
-rw-r--r--js/src/Ice/LocatorTable.js94
-rw-r--r--js/src/Ice/Logger.js62
-rw-r--r--js/src/Ice/Long.js72
-rw-r--r--js/src/Ice/MapUtil.js51
-rw-r--r--js/src/Ice/ModuleRegistry.js43
-rw-r--r--js/src/Ice/Object.js287
-rw-r--r--js/src/Ice/ObjectAdapterFactory.js86
-rw-r--r--js/src/Ice/ObjectAdapterI.js404
-rw-r--r--js/src/Ice/ObjectFactory.js21
-rw-r--r--js/src/Ice/ObjectFactoryManager.js71
-rw-r--r--js/src/Ice/ObjectPrx.js860
-rw-r--r--js/src/Ice/OpaqueEndpointI.js196
-rw-r--r--js/src/Ice/Operation.js589
-rw-r--r--js/src/Ice/OptionalFormat.js2
-rw-r--r--js/src/Ice/OutgoingAsync.js476
-rw-r--r--js/src/Ice/OutgoingConnectionFactory.js706
-rw-r--r--js/src/Ice/ProcessLogger.js6
-rw-r--r--js/src/Ice/Promise.js293
-rw-r--r--js/src/Ice/Properties.js249
-rw-r--r--js/src/Ice/Property.js40
-rw-r--r--js/src/Ice/PropertyNames.js9
-rw-r--r--js/src/Ice/Protocol.js57
-rw-r--r--js/src/Ice/ProtocolInstance.js72
-rw-r--r--js/src/Ice/ProxyFactory.js138
-rw-r--r--js/src/Ice/Reference.js1313
-rw-r--r--js/src/Ice/ReferenceMode.js2
-rw-r--r--js/src/Ice/RequestHandlerFactory.js40
-rw-r--r--js/src/Ice/RetryException.js23
-rw-r--r--js/src/Ice/RetryQueue.js131
-rw-r--r--js/src/Ice/RouterInfo.js149
-rw-r--r--js/src/Ice/RouterManager.js44
-rw-r--r--js/src/Ice/ServantManager.js173
-rw-r--r--js/src/Ice/SocketOperation.js2
-rw-r--r--js/src/Ice/Stream.js3515
-rw-r--r--js/src/Ice/StreamHelpers.js195
-rw-r--r--js/src/Ice/StringUtil.js515
-rw-r--r--js/src/Ice/Struct.js74
-rw-r--r--js/src/Ice/TcpEndpointFactory.js47
-rw-r--r--js/src/Ice/TcpEndpointI.js130
-rw-r--r--js/src/Ice/TcpTransceiver.js261
-rw-r--r--js/src/Ice/Timer.js72
-rw-r--r--js/src/Ice/TimerUtil.js8
-rw-r--r--js/src/Ice/ToStringMode.js (renamed from js/src/Ice/DispatchStatus.js)6
-rw-r--r--js/src/Ice/TraceLevels.js113
-rw-r--r--js/src/Ice/TraceUtil.js337
-rw-r--r--js/src/Ice/UUID.js8
-rw-r--r--js/src/Ice/UnknownSlicedObject.js76
-rw-r--r--js/src/Ice/UnknownSlicedValue.js85
-rw-r--r--js/src/Ice/Value.js216
-rw-r--r--js/src/Ice/ValueFactoryManagerI.js46
-rw-r--r--js/src/Ice/WSEndpoint.js127
-rw-r--r--js/src/Ice/WSEndpointFactory.js46
-rw-r--r--js/src/Ice/browser/Buffer.js419
-rw-r--r--js/src/Ice/browser/Debug.js29
-rw-r--r--js/src/Ice/browser/ModuleRegistry.js34
-rw-r--r--js/src/Ice/browser/TimerUtil.js179
-rw-r--r--js/src/Ice/browser/WSTransceiver.js199
-rw-r--r--js/src/Ice/sources.json15
-rw-r--r--js/src/IceGrid/IceGrid.js7
-rw-r--r--js/src/IceGrid/sources.json3
-rw-r--r--js/src/es5/index.js16
-rw-r--r--js/src/index.js (renamed from js/src/ice.js)0
98 files changed, 10805 insertions, 11032 deletions
diff --git a/js/src/Glacier2/Glacier2.js b/js/src/Glacier2/Glacier2.js
index 30dd37f12ea..099fc03b439 100644
--- a/js/src/Glacier2/Glacier2.js
+++ b/js/src/Glacier2/Glacier2.js
@@ -7,9 +7,9 @@
//
// **********************************************************************
-var __M = require("../Ice/ModuleRegistry").Ice.__M;
+var _ModuleRegistry = require("../Ice/ModuleRegistry").Ice._ModuleRegistry;
-module.exports.Glacier2 = __M.require(module,
+module.exports.Glacier2 = _ModuleRegistry.require(module,
[
"../Glacier2/PermissionsVerifier",
"../Glacier2/Router",
diff --git a/js/src/Ice/ACM.js b/js/src/Ice/ACM.js
index 0af2df51856..b7631fb17f9 100644
--- a/js/src/Ice/ACM.js
+++ b/js/src/Ice/ACM.js
@@ -7,14 +7,14 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Class", "../Ice/Debug", "../Ice/Connection", "../Ice/Debug"]);
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module, ["../Ice/Debug", "../Ice/Connection"]);
-var Class = Ice.Class;
-var Debug = Ice.Debug;
+const Debug = Ice.Debug;
-var ACMConfig = Class({
- __init__: function(p, l, prefix, dflt)
+class ACMConfig
+{
+ constructor(p, l, prefix, dflt)
{
if(p === undefined)
{
@@ -24,7 +24,7 @@ var ACMConfig = Class({
return;
}
- var timeoutProperty;
+ let timeoutProperty;
if((prefix == "Ice.ACM.Client" || prefix == "Ice.ACM.Server") &&
p.getProperty(prefix + ".Timeout").length === 0)
{
@@ -37,7 +37,7 @@ var ACMConfig = Class({
this.timeout = p.getPropertyAsIntWithDefault(timeoutProperty, dflt.timeout / 1000) * 1000; // To ms
- var hb = p.getPropertyAsIntWithDefault(prefix + ".Heartbeat", dflt.heartbeat.value);
+ const hb = p.getPropertyAsIntWithDefault(prefix + ".Heartbeat", dflt.heartbeat.value);
if(hb >= 0 && hb <= Ice.ACMHeartbeat.maxValue)
{
this.heartbeat = Ice.ACMHeartbeat.valueOf(hb);
@@ -49,7 +49,7 @@ var ACMConfig = Class({
this.heartbeat = dflt.heartbeat;
}
- var cl = p.getPropertyAsIntWithDefault(prefix + ".Close", dflt.close.value);
+ const cl = p.getPropertyAsIntWithDefault(prefix + ".Close", dflt.close.value);
if(cl >= 0 && cl <= Ice.ACMClose.maxValue)
{
this.close = Ice.ACMClose.valueOf(cl);
@@ -61,42 +61,19 @@ var ACMConfig = Class({
this.close = dflt.close;
}
}
-});
+}
-var ACMMonitor = Class({
- add: function(con)
- {
- Debug.assert(false); // Absract
- },
- remove: function(con)
- {
- Debug.assert(false); // Absract
- },
- reap: function(con)
- {
- Debug.assert(false); // Absract
- },
- acm: function(timeout)
- {
- Debug.assert(false); // Absract
- return null;
- },
- getACM: function()
- {
- Debug.assert(false); // Absract
- return 0;
- }
-});
-
-var FactoryACMMonitor = Class(ACMMonitor, {
- __init__: function(instance, config)
+class FactoryACMMonitor
+{
+ constructor(instance, config)
{
this._instance = instance;
this._config = config;
this._reapedConnections = [];
this._connections = [];
- },
- destroy: function()
+ }
+
+ destroy()
{
if(this._instance === null)
{
@@ -104,8 +81,9 @@ var FactoryACMMonitor = Class(ACMMonitor, {
}
this._instance = null;
this._connections = null;
- },
- add: function(connection)
+ }
+
+ add(connection)
{
if(this._config.timeout === 0)
{
@@ -115,40 +93,37 @@ var FactoryACMMonitor = Class(ACMMonitor, {
this._connections.push(connection);
if(this._connections.length == 1)
{
- var self = this;
this._timerToken = this._instance.timer().scheduleRepeated(
- function()
- {
- self.runTimerTask();
- },
- this._config.timeout / 2);
+ () => this.runTimerTask(), this._config.timeout / 2);
}
- },
- remove: function(connection)
+ }
+
+ remove(connection)
{
if(this._config.timeout === 0)
{
return;
}
- var i = this._connections.indexOf(connection);
+ let i = this._connections.indexOf(connection);
Debug.assert(i >= 0);
this._connections.splice(i, 1);
if(this._connections.length === 0)
{
this._instance.timer().cancel(this._timerToken);
- return;
}
- },
- reap: function(connection)
+ }
+
+ reap(connection)
{
this._reapedConnections.push(connection);
- },
- acm: function(timeout, close, heartbeat)
+ }
+
+ acm(timeout, close, heartbeat)
{
Debug.assert(this._instance !== null);
- var config = new ACMConfig();
+ let config = new ACMConfig();
config.timeout = this._config.timeout;
config.close = this._config.close;
config.heartbeat = this._config.heartbeat;
@@ -165,22 +140,25 @@ var FactoryACMMonitor = Class(ACMMonitor, {
config.heartbeat = heartbeat;
}
return new ConnectionACMMonitor(this, this._instance.timer(), config);
- },
- getACM: function()
+ }
+
+ getACM()
{
return new Ice.ACM(this._config.timeout / 1000, this._config.close, this._config.heartbeat);
- },
- swapReapedConnections: function()
+ }
+
+ swapReapedConnections()
{
if(this._reapedConnections.length === 0)
{
return null;
}
- var connections = this._reapedConnections;
+ let connections = this._reapedConnections;
this._reapedConnections = [];
return connections;
- },
- runTimerTask: function()
+ }
+
+ runTimerTask()
{
if(this._instance === null)
{
@@ -191,20 +169,22 @@ var FactoryACMMonitor = Class(ACMMonitor, {
// Monitor connections outside the thread synchronization, so
// that connections can be added or removed during monitoring.
//
- var now = Date.now();
- for(var i = 0; i < this._connections.length; i++)
- {
- try
- {
- this._connections[i].monitor(now, this._config);
- }
- catch(ex)
+ let now = Date.now();
+
+ this._connections.forEach(connection =>
{
- this.handleException(ex);
- }
- }
- },
- handleException: function(ex)
+ try
+ {
+ connection.monitor(now, this._config);
+ }
+ catch(ex)
+ {
+ this.handleException(ex);
+ }
+ });
+ }
+
+ handleException(ex)
{
if(this._instance === null)
{
@@ -212,28 +192,29 @@ var FactoryACMMonitor = Class(ACMMonitor, {
}
this._instance.initializationData().logger.error("exception in connection monitor:\n" + ex);
}
-});
+}
-var ConnectionACMMonitor = Class(ACMMonitor, {
- __init__: function(parent, timer, config)
+class ConnectionACMMonitor
+{
+ constructor(parent, timer, config)
{
this._parent = parent;
this._timer = timer;
this._config = config;
this._connection = null;
- },
- add: function(connection)
+ }
+
+ add(connection)
{
Debug.assert(this._connection === null);
this._connection = connection;
if(this._config.timeout > 0)
{
- var self = this;
- this._timerToken = this._timer.scheduleRepeated(function() { self.runTimerTask(); },
- this._config.timeout / 2);
+ this._timerToken = this._timer.scheduleRepeated(() => this.runTimerTask(), this._config.timeout / 2);
}
- },
- remove: function(connection)
+ }
+
+ remove(connection)
{
Debug.assert(this._connection === connection);
this._connection = null;
@@ -241,20 +222,24 @@ var ConnectionACMMonitor = Class(ACMMonitor, {
{
this._timer.cancel(this._timerToken);
}
- },
- reap: function(connection)
+ }
+
+ reap(connection)
{
this._parent.reap(connection);
- },
- acm: function(timeout, close, heartbeat)
+ }
+
+ acm(timeout, close, heartbeat)
{
return this._parent.acm(timeout, close, heartbeat);
- },
- getACM: function()
+ }
+
+ getACM()
{
return new Ice.ACM(this._config.timeout / 1000, this._config.close, this._config.heartbeat);
- },
- runTimerTask: function()
+ }
+
+ runTimerTask()
{
try
{
@@ -265,7 +250,7 @@ var ConnectionACMMonitor = Class(ACMMonitor, {
this._parent.handleException(ex);
}
}
-});
+}
Ice.FactoryACMMonitor = FactoryACMMonitor;
Ice.ACMConfig = ACMConfig;
diff --git a/js/src/Ice/Address.js b/js/src/Ice/Address.js
index 6df7ade1de1..817862838b6 100644
--- a/js/src/Ice/Address.js
+++ b/js/src/Ice/Address.js
@@ -8,10 +8,16 @@
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.Address = function(host, port)
+const Ice = require("../Ice/ModuleRegistry").Ice;
+
+class Address
{
- this.host = host;
- this.port = port;
-};
+ constructor(host, port)
+ {
+ this.host = host;
+ this.port = port;
+ }
+}
+
+Ice.Address = Address;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/ArrayUtil.js b/js/src/Ice/ArrayUtil.js
index 303842ea687..a3e89db4bc4 100644
--- a/js/src/Ice/ArrayUtil.js
+++ b/js/src/Ice/ArrayUtil.js
@@ -7,11 +7,11 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-var __M = Ice.__M;
-var Slice = Ice.Slice;
+const Ice = require("../Ice/ModuleRegistry").Ice;
+const _ModuleRegistry = Ice._ModuleRegistry;
+const Slice = Ice.Slice;
-var eq = function(e1, e2)
+const eq = function(e1, e2)
{
if(e1 === e2)
{
@@ -36,9 +36,9 @@ var eq = function(e1, e2)
return false;
};
-var ArrayUtil =
+class ArrayUtil
{
- clone: function(arr)
+ static clone(arr)
{
if(arr === undefined)
{
@@ -52,16 +52,17 @@ var ArrayUtil =
{
return arr.slice();
}
- },
- equals: function(v1, v2, valuesEqual)
+ }
+
+ static equals(v1, v2, valuesEqual)
{
if(v1.length != v2.length)
{
return false;
}
- var i, length, equalFn = valuesEqual || eq;
- for(i = 0, length = v1.length; i < length; ++i)
+ const equalFn = valuesEqual || eq;
+ for(let i = 0; i < v1.length; ++i)
{
if(!equalFn.call(equalFn, v1[i], v2[i]))
{
@@ -70,69 +71,36 @@ var ArrayUtil =
}
return true;
- },
- shuffle: function(arr)
+ }
+
+ static shuffle(arr)
{
- for(var i = arr.length; i > 1; --i)
+ for(let i = arr.length; i > 1; --i)
{
- var e = arr[i - 1];
- var rand = Math.floor(Math.random() * i);
+ let e = arr[i - 1];
+ let rand = Math.floor(Math.random() * i);
arr[i - 1] = arr[rand];
arr[rand] = e;
}
- },
- indexOf: function(arr, elem, equalFn)
- {
- if(equalFn !== undefined && equalFn !== null)
- {
- for(var i = 0; i < arr.length; ++i)
- {
- if(equalFn.call(equalFn, arr[i], elem))
- {
- return i;
- }
- }
- }
- else
- {
- return arr.indexOf(elem);
- }
-
- return -1;
- },
- filter: function(arr, includeFn, obj)
- {
- obj = obj === undefined ? includeFn : obj;
- var result = [];
- for(var i = 0; i < arr.length; ++i)
- {
- if(includeFn.call(obj, arr[i], i, arr))
- {
- result.push(arr[i]);
- }
- }
- return result;
}
-};
+}
ArrayUtil.eq = eq;
Slice.defineSequence = function(module, name, valueHelper, fixed, elementType)
{
- var helper = null;
+ let helper = null;
Object.defineProperty(module, name,
- {
- get: function()
- {
- if(helper === null)
+ {
+ get: function()
{
- /*jshint -W061 */
- helper = Ice.StreamHelpers.generateSeqHelper(__M.type(valueHelper), fixed, __M.type(elementType));
- /*jshint +W061 */
+ if(helper === null)
+ {
+ helper = Ice.StreamHelpers.generateSeqHelper(_ModuleRegistry.type(valueHelper), fixed, _ModuleRegistry.type(elementType));
+ }
+ return helper;
}
- return helper;
- }
- });
+ });
};
Ice.ArrayUtil = ArrayUtil;
diff --git a/js/src/Ice/AsyncResult.js b/js/src/Ice/AsyncResult.js
index 672421ba824..60c5c79a0c1 100644
--- a/js/src/Ice/AsyncResult.js
+++ b/js/src/Ice/AsyncResult.js
@@ -7,69 +7,64 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/AsyncResultBase",
"../Ice/Debug",
- "../Ice/Promise",
"../Ice/Protocol",
"../Ice/Exception",
- "../Ice/BasicStream"
+ "../Ice/Stream"
]);
-var AsyncResultBase = Ice.AsyncResultBase;
-var Debug = Ice.Debug;
-var Promise = Ice.Promise;
-var Protocol = Ice.Protocol;
-var UserException = Ice.UserException;
-var BasicStream = Ice.BasicStream;
-
-var AsyncResult = Ice.Class(AsyncResultBase, {
- __init__: function(com, op, connection, proxy, adapter, completedFn)
- {
- //
- // AsyncResult can be constructed by a sub-type's prototype, in which case the
- // arguments are undefined.
- //
- AsyncResultBase.call(this, com, op, connection, proxy, adapter);
- if(com === undefined)
- {
- return;
- }
+const AsyncResultBase = Ice.AsyncResultBase;
+const Debug = Ice.Debug;
+const Protocol = Ice.Protocol;
+const UserException = Ice.UserException;
+const OutputStream = Ice.OutputStream;
+class AsyncResult extends AsyncResultBase
+{
+ constructor(com, op, connection, proxy, adapter, completedFn)
+ {
+ super(com, op, connection, proxy, adapter);
this._completed = completedFn;
this._is = null;
- this._os = com !== null ? new BasicStream(this._instance, Protocol.currentProtocolEncoding) : null;
+ this._os = com !== null ? new OutputStream(this._instance, Protocol.currentProtocolEncoding) : null;
this._state = 0;
this._exception = null;
this._sentSynchronously = false;
- },
- cancel: function()
+ }
+
+ cancel()
{
- this.__cancel(new Ice.InvocationCanceledException());
- },
- isCompleted: function()
+ this.cancelWithException(new Ice.InvocationCanceledException());
+ }
+
+ isCompleted()
{
return (this._state & AsyncResult.Done) > 0;
- },
- isSent: function()
+ }
+
+ isSent()
{
return (this._state & AsyncResult.Sent) > 0;
- },
- throwLocalException: function()
+ }
+
+ throwLocalException()
{
if(this._exception !== null)
{
throw this._exception;
}
- },
- sentSynchronously: function()
+ }
+
+ sentSynchronously()
{
return this._sentSynchronously;
- },
- __markSent: function(done)
+ }
+
+ markSent(done)
{
Debug.assert((this._state & AsyncResult.Done) === 0);
this._state |= AsyncResult.Sent;
@@ -77,10 +72,11 @@ var AsyncResult = Ice.Class(AsyncResultBase, {
{
this._state |= AsyncResult.Done | AsyncResult.OK;
this._cancellationHandler = null;
- this.succeed(this);
+ this.resolve();
}
- },
- __markFinished: function(ok, completed)
+ }
+
+ markFinished(ok, completed)
{
Debug.assert((this._state & AsyncResult.Done) === 0);
this._state |= AsyncResult.Done;
@@ -95,26 +91,29 @@ var AsyncResult = Ice.Class(AsyncResultBase, {
}
else
{
- this.succeed(this);
+ this.resolve();
}
- },
- __markFinishedEx: function(ex)
+ }
+
+ markFinishedEx(ex)
{
Debug.assert((this._state & AsyncResult.Done) === 0);
this._exception = ex;
this._state |= AsyncResult.Done;
this._cancellationHandler = null;
- this.fail(ex, this);
- },
- __cancel: function(ex)
+ this.reject(ex);
+ }
+
+ cancelWithException(ex)
{
this._cancellationException = ex;
if(this._cancellationHandler)
{
this._cancellationHandler.asyncRequestCanceled(this, ex);
}
- },
- __cancelable: function(handler)
+ }
+
+ cancelable(handler)
{
if(this._cancellationException)
{
@@ -128,53 +127,51 @@ var AsyncResult = Ice.Class(AsyncResultBase, {
}
}
this._cancellationHandler = handler;
- },
- __os: function()
+ }
+
+ getOs()
{
return this._os;
- },
- __is: function()
- {
- return this._is;
- },
- __startReadParams: function()
+ }
+
+ startReadParams()
{
- this._is.startReadEncaps();
+ this._is.startEncapsulation();
return this._is;
- },
- __endReadParams: function()
- {
- this._is.endReadEncaps();
- },
- __readEmptyParams: function()
+ }
+
+ endReadParams()
{
- this._is.skipEmptyEncaps();
- },
- __readParamEncaps: function()
+ this._is.endEncapsulation();
+ }
+
+ readEmptyParams()
{
- return this._is.readEncaps(null);
- },
- __throwUserException: function()
+ this._is.skipEmptyEncapsulation();
+ }
+
+ throwUserException()
{
Debug.assert((this._state & AsyncResult.Done) !== 0);
if((this._state & AsyncResult.OK) === 0)
{
try
{
- this._is.startReadEncaps();
+ this._is.startEncapsulation();
this._is.throwException();
}
catch(ex)
{
if(ex instanceof UserException)
{
- this._is.endReadEncaps();
+ this._is.endEncapsulation();
}
throw ex;
}
}
- },
-});
+ }
+
+}
AsyncResult.OK = 0x1;
AsyncResult.Done = 0x2;
diff --git a/js/src/Ice/AsyncResultBase.js b/js/src/Ice/AsyncResultBase.js
index 85536e49b7c..2ee5457624d 100644
--- a/js/src/Ice/AsyncResultBase.js
+++ b/js/src/Ice/AsyncResultBase.js
@@ -7,53 +7,46 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Class", "../Ice/Debug", "../Ice/Promise", "../Ice/Exception"]);
+const Ice = require("../Ice/Promise").Ice;
-var Promise = Ice.Promise;
-
-var AsyncResultBase = Ice.Class(Promise, {
- __init__: function(communicator, op, connection, proxy, adapter)
+class AsyncResultBase extends Ice.Promise
+{
+ constructor(communicator, op, connection, proxy, adapter)
{
- //
- // AsyncResultBase can be constructed by a sub-type's prototype, in which case the
- // arguments are undefined.
- //
- Promise.call(this);
- if(communicator !== undefined)
- {
- this._communicator = communicator;
- this._instance = communicator !== null ? communicator.instance : null;
- this._operation = op;
- this._connection = connection;
- this._proxy = proxy;
- this._adapter = adapter;
- }
+ super();
+ this._communicator = communicator;
+ this._instance = communicator !== null ? communicator.instance : null;
+ this._operation = op;
+ this._connection = connection;
+ this._proxy = proxy;
+ this._adapter = adapter;
}
-});
-
-var prototype = AsyncResultBase.prototype;
-var defineProperty = Object.defineProperty;
-defineProperty(prototype, "communicator", {
- get: function() { return this._communicator; }
-});
+ get communicator()
+ {
+ return this._communicator;
+ }
-defineProperty(prototype, "connection", {
- get: function() { return this._connection; }
-});
+ get connection()
+ {
+ return this._connection;
+ }
-defineProperty(prototype, "proxy", {
- get: function() { return this._proxy; }
-});
+ get proxy()
+ {
+ return this._proxy;
+ }
-defineProperty(prototype, "adapter", {
- get: function() { return this._adapter; }
-});
+ get adapter()
+ {
+ return this._adapter;
+ }
-defineProperty(prototype, "operation", {
- get: function() { return this._operation; }
-});
+ get operation()
+ {
+ return this._operation;
+ }
+}
Ice.AsyncResultBase = AsyncResultBase;
diff --git a/js/src/Ice/AsyncStatus.js b/js/src/Ice/AsyncStatus.js
index 086b5e268e1..05a758fcfcf 100644
--- a/js/src/Ice/AsyncStatus.js
+++ b/js/src/Ice/AsyncStatus.js
@@ -7,6 +7,6 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.AsyncStatus = {Queued: 0, Sent: 1};
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice.AsyncStatus = { Queued: 0, Sent: 1 };
module.exports.Ice = Ice;
diff --git a/js/src/Ice/Base64.js b/js/src/Ice/Base64.js
index 3baff7b9e06..03e38e08707 100644
--- a/js/src/Ice/Base64.js
+++ b/js/src/Ice/Base64.js
@@ -7,265 +7,263 @@
//
// **********************************************************************
-var Ice = require("../Ice/Buffer").Ice;
+const Ice = require("../Ice/Buffer").Ice;
-var Buffer = Ice.Buffer;
+const Buffer = Ice.Buffer;
-var Base64 = {};
+const _codeA = "A".charCodeAt(0);
+const _codea = "a".charCodeAt(0);
+const _code0 = "0".charCodeAt(0);
-var _codeA = "A".charCodeAt(0);
-var _codea = "a".charCodeAt(0);
-var _code0 = "0".charCodeAt(0);
-
-Base64.encode = function(buf) // Expects native Buffer
+function encodeChar(uc)
{
- if(buf === null || buf.length === 0)
+ if(uc < 26)
{
- return "";
+ return String.fromCharCode(_codeA + uc);
}
- var base64Bytes = (((buf.length * 4) / 3) + 1);
- var newlineBytes = (((base64Bytes * 2) / 76) + 1);
- var totalBytes = base64Bytes + newlineBytes;
-
- var v = [];
-
- var by1;
- var by2;
- var by3;
- var by4;
- var by5;
- var by6;
- var by7;
-
- for(var i = 0; i < buf.length; i += 3)
+ if(uc < 52)
{
- by1 = buf[i] & 0xff;
- by2 = 0;
- by3 = 0;
-
- if((i + 1) < buf.length)
- {
- by2 = buf[i + 1] & 0xff;
- }
-
- if((i + 2) < buf.length)
- {
- by3 = buf[i + 2] & 0xff;
- }
-
- by4 = (by1 >> 2) & 0xff;
- by5 = (((by1 & 0x3) << 4) | (by2 >> 4)) & 0xff;
- by6 = (((by2 & 0xf) << 2) | (by3 >> 6)) & 0xff;
- by7 = by3 & 0x3f;
-
- v.push(encodeChar(by4));
- v.push(encodeChar(by5));
-
- if((i + 1) < buf.length)
- {
- v.push(encodeChar(by6));
- }
- else
- {
- v.push("=");
- }
-
- if((i + 2) < buf.length)
- {
- v.push(encodeChar(by7));
- }
- else
- {
- v.push("=");
- }
+ return String.fromCharCode(_codea + (uc - 26));
}
- var retval = v.join("");
- var outString = [];
- var iter = 0;
-
- while((retval.length - iter) > 76)
+ if(uc < 62)
{
- outString.push(retval.substring(iter, iter + 76));
- outString.push("\r\n");
- iter += 76;
+ return String.fromCharCode(_code0 + (uc - 52));
}
- outString.push(retval.substring(iter));
+ if(uc == 62)
+ {
+ return "+";
+ }
- return outString.join("");
-};
+ return "/";
+}
-Base64.decode = function(str) // Returns native Buffer
+function decodeChar(c)
{
- var newStr = [];
-
- for(var j = 0; j < str.length; j++)
+ if(c >= 'A' && c <= 'Z')
{
- var c = str.charAt(j);
- if(Base64.isBase64(c))
- {
- newStr.push(c);
- }
+ return c.charCodeAt(0) - _codeA;
}
- if(newStr.length === 0)
+ if(c >= 'a' && c <= 'z')
{
- return null;
+ return c.charCodeAt(0) - _codea + 26;
}
- // Note: This is how we were previously computing the size of the return
- // sequence. The method below is more efficient (and correct).
- // size_t lines = str.size() / 78;
- // size_t totalBytes = (lines * 76) + (((str.size() - (lines * 78)) * 3) / 4);
-
- // Figure out how long the final sequence is going to be.
- var totalBytes = (newStr.length * 3 / 4) + 1;
-
- var retval = new Buffer();
- retval.resize(totalBytes);
-
- var by1;
- var by2;
- var by3;
- var by4;
-
- var c1;
- var c2;
- var c3;
- var c4;
-
- var off = 0;
+ if(c >= '0' && c <= '9')
+ {
+ return c.charCodeAt(0) - _code0 + 52;
+ }
- for(var i = 0; i < newStr.length; i += 4)
+ if(c == '+')
{
- c1 = "A";
- c2 = "A";
- c3 = "A";
- c4 = "A";
+ return 62;
+ }
- c1 = newStr[i];
+ return 63;
+}
- if((i + 1) < newStr.length)
+class Base64
+{
+ // Expects native Buffer
+ static encode(buf)
+ {
+ if(buf === null || buf.length === 0)
{
- c2 = newStr[i + 1];
+ return "";
}
- if((i + 2) < newStr.length)
+ let v = [];
+
+ let by1;
+ let by2;
+ let by3;
+ let by4;
+ let by5;
+ let by6;
+ let by7;
+
+ for(let i = 0; i < buf.length; i += 3)
{
- c3 = newStr[i + 2];
+ by1 = buf[i] & 0xff;
+ by2 = 0;
+ by3 = 0;
+
+ if((i + 1) < buf.length)
+ {
+ by2 = buf[i + 1] & 0xff;
+ }
+
+ if((i + 2) < buf.length)
+ {
+ by3 = buf[i + 2] & 0xff;
+ }
+
+ by4 = (by1 >> 2) & 0xff;
+ by5 = (((by1 & 0x3) << 4) | (by2 >> 4)) & 0xff;
+ by6 = (((by2 & 0xf) << 2) | (by3 >> 6)) & 0xff;
+ by7 = by3 & 0x3f;
+
+ v.push(encodeChar(by4));
+ v.push(encodeChar(by5));
+
+ if((i + 1) < buf.length)
+ {
+ v.push(encodeChar(by6));
+ }
+ else
+ {
+ v.push("=");
+ }
+
+ if((i + 2) < buf.length)
+ {
+ v.push(encodeChar(by7));
+ }
+ else
+ {
+ v.push("=");
+ }
}
- if((i + 3) < newStr.length)
+ let retval = v.join("");
+ let outString = [];
+ let iter = 0;
+
+ while((retval.length - iter) > 76)
{
- c4 = newStr[i + 3];
+ outString.push(retval.substring(iter, iter + 76));
+ outString.push("\r\n");
+ iter += 76;
}
- by1 = decodeChar(c1) & 0xff;
- by2 = decodeChar(c2) & 0xff;
- by3 = decodeChar(c3) & 0xff;
- by4 = decodeChar(c4) & 0xff;
+ outString.push(retval.substring(iter));
+
+ return outString.join("");
+ }
- retval.put((by1 << 2) | (by2 >> 4));
+ static decode(str) // Returns native Buffer
+ {
+ let newStr = [];
- if(c3 != "=")
+ for(let j = 0; j < str.length; j++)
{
- retval.put(((by2 & 0xf) << 4) | (by3 >> 2));
+ let c = str.charAt(j);
+ if(Base64.isBase64(c))
+ {
+ newStr.push(c);
+ }
}
- if(c4 != "=")
+ if(newStr.length === 0)
{
- retval.put(((by3 & 0x3) << 6) | by4);
+ return null;
}
- }
- return retval.remaining > 0 ? retval.getArrayAt(0, retval.position) : retval.getArrayAt(0);
-};
+ // Note: This is how we were previously computing the size of the return
+ // sequence. The method below is more efficient (and correct).
+ // size_t lines = str.size() / 78;
+ // size_t totalBytes = (lines * 76) + (((str.size() - (lines * 78)) * 3) / 4);
-Base64.isBase64 = function(c)
-{
- if(c >= 'A' && c <= 'Z')
- {
- return true;
- }
+ // Figure out how long the final sequence is going to be.
+ let totalBytes = (newStr.length * 3 / 4) + 1;
- if(c >= 'a' && c <= 'z')
- {
- return true;
- }
+ let retval = new Buffer();
+ retval.resize(totalBytes);
- if(c >= '0' && c <= '9')
- {
- return true;
- }
+ let by1;
+ let by2;
+ let by3;
+ let by4;
- if(c == '+')
- {
- return true;
- }
-
- if(c == '/')
- {
- return true;
- }
-
- if(c == '=')
- {
- return true;
- }
+ let c1;
+ let c2;
+ let c3;
+ let c4;
- return false;
-};
+ let off = 0;
-function encodeChar(uc)
-{
- if(uc < 26)
- {
- return String.fromCharCode(_codeA + uc);
- }
+ for(let i = 0; i < newStr.length; i += 4)
+ {
+ c1 = "A";
+ c2 = "A";
+ c3 = "A";
+ c4 = "A";
+
+ c1 = newStr[i];
+
+ if((i + 1) < newStr.length)
+ {
+ c2 = newStr[i + 1];
+ }
+
+ if((i + 2) < newStr.length)
+ {
+ c3 = newStr[i + 2];
+ }
+
+ if((i + 3) < newStr.length)
+ {
+ c4 = newStr[i + 3];
+ }
+
+ by1 = decodeChar(c1) & 0xff;
+ by2 = decodeChar(c2) & 0xff;
+ by3 = decodeChar(c3) & 0xff;
+ by4 = decodeChar(c4) & 0xff;
+
+ retval.put((by1 << 2) | (by2 >> 4));
+
+ if(c3 != "=")
+ {
+ retval.put(((by2 & 0xf) << 4) | (by3 >> 2));
+ }
+
+ if(c4 != "=")
+ {
+ retval.put(((by3 & 0x3) << 6) | by4);
+ }
+ }
- if(uc < 52)
- {
- return String.fromCharCode(_codea + (uc - 26));
+ return retval.remaining > 0 ? retval.getArrayAt(0, retval.position) : retval.getArrayAt(0);
}
- if(uc < 62)
+ static isBase64(c)
{
- return String.fromCharCode(_code0 + (uc - 52));
- }
+ if(c >= 'A' && c <= 'Z')
+ {
+ return true;
+ }
- if(uc == 62)
- {
- return "+";
- }
+ if(c >= 'a' && c <= 'z')
+ {
+ return true;
+ }
- return "/";
-}
+ if(c >= '0' && c <= '9')
+ {
+ return true;
+ }
-function decodeChar(c)
-{
- if(c >= 'A' && c <= 'Z')
- {
- return c.charCodeAt(0) - _codeA;
- }
+ if(c == '+')
+ {
+ return true;
+ }
- if(c >= 'a' && c <= 'z')
- {
- return c.charCodeAt(0) - _codea + 26;
- }
+ if(c == '/')
+ {
+ return true;
+ }
- if(c >= '0' && c <= '9')
- {
- return c.charCodeAt(0) - _code0 + 52;
- }
+ if(c == '=')
+ {
+ return true;
+ }
- if(c == '+')
- {
- return 62;
+ return false;
}
-
- return 63;
}
Ice.Base64 = Base64;
diff --git a/js/src/Ice/BasicStream.js b/js/src/Ice/BasicStream.js
deleted file mode 100644
index c6ac956fe7b..00000000000
--- a/js/src/Ice/BasicStream.js
+++ /dev/null
@@ -1,3016 +0,0 @@
-// **********************************************************************
-//
-// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
-//
-// This copy of Ice is licensed to you under the terms described in the
-// ICE_LICENSE file included in this distribution.
-//
-// **********************************************************************
-
-var Ice = require("../Ice/ModuleRegistry").Ice;
-var __M = Ice.__M;
-__M.require(module,
- [
- "../Ice/Class",
- "../Ice/Debug",
- "../Ice/ExUtil",
- "../Ice/FormatType",
- "../Ice/HashMap",
- "../Ice/Object",
- "../Ice/OptionalFormat",
- "../Ice/Protocol",
- "../Ice/TraceUtil",
- "../Ice/Buffer",
- "../Ice/Exception",
- "../Ice/LocalException",
- "../Ice/Version",
- "../Ice/CompactIdRegistry",
- "../Ice/ArrayUtil",
- "../Ice/UnknownSlicedObject"
- ]);
-
-var Debug = Ice.Debug;
-var ExUtil = Ice.ExUtil;
-var FormatType = Ice.FormatType;
-var HashMap = Ice.HashMap;
-var IceObject = Ice.Object;
-var OptionalFormat = Ice.OptionalFormat;
-var Protocol = Ice.Protocol;
-var TraceUtil = Ice.TraceUtil;
-var ArrayUtil = Ice.ArrayUtil;
-var SlicedData = Ice.SlicedData;
-
-var SliceType = {};
-SliceType.NoSlice = 0;
-SliceType.ObjectSlice = 1;
-SliceType.ExceptionSlice = 2;
-
-var OPTIONAL_END_MARKER = 0xFF;
-var FLAG_HAS_TYPE_ID_STRING = (1<<0);
-var FLAG_HAS_TYPE_ID_INDEX = (1<<1);
-var FLAG_HAS_TYPE_ID_COMPACT = (1<<1 | 1<<0);
-var FLAG_HAS_OPTIONAL_MEMBERS = (1<<2);
-var FLAG_HAS_INDIRECTION_TABLE = (1<<3);
-var FLAG_HAS_SLICE_SIZE = (1<<4);
-var FLAG_IS_LAST_SLICE = (1<<5);
-
-//
-// Number.isNaN polyfill for compatibility with IE
-//
-// see: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
-//
-Number.isNaN = Number.isNaN || function(value)
-{
- return typeof value === "number" && isNaN(value);
-};
-
-var IndirectPatchEntry = function(index, patcher)
-{
- this.index = index;
- this.patcher = patcher;
-};
-
-var Class = Ice.Class;
-
-var EncapsDecoder = Class({
- __init__: function(stream, encaps, sliceObjects, f)
- {
- this._stream = stream;
- this._encaps = encaps;
- this._sliceObjects = sliceObjects;
- this._servantFactoryManager = f;
- this._patchMap = null; // Lazy initialized, HashMap<int, Patcher[] >()
- this._unmarshaledMap = new HashMap(); // HashMap<int, Ice.Object>()
- this._typeIdMap = null; // Lazy initialized, HashMap<int, String>
- this._typeIdIndex = 0;
- this._objectList = null; // Lazy initialized. Ice.Object[]
- },
- readOpt: function()
- {
- return false;
- },
- readPendingObjects: function()
- {
- },
- readTypeId: function(isIndex)
- {
- var typeId, index;
- if(this._typeIdMap === null) // Lazy initialization
- {
- this._typeIdMap = new HashMap(); // Map<int, String>();
- }
-
- if(isIndex)
- {
- index = this._stream.readSize();
- typeId = this._typeIdMap.get(index);
- if(typeId === undefined)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- }
- else
- {
- typeId = this._stream.readString();
- this._typeIdMap.set(++this._typeIdIndex, typeId);
- }
- return typeId;
- },
- newInstance: function(typeId)
- {
- //
- // Try to find a factory registered for the specific type.
- //
- var userFactory = this._servantFactoryManager.find(typeId);
- var v = null;
-
- if(userFactory !== undefined)
- {
- v = userFactory.create(typeId);
- }
-
- //
- // If that fails, invoke the default factory if one has been
- // registered.
- //
- if(v === null || v === undefined)
- {
- userFactory = this._servantFactoryManager.find("");
- if(userFactory !== undefined)
- {
- v = userFactory.create(typeId);
- }
- }
-
- //
- // Last chance: try to instantiate the class dynamically.
- //
- if(v === null || v === undefined)
- {
- v = this._stream.createObject(typeId);
- }
-
- return v;
- },
- addPatchEntry: function(index, patcher)
- {
- Debug.assert(index > 0);
- //
- // Check if already un-marshalled the object. If that's the case,
- // just patch the object smart pointer and we're done.
- //
- var obj = this._unmarshaledMap.get(index);
- if(obj !== undefined && obj !== null)
- {
- patcher.call(null, obj);
- return;
- }
-
- if(this._patchMap === null) // Lazy initialization
- {
- this._patchMap = new HashMap(); // HashMap<Integer, Patcher[] >();
- }
-
- //
- // Add patch entry if the object isn't un-marshalled yet,
- // the smart pointer will be patched when the instance is
- // un-marshalled.
- //
- var l = this._patchMap.get(index);
- if(l === undefined)
- {
- //
- // We have no outstanding instances to be patched for this
- // index, so make a new entry in the patch map.
- //
- l = []; // Patcher[];
- this._patchMap.set(index, l);
- }
-
- //
- // Append a patch entry for this instance.
- //
- l.push(patcher);
- },
- unmarshal: function(index, v)
- {
- var i, length, l;
- //
- // Add the object to the map of un-marshalled objects, this must
- // be done before reading the objects (for circular references).
- //
- this._unmarshaledMap.set(index, v);
-
- //
- // Read the object.
- //
- v.__read(this._stream);
- if(this._patchMap !== null)
- {
- //
- // Patch all instances now that the object is un-marshalled.
- //
- l = this._patchMap.get(index);
- if(l !== undefined)
- {
- Debug.assert(l.length > 0);
- //
- // Patch all pointers that refer to the instance.
- //
- for(i = 0, length = l.length; i < length; ++i)
- {
- l[i](v);
- }
- //
- // Clear out the patch map for that index -- there is nothing left
- // to patch for that index for the time being.
- //
- this._patchMap.delete(index);
- }
- }
-
- if((this._patchMap === null || this._patchMap.size === 0) && this._objectList === null)
- {
- try
- {
- v.ice_postUnmarshal();
- }
- catch(ex)
- {
- this._stream.instance.initializationData().logger.warning("exception raised by ice_postUnmarshal:\n" +
- ex.toString());
- }
- }
- else
- {
- if(this._objectList === null) // Lazy initialization
- {
- this._objectList = []; // Ice.Object[]
- }
- this._objectList.push(v);
-
- if(this._patchMap === null || this._patchMap.size === 0)
- {
- //
- // Iterate over the object list and invoke ice_postUnmarshal on
- // each object. We must do this after all objects have been
- // unmarshaled in order to ensure that any object data members
- // have been properly patched.
- //
- for(i = 0, length = this._objectList.length; i < length; i++)
- {
- try
- {
- this._objectList[i].ice_postUnmarshal();
- }
- catch(ex)
- {
- this._stream.instance.initializationData().logger.warning(
- "exception raised by ice_postUnmarshal:\n" + ex.toString());
- }
- }
- this._objectList = [];
- }
- }
- }
-});
-
-var EncapsDecoder10 = Class(EncapsDecoder, {
- __init__: function(stream, encaps, sliceObjects, f)
- {
- EncapsDecoder.call(this, stream, encaps, sliceObjects, f);
- this._sliceType = SliceType.NoSlice;
- },
- readObject: function(patcher)
- {
- Debug.assert(patcher !== null);
-
- //
- // Object references are encoded as a negative integer in 1.0.
- //
- var index = this._stream.readInt();
- if(index > 0)
- {
- throw new Ice.MarshalException("invalid object id");
- }
- index = -index;
-
- if(index === 0)
- {
- patcher.call(null, null);
- }
- else
- {
- this.addPatchEntry(index, patcher);
- }
- },
- throwException: function()
- {
- Debug.assert(this._sliceType === SliceType.NoSlice);
-
- //
- // User exception with the 1.0 encoding start with a boolean flag
- // that indicates whether or not the exception has classes.
- //
- // This allows reading the pending objects even if some part of
- // the exception was sliced.
- //
- var usesClasses = this._stream.readBool();
- this._sliceType = SliceType.ExceptionSlice;
- this._skipFirstSlice = false;
-
- //
- // Read the first slice header.
- //
- this.startSlice();
- var mostDerivedId = this._typeId;
- while(true)
- {
- var userEx = this._stream.createUserException(this._typeId);
-
- //
- // We found the exception.
- //
- if(userEx !== null)
- {
- userEx.__read(this._stream);
- if(usesClasses)
- {
- this.readPendingObjects();
- }
- throw userEx;
-
- // Never reached.
- }
-
- //
- // Slice off what we don't understand.
- //
- this.skipSlice();
- try
- {
- this.startSlice();
- }
- catch(ex)
- {
- //
- // An oversight in the 1.0 encoding means there is no marker to indicate
- // the last slice of an exception. As a result, we just try to read the
- // next type ID, which raises UnmarshalOutOfBoundsException when the
- // input buffer underflows.
- //
- // Set the reason member to a more helpful message.
- //
- if(ex instanceof Ice.UnmarshalOutOfBoundsException)
- {
- ex.reason = "unknown exception type `" + mostDerivedId + "'";
- }
- throw ex;
- }
- }
- },
- startInstance: function(sliceType)
- {
- Debug.assert(this._sliceType === sliceType);
- this._skipFirstSlice = true;
- },
- endInstance: function(/*preserve*/)
- {
- var sz;
- //
- // Read the Ice::Object slice.
- //
- if(this._sliceType === SliceType.ObjectSlice)
- {
- this.startSlice();
- sz = this._stream.readSize(); // For compatibility with the old AFM.
- if(sz !== 0)
- {
- throw new Ice.MarshalException("invalid Object slice");
- }
- this.endSlice();
- }
-
- this._sliceType = SliceType.NoSlice;
- return null;
- },
- startSlice: function()
- {
- var isIndex;
- //
- // If first slice, don't read the header, it was already read in
- // readInstance or throwException to find the factory.
- //
- if(this._skipFirstSlice)
- {
- this._skipFirstSlice = false;
- return this._typeId;
- }
-
- //
- // For objects, first read the type ID boolean which indicates
- // whether or not the type ID is encoded as a string or as an
- // index. For exceptions, the type ID is always encoded as a
- // string.
- //
- if(this._sliceType === SliceType.ObjectSlice) // For exceptions, the type ID is always encoded as a string
- {
- isIndex = this._stream.readBool();
- this._typeId = this.readTypeId(isIndex);
- }
- else
- {
- this._typeId = this._stream.readString();
- }
-
- this._sliceSize = this._stream.readInt();
- if(this._sliceSize < 4)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
-
- return this._typeId;
- },
- endSlice: function()
- {
- },
- skipSlice: function()
- {
- if(this._stream.instance.traceLevels().slicing > 0)
- {
- var logger = this._stream.instance.initializationData().logger;
- if(this._sliceType === SliceType.ObjectSlice)
- {
- TraceUtil.traceSlicing("object", this._typeId, this._stream.instance.traceLevels().slicingCat, logger);
- }
- else
- {
- TraceUtil.traceSlicing("exception", this._typeId, this._stream.instance.traceLevels().slicingCat, logger);
- }
- }
- Debug.assert(this._sliceSize >= 4);
- this._stream.skip(this._sliceSize - 4);
- },
- readPendingObjects: function()
- {
- var k, num;
- do
- {
- num = this._stream.readSize();
- for(k = num; k > 0; --k)
- {
- this.readInstance();
- }
- }
- while(num > 0);
-
- if(this._patchMap !== null && this._patchMap.size !== 0)
- {
- //
- // If any entries remain in the patch map, the sender has sent an index for an object, but failed
- // to supply the object.
- //
- throw new Ice.MarshalException("index for class received, but no instance");
- }
- },
- readInstance: function()
- {
- var index = this._stream.readInt(),
- mostDerivedId,
- v = null;
-
- if(index <= 0)
- {
- throw new Ice.MarshalException("invalid object id");
- }
-
- this._sliceType = SliceType.ObjectSlice;
- this._skipFirstSlice = false;
-
- //
- // Read the first slice header.
- //
- this.startSlice();
- mostDerivedId = this._typeId;
- while(true)
- {
- //
- // For the 1.0 encoding, the type ID for the base Object class
- // marks the last slice.
- //
- if(this._typeId == IceObject.ice_staticId())
- {
- throw new Ice.NoObjectFactoryException("", mostDerivedId);
- }
-
- v = this.newInstance(this._typeId);
-
- //
- // We found a factory, we get out of this loop.
- //
- if(v)
- {
- break;
- }
-
- //
- // If object slicing is disabled, stop un-marshalling.
- //
- if(!this._sliceObjects)
- {
- throw new Ice.NoObjectFactoryException("no object factory found and object slicing is disabled",
- this._typeId);
- }
-
- //
- // Slice off what we don't understand.
- //
- this.skipSlice();
- this.startSlice(); // Read next Slice header for next iteration.
- }
-
- //
- // Un-marshal the object and add-it to the map of un-marshaled objects.
- //
- this.unmarshal(index, v);
- }
-});
-
-var EncapsDecoder11 = Class(EncapsDecoder, {
- __init__: function(stream, encaps, sliceObjects, f)
- {
- EncapsDecoder.call(this, stream, encaps, sliceObjects, f);
- this._current = null;
- this._objectIdIndex = 1;
- },
- readObject: function(patcher)
- {
- Debug.assert(patcher !== undefined);
- var index = this._stream.readSize();
-
- if(index < 0)
- {
- throw new Ice.MarshalException("invalid object id");
- }
-
- if(index === 0)
- {
- if(patcher !== null)
- {
- patcher.call(null, null);
- }
- }
- else if(this._current !== null && (this._current.sliceFlags & FLAG_HAS_INDIRECTION_TABLE) !== 0)
- {
- //
- // When reading an object within a slice and there's an
- // indirect object table, always read an indirect reference
- // that points to an object from the indirect object table
- // marshaled at the end of the Slice.
- //
- // Maintain a list of indirect references. Note that the
- // indirect index starts at 1, so we decrement it by one to
- // derive an index into the indirection table that we'll read
- // at the end of the slice.
- //
- if(patcher !== null)
- {
- if(this._current.indirectPatchList === null) // Lazy initialization
- {
- this._current.indirectPatchList = []; // IndirectPatchEntry[]
- }
- var e = new IndirectPatchEntry();
- e.index = index - 1;
- e.patcher = patcher;
- this._current.indirectPatchList.push(e);
- }
- }
- else
- {
- this.readInstance(index, patcher);
- }
- },
- throwException: function()
- {
- Debug.assert(this._current === null);
- this.push(SliceType.ExceptionSlice);
-
- //
- // Read the first slice header.
- //
- this.startSlice();
- var mostDerivedId = this._current.typeId;
- while(true)
- {
-
- var userEx = this._stream.createUserException(this._current.typeId);
-
- //
- // We found the exception.
- //
- if(userEx !== null)
- {
- userEx.__read(this._stream);
- throw userEx;
-
- // Never reached.
- }
-
- //
- // Slice off what we don't understand.
- //
- this.skipSlice();
-
- if((this._current.sliceFlags & FLAG_IS_LAST_SLICE) !== 0)
- {
- if(mostDerivedId.indexOf("::") === 0)
- {
- throw new Ice.UnknownUserException(mostDerivedId.substr(2));
- }
- throw new Ice.UnknownUserException(mostDerivedId);
- }
-
- this.startSlice();
- }
- },
- startInstance: function(sliceType)
- {
- Debug.assert(sliceType !== undefined);
- Debug.assert(this._current.sliceType !== null && this._current.sliceType === sliceType);
- this._current.skipFirstSlice = true;
- },
- endInstance: function(preserve)
- {
- var slicedData = null;
- if(preserve)
- {
- slicedData = this.readSlicedData();
- }
- if(this._current.slices !== null)
- {
- this._current.slices.length = 0; // Clear the array.
- this._current.indirectionTables.length = 0; // Clear the array.
- }
- this._current = this._current.previous;
- return slicedData;
- },
- startSlice: function()
- {
- //
- // If first slice, don't read the header, it was already read in
- // readInstance or throwException to find the factory.
- //
- if(this._current.skipFirstSlice)
- {
- this._current.skipFirstSlice = false;
- return this._current.typeId;
- }
-
- this._current.sliceFlags = this._stream.readByte();
-
- //
- // Read the type ID, for object slices the type ID is encoded as a
- // string or as an index, for exceptions it's always encoded as a
- // string.
- //
- if(this._current.sliceType === SliceType.ObjectSlice)
- {
- if((this._current.sliceFlags & FLAG_HAS_TYPE_ID_COMPACT) === FLAG_HAS_TYPE_ID_COMPACT) // Must be checked 1st!
- {
- this._current.typeId = "";
- this._current.compactId = this._stream.readSize();
- }
- else if((this._current.sliceFlags & (FLAG_HAS_TYPE_ID_INDEX | FLAG_HAS_TYPE_ID_STRING)) !== 0)
- {
- this._current.typeId = this.readTypeId((this._current.sliceFlags & FLAG_HAS_TYPE_ID_INDEX) !== 0);
- this._current.compactId = -1;
- }
- else
- {
- // Only the most derived slice encodes the type ID for the compact format.
- this._current.typeId = "";
- this._current.compactId = -1;
- }
- }
- else
- {
- this._current.typeId = this._stream.readString();
- this._current.compactId = -1;
- }
-
- //
- // Read the slice size if necessary.
- //
- if((this._current.sliceFlags & FLAG_HAS_SLICE_SIZE) !== 0)
- {
- this._current.sliceSize = this._stream.readInt();
- if(this._current.sliceSize < 4)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- }
- else
- {
- this._current.sliceSize = 0;
- }
- return this._current.typeId;
- },
- endSlice: function()
- {
- var e,
- i,
- indirectionTable = [],
- length;
-
- if((this._current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) !== 0)
- {
- this._stream.skipOpts();
- }
-
- //
- // Read the indirection table if one is present and transform the
- // indirect patch list into patch entries with direct references.
- //
- if((this._current.sliceFlags & FLAG_HAS_INDIRECTION_TABLE) !== 0)
- {
- //
- // The table is written as a sequence<size> to conserve space.
- //
- length = this._stream.readAndCheckSeqSize(1);
- for(i = 0; i < length; ++i)
- {
- indirectionTable[i] = this.readInstance(this._stream.readSize(), null);
- }
-
- //
- // Sanity checks. If there are optional members, it's possible
- // that not all object references were read if they are from
- // unknown optional data members.
- //
- if(indirectionTable.length === 0)
- {
- throw new Ice.MarshalException("empty indirection table");
- }
- if((this._current.indirectPatchList === null || this._current.indirectPatchList.length === 0) &&
- (this._current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) === 0)
- {
- throw new Ice.MarshalException("no references to indirection table");
- }
-
- //
- // Convert indirect references into direct references.
- //
- if(this._current.indirectPatchList !== null)
- {
- for(i = 0, length = this._current.indirectPatchList.length; i < length; ++i)
- {
- e = this._current.indirectPatchList[i];
- Debug.assert(e.index >= 0);
- if(e.index >= indirectionTable.length)
- {
- throw new Ice.MarshalException("indirection out of range");
- }
- this.addPatchEntry(indirectionTable[e.index], e.patcher);
- }
- this._current.indirectPatchList.length = 0;
- }
- }
- },
- skipSlice: function()
- {
- if(this._stream.instance.traceLevels().slicing > 0)
- {
- var logger = this._stream.instance.initializationData().logger;
- var slicingCat = this._stream.instance.traceLevels().slicingCat;
- if(this._current.sliceType === SliceType.ExceptionSlice)
- {
- TraceUtil.traceSlicing("exception", this._current.typeId, slicingCat, logger);
- }
- else
- {
- TraceUtil.traceSlicing("object", this._current.typeId, slicingCat, logger);
- }
- }
-
- var start = this._stream.pos;
-
- if((this._current.sliceFlags & FLAG_HAS_SLICE_SIZE) !== 0)
- {
- Debug.assert(this._current.sliceSize >= 4);
- this._stream.skip(this._current.sliceSize - 4);
- }
- else
- {
- if(this._current.sliceType === SliceType.ObjectSlice)
- {
- throw new Ice.NoObjectFactoryException("no object factory found and compact format prevents slicing " +
- "(the sender should use the sliced format instead)",
- this._current.typeId);
- }
-
- if(this._current.typeId.indexOf("::") === 0)
- {
- throw new Ice.UnknownUserException(this._current.typeId.substring(2));
- }
-
- throw new Ice.UnknownUserException(this._current.typeId);
- }
-
- //
- // Preserve this slice.
- //
- var info = new Ice.SliceInfo();
- info.typeId = this._current.typeId;
- info.compactId = this._current.compactId;
- info.hasOptionalMembers = (this._current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) !== 0;
- info.isLastSlice = (this._current.sliceFlags & FLAG_IS_LAST_SLICE) !== 0;
-
- var b = this._stream._buf;
- var end = b.position;
- var dataEnd = end;
- if(info.hasOptionalMembers)
- {
- //
- // Don't include the optional member end marker. It will be re-written by
- // endSlice when the sliced data is re-written.
- //
- --dataEnd;
- }
-
- b.position = start;
- info.bytes = b.getArray(dataEnd - start);
- b.position = end;
-
- if(this._current.slices === null) // Lazy initialization
- {
- this._current.slices = []; // Ice.SliceInfo[]
- this._current.indirectionTables = []; // int[]
- }
-
- //
- // Read the indirect object table. We read the instances or their
- // IDs if the instance is a reference to an already un-marhsaled
- // object.
- //
- // The SliceInfo object sequence is initialized only if
- // readSlicedData is called.
- //
-
- if((this._current.sliceFlags & FLAG_HAS_INDIRECTION_TABLE) !== 0)
- {
- var length = this._stream.readAndCheckSeqSize(1);
- var indirectionTable = [];
- for(var i = 0; i < length; ++i)
- {
- indirectionTable[i] = this.readInstance(this._stream.readSize(), null);
- }
- this._current.indirectionTables.push(indirectionTable);
- }
- else
- {
- this._current.indirectionTables.push(null);
- }
- this._current.slices.push(info);
- },
- readOpt: function(readTag, expectedFormat)
- {
- if(this._current === null)
- {
- return this._stream.readOptImpl(readTag, expectedFormat);
- }
-
- if((this._current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) !== 0)
- {
- return this._stream.readOptImpl(readTag, expectedFormat);
- }
- return false;
- },
- readInstance: function(index, patcher)
- {
- Debug.assert(index > 0);
-
- var mostDerivedId,
- v = null;
-
- if(index > 1)
- {
- if(patcher !== null)
- {
- this.addPatchEntry(index, patcher);
- }
- return index;
- }
-
- this.push(SliceType.ObjectSlice);
-
- //
- // Get the object ID before we start reading slices. If some
- // slices are skiped, the indirect object table are still read and
- // might read other objects.
- //
- index = ++this._objectIdIndex;
-
- //
- // Read the first slice header.
- //
- this.startSlice();
- mostDerivedId = this._current.typeId;
- while(true)
- {
- if(this._current.compactId >= 0)
- {
- //
- // Translate a compact (numeric) type ID into a string type ID.
- //
- this._current.typeId = "";
- if(this._current.typeId.length === 0)
- {
- this._current.typeId = this._stream.getTypeId(this._current.compactId);
- }
- }
-
- if(this._current.typeId.length > 0)
- {
- v = this.newInstance(this._current.typeId);
- //
- // We found a factory, we get out of this loop.
- //
- if(v !== null && v !== undefined)
- {
- break;
- }
- }
-
- //
- // If object slicing is disabled, stop un-marshalling.
- //
- if(!this._sliceObjects)
- {
- throw new Ice.NoObjectFactoryException("no object factory found and object slicing is disabled",
- this._current.typeId);
- }
-
- //
- // Slice off what we don't understand.
- //
- this.skipSlice();
- //
- // If this is the last slice, keep the object as an opaque
- // UnknownSlicedData object.
- //
- if((this._current.sliceFlags & FLAG_IS_LAST_SLICE) !== 0)
- {
- v = new Ice.UnknownSlicedObject(mostDerivedId);
- break;
- }
-
- this.startSlice(); // Read next Slice header for next iteration.
- }
-
- //
- // Un-marshal the object
- //
- this.unmarshal(index, v);
- if(this._current === null && this._patchMap !== null && this._patchMap.size !== 0)
- {
- //
- // If any entries remain in the patch map, the sender has sent an index for an object, but failed
- // to supply the object.
- //
- throw new Ice.MarshalException("index for class received, but no instance");
- }
-
- if(patcher !== null)
- {
- patcher.call(null, v);
- }
- return index;
- },
- readSlicedData: function()
- {
- var i, ii, table, info, j, jj;
-
- if(this._current.slices === null) // No preserved slices.
- {
- return null;
- }
- //
- // The _indirectionTables member holds the indirection table for each slice
- // in _slices.
- //
- Debug.assert(this._current.slices.length === this._current.indirectionTables.length);
- for(i = 0, ii = this._current.slices.length; i < ii; ++i)
- {
- //
- // We use the "objects" list in SliceInfo to hold references
- // to the target objects. Note that the objects might not have
- // been read yet in the case of a circular reference to an
- // enclosing object.
- //
- table = this._current.indirectionTables[i];
- info = this._current.slices[i];
- info.objects = [];
- jj = table ? table.length : 0;
- for(j = 0; j < jj; ++j)
- {
- this.addPatchEntry(table[j], sequencePatcher(info.objects, j, IceObject));
- }
- }
- return new SlicedData(ArrayUtil.clone(this._current.slices));
- },
- push: function(sliceType)
- {
- if(this._current === null)
- {
- this._current = new EncapsDecoder11.InstanceData(null);
- }
- else
- {
- this._current = !this._current.next ? new EncapsDecoder11.InstanceData(this._current) : this._current.next;
- }
- this._current.sliceType = sliceType;
- this._current.skipFirstSlice = false;
- }
-});
-
-EncapsDecoder11.InstanceData = function(previous)
-{
- if(previous !== null)
- {
- previous.next = this;
- }
- this.previous = previous;
- this.next = null;
-
- // Instance attributes
- this.sliceType = null;
- this.skipFirstSlice = false;
- this.slices = null; // Preserved slices. Ice.SliceInfo[]
- this.indirectionTables = null; // int[]
-
- // Slice attributes
- this.sliceFlags = 0;
- this.sliceSize = 0;
- this.typeId = null;
- this.compactId = 0;
- this.indirectPatchList = null; // Lazy initialized, IndirectPatchEntry[]
-};
-
-var sequencePatcher = function(seq, index, T){
- return function(v)
- {
- if(v !== null && !(v instanceof T))
- {
- ExUtil.throwUOE(T.ice_staticId(), v);
- }
- seq[index] = v;
- };
-};
-
-var EncapsEncoder = Class({
- __init__: function(stream, encaps)
- {
- this._stream = stream;
- this._encaps = encaps;
- this._marshaledMap = new HashMap(); // HashMap<Ice.Object, int>;
- this._typeIdMap = null; // Lazy initialized. HashMap<String, int>
- this._typeIdIndex = 0;
- },
- writeOpt: function()
- {
- return false;
- },
- writePendingObjects: function()
- {
- return undefined;
- },
- registerTypeId: function(typeId)
- {
- if(this._typeIdMap === null) // Lazy initialization
- {
- this._typeIdMap = new HashMap(); // HashMap<String, int>
- }
-
- var p = this._typeIdMap.get(typeId);
- if(p !== undefined)
- {
- return p;
- }
- this._typeIdMap.set(typeId, ++this._typeIdIndex);
- return -1;
- }
-});
-
-var EncapsEncoder10 = Class(EncapsEncoder, {
- __init__: function(stream, encaps)
- {
- EncapsEncoder.call(this, stream, encaps);
- // Instance attributes
- this._sliceType = SliceType.NoSlice;
- this._writeSlice = 0; // Position of the slice data members
- // Encapsulation attributes for object marshalling.
- this._objectIdIndex = 0;
- this._toBeMarshaledMap = new HashMap(); // HashMap<Ice.Object, Integer>();
- },
- writeObject: function(v)
- {
- Debug.assert(v !== undefined);
- //
- // Object references are encoded as a negative integer in 1.0.
- //
- if(v !== null)
- {
- this._stream.writeInt(-this.registerObject(v));
- }
- else
- {
- this._stream.writeInt(0);
- }
- },
- writeUserException: function(v)
- {
- Debug.assert(v !== null && v !== undefined);
- //
- // User exception with the 1.0 encoding start with a boolean
- // flag that indicates whether or not the exception uses
- // classes.
- //
- // This allows reading the pending objects even if some part of
- // the exception was sliced.
- //
- var usesClasses = v.__usesClasses();
- this._stream.writeBool(usesClasses);
- v.__write(this._stream);
- if(usesClasses)
- {
- this.writePendingObjects();
- }
- },
- startInstance: function(sliceType)
- {
- this._sliceType = sliceType;
- },
- endInstance: function()
- {
- if(this._sliceType === SliceType.ObjectSlice)
- {
- //
- // Write the Object slice.
- //
- this.startSlice(IceObject.ice_staticId(), -1, true);
- this._stream.writeSize(0); // For compatibility with the old AFM.
- this.endSlice();
- }
- this._sliceType = SliceType.NoSlice;
- },
- startSlice: function(typeId)
- {
- //
- // For object slices, encode a boolean to indicate how the type ID
- // is encoded and the type ID either as a string or index. For
- // exception slices, always encode the type ID as a string.
- //
- if(this._sliceType === SliceType.ObjectSlice)
- {
- var index = this.registerTypeId(typeId);
- if(index < 0)
- {
- this._stream.writeBool(false);
- this._stream.writeString(typeId);
- }
- else
- {
- this._stream.writeBool(true);
- this._stream.writeSize(index);
- }
- }
- else
- {
- this._stream.writeString(typeId);
- }
-
- this._stream.writeInt(0); // Placeholder for the slice length.
-
- this._writeSlice = this._stream.pos;
- },
- endSlice: function()
- {
- //
- // Write the slice length.
- //
- var sz = this._stream.pos - this._writeSlice + 4;
- this._stream.rewriteInt(sz, this._writeSlice - 4);
- },
- writePendingObjects: function()
- {
- var self = this,
- writeCB = function(key, value)
- {
- //
- // Ask the instance to marshal itself. Any new class
- // instances that are triggered by the classes marshaled
- // are added to toBeMarshaledMap.
- //
- self._stream.writeInt(value);
-
- try
- {
- key.ice_preMarshal();
- }
- catch(ex)
- {
- self._stream.instance.initializationData().logger.warning(
- "exception raised by ice_preMarshal:\n" + ex.toString());
- }
-
- key.__write(self._stream);
- },
- savedMap;
-
- while(this._toBeMarshaledMap.size > 0)
- {
- //
- // Consider the to be marshalled objects as marshalled now,
- // this is necessary to avoid adding again the "to be
- // marshalled objects" into _toBeMarshaledMap while writing
- // objects.
- //
- this._marshaledMap.merge(this._toBeMarshaledMap);
-
- savedMap = this._toBeMarshaledMap;
- this._toBeMarshaledMap = new HashMap(); // HashMap<Ice.Object, int>();
- this._stream.writeSize(savedMap.size);
- savedMap.forEach(writeCB);
- }
- this._stream.writeSize(0); // Zero marker indicates end of sequence of sequences of instances.
- },
- registerObject: function(v)
- {
- Debug.assert(v !== null);
-
- //
- // Look for this instance in the to-be-marshaled map.
- //
- var p = this._toBeMarshaledMap.get(v);
- if(p !== undefined)
- {
- return p;
- }
-
- //
- // Didn't find it, try the marshaled map next.
- //
- p = this._marshaledMap.get(v);
- if(p !== undefined)
- {
- return p;
- }
-
- //
- // We haven't seen this instance previously, create a new
- // index, and insert it into the to-be-marshaled map.
- //
- this._toBeMarshaledMap.set(v, ++this._objectIdIndex);
- return this._objectIdIndex;
- }
-});
-
-var EncapsEncoder11 = Class(EncapsEncoder, {
- __init__: function(stream, encaps)
- {
- EncapsEncoder.call(this, stream, encaps);
- this._current = null;
- this._objectIdIndex = 1;
- },
- writeObject: function(v)
- {
- Debug.assert(v !== undefined);
- var index, idx;
- if(v === null)
- {
- this._stream.writeSize(0);
- }
- else if(this._current !== null && this._encaps.format === FormatType.SlicedFormat)
- {
- if(this._current.indirectionTable === null) // Lazy initialization
- {
- this._current.indirectionTable = []; // Ice.Object[]
- this._current.indirectionMap = new HashMap(); // HashMap<Ice.Object, int>
- }
-
- //
- // If writting an object within a slice and using the sliced
- // format, write an index from the object indirection
- // table. The indirect object table is encoded at the end of
- // each slice and is always read (even if the Slice is
- // unknown).
- //
- index = this._current.indirectionMap.get(v);
- if(index === undefined)
- {
- this._current.indirectionTable.push(v);
- idx = this._current.indirectionTable.length; // Position + 1 (0 is reserved for nil)
- this._current.indirectionMap.set(v, idx);
- this._stream.writeSize(idx);
- }
- else
- {
- this._stream.writeSize(index);
- }
- }
- else
- {
- this.writeInstance(v); // Write the instance or a reference if already marshaled.
- }
- },
- writePendingObjects: function()
- {
- return undefined;
- },
- writeUserException: function(v)
- {
- Debug.assert(v !== null && v !== undefined);
- v.__write(this._stream);
- },
- startInstance: function(sliceType, data)
- {
- if(this._current === null)
- {
- this._current = new EncapsEncoder11.InstanceData(null);
- }
- else
- {
- this._current = (this._current.next === null) ? new EncapsEncoder11.InstanceData(this._current) : this._current.next;
- }
- this._current.sliceType = sliceType;
- this._current.firstSlice = true;
-
- if(data !== null && data !== undefined)
- {
- this.writeSlicedData(data);
- }
- },
- endInstance: function()
- {
- this._current = this._current.previous;
- },
- startSlice: function(typeId, compactId, last)
- {
- Debug.assert((this._current.indirectionTable === null || this._current.indirectionTable.length === 0) &&
- (this._current.indirectionMap === null || this._current.indirectionMap.size === 0));
-
- this._current.sliceFlagsPos = this._stream.pos;
-
- this._current.sliceFlags = 0;
- if(this._encaps.format === FormatType.SlicedFormat)
- {
- this._current.sliceFlags |= FLAG_HAS_SLICE_SIZE; // Encode the slice size if using the sliced format.
- }
- if(last)
- {
- this._current.sliceFlags |= FLAG_IS_LAST_SLICE; // This is the last slice.
- }
-
- this._stream.writeByte(0); // Placeholder for the slice flags
-
- //
- // For object slices, encode the flag and the type ID either as a
- // string or index. For exception slices, always encode the type
- // ID a string.
- //
- if(this._current.sliceType === SliceType.ObjectSlice)
- {
- //
- // Encode the type ID (only in the first slice for the compact
- // encoding).
- //
- if(this._encaps.format === FormatType.SlicedFormat || this._current.firstSlice)
- {
- if(compactId >= 0)
- {
- this._current.sliceFlags |= FLAG_HAS_TYPE_ID_COMPACT;
- this._stream.writeSize(compactId);
- }
- else
- {
- var index = this.registerTypeId(typeId);
- if(index < 0)
- {
- this._current.sliceFlags |= FLAG_HAS_TYPE_ID_STRING;
- this._stream.writeString(typeId);
- }
- else
- {
- this._current.sliceFlags |= FLAG_HAS_TYPE_ID_INDEX;
- this._stream.writeSize(index);
- }
- }
- }
- }
- else
- {
- this._stream.writeString(typeId);
- }
-
- if((this._current.sliceFlags & FLAG_HAS_SLICE_SIZE) !== 0)
- {
- this._stream.writeInt(0); // Placeholder for the slice length.
- }
-
- this._current.writeSlice = this._stream.pos;
- this._current.firstSlice = false;
- },
- endSlice: function()
- {
- var sz, i, length;
-
- //
- // Write the optional member end marker if some optional members
- // were encoded. Note that the optional members are encoded before
- // the indirection table and are included in the slice size.
- //
- if((this._current.sliceFlags & FLAG_HAS_OPTIONAL_MEMBERS) !== 0)
- {
- this._stream.writeByte(OPTIONAL_END_MARKER);
- }
-
- //
- // Write the slice length if necessary.
- //
- if((this._current.sliceFlags & FLAG_HAS_SLICE_SIZE) !== 0)
- {
- sz = this._stream.pos - this._current.writeSlice + 4;
- this._stream.rewriteInt(sz, this._current.writeSlice - 4);
- }
-
- //
- // Only write the indirection table if it contains entries.
- //
- if(this._current.indirectionTable !== null && this._current.indirectionTable.length !== 0)
- {
- Debug.assert(this._encaps.format === FormatType.SlicedFormat);
- this._current.sliceFlags |= FLAG_HAS_INDIRECTION_TABLE;
-
- //
- // Write the indirection object table.
- //
- this._stream.writeSize(this._current.indirectionTable.length);
- for(i = 0, length = this._current.indirectionTable.length; i < length; ++i)
- {
- this.writeInstance(this._current.indirectionTable[i]);
- }
- this._current.indirectionTable.length = 0; // Faster way to clean array in JavaScript
- this._current.indirectionMap.clear();
- }
-
- //
- // Finally, update the slice flags.
- //
- this._stream.rewriteByte(this._current.sliceFlags, this._current.sliceFlagsPos);
- },
- writeOpt: function(tag, format)
- {
- if(this._current === null)
- {
- return this._stream.writeOptImpl(tag, format);
- }
-
- if(this._stream.writeOptImpl(tag, format))
- {
- this._current.sliceFlags |= FLAG_HAS_OPTIONAL_MEMBERS;
- return true;
- }
-
- return false;
- },
- writeSlicedData: function(slicedData)
- {
- Debug.assert(slicedData !== null && slicedData !== undefined);
-
- //
- // We only remarshal preserved slices if we are using the sliced
- // format. Otherwise, we ignore the preserved slices, which
- // essentially "slices" the object into the most-derived type
- // known by the sender.
- //
- if(this._encaps.format !== FormatType.SlicedFormat)
- {
- return;
- }
-
- var i, ii, info,
- j, jj;
-
- for(i = 0, ii = slicedData.slices.length; i < ii; ++i)
- {
- info = slicedData.slices[i];
- this.startSlice(info.typeId, info.compactId, info.isLastSlice);
-
- //
- // Write the bytes associated with this slice.
- //
- this._stream.writeBlob(info.bytes);
-
- if(info.hasOptionalMembers)
- {
- this._current.sliceFlags |= FLAG_HAS_OPTIONAL_MEMBERS;
- }
-
- //
- // Make sure to also re-write the object indirection table.
- //
- if(info.objects !== null && info.objects.length > 0)
- {
- if(this._current.indirectionTable === null) // Lazy initialization
- {
- this._current.indirectionTable = []; // Ice.Object[]
- this._current.indirectionMap = new HashMap(); // HashMap<Ice.Object, int>
- }
-
- for(j = 0, jj = info.objects.length; j < jj; ++j)
- {
- this._current.indirectionTable.push(info.objects[j]);
- }
- }
-
- this.endSlice();
- }
- },
- writeInstance: function(v)
- {
- Debug.assert(v !== null && v !== undefined);
-
- //
- // If the instance was already marshaled, just write it's ID.
- //
- var p = this._marshaledMap.get(v);
- if(p !== undefined)
- {
- this._stream.writeSize(p);
- return;
- }
-
- //
- // We haven't seen this instance previously, create a new ID,
- // insert it into the marshaled map, and write the instance.
- //
- this._marshaledMap.set(v, ++this._objectIdIndex);
-
- try
- {
- v.ice_preMarshal();
- }
- catch(ex)
- {
- this._stream.instance.initializationData().logger.warning("exception raised by ice_preMarshal:\n" +
- ex.toString());
- }
-
- this._stream.writeSize(1); // Object instance marker.
- v.__write(this._stream);
- }
-});
-
-EncapsEncoder11.InstanceData = function(previous)
-{
- Debug.assert(previous !== undefined);
- if(previous !== null)
- {
- previous.next = this;
- }
- this.previous = previous;
- this.next = null;
-
- // Instance attributes
- this.sliceType = null;
- this.firstSlice = false;
-
- // Slice attributes
- this.sliceFlags = 0;
- this.writeSlice = 0; // Position of the slice data members
- this.sliceFlagsPos = 0; // Position of the slice flags
- this.indirectionTable = null; // Ice.Object[]
- this.indirectionMap = null; // HashMap<Ice.Object, int>
-};
-
-var ReadEncaps = Class({
- __init__: function()
- {
- this.start = 0;
- this.sz = 0;
- this.encoding = null;
- this.encoding_1_0 = false;
- this.decoder = null;
- this.next = null;
- },
- reset: function()
- {
- this.decoder = null;
- },
- setEncoding: function(encoding)
- {
- this.encoding = encoding;
- this.encoding_1_0 = encoding.equals(Ice.Encoding_1_0);
- }
-});
-
-var WriteEncaps = Class({
- __init__: function()
- {
- this.start = 0;
- this.format = FormatType.DefaultFormat;
- this.encoding = null;
- this.encoding_1_0 = false;
- this.encoder = null;
- this.next = null;
- },
- reset: function()
- {
- this.encoder = null;
- },
- setEncoding: function(encoding)
- {
- this.encoding = encoding;
- this.encoding_1_0 = encoding.equals(Ice.Encoding_1_0);
- }
-});
-
-var BasicStream = Class({
- __init__: function(instance, encoding, data)
- {
- this._instance = instance;
- this._closure = null;
- this._encoding = encoding;
-
- this._readEncapsStack = null;
- this._writeEncapsStack = null;
- this._readEncapsCache = null;
- this._writeEncapsCache = null;
-
- this._sliceObjects = true;
-
- this._startSeq = -1;
- this._sizePos = -1;
-
- if(data !== undefined)
- {
- this._buf = new Ice.Buffer(data);
- }
- else
- {
- this._buf = new Ice.Buffer();
- }
- },
- //
- // This function allows this object to be reused, rather than
- // reallocated.
- //
- reset: function()
- {
- this._buf.reset();
- this.clear();
- },
- clear: function()
- {
- if(this._readEncapsStack !== null)
- {
- Debug.assert(this._readEncapsStack.next);
- this._readEncapsStack.next = this._readEncapsCache;
- this._readEncapsCache = this._readEncapsStack;
- this._readEncapsCache.reset();
- this._readEncapsStack = null;
- }
-
- if(this._writeEncapsStack !== null)
- {
- Debug.assert(this._writeEncapsStack.next);
- this._writeEncapsStack.next = this._writeEncapsCache;
- this._writeEncapsCache = this._writeEncapsStack;
- this._writeEncapsCache.reset();
- this._writeEncapsStack = null;
- }
- this._startSeq = -1;
- this._sliceObjects = true;
- },
- swap: function(other)
- {
- Debug.assert(this._instance === other._instance);
-
- var tmpBuf, tmpClosure, tmpStartSeq, tmpMinSeqSize, tmpSizePos;
-
- tmpBuf = other._buf;
- other._buf = this._buf;
- this._buf = tmpBuf;
-
- tmpClosure = other._closure;
- other._closure = this._closure;
- this._closure = tmpClosure;
-
- //
- // Swap is never called for BasicStreams that have encapsulations being read/write. However,
- // encapsulations might still be set in case marshalling or un-marshalling failed. We just
- // reset the encapsulations if there are still some set.
- //
- this.resetEncaps();
- other.resetEncaps();
-
- tmpStartSeq = other._startSeq;
- other._startSeq = this._startSeq;
- this._startSeq = tmpStartSeq;
-
- tmpMinSeqSize = other._minSeqSize;
- other._minSeqSize = this._minSeqSize;
- this._minSeqSize = tmpMinSeqSize;
-
- tmpSizePos = other._sizePos;
- other._sizePos = this._sizePos;
- this._sizePos = tmpSizePos;
- },
- resetEncaps: function()
- {
- this._readEncapsStack = null;
- this._writeEncapsStack = null;
- },
- resize: function(sz)
- {
- this._buf.resize(sz);
- this._buf.position = sz;
- },
- prepareWrite: function()
- {
- this._buf.position = 0;
- return this._buf;
- },
- startWriteObject: function(data)
- {
- Debug.assert(this._writeEncapsStack !== null && this._writeEncapsStack.encoder !== null);
- this._writeEncapsStack.encoder.startInstance(SliceType.ObjectSlice, data);
- },
- endWriteObject: function()
- {
- Debug.assert(this._writeEncapsStack !== null && this._writeEncapsStack.encoder !== null);
- this._writeEncapsStack.encoder.endInstance();
- },
- startReadObject: function()
- {
- Debug.assert(this._readEncapsStack !== null && this._readEncapsStack.decoder !== null);
- this._readEncapsStack.decoder.startInstance(SliceType.ObjectSlice);
- },
- endReadObject: function(preserve)
- {
- Debug.assert(this._readEncapsStack !== null && this._readEncapsStack.decoder !== null);
- return this._readEncapsStack.decoder.endInstance(preserve);
- },
- startWriteException: function(data)
- {
- Debug.assert(this._writeEncapsStack !== null && this._writeEncapsStack.encoder !== null);
- this._writeEncapsStack.encoder.startInstance(SliceType.ExceptionSlice, data);
- },
- endWriteException: function()
- {
- Debug.assert(this._writeEncapsStack !== null && this._writeEncapsStack.encoder !== null);
- this._writeEncapsStack.encoder.endInstance();
- },
- startReadException: function()
- {
- Debug.assert(this._readEncapsStack !== null && this._readEncapsStack.decoder !== null);
- this._readEncapsStack.decoder.startInstance(SliceType.ExceptionSlice);
- },
- endReadException: function(preserve)
- {
- Debug.assert(this._readEncapsStack !== null && this._readEncapsStack.decoder !== null);
- return this._readEncapsStack.decoder.endInstance(preserve);
- },
- startWriteEncaps: function(encoding, format)
- {
- //
- // If no encoding version is specified, use the current write
- // encapsulation encoding version if there's a current write
- // encapsulation, otherwise, use the stream encoding version.
- //
-
- if(encoding === undefined)
- {
- if(this._writeEncapsStack !== null)
- {
- encoding = this._writeEncapsStack.encoding;
- format = this._writeEncapsStack.format;
- }
- else
- {
- encoding = this._encoding;
- format = FormatType.DefaultFormat;
- }
- }
-
- Protocol.checkSupportedEncoding(encoding);
-
- var curr = this._writeEncapsCache;
- if(curr !== null)
- {
- curr.reset();
- this._writeEncapsCache = this._writeEncapsCache.next;
- }
- else
- {
- curr = new WriteEncaps();
- }
- curr.next = this._writeEncapsStack;
- this._writeEncapsStack = curr;
-
- this._writeEncapsStack.format = format;
- this._writeEncapsStack.setEncoding(encoding);
- this._writeEncapsStack.start = this._buf.limit;
-
- this.writeInt(0); // Placeholder for the encapsulation length.
- this._writeEncapsStack.encoding.__write(this);
- },
- endWriteEncaps: function()
- {
- Debug.assert(this._writeEncapsStack);
-
- // Size includes size and version.
- var start = this._writeEncapsStack.start;
-
- var sz = this._buf.limit - start;
- this._buf.putIntAt(start, sz);
-
- var curr = this._writeEncapsStack;
- this._writeEncapsStack = curr.next;
- curr.next = this._writeEncapsCache;
- this._writeEncapsCache = curr;
- this._writeEncapsCache.reset();
- },
- endWriteEncapsChecked: function() // Used by public stream API.
- {
- if(this._writeEncapsStack === null)
- {
- throw new Ice.EncapsulationException("not in an encapsulation");
- }
- this.endWriteEncaps();
- },
- writeEmptyEncaps: function(encoding)
- {
- Protocol.checkSupportedEncoding(encoding);
- this.writeInt(6); // Size
- encoding.__write(this);
- },
- writeEncaps: function(v)
- {
- if(v.length < 6)
- {
- throw new Ice.EncapsulationException();
- }
- this.expand(v.length);
- this._buf.putArray(v);
- },
- getWriteEncoding: function()
- {
- return this._writeEncapsStack !== null ? this._writeEncapsStack.encoding : this._encoding;
- },
- startReadEncaps: function()
- {
- var curr = this._readEncapsCache;
- if(curr !== null)
- {
- curr.reset();
- this._readEncapsCache = this._readEncapsCache.next;
- }
- else
- {
- curr = new ReadEncaps();
- }
- curr.next = this._readEncapsStack;
- this._readEncapsStack = curr;
-
- this._readEncapsStack.start = this._buf.position;
-
- //
- // I don't use readSize() and writeSize() for encapsulations,
- // because when creating an encapsulation, I must know in advance
- // how many bytes the size information will require in the data
- // stream. If I use an Int, it is always 4 bytes. For
- // readSize()/writeSize(), it could be 1 or 5 bytes.
- //
- var sz = this.readInt();
- if(sz < 6)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- if(sz - 4 > this._buf.remaining)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- this._readEncapsStack.sz = sz;
-
- var encoding = new Ice.EncodingVersion();
- encoding.__read(this);
- Protocol.checkSupportedEncoding(encoding); // Make sure the encoding is supported.
- this._readEncapsStack.setEncoding(encoding);
-
- return encoding;
- },
- endReadEncaps: function()
- {
- Debug.assert(this._readEncapsStack !== null);
-
- if(!this._readEncapsStack.encoding_1_0)
- {
- this.skipOpts();
- if(this._buf.position !== this._readEncapsStack.start + this._readEncapsStack.sz)
- {
- throw new Ice.EncapsulationException();
- }
- }
- else if(this._buf.position !== this._readEncapsStack.start + this._readEncapsStack.sz)
- {
- if(this._buf.position + 1 !== this._readEncapsStack.start + this._readEncapsStack.sz)
- {
- throw new Ice.EncapsulationException();
- }
-
- //
- // Ice version < 3.3 had a bug where user exceptions with
- // class members could be encoded with a trailing byte
- // when dispatched with AMD. So we tolerate an extra byte
- // in the encapsulation.
- //
-
- try
- {
- this._buf.get();
- }
- catch(ex)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- }
-
- var curr = this._readEncapsStack;
- this._readEncapsStack = curr.next;
- curr.next = this._readEncapsCache;
- this._readEncapsCache = curr;
- this._readEncapsCache.reset();
- },
- skipEmptyEncaps: function()
- {
- var sz = this.readInt();
- if(sz < 6)
- {
- throw new Ice.EncapsulationException();
- }
- if(sz - 4 > this._buf.remaining)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
-
- var encoding = new Ice.EncodingVersion();
- encoding.__read(this);
- if(encoding.equals(Ice.Encoding_1_0))
- {
- if(sz != 6)
- {
- throw new Ice.EncapsulationException();
- }
- }
- else
- {
- // Skip the optional content of the encapsulation if we are expecting an
- // empty encapsulation.
- this._buf.position = this._buf.position + sz - 6;
- }
- return encoding;
- },
- endReadEncapsChecked: function() // Used by public stream API.
- {
- if(this._readEncapsStack === null)
- {
- throw new Ice.EncapsulationException("not in an encapsulation");
- }
- this.endReadEncaps();
- },
- readEncaps: function(encoding)
- {
- Debug.assert(encoding !== undefined);
- var sz = this.readInt();
- if(sz < 6)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
-
- if(sz - 4 > this._buf.remaining)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
-
- if(encoding !== null)
- {
- encoding.__read(this);
- this._buf.position = this._buf.position - 6;
- }
- else
- {
- this._buf.position = this._buf.position - 4;
- }
-
- try
- {
- return this._buf.getArray(sz);
- }
- catch(ex)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- },
- getReadEncoding: function()
- {
- return this._readEncapsStack !== null ? this._readEncapsStack.encoding : this._encoding;
- },
- getReadEncapsSize: function()
- {
- Debug.assert(this._readEncapsStack !== null);
- return this._readEncapsStack.sz - 6;
- },
- skipEncaps: function()
- {
- var sz = this.readInt();
- if(sz < 6)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- var encoding = new Ice.EncodingVersion();
- encoding.__read(this);
- try
- {
- this._buf.position = this._buf.position + sz - 6;
- }
- catch(ex)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- return encoding;
- },
- startWriteSlice: function(typeId, compactId, last)
- {
- Debug.assert(this._writeEncapsStack !== null && this._writeEncapsStack.encoder !== null);
- this._writeEncapsStack.encoder.startSlice(typeId, compactId, last);
- },
- endWriteSlice: function()
- {
- Debug.assert(this._writeEncapsStack !== null && this._writeEncapsStack.encoder !== null);
- this._writeEncapsStack.encoder.endSlice();
- },
- startReadSlice: function() // Returns type ID of next slice
- {
- Debug.assert(this._readEncapsStack !== null && this._readEncapsStack.decoder !== null);
- return this._readEncapsStack.decoder.startSlice();
- },
- endReadSlice: function()
- {
- Debug.assert(this._readEncapsStack !== null && this._readEncapsStack.decoder !== null);
- this._readEncapsStack.decoder.endSlice();
- },
- skipSlice: function()
- {
- Debug.assert(this._readEncapsStack !== null && this._readEncapsStack.decoder !== null);
- this._readEncapsStack.decoder.skipSlice();
- },
- readPendingObjects: function()
- {
- if(this._readEncapsStack !== null && this._readEncapsStack.decoder !== null)
- {
- this._readEncapsStack.decoder.readPendingObjects();
- }
- else if((this._readEncapsStack !== null && this._readEncapsStack.encoding_1_0) ||
- (this._readEncapsStack === null && this._encoding.equals(Ice.Encoding_1_0)))
- {
- //
- // If using the 1.0 encoding and no objects were read, we
- // still read an empty sequence of pending objects if
- // requested (i.e.: if this is called).
- //
- // This is required by the 1.0 encoding, even if no objects
- // are written we do marshal an empty sequence if marshaled
- // data types use classes.
- //
- this.skipSize();
- }
- },
- writePendingObjects: function()
- {
- if(this._writeEncapsStack !== null && this._writeEncapsStack.encoder !== null)
- {
- this._writeEncapsStack.encoder.writePendingObjects();
- }
- else if((this._writeEncapsStack !== null && this._writeEncapsStack.encoding_1_0) ||
- (this._writeEncapsStack === null && this._encoding.equals(Ice.Encoding_1_0)))
- {
- //
- // If using the 1.0 encoding and no objects were written, we
- // still write an empty sequence for pending objects if
- // requested (i.e.: if this is called).
- //
- // This is required by the 1.0 encoding, even if no objects
- // are written we do marshal an empty sequence if marshaled
- // data types use classes.
- //
- this.writeSize(0);
- }
- },
- writeSize: function(v)
- {
- if(v > 254)
- {
- this.expand(5);
- this._buf.put(255);
- this._buf.putInt(v);
- }
- else
- {
- this.expand(1);
- this._buf.put(v);
- }
- },
- readSize: function()
- {
- try
- {
- var b = this._buf.get();
- if(b === 255)
- {
- var v = this._buf.getInt();
- if(v < 0)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- return v;
- }
- return b;
- }
- catch(ex)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- },
- readAndCheckSeqSize: function(minSize)
- {
- var sz = this.readSize();
-
- if(sz === 0)
- {
- return sz;
- }
-
- //
- // The _startSeq variable points to the start of the sequence for which
- // we expect to read at least _minSeqSize bytes from the stream.
- //
- // If not initialized or if we already read more data than _minSeqSize,
- // we reset _startSeq and _minSeqSize for this sequence (possibly a
- // top-level sequence or enclosed sequence it doesn't really matter).
- //
- // Otherwise, we are reading an enclosed sequence and we have to bump
- // _minSeqSize by the minimum size that this sequence will require on
- // the stream.
- //
- // The goal of this check is to ensure that when we start un-marshalling
- // a new sequence, we check the minimal size of this new sequence against
- // the estimated remaining buffer size. This estimatation is based on
- // the minimum size of the enclosing sequences, it's _minSeqSize.
- //
- if(this._startSeq === -1 || this._buf.position > (this._startSeq + this._minSeqSize))
- {
- this._startSeq = this._buf.position;
- this._minSeqSize = sz * minSize;
- }
- else
- {
- this._minSeqSize += sz * minSize;
- }
-
- //
- // If there isn't enough data to read on the stream for the sequence (and
- // possibly enclosed sequences), something is wrong with the marshalled
- // data: it's claiming having more data that what is possible to read.
- //
- if(this._startSeq + this._minSeqSize > this._buf.limit)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
-
- return sz;
- },
- startSize: function()
- {
- var pos = this._buf.position;
- this.writeInt(0); // Placeholder for 32-bit size
- return pos;
- },
- endSize: function(pos)
- {
- Debug.assert(pos >= 0);
- this.rewriteInt(this._buf.position - pos - 4, pos);
- },
- writeBlob: function(v)
- {
- if(v === null)
- {
- return;
- }
- this.expand(v.length);
- this._buf.putArray(v);
- },
- readBlob: function(sz)
- {
- if(this._buf.remaining < sz)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- try
- {
- return this._buf.getArray(sz);
- }
- catch(ex)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- },
- // Read/write format and tag for optionals
- writeOpt: function(tag, format)
- {
- Debug.assert(this._writeEncapsStack !== null);
- if(this._writeEncapsStack.encoder !== null)
- {
- return this._writeEncapsStack.encoder.writeOpt(tag, format);
- }
- return this.writeOptImpl(tag, format);
- },
- readOpt: function(tag, expectedFormat)
- {
- Debug.assert(this._readEncapsStack !== null);
- if(this._readEncapsStack.decoder !== null)
- {
- return this._readEncapsStack.decoder.readOpt(tag, expectedFormat);
- }
- return this.readOptImpl(tag, expectedFormat);
- },
- writeOptValue: function(tag, format, write, v)
- {
- if(v !== undefined)
- {
- if(this.writeOpt(tag, format))
- {
- write.call(this, v);
- }
- }
- },
- readOptValue: function(tag, format, read)
- {
- if(this.readOpt(tag, format))
- {
- return read.call(this);
- }
- else
- {
- return undefined;
- }
- },
- writeByte: function(v)
- {
- this.expand(1);
- this._buf.put(v);
- },
- rewriteByte: function(v, dest)
- {
- this._buf.putAt(dest, v);
- },
- readByte: function()
- {
- try
- {
- return this._buf.get();
- }
- catch(ex)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- },
- writeByteSeq: function(v)
- {
- if(v === null || v.length === 0)
- {
- this.writeSize(0);
- }
- else
- {
- this.writeSize(v.length);
- this.expand(v.length);
- this._buf.putArray(v);
- }
- },
- readByteSeq: function()
- {
- return this._buf.getArray(this.readAndCheckSeqSize(1));
- },
- writeBool: function(v)
- {
- this.expand(1);
- this._buf.put(v ? 1 : 0);
- },
- rewriteBool: function(v, dest)
- {
- this._buf.putAt(dest, v ? 1 : 0);
- },
- readBool: function()
- {
- try
- {
- return this._buf.get() === 1;
- }
- catch(ex)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- },
- writeShort: function(v)
- {
- this.expand(2);
- this._buf.putShort(v);
- },
- readShort: function()
- {
- try
- {
- return this._buf.getShort();
- }
- catch(ex)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- },
- writeInt: function(v)
- {
- this.expand(4);
- this._buf.putInt(v);
- },
- rewriteInt: function(v, dest)
- {
- this._buf.putIntAt(dest, v);
- },
- readInt: function()
- {
- try
- {
- return this._buf.getInt();
- }
- catch(ex)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- },
- writeLong: function(v)
- {
- this.expand(8);
- this._buf.putLong(v);
- },
- readLong: function()
- {
- try
- {
- return this._buf.getLong();
- }
- catch(ex)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- },
- writeFloat: function(v)
- {
- this.expand(4);
- this._buf.putFloat(v);
- },
- readFloat: function()
- {
- try
- {
- return this._buf.getFloat();
- }
- catch(ex)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- },
- writeDouble: function(v)
- {
- this.expand(8);
- this._buf.putDouble(v);
- },
- readDouble: function()
- {
- try
- {
- return this._buf.getDouble();
- }
- catch(ex)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- },
- writeString: function(v)
- {
- if(v === null || v.length === 0)
- {
- this.writeSize(0);
- }
- else
- {
- this._buf.writeString(this, v);
- }
- },
- readString: function()
- {
- var len = this.readSize();
- if(len === 0)
- {
- return "";
- }
- //
- // Check the buffer has enough bytes to read.
- //
- if(this._buf.remaining < len)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
-
- try
- {
- return this._buf.getString(len);
- }
- catch(ex)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- },
- writeProxy: function(v)
- {
- this._instance.proxyFactory().proxyToStream(v, this);
- },
- writeOptProxy: function(tag, v)
- {
- if(v !== undefined)
- {
- if(this.writeOpt(tag, OptionalFormat.FSize))
- {
- var pos = this.startSize();
- this.writeProxy(v);
- this.endSize(pos);
- }
- }
- },
- readProxy: function(type)
- {
- return this._instance.proxyFactory().streamToProxy(this, type);
- },
- readOptProxy: function(tag, type)
- {
- if(this.readOpt(tag, OptionalFormat.FSize))
- {
- this.skip(4);
- return this.readProxy(type);
- }
- else
- {
- return undefined;
- }
- },
- writeEnum: function(v)
- {
- if(this.isWriteEncoding_1_0())
- {
- if(v.maxValue < 127)
- {
- this.writeByte(v.value);
- }
- else if(v.maxValue < 32767)
- {
- this.writeShort(v.value);
- }
- else
- {
- this.writeInt(v.value);
- }
- }
- else
- {
- this.writeSize(v.value);
- }
- },
- readEnum: function(T)
- {
- var v;
- if(this.getReadEncoding().equals(Ice.Encoding_1_0))
- {
- if(T.maxValue < 127)
- {
- v = this.readByte();
- }
- else if(T.maxValue < 32767)
- {
- v = this.readShort();
- }
- else
- {
- v = this.readInt();
- }
- }
- else
- {
- v = this.readSize();
- }
-
- var e = T.valueOf(v);
- if(e === undefined)
- {
- throw new Ice.MarshalException("enumerator value " + v + " is out of range");
- }
- return e;
- },
- readOptEnum: function(tag, T)
- {
- if(this.readOpt(tag, OptionalFormat.Size))
- {
- return this.readEnum(T);
- }
- else
- {
- return undefined;
- }
- },
- writeObject: function(v)
- {
- this.initWriteEncaps();
- this._writeEncapsStack.encoder.writeObject(v);
- },
- writeOptObject: function(tag, v)
- {
- if(v !== undefined)
- {
- if(this.writeOpt(tag, OptionalFormat.Class))
- {
- this.writeObject(v);
- }
- }
- },
- readObject: function(patcher, T)
- {
- this.initReadEncaps();
- //
- // BUGFIX:
- // With Chrome linux the invokation of readObject on the decoder some times
- // calls BasicStream.readObject with the decoder object as this param.
- // Use call instead of directly invoke the method to workaround this bug.
- //
- this._readEncapsStack.decoder.readObject.call(
- this._readEncapsStack.decoder,
- function(obj){
- if(obj !== null && !(obj.ice_instanceof(T)))
- {
- ExUtil.throwUOE(T.ice_staticId(), obj);
- }
- patcher(obj);
- });
- },
- readOptObject: function(tag, patcher, T)
- {
- if(this.readOpt(tag, OptionalFormat.Class))
- {
- this.readObject(patcher, T);
- }
- else
- {
- patcher(undefined);
- }
- },
- writeUserException: function(e)
- {
- this.initWriteEncaps();
- this._writeEncapsStack.encoder.writeUserException(e);
- },
- throwException: function()
- {
- this.initReadEncaps();
- this._readEncapsStack.decoder.throwException();
- },
- sliceObjects: function(b)
- {
- this._sliceObjects = b;
- },
- readOptImpl: function(readTag, expectedFormat)
- {
- var b, v, format, tag, offset;
-
- if(this.isReadEncoding_1_0())
- {
- return false; // Optional members aren't supported with the 1.0 encoding.
- }
-
- while(true)
- {
- if(this._buf.position >= this._readEncapsStack.start + this._readEncapsStack.sz)
- {
- return false; // End of encapsulation also indicates end of optionals.
- }
-
- v = this.readByte();
-
- if(v === OPTIONAL_END_MARKER)
- {
- this._buf.position -= 1; // Rewind.
- return false;
- }
-
- format = OptionalFormat.valueOf(v & 0x07); // First 3 bits.
- tag = v >> 3;
- if(tag === 30)
- {
- tag = this.readSize();
- }
-
- if(tag > readTag)
- {
- offset = tag < 30 ? 1 : (tag < 255 ? 2 : 6); // Rewind
- this._buf.position -= offset;
- return false; // No optional data members with the requested tag.
- }
-
- if(tag < readTag)
- {
- this.skipOpt(format); // Skip optional data members
- }
- else
- {
- if(format !== expectedFormat)
- {
- throw new Ice.MarshalException("invalid optional data member `" + tag + "': unexpected format");
- }
- return true;
- }
- }
- },
- writeOptImpl: function(tag, format)
- {
- if(this.isWriteEncoding_1_0())
- {
- return false; // Optional members aren't supported with the 1.0 encoding.
- }
-
- var v = format.value;
- if(tag < 30)
- {
- v |= tag << 3;
- this.writeByte(v);
- }
- else
- {
- v |= 0x0F0; // tag = 30
- this.writeByte(v);
- this.writeSize(tag);
- }
- return true;
- },
- skipOpt: function(format)
- {
- switch(format)
- {
- case OptionalFormat.F1:
- this.skip(1);
- break;
- case OptionalFormat.F2:
- this.skip(2);
- break;
- case OptionalFormat.F4:
- this.skip(4);
- break;
- case OptionalFormat.F8:
- this.skip(8);
- break;
- case OptionalFormat.Size:
- this.skipSize();
- break;
- case OptionalFormat.VSize:
- this.skip(this.readSize());
- break;
- case OptionalFormat.FSize:
- this.skip(this.readInt());
- break;
- case OptionalFormat.Class:
- this.readObject(null, Ice.Object);
- break;
- }
- },
- skipOpts: function()
- {
- var b, v, format;
- //
- // Skip remaining un-read optional members.
- //
- while(true)
- {
- if(this._buf.position >= this._readEncapsStack.start + this._readEncapsStack.sz)
- {
- return; // End of encapsulation also indicates end of optionals.
- }
-
- b = this.readByte();
- v = b < 0 ? b + 256 : b;
- if(v === OPTIONAL_END_MARKER)
- {
- return;
- }
-
- format = OptionalFormat.valueOf(v & 0x07); // Read first 3 bits.
- if((v >> 3) === 30)
- {
- this.skipSize();
- }
- this.skipOpt(format);
- }
- },
- skip: function(size)
- {
- if(size > this._buf.remaining)
- {
- throw new Ice.UnmarshalOutOfBoundsException();
- }
- this._buf.position += size;
- },
- skipSize: function()
- {
- var b = this.readByte();
- if(b === 255)
- {
- this.skip(4);
- }
- },
- isEmpty: function()
- {
- return this._buf.empty();
- },
- expand: function(n)
- {
- this._buf.expand(n);
- },
- createObject: function(id)
- {
- var obj = null, Class;
- try
- {
- var typeId = id.length > 2 ? id.substr(2).replace(/::/g, ".") : "";
- /*jshint -W061 */
- Class = __M.type(typeId);
- /*jshint +W061 */
- if(Class !== undefined)
- {
- obj = new Class();
- }
- }
- catch(ex)
- {
- throw new Ice.NoObjectFactoryException("no object factory", id, ex);
- }
-
- return obj;
- },
- getTypeId: function(compactId)
- {
- var typeId = Ice.CompactIdRegistry.get(compactId);
- return typeId === undefined ? "" : typeId;
- },
- isReadEncoding_1_0: function()
- {
- return this._readEncapsStack !== null ? this._readEncapsStack.encoding_1_0 : this._encoding.equals(Ice.Encoding_1_0);
- },
- isWriteEncoding_1_0: function()
- {
- return this._writeEncapsStack ? this._writeEncapsStack.encoding_1_0 : this._encoding.equals(Ice.Encoding_1_0);
- },
- initReadEncaps: function()
- {
- if(this._readEncapsStack === null) // Lazy initialization
- {
- this._readEncapsStack = this._readEncapsCache;
- if(this._readEncapsStack !== null)
- {
- this._readEncapsCache = this._readEncapsCache.next;
- }
- else
- {
- this._readEncapsStack = new ReadEncaps();
- }
- this._readEncapsStack.setEncoding(this._encoding);
- this._readEncapsStack.sz = this._buf.limit;
- }
-
- if(this._readEncapsStack.decoder === null) // Lazy initialization.
- {
- var factoryManager = this._instance.servantFactoryManager();
- if(this._readEncapsStack.encoding_1_0)
- {
- this._readEncapsStack.decoder = new EncapsDecoder10(this, this._readEncapsStack, this._sliceObjects, factoryManager);
- }
- else
- {
- this._readEncapsStack.decoder = new EncapsDecoder11(this, this._readEncapsStack, this._sliceObjects, factoryManager);
- }
- }
- },
- initWriteEncaps: function()
- {
- if(!this._writeEncapsStack) // Lazy initialization
- {
- this._writeEncapsStack = this._writeEncapsCache;
- if(this._writeEncapsStack)
- {
- this._writeEncapsCache = this._writeEncapsCache.next;
- }
- else
- {
- this._writeEncapsStack = new WriteEncaps();
- }
- this._writeEncapsStack.setEncoding(this._encoding);
- }
-
- if(this._writeEncapsStack.format === FormatType.DefaultFormat)
- {
- this._writeEncapsStack.format = this._instance.defaultsAndOverrides().defaultFormat;
- }
-
- if(!this._writeEncapsStack.encoder) // Lazy initialization.
- {
- if(this._writeEncapsStack.encoding_1_0)
- {
- this._writeEncapsStack.encoder = new EncapsEncoder10(this, this._writeEncapsStack);
- }
- else
- {
- this._writeEncapsStack.encoder = new EncapsEncoder11(this, this._writeEncapsStack);
- }
- }
- },
- createUserException: function(id)
- {
- var userEx = null, Class;
-
- try
- {
- var typeId = id.length > 2 ? id.substr(2).replace(/::/g, ".") : "";
- /*jshint -W061 */
- Class = __M.type(typeId);
- /*jshint +W061 */
- if(Class !== undefined)
- {
- userEx = new Class();
- }
- }
- catch(ex)
- {
- throw new Ice.MarshalException(ex);
- }
-
- return userEx;
- }
-});
-
-var defineProperty = Object.defineProperty;
-
-defineProperty(BasicStream.prototype, "pos", {
- get: function() { return this._buf.position; },
- set: function(n) { this._buf.position = n; }
-});
-
-defineProperty(BasicStream.prototype, "size", {
- get: function() { return this._buf.limit; }
-});
-
-defineProperty(BasicStream.prototype, "instance", {
- get: function() { return this._instance; }
-});
-
-defineProperty(BasicStream.prototype, "closure", {
- get: function() { return this._type; },
- set: function(type) { this._type = type; }
-});
-
-defineProperty(BasicStream.prototype, "buffer", {
- get: function() { return this._buf; }
-});
-
-var defineBuiltinHelper = function(write, read, sz, format, min, max)
-{
- var helper = {
- write: function(os, v) { return write.call(os, v); },
- read: function(is) { return read.call(is); },
- writeOpt: function(os, tag, v) { os.writeOptValue(tag, format, write, v); },
- readOpt: function(is, tag) { return is.readOptValue(tag, format, read); },
- };
-
- if(min !== undefined && max !== undefined)
- {
- helper.validate = function(v) {
- return v >= min && v <= max;
- };
- }
- defineProperty(helper, "minWireSize", {
- get: function() { return sz; }
- });
- return helper;
-};
-
-var stream = BasicStream.prototype;
-
-
-//
-// Constants to use in number type range checks.
-//
-var MIN_UINT8_VALUE = 0x0;
-var MAX_UINT8_VALUE = 0xFF;
-
-var MIN_INT16_VALUE = -0x8000;
-var MAX_INT16_VALUE = 0x7FFF;
-
-var MIN_UINT32_VALUE = 0x0;
-var MAX_UINT32_VALUE = 0xFFFFFFFF;
-
-var MIN_INT32_VALUE = -0x80000000;
-var MAX_INT32_VALUE = 0x7FFFFFFF;
-
-var MIN_FLOAT32_VALUE = -3.4028234664e+38;
-var MAX_FLOAT32_VALUE = 3.4028234664e+38;
-
-Ice.ByteHelper = defineBuiltinHelper(stream.writeByte, stream.readByte, 1, Ice.OptionalFormat.F1,
- MIN_UINT8_VALUE, MAX_UINT8_VALUE);
-
-Ice.ShortHelper = defineBuiltinHelper(stream.writeShort, stream.readShort, 2, Ice.OptionalFormat.F2,
- MIN_INT16_VALUE, MAX_INT16_VALUE);
-
-Ice.IntHelper = defineBuiltinHelper(stream.writeInt, stream.readInt, 4, Ice.OptionalFormat.F4,
- MIN_INT32_VALUE, MAX_INT32_VALUE);
-
-Ice.FloatHelper = defineBuiltinHelper(stream.writeFloat, stream.readFloat, 4, Ice.OptionalFormat.F4,
- MIN_FLOAT32_VALUE, MAX_FLOAT32_VALUE);
-Ice.FloatHelper.validate = function(v)
-{
- return Number.isNaN(v) || v == Number.POSITIVE_INFINITY || v == Number.NEGATIVE_INFINITY ||
- (v >= MIN_FLOAT32_VALUE && v <= MAX_FLOAT32_VALUE);
-};
-
-Ice.DoubleHelper = defineBuiltinHelper(stream.writeDouble, stream.readDouble, 8, Ice.OptionalFormat.F8,
- -Number.MAX_VALUE, Number.MAX_VALUE);
-Ice.DoubleHelper.validate = function(v)
-{
- return Number.isNaN(v) || v == Number.POSITIVE_INFINITY || v == Number.NEGATIVE_INFINITY ||
- (v >= -Number.MAX_VALUE && v <= Number.MAX_VALUE);
-};
-
-Ice.BoolHelper = defineBuiltinHelper(stream.writeBool, stream.readBool, 1, Ice.OptionalFormat.F1);
-Ice.LongHelper = defineBuiltinHelper(stream.writeLong, stream.readLong, 8, Ice.OptionalFormat.F8);
-Ice.LongHelper.validate = function(v)
-{
- //
- // For a long to be valid both words must be within the range of UINT32
- //
- return v.low >= MIN_UINT32_VALUE && v.low <= MAX_UINT32_VALUE &&
- v.high >= MIN_UINT32_VALUE && v.high <= MAX_UINT32_VALUE;
-};
-
-Ice.StringHelper = defineBuiltinHelper(stream.writeString, stream.readString, 1, Ice.OptionalFormat.VSize);
-
-Ice.ObjectHelper = {
- write: function(os, v)
- {
- os.writeObject(v);
- },
- read: function(is)
- {
- var o;
- is.readObject(function(v) { o = v; }, Ice.Object);
- return o;
- },
- writeOpt: function(os, tag, v)
- {
- os.writeOptValue(tag, Ice.OptionalFormat.Class, stream.writeObject, v);
- },
- readOpt: function(is, tag)
- {
- var o;
- is.readOptObject(tag, function(v) { o = v; }, Ice.Object);
- return o;
- },
-};
-
-defineProperty(Ice.ObjectHelper, "minWireSize", {
- get: function() { return 1; }
-});
-
-Ice.BasicStream = BasicStream;
-module.exports.Ice = Ice;
diff --git a/js/src/Ice/BatchRequestQueue.js b/js/src/Ice/BatchRequestQueue.js
index 6b33a1d6b81..c9a7afe84fa 100644
--- a/js/src/Ice/BatchRequestQueue.js
+++ b/js/src/Ice/BatchRequestQueue.js
@@ -7,30 +7,29 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
- "../Ice/BasicStream",
+ "../Ice/Stream",
"../Ice/Debug",
"../Ice/ExUtil",
"../Ice/Protocol",
]);
-var BasicStream = Ice.BasicStream;
-var Debug = Ice.Debug;
-var ExUtil = Ice.ExUtil;
-var Class = Ice.Class;
-var Protocol = Ice.Protocol;
+const OutputStream = Ice.OutputStream;
+const Debug = Ice.Debug;
+const ExUtil = Ice.ExUtil;
+const Protocol = Ice.Protocol;
-var udpOverhead = 20 + 8;
+const udpOverhead = 20 + 8;
-var BatchRequestQueue = Class({
- __init__: function(instance, datagram)
+class BatchRequestQueue
+{
+ constructor(instance, datagram)
{
this._batchStreamInUse = false;
this._batchRequestNum = 0;
- this._batchStream = new BasicStream(instance, Protocol.currentProtocolEncoding);
+ this._batchStream = new OutputStream(instance, Protocol.currentProtocolEncoding);
this._batchStream.writeBlob(Protocol.requestBatchHdr);
this._batchMarker = this._batchStream.size;
this._exception = null;
@@ -38,23 +37,25 @@ var BatchRequestQueue = Class({
this._maxSize = instance.batchAutoFlushSize();
if(this._maxSize > 0 && datagram)
{
- var props = instance.initializationData().properties;
- var udpSndSize = props.getPropertyAsIntWithDefault("Ice.UDP.SndSize", 65535 - udpOverhead);
+ const udpSndSize = instance.initializationData().properties.getPropertyAsIntWithDefault(
+ "Ice.UDP.SndSize", 65535 - udpOverhead);
if(udpSndSize < this._maxSize)
{
this._maxSize = udpSndSize;
}
}
- },
- prepareBatchRequest: function(os)
+ }
+
+ prepareBatchRequest(os)
{
if(this._exception)
{
throw this._exception;
}
this._batchStream.swap(os);
- },
- finishBatchRequest: function(os, proxy, operation)
+ }
+
+ finishBatchRequest(os, proxy, operation)
{
//
// No need for synchronization, no other threads are supposed
@@ -77,29 +78,31 @@ var BatchRequestQueue = Class({
{
this._batchStream.resize(this._batchMarker);
}
- },
- abortBatchRequest: function(os)
+ }
+
+ abortBatchRequest(os)
{
this._batchStream.swap(os);
this._batchStream.resize(this._batchMarker);
- },
- swap: function(os)
+ }
+
+ swap(os)
{
if(this._batchRequestNum === 0)
{
return 0;
}
- var lastRequest = null;
+ let lastRequest = null;
if(this._batchMarker < this._batchStream.size)
{
- var length = this._batchStream.size - this._batchMarker;
+ const length = this._batchStream.size - this._batchMarker;
this._batchStream.pos = this._batchMarker;
lastRequest = this._batchStream.buffer.getArray(length);
this._batchStream.resize(this._batchMarker);
}
- var requestNum = this._batchRequestNum;
+ const requestNum = this._batchRequestNum;
this._batchStream.swap(os);
//
@@ -113,16 +116,18 @@ var BatchRequestQueue = Class({
this._batchStream.writeBlob(lastRequest);
}
return requestNum;
- },
- destroy: function(ex)
+ }
+
+ destroy(ex)
{
this._exception = ex;
- },
- isEmpty: function()
+ }
+
+ isEmpty()
{
return this._batchStream.size === Protocol.requestBatchHdr.length;
}
-});
+}
Ice.BatchRequestQueue = BatchRequestQueue;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/Buffer.js b/js/src/Ice/Buffer.js
index d9a27ac2942..d6f395629ba 100644
--- a/js/src/Ice/Buffer.js
+++ b/js/src/Ice/Buffer.js
@@ -7,46 +7,42 @@
//
// **********************************************************************
-//
-// Ice.Buffer implementation to be used by Node.js, it uses node Buffer
-// as the store.
-//
+const Ice = require("../Ice/Long").Ice;
+const Long = Ice.Long;
+
+const bufferOverflowExceptionMsg = "BufferOverflowException";
+const bufferUnderflowExceptionMsg = "BufferUnderflowException";
+const indexOutOfBoundsExceptionMsg = "IndexOutOfBoundsException";
//
-// Define Node.Buffer as an alias to NodeJS global Buffer type,
-// that allow us to refer to Ice.Buffer as Buffer in this file.
+// Buffer implementation to be used by web browsers, it uses ArrayBuffer as
+// the store.
//
-var Node = { Buffer: global.Buffer };
-
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Long", "../Ice/Class"]);
-
-var Long = Ice.Long;
-
-var __BufferOverflowException__ = "BufferOverflowException";
-var __BufferUnderflowException__ = "BufferUnderflowException";
-var __IndexOutOfBoundsException__ = "IndexOutOfBoundsException";
-
-var Buffer = Ice.Class({
- __init__: function(buffer)
+class Buffer
+{
+ constructor(buffer)
{
if(buffer !== undefined)
{
this.b = buffer;
+ this.v = new DataView(this.b);
}
else
{
- this.b = null;
+ this.b = null; // ArrayBuffer
+ this.v = null; // DataView
}
this._position = 0;
this._limit = 0;
this._shrinkCounter = 0;
- },
- empty: function()
+ }
+
+ empty()
{
return this._limit === 0;
- },
- resize: function(n)
+ }
+
+ resize(n)
{
if(n === 0)
{
@@ -57,28 +53,32 @@ var Buffer = Ice.Class({
this.reserve(n);
}
this._limit = n;
- },
- clear: function()
+ }
+
+ clear()
{
this.b = null;
+ this.v = null;
this._position = 0;
this._limit = 0;
- },
+ }
+
//
// Call expand(n) to add room for n additional bytes. Note that expand()
// examines the current position of the buffer first; we don't want to
// expand the buffer if the caller is writing to a location that is
// already in the buffer.
//
- expand: function(n)
+ expand(n)
{
var sz = this.capacity === 0 ? n : this._position + n;
if(sz > this._limit)
{
this.resize(sz);
}
- },
- reset: function()
+ }
+
+ reset()
{
if(this._limit > 0 && this._limit * 2 < this.capacity)
{
@@ -100,331 +100,333 @@ var Buffer = Ice.Class({
}
this._limit = 0;
this._position = 0;
- },
- reserve: function(n)
+ }
+
+ reserve(n)
{
- var b, capacity;
if(n > this.capacity)
{
- capacity = Math.max(n, 2 * this.capacity);
+ var capacity = Math.max(n, 2 * this.capacity);
capacity = Math.max(1024, capacity);
- if(this.b === null)
+ if(!this.b)
{
- this.b = new Node.Buffer(capacity);
+ this.b = new ArrayBuffer(capacity);
}
else
{
- b = new Node.Buffer(capacity);
- this.b.copy(b);
- this.b = b;
+ var b = new Uint8Array(capacity);
+ b.set(new Uint8Array(this.b));
+ this.b = b.buffer;
}
+ this.v = new DataView(this.b);
}
else if(n < this.capacity)
{
this.b = this.b.slice(0, this.capacity);
+ this.v = new DataView(this.b);
}
else
{
return;
}
- },
- put: function(v)
+ }
+
+ put(v)
{
if(this._position === this._limit)
{
- throw new Error(__BufferOverflowException__);
+ throw new Error(bufferOverflowExceptionMsg);
}
- this.b.writeUInt8(v, this._position, true);
+ this.v.setUint8(this._position, v);
this._position++;
- },
- putAt: function(i, v)
+ }
+
+ putAt(i, v)
{
if(i >= this._limit)
{
- throw new Error(__IndexOutOfBoundsException__);
+ throw new Error(indexOutOfBoundsExceptionMsg);
}
- this.b.writeUInt8(v, i, true);
- },
- putArray: function(v)
+ this.v.setUint8(i, v);
+ }
+
+ putArray(v)
{
- //Expects a Nodejs Buffer
- if(!Node.Buffer.isBuffer(v))
+ //Expects an Uint8Array
+ if(!(v instanceof Uint8Array))
{
- throw new TypeError("argument is not a Node.Buffer");
+ throw new TypeError('argument is not a Uint8Array');
}
- if(this._position + v.length > this._limit)
+ if(v.byteLength > 0)
{
- throw new Error(__BufferOverflowException__);
+ if(this._position + v.length > this._limit)
+ {
+ throw new Error(bufferOverflowExceptionMsg);
+ }
+ new Uint8Array(this.b, 0, this.b.byteLength).set(v, this._position);
+ this._position += v.byteLength;
}
- v.copy(this.b, this._position);
- this._position += v.length;
- },
- putShort: function(v)
+ }
+
+ putShort(v)
{
if(this._position + 2 > this._limit)
{
- throw new Error(__BufferOverflowException__);
+ throw new Error(bufferOverflowExceptionMsg);
}
- this.b.writeInt16LE(v, this._position, true);
+ this.v.setInt16(this._position, v, true);
this._position += 2;
- },
- putShortAt: function(i, v)
- {
- if(i + 2 > this._limit || i < 0)
- {
- throw new Error(__IndexOutOfBoundsException__);
- }
- this.b.writeInt16LE(v, i, true);
- },
- putInt: function(v)
+ }
+
+ putInt(v)
{
if(this._position + 4 > this._limit)
{
- throw new Error(__BufferOverflowException__);
+ throw new Error(bufferOverflowExceptionMsg);
}
- this.b.writeInt32LE(v, this._position, true);
+ this.v.setInt32(this._position, v, true);
this._position += 4;
- },
- putIntAt: function(i, v)
+ }
+
+ putIntAt(i, v)
{
if(i + 4 > this._limit || i < 0)
{
- throw new Error(__IndexOutOfBoundsException__);
+ throw new Error(indexOutOfBoundsExceptionMsg);
}
- this.b.writeInt32LE(v, i, true);
- },
- putFloat: function(v)
+ this.v.setInt32(i, v, true);
+ }
+
+ putFloat(v)
{
if(this._position + 4 > this._limit)
{
- throw new Error(__BufferOverflowException__);
+ throw new Error(bufferOverflowExceptionMsg);
}
- this.b.writeFloatLE(v, this._position, true);
+ this.v.setFloat32(this._position, v, true);
this._position += 4;
- },
- putFloatAt: function(i, v)
- {
- if(i + 4 > this._limit || i < 0)
- {
- throw new Error(__IndexOutOfBoundsException__);
- }
- this.b.writeFloatLE(v, i, true);
- },
- putDouble: function(v)
+ }
+
+ putDouble(v)
{
if(this._position + 8 > this._limit)
{
- throw new Error(__BufferOverflowException__);
+ throw new Error(bufferOverflowExceptionMsg);
}
- this.b.writeDoubleLE(v, this._position, true);
+ this.v.setFloat64(this._position, v, true);
this._position += 8;
- },
- putDoubleAt: function(i, v)
- {
- if(i + 8 > this._limit || i < 0)
- {
- throw new Error(__IndexOutOfBoundsException__);
- }
- this.b.writeDoubleLE(v, i, true);
- },
- putLong: function(v)
+ }
+
+ putLong(v)
{
if(this._position + 8 > this._limit)
{
- throw new Error(__BufferOverflowException__);
+ throw new Error(bufferOverflowExceptionMsg);
}
- this.b.writeUInt32LE(v.low, this._position, true);
+ this.v.setInt32(this._position, v.low, true);
this._position += 4;
- this.b.writeUInt32LE(v.high, this._position, true);
+ this.v.setInt32(this._position, v.high, true);
this._position += 4;
- },
- putLongAt: function(i, v)
- {
- if(i + 8 > this._limit || i < 0)
- {
- throw new Error(__IndexOutOfBoundsException__);
- }
- this.b.writeUInt32LE(v.low, i, true);
- this.b.writeUInt32LE(v.high, i + 4, true);
- },
- writeString: function(stream, v)
+ }
+
+ writeString(stream, v)
{
- var sz = Node.Buffer.byteLength(v);
- stream.writeSize(sz);
- stream.expand(sz);
- this.putString(v, sz);
- },
- putString: function(v, sz)
+ //
+ // Encode the string as utf8
+ //
+ var encoded = unescape(encodeURIComponent(v));
+
+ stream.writeSize(encoded.length);
+ stream.expand(encoded.length);
+ this.putString(encoded, encoded.length);
+ }
+
+ putString(v, sz)
{
if(this._position + sz > this._limit)
{
- throw new Error(__BufferOverflowException__);
+ throw new Error(bufferOverflowExceptionMsg);
}
- var bytes = this.b.write(v, this._position);
- //
- // Check all bytes were written
- //
- if(bytes < sz)
+ for(var i = 0; i < sz; ++i)
{
- throw new Error(__IndexOutOfBoundsException__);
+ this.v.setUint8(this._position, v.charCodeAt(i));
+ this._position++;
}
- this._position += sz;
- },
- get: function()
+ }
+
+ get()
{
if(this._position >= this._limit)
{
- throw new Error(__BufferUnderflowException__);
+ throw new Error(bufferUnderflowExceptionMsg);
}
- var v = this.b.readUInt8(this._position, true);
+ var v = this.v.getUint8(this._position);
this._position++;
return v;
- },
- getAt: function(i)
+ }
+
+ getAt(i)
{
if(i < 0 || i >= this._limit)
{
- throw new Error(__IndexOutOfBoundsException__);
+ throw new Error(indexOutOfBoundsExceptionMsg);
}
- return this.b.readUInt8(i, true);
- },
- getArray: function(length)
+ return this.v.getUint8(i);
+ }
+
+ getArray(length)
{
if(this._position + length > this._limit)
{
- throw new Error(__BufferUnderflowException__);
+ throw new Error(bufferUnderflowExceptionMsg);
}
- var buffer = new Node.Buffer(length);
- this.b.slice(this._position, this._position + length).copy(buffer);
+ var buffer = this.b.slice(this._position, this._position + length);
this._position += length;
- return buffer;
- },
- getArrayAt: function(position, length)
+ return new Uint8Array(buffer);
+ }
+
+ getArrayAt(position, length)
{
if(position + length > this._limit)
{
- throw new Error(__BufferUnderflowException__);
+ throw new Error(bufferUnderflowExceptionMsg);
}
- length = length === undefined ? (this.b.length - position) : length;
- var buffer = new Node.Buffer(length);
- this.b.slice(position, position + length).copy(buffer);
- return buffer;
- },
- getShort: function()
+ length = length === undefined ? (this.b.byteLength - position) : length;
+ return new Uint8Array(this.b.slice(position, position + length));
+ }
+
+ getShort()
{
- var v;
if(this._limit - this._position < 2)
{
- throw new Error(__BufferUnderflowException__);
+ throw new Error(bufferUnderflowExceptionMsg);
}
- v = this.b.readInt16LE(this._position, true);
+ var v = this.v.getInt16(this._position, true);
this._position += 2;
return v;
- },
- getInt: function()
+ }
+
+ getInt()
{
- var v;
if(this._limit - this._position < 4)
{
- throw new Error(__BufferUnderflowException__);
+ throw new Error(bufferUnderflowExceptionMsg);
}
- v = this.b.readInt32LE(this._position, true);
+ var v = this.v.getInt32(this._position, true);
this._position += 4;
return v;
- },
- getFloat: function()
+ }
+
+ getFloat()
{
if(this._limit - this._position < 4)
{
- throw new Error(__BufferUnderflowException__);
+ throw new Error(bufferUnderflowExceptionMsg);
}
- var v = this.b.readFloatLE(this._position, true);
+ var v = this.v.getFloat32(this._position, true);
this._position += 4;
return v;
- },
- getDouble: function()
+ }
+
+ getDouble()
{
if(this._limit - this._position < 8)
{
- throw new Error(__BufferUnderflowException__);
+ throw new Error(bufferUnderflowExceptionMsg);
}
- var v = this.b.readDoubleLE(this._position, true);
+ var v = this.v.getFloat64(this._position, true);
this._position += 8;
return v;
- },
- getLong: function()
+ }
+
+ getLong()
{
if(this._limit - this._position < 8)
{
- throw new Error(__BufferUnderflowException__);
+ throw new Error(bufferUnderflowExceptionMsg);
}
- var v = new Long();
- v.low = this.b.readUInt32LE(this._position, true);
+ const low = this.v.getUint32(this._position, true);
this._position += 4;
- v.high = this.b.readUInt32LE(this._position, true);
+ const high = this.v.getUint32(this._position, true);
this._position += 4;
- return v;
- },
- getString: function(length)
+
+ return new Long(high, low);
+ }
+
+ getString(length)
{
if(this._position + length > this._limit)
{
- throw new Error(__BufferUnderflowException__);
+ throw new Error(bufferUnderflowExceptionMsg);
+ }
+
+ var data = new DataView(this.b, this._position, length);
+ var s = "";
+
+ for(var i = 0; i < length; ++i)
+ {
+ s += String.fromCharCode(data.getUint8(i));
}
- var s =this.b.toString("utf8", this._position, this._position + length);
this._position += length;
+ s = decodeURIComponent(escape(s));
return s;
}
-});
-
-var prototype = Buffer.prototype;
-
-Object.defineProperty(prototype, "position", {
- get: function() { return this._position; },
- set: function(position){
- if(position >= 0 && position <= this._limit)
+
+ get position()
+ {
+ return this._position;
+ }
+
+ set position(value)
+ {
+ if(value >= 0 && value <= this._limit)
{
- this._position = position;
+ this._position = value;
}
}
-});
-
-Object.defineProperty(prototype, "limit", {
- get: function() { return this._limit; },
- set: function(limit){
- if(limit <= this.capacity)
+
+ get limit()
+ {
+ return this._limit;
+ }
+
+ set limit(value)
+ {
+ if(value <= this.capacity)
{
- this._limit = limit;
- if(this._position > limit)
+ this._limit = value;
+ if(this._position > value)
{
- this._position = limit;
+ this._position = value;
}
}
}
-});
-
-Object.defineProperty(prototype, "capacity", {
- get: function() { return this.b === null ? 0 : this.b.length; }
-});
-
-Object.defineProperty(prototype, "remaining", {
- get: function() { return this._limit - this._position; }
-});
-
-//
-// Create a native buffer from an array of bytes.
-//
-Buffer.createNative = function(data)
-{
- if(data === undefined)
+
+ get capacity()
+ {
+ return this.b === null ? 0 : this.b.byteLength;
+ }
+
+ get remaining()
{
- return new Node.Buffer(0);
+ return this._limit - this._position;
}
- else
+
+ //
+ // Create a native buffer from an array of bytes.
+ //
+ static createNative(data)
{
- return new Node.Buffer(data);
+ if(data === undefined)
+ {
+ return new Uint8Array(0);
+ }
+ else
+ {
+ return new Uint8Array(data);
+ }
}
-};
+}
Ice.Buffer = Buffer;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/Class.js b/js/src/Ice/Class.js
deleted file mode 100644
index 3ef5b3390a2..00000000000
--- a/js/src/Ice/Class.js
+++ /dev/null
@@ -1,55 +0,0 @@
-// **********************************************************************
-//
-// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
-//
-// This copy of Ice is licensed to you under the terms described in the
-// ICE_LICENSE file included in this distribution.
-//
-// **********************************************************************
-
-var Ice = require("../Ice/ModuleRegistry").Ice;
-
-Ice.Class = function()
-{
- var base;
- var desc;
- var constructor;
-
- if(arguments.length == 1)
- {
- desc = arguments[0];
- }
- else if(arguments.length == 2)
- {
- base = arguments[0];
- desc = arguments[1];
- }
-
- if(desc !== undefined)
- {
- constructor = desc.__init__;
- if(constructor)
- {
- delete desc.__init__;
- }
- }
-
- var o = constructor || function(){};
-
- if(base !== undefined)
- {
- o.prototype = new base();
- o.prototype.constructor = o;
- }
-
- if(desc !== undefined)
- {
- for(var key in desc)
- {
- o.prototype[key] = desc[key];
- }
- }
- return o;
-};
-
-module.exports.Ice = Ice;
diff --git a/js/src/Ice/Communicator.js b/js/src/Ice/Communicator.js
index e11f6a028ad..bb9f385e23b 100644
--- a/js/src/Ice/Communicator.js
+++ b/js/src/Ice/Communicator.js
@@ -7,82 +7,93 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/Instance",
- "../Ice/Promise",
"../Ice/UUID",
"../Ice/AsyncResultBase"
]);
-var Instance = Ice.Instance;
-var Promise = Ice.Promise;
+const Instance = Ice.Instance;
//
// Ice.Communicator
//
-var Communicator = Ice.Class({
- __init__: function(initData)
+class Communicator
+{
+ constructor(initData)
{
this._instance = new Instance(initData);
- },
+ }
+
//
// Certain initialization tasks need to be completed after the
// constructor.
//
- finishSetup: function(promise)
+ finishSetup(promise)
{
this._instance.finishSetup(this, promise);
- },
- destroy: function()
+ }
+
+ destroy()
{
return this._instance.destroy();
- },
- shutdown: function()
+ }
+
+ shutdown()
{
this._instance.objectAdapterFactory().shutdown();
- },
- waitForShutdown: function()
+ }
+
+ waitForShutdown()
{
return this._instance.objectAdapterFactory().waitForShutdown();
- },
- isShutdown: function()
+ }
+
+ isShutdown()
{
return this._instance.objectAdapterFactory().isShutdown();
- },
- stringToProxy: function(s)
+ }
+
+ stringToProxy(s)
{
return this._instance.proxyFactory().stringToProxy(s);
- },
- proxyToString: function(proxy)
+ }
+
+ proxyToString(proxy)
{
return this._instance.proxyFactory().proxyToString(proxy);
- },
- propertyToProxy: function(s)
+ }
+
+ propertyToProxy(s)
{
return this._instance.proxyFactory().propertyToProxy(s);
- },
- proxyToProperty: function(proxy, prefix)
+ }
+
+ proxyToProperty(proxy, prefix)
{
return this._instance.proxyFactory().proxyToProperty(proxy, prefix);
- },
- stringToIdentity: function(s)
+ }
+
+ stringToIdentity(s)
{
- return this._instance.stringToIdentity(s);
- },
- identityToString: function(ident)
+ return Ice.stringToIdentity(s);
+ }
+
+ identityToString(ident)
{
- return this._instance.identityToString(ident);
- },
- createObjectAdapter: function(name)
+ return Ice.identityToString(ident, this._instance.toStringMode());
+ }
+
+ createObjectAdapter(name)
{
- var promise = new Ice.AsyncResultBase(this, "createObjectAdapter", this, null, null);
+ const promise = new Ice.AsyncResultBase(this, "createObjectAdapter", this, null, null);
this._instance.objectAdapterFactory().createObjectAdapter(name, null, promise);
return promise;
- },
- createObjectAdapterWithEndpoints: function(name, endpoints)
+ }
+
+ createObjectAdapterWithEndpoints(name, endpoints)
{
if(name.length === 0)
{
@@ -90,76 +101,92 @@ var Communicator = Ice.Class({
}
this.getProperties().setProperty(name + ".Endpoints", endpoints);
- var promise = new Ice.AsyncResultBase(this, "createObjectAdapterWithEndpoints", this, null, null);
+ const promise = new Ice.AsyncResultBase(this, "createObjectAdapterWithEndpoints", this, null, null);
this._instance.objectAdapterFactory().createObjectAdapter(name, null, promise);
return promise;
- },
- createObjectAdapterWithRouter: function(name, router)
+ }
+
+ createObjectAdapterWithRouter(name, router)
{
if(name.length === 0)
{
name = Ice.generateUUID();
}
- var promise = new Ice.AsyncResultBase(this, "createObjectAdapterWithRouter", this, null, null);
+ const promise = new Ice.AsyncResultBase(this, "createObjectAdapterWithRouter", this, null, null);
//
// We set the proxy properties here, although we still use the proxy supplied.
//
- var properties = this.proxyToProperty(router, name + ".Router");
- for(var e = properties.entries; e !== null; e = e.next)
- {
- this.getProperties().setProperty(e.key, e.value);
- }
+ this.proxyToProperty(router, name + ".Router").forEach((value, key) =>
+ {
+ this.getProperties().setProperty(key, value);
+ });
this._instance.objectAdapterFactory().createObjectAdapter(name, router, promise);
return promise;
- },
- addObjectFactory: function(factory, id)
+ }
+
+ addObjectFactory(factory, id)
+ {
+ this._instance.addObjectFactory(factory, id);
+ }
+
+ findObjectFactory(id)
{
- this._instance.servantFactoryManager().add(factory, id);
- },
- findObjectFactory: function(id)
+ return this._instance.findObjectFactory(id);
+ }
+
+ getValueFactoryManager()
{
- return this._instance.servantFactoryManager().find(id);
- },
- getImplicitContext: function()
+ return this._instance.initializationData().valueFactoryManager;
+ }
+
+ getImplicitContext()
{
return this._instance.getImplicitContext();
- },
- getProperties: function()
+ }
+
+ getProperties()
{
return this._instance.initializationData().properties;
- },
- getLogger: function()
+ }
+
+ getLogger()
{
return this._instance.initializationData().logger;
- },
- getDefaultRouter: function()
+ }
+
+ getDefaultRouter()
{
return this._instance.referenceFactory().getDefaultRouter();
- },
- setDefaultRouter: function(router)
+ }
+
+ setDefaultRouter(router)
{
this._instance.setDefaultRouter(router);
- },
- getDefaultLocator: function()
+ }
+
+ getDefaultLocator()
{
return this._instance.referenceFactory().getDefaultLocator();
- },
- setDefaultLocator: function(locator)
+ }
+
+ setDefaultLocator(locator)
{
this._instance.setDefaultLocator(locator);
- },
- flushBatchRequests: function()
+ }
+
+ flushBatchRequests()
{
return this._instance.outgoingConnectionFactory().flushAsyncBatchRequests();
}
-});
-Object.defineProperty(Communicator.prototype, "instance", {
- get: function() { return this._instance; }
-});
+ get instance()
+ {
+ return this._instance;
+ }
+}
Ice.Communicator = Communicator;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/CompactIdRegistry.js b/js/src/Ice/CompactIdRegistry.js
index 718f2a394c1..269c0cf9c5f 100644
--- a/js/src/Ice/CompactIdRegistry.js
+++ b/js/src/Ice/CompactIdRegistry.js
@@ -7,6 +7,6 @@
//
// **********************************************************************
-var Ice = require("../Ice/HashMap").Ice;
-Ice.CompactIdRegistry = new Ice.HashMap();
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice.CompactIdRegistry = new Map();
module.exports.Ice = Ice;
diff --git a/js/src/Ice/ConnectRequestHandler.js b/js/src/Ice/ConnectRequestHandler.js
index eb38f0945d2..3c6c99f5d41 100644
--- a/js/src/Ice/ConnectRequestHandler.js
+++ b/js/src/Ice/ConnectRequestHandler.js
@@ -7,39 +7,27 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
- "../Ice/AsyncResult",
"../Ice/AsyncStatus",
- "../Ice/BasicStream",
"../Ice/ConnectionRequestHandler",
"../Ice/Debug",
- "../Ice/ExUtil",
"../Ice/RetryException",
- "../Ice/OutgoingAsync",
- "../Ice/Protocol",
"../Ice/ReferenceMode",
"../Ice/Exception",
- "../Ice/Promise"
]);
-var AsyncResult = Ice.AsyncResult;
-var AsyncStatus = Ice.AsyncStatus;
-var BasicStream = Ice.BasicStream;
-var ConnectionRequestHandler = Ice.ConnectionRequestHandler;
-var Debug = Ice.Debug;
-var ExUtil = Ice.ExUtil;
-var RetryException = Ice.RetryException;
-var OutgoingAsync = Ice.OutgoingAsync;
-var Protocol = Ice.Protocol;
-var ReferenceMode = Ice.ReferenceMode;
-var LocalException = Ice.LocalException;
-var Promise = Ice.Promise;
+const AsyncStatus = Ice.AsyncStatus;
+const ConnectionRequestHandler = Ice.ConnectionRequestHandler;
+const Debug = Ice.Debug;
+const RetryException = Ice.RetryException;
+const ReferenceMode = Ice.ReferenceMode;
+const LocalException = Ice.LocalException;
-var ConnectRequestHandler = Ice.Class({
- __init__: function(ref, proxy)
+class ConnectRequestHandler
+{
+ constructor(ref, proxy)
{
this._reference = ref;
this._response = ref.getMode() === ReferenceMode.ModeTwoway;
@@ -48,27 +36,29 @@ var ConnectRequestHandler = Ice.Class({
this._initialized = false;
this._connection = null;
- this._compress = false;
this._exception = null;
this._requests = [];
- },
- connect: function(proxy)
+ }
+
+ connect(proxy)
{
if(!this.initialized())
{
this._proxies.push(proxy);
}
return this._requestHandler ? this._requestHandler : this;
- },
- update: function(previousHandler, newHandler)
+ }
+
+ update(previousHandler, newHandler)
{
return previousHandler === this ? newHandler : this;
- },
- sendAsyncRequest: function(out)
+ }
+
+ sendAsyncRequest(out)
{
if(!this._initialized)
{
- out.__cancelable(this); // This will throw if the request is canceled
+ out.cancelable(this); // This will throw if the request is canceled
}
if(!this.initialized())
@@ -76,9 +66,10 @@ var ConnectRequestHandler = Ice.Class({
this._requests.push(out);
return AsyncStatus.Queued;
}
- return out.__invokeRemote(this._connection, this._compress, this._response);
- },
- asyncRequestCanceled: function(out, ex)
+ return out.invokeRemote(this._connection, this._response);
+ }
+
+ asyncRequestCanceled(out, ex)
{
if(this._exception !== null)
{
@@ -87,11 +78,11 @@ var ConnectRequestHandler = Ice.Class({
if(!this.initialized())
{
- for(var i = 0; i < this._requests.length; i++)
+ for(let i = 0; i < this._requests.length; i++)
{
if(this._requests[i] === out)
{
- out.__completedEx(ex);
+ out.completedEx(ex);
this._requests.splice(i, 1);
return;
}
@@ -99,12 +90,14 @@ var ConnectRequestHandler = Ice.Class({
Debug.assert(false); // The request has to be queued if it timed out and we're not initialized yet.
}
this._connection.asyncRequestCanceled(out, ex);
- },
- getReference: function()
+ }
+
+ getReference()
{
return this._reference;
- },
- getConnection: function()
+ }
+
+ getConnection()
{
if(this._exception !== null)
{
@@ -114,37 +107,30 @@ var ConnectRequestHandler = Ice.Class({
{
return this._connection;
}
- },
+ }
+
//
// Implementation of Reference_GetConnectionCallback
//
- setConnection: function(connection, compress)
+ setConnection(connection)
{
Debug.assert(this._exception === null && this._connection === null);
this._connection = connection;
- this._compress = compress;
//
// If this proxy is for a non-local object, and we are using a router, then
// add this proxy to the router info object.
//
- var ri = this._reference.getRouterInfo();
+ let ri = this._reference.getRouterInfo();
if(ri !== null)
{
- var self = this;
- ri.addProxy(this._proxy).then(function()
- {
- //
- // The proxy was added to the router info, we're now ready to send the
- // queued requests.
- //
- self.flushRequests();
- },
- function(ex)
- {
- self.setException(ex);
- });
+ //
+ ri.addProxy(this._proxy).then(() => this.flushRequests(), // The proxy was added to the router
+ // info, we're now ready to send the
+ // queued requests.
+ //
+ ex => this.setException(ex));
return; // The request handler will be initialized once addProxy completes.
}
@@ -152,8 +138,9 @@ var ConnectRequestHandler = Ice.Class({
// We can now send the queued requests.
//
this.flushRequests();
- },
- setException: function(ex)
+ }
+
+ setException(ex)
{
Debug.assert(!this._initialized && this._exception === null);
@@ -176,17 +163,17 @@ var ConnectRequestHandler = Ice.Class({
// Ignore
}
- for(var i = 0; i < this._requests.length; ++i)
- {
- var request = this._requests[i];
- if(request !== null)
+ this._requests.forEach(request =>
{
- request.__completedEx(this._exception);
- }
- }
+ if(request !== null)
+ {
+ request.completedEx(this._exception);
+ }
+ });
this._requests.length = 0;
- },
- initialized: function()
+ }
+
+ initialized()
{
if(this._initialized)
{
@@ -214,47 +201,44 @@ var ConnectRequestHandler = Ice.Class({
return this._initialized;
}
}
- },
- flushRequests: function()
+ }
+
+ flushRequests()
{
Debug.assert(this._connection !== null && !this._initialized);
- var exception = null;
- for(var i = 0; i < this._requests.length; ++i)
- {
- var request = this._requests[i];
- try
- {
- request.__invokeRemote(this._connection, this._compress, this._response);
- }
- catch(ex)
+ let exception = null;
+ this._requests.forEach(request =>
{
- if(ex instanceof RetryException)
+ try
{
- exception = ex.inner;
-
- // Remove the request handler before retrying.
- this._reference.getInstance().requestHandlerFactory().removeRequestHandler(this._reference, this);
-
- request.__retryException(ex.inner);
+ request.invokeRemote(this._connection, this._response);
}
- else
+ catch(ex)
{
- Debug.assert(ex instanceof LocalException);
- exception = ex;
- request.out.__completedEx(ex);
+ if(ex instanceof RetryException)
+ {
+ exception = ex.inner;
+
+ // Remove the request handler before retrying.
+ this._reference.getInstance().requestHandlerFactory().removeRequestHandler(this._reference, this);
+
+ request.retryException(ex.inner);
+ }
+ else
+ {
+ Debug.assert(ex instanceof LocalException);
+ exception = ex;
+ request.out.completedEx(ex);
+ }
}
- }
- }
+ });
this._requests.length = 0;
if(this._reference.getCacheConnection() && exception === null)
{
- this._requestHandler = new ConnectionRequestHandler(this._reference, this._connection, this._compress);
- for(var k = 0; k < this._proxies.length; ++k)
- {
- this._proxies[k].__updateRequestHandler(this, this._requestHandler);
- }
+ this._requestHandler = new ConnectionRequestHandler(this._reference, this._connection);
+ this._proxies.forEach(proxy => proxy._updateRequestHandler(this, this._requestHandler));
}
Debug.assert(!this._initialized);
@@ -270,7 +254,7 @@ var ConnectRequestHandler = Ice.Class({
this._proxies.length = 0;
this._proxy = null; // Break cyclic reference count.
}
-});
+}
Ice.ConnectRequestHandler = ConnectRequestHandler;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/ConnectionI.js b/js/src/Ice/ConnectionI.js
index 04dd1a0c4f3..1bf5c7d0b28 100644
--- a/js/src/Ice/ConnectionI.js
+++ b/js/src/Ice/ConnectionI.js
@@ -7,12 +7,11 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/AsyncStatus",
- "../Ice/BasicStream",
+ "../Ice/Stream",
"../Ice/OutgoingAsync",
"../Ice/Debug",
"../Ice/ExUtil",
@@ -30,52 +29,54 @@ Ice.__M.require(module,
"../Ice/BatchRequestQueue",
]);
-var AsyncStatus = Ice.AsyncStatus;
-var AsyncResultBase = Ice.AsyncResultBase;
-var BasicStream = Ice.BasicStream;
-var BatchRequestQueue = Ice.BatchRequestQueue;
-var ConnectionFlushBatch = Ice.ConnectionFlushBatch;
-var Debug = Ice.Debug;
-var ExUtil = Ice.ExUtil;
-var HashMap = Ice.HashMap;
-var IncomingAsync = Ice.IncomingAsync;
-var RetryException = Ice.RetryException;
-var Promise = Ice.Promise;
-var Protocol = Ice.Protocol;
-var SocketOperation = Ice.SocketOperation;
-var Timer = Ice.Timer;
-var TraceUtil = Ice.TraceUtil;
-var ProtocolVersion = Ice.ProtocolVersion;
-var EncodingVersion = Ice.EncodingVersion;
-var ACM = Ice.ACM;
-var ACMClose = Ice.ACMClose;
-var ACMHeartbeat = Ice.ACMHeartbeat;
-
-var StateNotInitialized = 0;
-var StateNotValidated = 1;
-var StateActive = 2;
-var StateHolding = 3;
-var StateClosing = 4;
-var StateClosed = 5;
-var StateFinished = 6;
-
-var MessageInfo = function(instance)
+const AsyncStatus = Ice.AsyncStatus;
+const AsyncResultBase = Ice.AsyncResultBase;
+const InputStream = Ice.InputStream;
+const OutputStream = Ice.OutputStream;
+const BatchRequestQueue = Ice.BatchRequestQueue;
+const ConnectionFlushBatch = Ice.ConnectionFlushBatch;
+const HeartbeatAsync = Ice.HeartbeatAsync;
+const Debug = Ice.Debug;
+const ExUtil = Ice.ExUtil;
+const HashMap = Ice.HashMap;
+const IncomingAsync = Ice.IncomingAsync;
+const RetryException = Ice.RetryException;
+const Protocol = Ice.Protocol;
+const SocketOperation = Ice.SocketOperation;
+const Timer = Ice.Timer;
+const TraceUtil = Ice.TraceUtil;
+const ProtocolVersion = Ice.ProtocolVersion;
+const EncodingVersion = Ice.EncodingVersion;
+const ACM = Ice.ACM;
+const ACMClose = Ice.ACMClose;
+const ACMHeartbeat = Ice.ACMHeartbeat;
+const ConnectionClose = Ice.ConnectionClose;
+
+const StateNotInitialized = 0;
+const StateNotValidated = 1;
+const StateActive = 2;
+const StateHolding = 3;
+const StateClosing = 4;
+const StateClosed = 5;
+const StateFinished = 6;
+
+class MessageInfo
{
- this.stream = new BasicStream(instance, Protocol.currentProtocolEncoding);
-
- this.invokeNum = 0;
- this.requestId = 0;
- this.compress = false;
- this.servantManager = null;
- this.adapter = null;
- this.outAsync = null;
- this.heartbeatCallback = null;
-};
-
-var Class = Ice.Class;
+ constructor(instance)
+ {
+ this.stream = new InputStream(instance, Protocol.currentProtocolEncoding);
+ this.invokeNum = 0;
+ this.requestId = 0;
+ this.servantManager = null;
+ this.adapter = null;
+ this.outAsync = null;
+ this.heartbeatCallback = null;
+ }
+}
-var ConnectionI = Class({
- __init__: function(communicator, instance, monitor, transceiver, endpoint, incoming, adapter)
+class ConnectionI
+{
+ constructor(communicator, instance, monitor, transceiver, endpoint, incoming, adapter)
{
this._communicator = communicator;
this._instance = instance;
@@ -86,7 +87,7 @@ var ConnectionI = Class({
this._endpoint = endpoint;
this._incoming = incoming;
this._adapter = adapter;
- var initData = instance.initializationData();
+ const initData = instance.initializationData();
this._logger = initData.logger; // Cached for better performance.
this._traceLevels = instance.traceLevels(); // Cached for better performance.
this._timer = instance.timer();
@@ -106,9 +107,9 @@ var ConnectionI = Class({
this._sendStreams = [];
- this._readStream = new BasicStream(instance, Protocol.currentProtocolEncoding);
+ this._readStream = new InputStream(instance, Protocol.currentProtocolEncoding);
this._readHeader = false;
- this._writeStream = new BasicStream(instance, Protocol.currentProtocolEncoding);
+ this._writeStream = new OutputStream(instance, Protocol.currentProtocolEncoding);
this._readStreamPos = -1;
this._writeStreamPos = -1;
@@ -140,9 +141,11 @@ var ConnectionI = Class({
{
this._servantManager = null;
}
- this._callback = null;
- },
- start: function()
+ this._closeCallback = null;
+ this._heartbeatCallback = null;
+ }
+
+ start()
{
Debug.assert(this._startPromise === null);
@@ -152,34 +155,14 @@ var ConnectionI = Class({
if(this._state >= StateClosed)
{
Debug.assert(this._exception !== null);
- return new Promise().fail(this._exception);
+ return Ice.Promise.reject(this._exception);
}
- this._startPromise = new Promise();
- var self = this;
+ this._startPromise = new Ice.Promise();
this._transceiver.setCallbacks(
- function() { self.message(SocketOperation.Write); }, // connected callback
- function() { self.message(SocketOperation.Read); }, // read callback
- function(bytesSent, bytesTotal) {
- self.message(SocketOperation.Write);
- if(self._instance.traceLevels().network >= 3 && bytesSent > 0)
- {
- var s = [];
- s.push("sent ");
- s.push(bytesSent);
- if(!self._endpoint.datagram())
- {
- s.push(" of ");
- s.push(bytesTotal);
- }
- s.push(" bytes via ");
- s.push(self._endpoint.protocol());
- s.push("\n");
- s.push(this.toString());
- self._instance.initializationData().logger.trace(self._instance.traceLevels().networkCat,
- s.join(""));
- }
- } // write callback
+ () => { this.message(SocketOperation.Write); }, // connected callback
+ () => { this.message(SocketOperation.Read); }, // read callback
+ () => { this.message(SocketOperation.Write); } // write callback
);
this.initialize();
}
@@ -189,12 +172,12 @@ var ConnectionI = Class({
{
this.exception(ex);
}
- return new Promise().fail(ex);
+ return Ice.Promise.reject(ex);
}
-
return this._startPromise;
- },
- activate: function()
+ }
+
+ activate()
{
if(this._state <= StateNotValidated)
{
@@ -206,8 +189,9 @@ var ConnectionI = Class({
this._acmLastActivity = Date.now();
}
this.setState(StateActive);
- },
- hold: function()
+ }
+
+ hold()
{
if(this._state <= StateNotValidated)
{
@@ -215,8 +199,9 @@ var ConnectionI = Class({
}
this.setState(StateHolding);
- },
- destroy: function(reason)
+ }
+
+ destroy(reason)
{
switch(reason)
{
@@ -232,53 +217,57 @@ var ConnectionI = Class({
break;
}
}
- },
- close: function(force)
+ }
+
+ close(mode)
{
- var __r = new AsyncResultBase(this._communicator, "close", this, null, null);
+ const r = new AsyncResultBase(this._communicator, "close", this, null, null);
- if(force)
+ if(mode == ConnectionClose.Forcefully)
{
- this.setState(StateClosed, new Ice.ForcedCloseConnectionException());
- __r.succeed(__r);
+ this.setState(StateClosed, new Ice.ConnectionManuallyClosedException(false));
+ r.resolve();
+ }
+ else if(mode == ConnectionClose.Gracefully)
+ {
+ this.setState(StateClosing, new Ice.ConnectionManuallyClosedException(true));
+ r.resolve();
}
else
{
+ Debug.assert(mode == ConnectionClose.GracefullyWithWait);
+
//
- // If we do a graceful shutdown, then we wait until all
- // outstanding requests have been completed. Otherwise,
- // the CloseConnectionException will cause all outstanding
- // requests to be retried, regardless of whether the
- // server has processed them or not.
+ // Wait until all outstanding requests have been completed.
//
- this._closePromises.push(__r);
+ this._closePromises.push(r);
this.checkClose();
}
- return __r;
- },
- checkClose: function()
+ return r;
+ }
+
+ checkClose()
{
//
- // If close(false) has been called, then we need to check if all
+ // If close(GracefullyWithWait) has been called, then we need to check if all
// requests have completed and we can transition to StateClosing.
// We also complete outstanding promises.
//
if(this._asyncRequests.size === 0 && this._closePromises.length > 0)
{
- this.setState(StateClosing, new Ice.CloseConnectionException());
- for(var i = 0; i < this._closePromises.length; ++i)
- {
- this._closePromises[i].succeed(this._closePromises[i]);
- }
+ this.setState(StateClosing, new Ice.ConnectionManuallyClosedException(true));
+ this._closePromises.forEach(p => p.resolve());
this._closePromises = [];
}
- },
- isActiveOrHolding: function()
+ }
+
+ isActiveOrHolding()
{
return this._state > StateNotValidated && this._state < StateClosing;
- },
- isFinished: function()
+ }
+
+ isFinished()
{
if(this._state !== StateFinished || this._dispatchCount !== 0)
{
@@ -287,30 +276,34 @@ var ConnectionI = Class({
Debug.assert(this._state === StateFinished);
return true;
- },
- throwException: function()
+ }
+
+ throwException()
{
if(this._exception !== null)
{
Debug.assert(this._state >= StateClosing);
throw this._exception;
}
- },
- waitUntilHolding: function()
+ }
+
+ waitUntilHolding()
{
- var promise = new Promise();
+ const promise = new Ice.Promise();
this._holdPromises.push(promise);
this.checkState();
return promise;
- },
- waitUntilFinished: function()
+ }
+
+ waitUntilFinished()
{
- var promise = new Promise();
+ const promise = new Ice.Promise();
this._finishedPromises.push(promise);
this.checkState();
return promise;
- },
- monitor: function(now, acm)
+ }
+
+ monitor(now, acm)
{
if(this._state !== StateActive)
{
@@ -321,22 +314,22 @@ var ConnectionI = Class({
// We send a heartbeat if there was no activity in the last
// (timeout / 4) period. Sending a heartbeat sooner than
// really needed is safer to ensure that the receiver will
- // receive in time the heartbeat. Sending the heartbeat if
+ // receive the heartbeat in time. Sending the heartbeat if
// there was no activity in the last (timeout / 2) period
// isn't enough since monitor() is called only every (timeout
// / 2) period.
//
// Note that this doesn't imply that we are sending 4 heartbeats
- // per timeout period because the monitor() method is sill only
+ // per timeout period because the monitor() method is still only
// called every (timeout / 2) period.
//
if(acm.heartbeat == Ice.ACMHeartbeat.HeartbeatAlways ||
- (acm.heartbeat != Ice.ACMHeartbeat.HeartbeatOff && this._writeStream.isEmpty() &&
- now >= (this._acmLastActivity + acm.timeout / 4)))
+ (acm.heartbeat != Ice.ACMHeartbeat.HeartbeatOff && this._writeStream.isEmpty() &&
+ now >= (this._acmLastActivity + acm.timeout / 4)))
{
if(acm.heartbeat != Ice.ACMHeartbeat.HeartbeatOnInvocation || this._dispatchCount > 0)
{
- this.heartbeat(); // Send heartbeat if idle in the last timeout / 2 period.
+ this.sendHeartbeatNow(); // Send heartbeat if idle in the last timeout / 2 period.
}
}
@@ -354,7 +347,7 @@ var ConnectionI = Class({
if(acm.close != Ice.ACMClose.CloseOff && now >= (this._acmLastActivity + acm.timeout))
{
if(acm.close == Ice.ACMClose.CloseOnIdleForceful ||
- (acm.close != Ice.ACMClose.CloseOnIdle && this._asyncRequests.size > 0))
+ (acm.close != Ice.ACMClose.CloseOnIdle && this._asyncRequests.size > 0))
{
//
// Close the connection if we didn't receive a heartbeat in
@@ -371,11 +364,12 @@ var ConnectionI = Class({
this.setState(StateClosing, new Ice.ConnectionTimeoutException());
}
}
- },
- sendAsyncRequest: function(out, compress, response, batchRequestNum)
+ }
+
+ sendAsyncRequest(out, response, batchRequestNum)
{
- var requestId = 0;
- var os = out.__os();
+ let requestId = 0;
+ const ostr = out.getOs();
if(this._exception !== null)
{
@@ -394,13 +388,13 @@ var ConnectionI = Class({
// Ensure the message isn't bigger than what we can send with the
// transport.
//
- this._transceiver.checkSendSize(os);
+ this._transceiver.checkSendSize(ostr);
//
// Notify the request that it's cancelable with this connection.
// This will throw if the request is canceled.
//
- out.__cancelable(this); // Notify the request that it's cancelable
+ out.cancelable(this); // Notify the request that it's cancelable
if(response)
{
@@ -417,19 +411,19 @@ var ConnectionI = Class({
//
// Fill in the request ID.
//
- os.pos = Protocol.headerSize;
- os.writeInt(requestId);
+ ostr.pos = Protocol.headerSize;
+ ostr.writeInt(requestId);
}
else if(batchRequestNum > 0)
{
- os.pos = Protocol.headerSize;
- os.writeInt(batchRequestNum);
+ ostr.pos = Protocol.headerSize;
+ ostr.writeInt(batchRequestNum);
}
- var status;
+ let status;
try
{
- status = this.sendMessage(OutgoingMessage.create(out, out.__os(), compress, requestId));
+ status = this.sendMessage(OutgoingMessage.create(out, out.getOs(), requestId));
}
catch(ex)
{
@@ -454,42 +448,58 @@ var ConnectionI = Class({
}
return status;
- },
- getBatchRequestQueue: function()
+ }
+
+ getBatchRequestQueue()
{
return this._batchRequestQueue;
- },
- flushBatchRequests: function()
+ }
+
+ flushBatchRequests()
{
- var result = new ConnectionFlushBatch(this, this._communicator, "flushBatchRequests");
- result.__invoke();
+ const result = new ConnectionFlushBatch(this, this._communicator, "flushBatchRequests");
+ result.invoke();
return result;
- },
- setCallback: function(callback)
+ }
+
+ setCloseCallback(callback)
{
if(this._state >= StateClosed)
{
if(callback !== null)
{
- var self = this;
- Timer.setImmediate(function() {
+ Timer.setImmediate(() =>
+ {
try
{
- callback.closed(this);
+ callback(this);
}
catch(ex)
{
- self._logger.error("connection callback exception:\n" + ex + '\n' + self._desc);
+ this._logger.error("connection callback exception:\n" + ex + '\n' + this._desc);
}
});
}
}
else
{
- this._callback = callback;
+ this._closeCallback = callback;
}
- },
- setACM: function(timeout, close, heartbeat)
+ }
+
+ setHeartbeatCallback(callback)
+ {
+ this._heartbeatCallback = callback;
+ }
+
+ heartbeat()
+ {
+ const result = new HeartbeatAsync(this, this._communicator);
+ result.invoke();
+ return result;
+ }
+
+ setACM(timeout, close, heartbeat)
{
if(this._monitor === null || this._state >= StateClosed)
{
@@ -513,17 +523,19 @@ var ConnectionI = Class({
{
this._acmLastActivity = Date.now();
}
- },
- getACM: function()
+ }
+
+ getACM()
{
return this._monitor !== null ? this._monitor.getACM() :
new ACM(0, ACMClose.CloseOff, ACMHeartbeat.HeartbeatOff);
- },
- asyncRequestCanceled: function(outAsync, ex)
+ }
+
+ asyncRequestCanceled(outAsync, ex)
{
- for(var i = 0; i < this._sendStreams.length; i++)
+ for(let i = 0; i < this._sendStreams.length; i++)
{
- var o = this._sendStreams[i];
+ let o = this._sendStreams[i];
if(o.outAsync === outAsync)
{
if(o.requestId > 0)
@@ -540,25 +552,26 @@ var ConnectionI = Class({
{
this._sendStreams.splice(i, 1);
}
- outAsync.__completedEx(ex);
+ outAsync.completedEx(ex);
return; // We're done.
}
}
if(outAsync instanceof Ice.OutgoingAsync)
{
- for(var e = this._asyncRequests.entries; e !== null; e = e.next)
+ for(let [key, value] of this._asyncRequests)
{
- if(e.value === outAsync)
+ if(value === outAsync)
{
- this._asyncRequests.delete(e.key);
- outAsync.__completedEx(ex);
+ this._asyncRequests.delete(key);
+ outAsync.completedEx(ex);
return; // We're done.
}
}
}
- },
- sendResponse: function(os, compressFlag)
+ }
+
+ sendResponse(os)
{
Debug.assert(this._state > StateNotValidated);
@@ -579,7 +592,7 @@ var ConnectionI = Class({
throw this._exception;
}
- this.sendMessage(OutgoingMessage.createForStream(os, compressFlag !== 0, true));
+ this.sendMessage(OutgoingMessage.createForStream(os, true));
if(this._state === StateClosing && this._dispatchCount === 0)
{
@@ -597,8 +610,9 @@ var ConnectionI = Class({
throw ex;
}
}
- },
- sendNoResponse: function()
+ }
+
+ sendNoResponse()
{
Debug.assert(this._state > StateNotValidated);
try
@@ -634,12 +648,14 @@ var ConnectionI = Class({
throw ex;
}
}
- },
- endpoint: function()
+ }
+
+ endpoint()
{
return this._endpoint;
- },
- setAdapter: function(adapter)
+ }
+
+ setAdapter(adapter)
{
if(this._state <= StateNotValidated || this._state >= StateClosing)
{
@@ -661,16 +677,19 @@ var ConnectionI = Class({
{
this._servantManager = null;
}
- },
- getAdapter: function()
+ }
+
+ getAdapter()
{
return this._adapter;
- },
- getEndpoint: function()
+ }
+
+ getEndpoint()
{
return this._endpoint;
- },
- createProxy: function(ident)
+ }
+
+ createProxy(ident)
{
//
// Create a reference and return a reverse proxy for this
@@ -678,8 +697,9 @@ var ConnectionI = Class({
//
return this._instance.proxyFactory().referenceToProxy(
this._instance.referenceFactory().createFixed(ident, this));
- },
- message: function(operation)
+ }
+
+ message(operation)
{
if(this._state >= StateClosed)
{
@@ -693,7 +713,7 @@ var ConnectionI = Class({
//
this._hasMoreData.value = (operation & SocketOperation.Read) !== 0;
- var info = null;
+ let info = null;
try
{
if((operation & SocketOperation.Write) !== 0 && this._writeStream.buffer.remaining > 0)
@@ -721,7 +741,7 @@ var ConnectionI = Class({
Debug.assert(this._readStream.buffer.remaining === 0);
this._readHeader = false;
- var pos = this._readStream.pos;
+ const pos = this._readStream.pos;
if(pos < Protocol.headerSize)
{
//
@@ -731,27 +751,25 @@ var ConnectionI = Class({
}
this._readStream.pos = 0;
- var magic0 = this._readStream.readByte();
- var magic1 = this._readStream.readByte();
- var magic2 = this._readStream.readByte();
- var magic3 = this._readStream.readByte();
+ const magic0 = this._readStream.readByte();
+ const magic1 = this._readStream.readByte();
+ const magic2 = this._readStream.readByte();
+ const magic3 = this._readStream.readByte();
if(magic0 !== Protocol.magic[0] || magic1 !== Protocol.magic[1] ||
- magic2 !== Protocol.magic[2] || magic3 !== Protocol.magic[3])
+ magic2 !== Protocol.magic[2] || magic3 !== Protocol.magic[3])
{
- var bme = new Ice.BadMagicException();
- bme.badMagic = Ice.Buffer.createNative([magic0, magic1, magic2, magic3]);
- throw bme;
+ throw new Ice.BadMagicException("", Ice.Buffer.createNative([magic0, magic1, magic2, magic3]));
}
- this._readProtocol.__read(this._readStream);
+ this._readProtocol._read(this._readStream);
Protocol.checkSupportedProtocol(this._readProtocol);
- this._readProtocolEncoding.__read(this._readStream);
+ this._readProtocolEncoding._read(this._readStream);
Protocol.checkSupportedProtocolEncoding(this._readProtocolEncoding);
this._readStream.readByte(); // messageType
this._readStream.readByte(); // compress
- var size = this._readStream.readInt();
+ const size = this._readStream.readInt();
if(size < Protocol.headerSize)
{
throw new Ice.IllegalMessageSizeException();
@@ -879,20 +897,21 @@ var ConnectionI = Class({
if(this._hasMoreData.value)
{
- var self = this;
- Timer.setImmediate(function() { self.message(SocketOperation.Read); }); // Don't tie up the thread.
+ Timer.setImmediate(() => { this.message(SocketOperation.Read); }); // Don't tie up the thread.
}
- },
- dispatch: function(info)
+ }
+
+ dispatch(info)
{
- var count = 0;
+ let count = 0;
//
// Notify the factory that the connection establishment and
// validation has completed.
//
if(this._startPromise !== null)
{
- this._startPromise.succeed();
+ this._startPromise.resolve();
+
this._startPromise = null;
++count;
}
@@ -901,14 +920,13 @@ var ConnectionI = Class({
{
if(info.outAsync !== null)
{
- info.outAsync.__completed(info.stream);
+ info.outAsync.completed(info.stream);
++count;
}
if(info.invokeNum > 0)
{
- this.invokeAll(info.stream, info.invokeNum, info.requestId, info.compress, info.servantManager,
- info.adapter);
+ this.invokeAll(info.stream, info.invokeNum, info.requestId, info.servantManager, info.adapter);
//
// Don't increase count, the dispatch count is
@@ -920,7 +938,7 @@ var ConnectionI = Class({
{
try
{
- info.heartbeatCallback.heartbeat(this);
+ info.heartbeatCallback(this);
}
catch(ex)
{
@@ -964,19 +982,19 @@ var ConnectionI = Class({
this.checkState();
}
}
- },
- finish: function()
+ }
+
+ finish()
{
Debug.assert(this._state === StateClosed);
this.unscheduleTimeout(SocketOperation.Read | SocketOperation.Write | SocketOperation.Connect);
- var s;
- var traceLevels = this._instance.traceLevels();
+ const traceLevels = this._instance.traceLevels();
if(!this._initialized)
{
if(traceLevels.network >= 2)
{
- s = [];
+ let s = [];
s.push("failed to establish ");
s.push(this._endpoint.protocol());
s.push(" connection\n");
@@ -990,7 +1008,7 @@ var ConnectionI = Class({
{
if(traceLevels.network >= 1)
{
- s = [];
+ let s = [];
s.push("closed ");
s.push(this._endpoint.protocol());
s.push(" connection\n");
@@ -1000,7 +1018,7 @@ var ConnectionI = Class({
// Trace the cause of unexpected connection closures
//
if(!(this._exception instanceof Ice.CloseConnectionException ||
- this._exception instanceof Ice.ForcedCloseConnectionException ||
+ this._exception instanceof Ice.ConnectionManuallyClosedException ||
this._exception instanceof Ice.ConnectionTimeoutException ||
this._exception instanceof Ice.CommunicatorDestroyedException ||
this._exception instanceof Ice.ObjectAdapterDeactivatedException))
@@ -1015,7 +1033,7 @@ var ConnectionI = Class({
if(this._startPromise !== null)
{
- this._startPromise.fail(this._exception);
+ this._startPromise.reject(this._exception);
this._startPromise = null;
}
@@ -1027,8 +1045,7 @@ var ConnectionI = Class({
// Return the stream to the outgoing call. This is important for
// retriable AMI calls which are not marshalled again.
//
- var message = this._sendStreams[0];
- this._writeStream.swap(message.stream);
+ this._writeStream.swap(this._sendStreams[0].stream);
}
//
@@ -1037,9 +1054,9 @@ var ConnectionI = Class({
// because it's either in the _requests/_asyncRequests set. This is fine, only the
// first call should be taken into account by the implementation of finished.
//
- for(var i = 0; i < this._sendStreams.length; ++i)
+ for(let i = 0; i < this._sendStreams.length; ++i)
{
- var p = this._sendStreams[i];
+ let p = this._sendStreams[i];
if(p.requestId > 0)
{
this._asyncRequests.delete(p.requestId);
@@ -1049,9 +1066,9 @@ var ConnectionI = Class({
this._sendStreams = [];
}
- for(var e = this._asyncRequests.entries; e !== null; e = e.next)
+ for(let value of this._asyncRequests.values())
{
- e.value.__completedEx(this._exception);
+ value.completedEx(this._exception);
}
this._asyncRequests.clear();
@@ -1063,19 +1080,21 @@ var ConnectionI = Class({
this._writeStream.clear();
this._writeStream.buffer.clear();
- if(this._callback !== null)
+ if(this._closeCallback !== null)
{
try
{
- this._callback.closed(this);
+ this._closeCallback(this);
}
catch(ex)
{
this._logger.error("connection callback exception:\n" + ex + '\n' + this._desc);
}
- this._callback = null;
+ this._closeCallback = null;
}
+ this._heartbeatCallback = null;
+
//
// This must be done last as this will cause waitUntilFinished() to return (and communicator
// objects such as the timer might be destroyed too).
@@ -1085,12 +1104,14 @@ var ConnectionI = Class({
this.reap();
}
this.setState(StateFinished);
- },
- toString: function()
+ }
+
+ toString()
{
return this._desc;
- },
- timedOut: function(event)
+ }
+
+ timedOut(event)
{
if(this._state <= StateNotValidated)
{
@@ -1104,39 +1125,48 @@ var ConnectionI = Class({
{
this.setState(StateClosed, new Ice.CloseTimeoutException());
}
- },
- type: function()
+ }
+
+ type()
{
return this._type;
- },
- timeout: function()
+ }
+
+ timeout()
{
return this._endpoint.timeout();
- },
- getInfo: function()
+ }
+
+ getInfo()
{
if(this._state >= StateClosed)
{
throw this._exception;
}
- var info = this._transceiver.getInfo();
- info.adapterName = this._adapter !== null ? this._adapter.getName() : "";
- info.incoming = this._incoming;
+ let info = this._transceiver.getInfo();
+ for(let p = info; p !== null; p = p.underlying)
+ {
+ p.adapterName = this._adapter !== null ? this._adapter.getName() : "";
+ p.incoming = this._incoming;
+ }
return info;
- },
- setBufferSize: function(rcvSize, sndSize)
+ }
+
+ setBufferSize(rcvSize, sndSize)
{
if(this._state >= StateClosed)
{
throw this._exception;
}
this._transceiver.setBufferSize(rcvSize, sndSize);
- },
- exception: function(ex)
+ }
+
+ exception(ex)
{
this.setState(StateClosed, ex);
- },
- invokeException: function(ex, invokeNum)
+ }
+
+ invokeException(ex, invokeNum)
{
//
// Fatal exception while invoking a request. Since sendResponse/sendNoResponse isn't
@@ -1159,8 +1189,9 @@ var ConnectionI = Class({
this.checkState();
}
}
- },
- setState: function(state, ex)
+ }
+
+ setState(state, ex)
{
if(ex !== undefined)
{
@@ -1190,7 +1221,7 @@ var ConnectionI = Class({
// Don't warn about certain expected exceptions.
//
if(!(this._exception instanceof Ice.CloseConnectionException ||
- this._exception instanceof Ice.ForcedCloseConnectionException ||
+ this._exception instanceof Ice.ConnectionManuallyClosedException ||
this._exception instanceof Ice.ConnectionTimeoutException ||
this._exception instanceof Ice.CommunicatorDestroyedException ||
this._exception instanceof Ice.ObjectAdapterDeactivatedException ||
@@ -1334,8 +1365,8 @@ var ConnectionI = Class({
{
if(ex instanceof Ice.LocalException)
{
- var msg = "unexpected connection exception:\n " + this._desc + "\n" + ex.toString();
- this._instance.initializationData().logger.error(msg);
+ this._instance.initializationData().logger.error(
+ `unexpected connection exception:\n${this._desc}\n${ex.toString()}`);
}
else
{
@@ -1391,29 +1422,27 @@ var ConnectionI = Class({
}
this.checkState();
- },
- initiateShutdown: function()
+ }
+
+ initiateShutdown()
{
- Debug.assert(this._state === StateClosing);
- Debug.assert(this._dispatchCount === 0);
+ Debug.assert(this._state === StateClosing && this._dispatchCount === 0);
Debug.assert(!this._shutdownInitiated);
if(!this._endpoint.datagram())
{
//
- // Before we shut down, we send a close connection
- // message.
+ // Before we shut down, we send a close connection message.
//
- var os = new BasicStream(this._instance, Protocol.currentProtocolEncoding);
+ const os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
os.writeBlob(Protocol.magic);
- Protocol.currentProtocol.__write(os);
- Protocol.currentProtocolEncoding.__write(os);
+ Protocol.currentProtocol._write(os);
+ Protocol.currentProtocolEncoding._write(os);
os.writeByte(Protocol.closeConnectionMsg);
os.writeByte(0); // compression status: always report 0 for CloseConnection.
os.writeInt(Protocol.headerSize); // Message size.
- var status = this.sendMessage(OutgoingMessage.createForStream(os, false, false));
- if((status & AsyncStatus.Sent) > 0)
+ if((this.sendMessage(OutgoingMessage.createForStream(os, false)) & AsyncStatus.Sent) > 0)
{
//
// Schedule the close timeout to wait for the peer to close the connection.
@@ -1431,23 +1460,24 @@ var ConnectionI = Class({
//
//this._transceiver.shutdownWrite();
}
- },
- heartbeat: function()
+ }
+
+ sendHeartbeatNow()
{
Debug.assert(this._state === StateActive);
if(!this._endpoint.datagram())
{
- var os = new BasicStream(this._instance, Protocol.currentProtocolEncoding);
+ const os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
os.writeBlob(Protocol.magic);
- Protocol.currentProtocol.__write(os);
- Protocol.currentProtocolEncoding.__write(os);
+ Protocol.currentProtocol._write(os);
+ Protocol.currentProtocolEncoding._write(os);
os.writeByte(Protocol.validateConnectionMsg);
os.writeByte(0);
os.writeInt(Protocol.headerSize); // Message size.
try
{
- this.sendMessage(OutgoingMessage.createForStream(os, false, false));
+ this.sendMessage(OutgoingMessage.createForStream(os, false));
}
catch(ex)
{
@@ -1455,10 +1485,11 @@ var ConnectionI = Class({
Debug.assert(this._exception !== null);
}
}
- },
- initialize: function()
+ }
+
+ initialize()
{
- var s = this._transceiver.initialize(this._readStream.buffer, this._writeStream.buffer);
+ const s = this._transceiver.initialize(this._readStream.buffer, this._writeStream.buffer);
if(s != SocketOperation.None)
{
this.scheduleTimeout(s, this.connectTimeout());
@@ -1472,8 +1503,9 @@ var ConnectionI = Class({
this._initialized = true;
this.setState(StateNotValidated);
return true;
- },
- validate: function()
+ }
+
+ validate()
{
if(!this._endpoint.datagram()) // Datagram connections are always implicitly validated.
{
@@ -1482,8 +1514,8 @@ var ConnectionI = Class({
if(this._writeStream.size === 0)
{
this._writeStream.writeBlob(Protocol.magic);
- Protocol.currentProtocol.__write(this._writeStream);
- Protocol.currentProtocolEncoding.__write(this._writeStream);
+ Protocol.currentProtocol._write(this._writeStream);
+ Protocol.currentProtocolEncoding._write(this._writeStream);
this._writeStream.writeByte(Protocol.validateConnectionMsg);
this._writeStream.writeByte(0); // Compression status (always zero for validate connection).
this._writeStream.writeInt(Protocol.headerSize); // Message size.
@@ -1514,29 +1546,26 @@ var ConnectionI = Class({
Debug.assert(this._readStream.pos === Protocol.headerSize);
this._readStream.pos = 0;
- var m = this._readStream.readBlob(4);
+ const m = this._readStream.readBlob(4);
if(m[0] !== Protocol.magic[0] || m[1] !== Protocol.magic[1] ||
m[2] !== Protocol.magic[2] || m[3] !== Protocol.magic[3])
{
- var bme = new Ice.BadMagicException();
- bme.badMagic = m;
- throw bme;
+ throw new Ice.BadMagicException("", m);
}
- this._readProtocol.__read(this._readStream);
+ this._readProtocol._read(this._readStream);
Protocol.checkSupportedProtocol(this._readProtocol);
- this._readProtocolEncoding.__read(this._readStream);
+ this._readProtocolEncoding._read(this._readStream);
Protocol.checkSupportedProtocolEncoding(this._readProtocolEncoding);
- var messageType = this._readStream.readByte();
+ const messageType = this._readStream.readByte();
if(messageType !== Protocol.validateConnectionMsg)
{
throw new Ice.ConnectionNotValidatedException();
}
this._readStream.readByte(); // Ignore compression status for validate connection.
- var size = this._readStream.readInt();
- if(size !== Protocol.headerSize)
+ if( this._readStream.readInt() !== Protocol.headerSize)
{
throw new Ice.IllegalMessageSizeException();
}
@@ -1552,10 +1581,10 @@ var ConnectionI = Class({
this._readHeader = true;
this._readStream.pos = 0;
- var traceLevels = this._instance.traceLevels();
+ const traceLevels = this._instance.traceLevels();
if(traceLevels.network >= 1)
{
- var s = [];
+ let s = [];
if(this._endpoint.datagram())
{
s.push("starting to send ");
@@ -1565,7 +1594,6 @@ var ConnectionI = Class({
}
else
{
- s = [];
s.push("established ");
s.push(this._endpoint.protocol());
s.push(" connection\n");
@@ -1575,8 +1603,9 @@ var ConnectionI = Class({
}
return true;
- },
- sendNextMessage: function()
+ }
+
+ sendNextMessage()
{
if(this._sendStreams.length === 0)
{
@@ -1591,7 +1620,7 @@ var ConnectionI = Class({
//
// Notify the message that it was sent.
//
- var message = this._sendStreams.shift();
+ let message = this._sendStreams.shift();
this._writeStream.swap(message.stream);
message.sent();
@@ -1620,21 +1649,15 @@ var ConnectionI = Class({
//
message = this._sendStreams[0];
Debug.assert(!message.prepared);
- var stream = message.stream;
+ let stream = message.stream;
stream.pos = 10;
stream.writeInt(stream.size);
stream.prepareWrite();
message.prepared = true;
- if(message.outAsync !== null)
- {
- TraceUtil.trace("sending asynchronous request", stream, this._logger, this._traceLevels);
- }
- else
- {
- TraceUtil.traceSend(stream, this._logger, this._traceLevels);
- }
+ TraceUtil.traceSend(stream, this._logger, this._traceLevels);
+
this._writeStream.swap(message.stream);
//
@@ -1671,8 +1694,9 @@ var ConnectionI = Class({
{
this.scheduleTimeout(SocketOperation.Write, this.closeTimeout());
}
- },
- sendMessage: function(message)
+ }
+
+ sendMessage(message)
{
if(this._sendStreams.length > 0)
{
@@ -1684,22 +1708,15 @@ var ConnectionI = Class({
Debug.assert(!message.prepared);
- var stream = message.stream;
+ let stream = message.stream;
stream.pos = 10;
stream.writeInt(stream.size);
stream.prepareWrite();
message.prepared = true;
- if(message.outAsync)
- {
- TraceUtil.trace("sending asynchronous request", message.stream, this._logger, this._traceLevels);
- }
- else
- {
- TraceUtil.traceSend(message.stream, this._logger, this._traceLevels);
- }
+ TraceUtil.traceSend(stream, this._logger, this._traceLevels);
- if(this.write(message.stream.buffer))
+ if(this.write(stream.buffer))
{
//
// Entire buffer was written immediately.
@@ -1714,17 +1731,18 @@ var ConnectionI = Class({
}
message.doAdopt();
- this._writeStream.swap(message.stream);
+ this._writeStream.swap(stream);
this._sendStreams.push(message);
this.scheduleTimeout(SocketOperation.Write, this._endpoint.timeout());
return AsyncStatus.Queued;
- },
- parseMessage: function()
+ }
+
+ parseMessage()
{
Debug.assert(this._state > StateNotValidated && this._state < StateClosed);
- var info = new MessageInfo(this._instance);
+ let info = new MessageInfo(this._instance);
this._readStream.swap(info.stream);
this._readStream.resize(Protocol.headerSize);
@@ -1748,13 +1766,11 @@ var ConnectionI = Class({
// been done by the caller.
//
info.stream.pos = 8;
- var messageType = info.stream.readByte();
- info.compress = info.stream.readByte();
- if(info.compress === 2)
+ const messageType = info.stream.readByte();
+ const compress = info.stream.readByte();
+ if(compress === 2)
{
- var ex = new Ice.FeatureNotSupportedException();
- ex.unsupportedFeature = "Cannot uncompress compressed message";
- throw ex;
+ throw new Ice.FeatureNotSupportedException("Cannot uncompress compressed message");
}
info.stream.pos = Protocol.headerSize;
@@ -1782,9 +1798,9 @@ var ConnectionI = Class({
{
if(this._state === StateClosing)
{
- TraceUtil.trace("received request during closing\n" +
- "(ignored by server, client will retry)",
- info.stream, this._logger, this._traceLevels);
+ TraceUtil.traceIn("received request during closing\n" +
+ "(ignored by server, client will retry)",
+ info.stream, this._logger, this._traceLevels);
}
else
{
@@ -1802,9 +1818,9 @@ var ConnectionI = Class({
{
if(this._state === StateClosing)
{
- TraceUtil.trace("received batch request during closing\n" +
- "(ignored by server, client will retry)",
- info.stream, this._logger, this._traceLevels);
+ TraceUtil.traceIn("received batch request during closing\n" +
+ "(ignored by server, client will retry)",
+ info.stream, this._logger, this._traceLevels);
}
else
{
@@ -1843,9 +1859,9 @@ var ConnectionI = Class({
case Protocol.validateConnectionMsg:
{
TraceUtil.traceRecv(info.stream, this._logger, this._traceLevels);
- if(this._callback !== null)
+ if(this._heartbeatCallback !== null)
{
- info.heartbeatCallback = this._callback;
+ info.heartbeatCallback = this._heartbeatCallback;
++this._dispatchCount;
}
break;
@@ -1853,8 +1869,8 @@ var ConnectionI = Class({
default:
{
- TraceUtil.trace("received unknown message\n(invalid, closing connection)",
- info.stream, this._logger, this._traceLevels);
+ TraceUtil.traceIn("received unknown message\n(invalid, closing connection)",
+ info.stream, this._logger, this._traceLevels);
throw new Ice.UnknownMessageException();
}
}
@@ -1882,10 +1898,10 @@ var ConnectionI = Class({
}
return info;
- },
- invokeAll: function(stream, invokeNum, requestId, compress, servantManager, adapter)
+ }
+
+ invokeAll(stream, invokeNum, requestId, servantManager, adapter)
{
- var inc = null;
try
{
while(invokeNum > 0)
@@ -1893,8 +1909,10 @@ var ConnectionI = Class({
//
// Prepare the invocation.
//
- var response = !this._endpoint.datagram() && requestId !== 0;
- inc = new IncomingAsync(this._instance, this, adapter, response, compress, requestId);
+ let inc = new IncomingAsync(this._instance, this,
+ adapter,
+ !this._endpoint.datagram() && requestId !== 0, // response
+ requestId);
//
// Dispatch the invocation.
@@ -1902,7 +1920,6 @@ var ConnectionI = Class({
inc.invoke(servantManager, stream);
--invokeNum;
- inc = null;
}
stream.clear();
@@ -1918,27 +1935,28 @@ var ConnectionI = Class({
throw ex;
}
}
- },
- scheduleTimeout: function(op, timeout)
+ }
+
+ scheduleTimeout(op, timeout)
{
if(timeout < 0)
{
return;
}
- var self = this;
if((op & SocketOperation.Read) !== 0)
{
- this._readTimeoutId = this._timer.schedule(function() { self.timedOut(); }, timeout);
+ this._readTimeoutId = this._timer.schedule(() => this.timedOut(), timeout);
this._readTimeoutScheduled = true;
}
if((op & (SocketOperation.Write | SocketOperation.Connect)) !== 0)
{
- this._writeTimeoutId = this._timer.schedule(function() { self.timedOut(); }, timeout);
+ this._writeTimeoutId = this._timer.schedule(() => this.timedOut(), timeout);
this._writeTimeoutScheduled = true;
}
- },
- unscheduleTimeout: function(op)
+ }
+
+ unscheduleTimeout(op)
{
if((op & SocketOperation.Read) !== 0 && this._readTimeoutScheduled)
{
@@ -1950,10 +1968,11 @@ var ConnectionI = Class({
this._timer.cancel(this._writeTimeoutId);
this._writeTimeoutScheduled = false;
}
- },
- connectTimeout: function()
+ }
+
+ connectTimeout()
{
- var defaultsAndOverrides = this._instance.defaultsAndOverrides();
+ const defaultsAndOverrides = this._instance.defaultsAndOverrides();
if(defaultsAndOverrides.overrideConnectTimeout)
{
return defaultsAndOverrides.overrideConnectTimeoutValue;
@@ -1962,10 +1981,11 @@ var ConnectionI = Class({
{
return this._endpoint.timeout();
}
- },
- closeTimeout: function()
+ }
+
+ closeTimeout()
{
- var defaultsAndOverrides = this._instance.defaultsAndOverrides();
+ const defaultsAndOverrides = this._instance.defaultsAndOverrides();
if(defaultsAndOverrides.overrideCloseTimeout)
{
return defaultsAndOverrides.overrideCloseTimeoutValue;
@@ -1974,27 +1994,22 @@ var ConnectionI = Class({
{
return this._endpoint.timeout();
}
- },
- warning: function(msg, ex)
+ }
+
+ warning(msg, ex)
{
this._logger.warning(msg + ":\n" + this._desc + "\n" + ex.toString());
- },
- checkState: function()
+ }
+
+ checkState()
{
if(this._state < StateHolding || this._dispatchCount > 0)
{
return;
}
- var i;
- if(this._holdPromises.length > 0)
- {
- for(i = 0; i < this._holdPromises.length; ++i)
- {
- this._holdPromises[i].succeed();
- }
- this._holdPromises = [];
- }
+ this._holdPromises.forEach(p => p.resolve());
+ this._holdPromises = [];
//
// We aren't finished until the state is finished and all
@@ -2008,28 +2023,26 @@ var ConnectionI = Class({
// Clear the OA. See bug 1673 for the details of why this is necessary.
//
this._adapter = null;
-
- for(i = 0; i < this._finishedPromises.length; ++i)
- {
- this._finishedPromises[i].succeed();
- }
+ this._finishedPromises.forEach(p => p.resolve());
this._finishedPromises = [];
}
- },
- reap: function()
+ }
+
+ reap()
{
if(this._monitor !== null)
{
this._monitor.reap(this);
}
- },
- read: function(buf)
+ }
+
+ read(buf)
{
- var start = buf.position;
- var ret = this._transceiver.read(buf, this._hasMoreData);
+ const start = buf.position;
+ const ret = this._transceiver.read(buf, this._hasMoreData);
if(this._instance.traceLevels().network >= 3 && buf.position != start)
{
- var s = [];
+ let s = [];
s.push("received ");
if(this._endpoint.datagram())
{
@@ -2048,14 +2061,15 @@ var ConnectionI = Class({
this._instance.initializationData().logger.trace(this._instance.traceLevels().networkCat, s.join(""));
}
return ret;
- },
- write: function(buf)
+ }
+
+ write(buf)
{
- var start = buf.position;
- var ret = this._transceiver.write(buf);
+ const start = buf.position;
+ const ret = this._transceiver.write(buf);
if(this._instance.traceLevels().network >= 3 && buf.position != start)
{
- var s = [];
+ let s = [];
s.push("sent ");
s.push(buf.position - start);
if(!this._endpoint.datagram())
@@ -2071,7 +2085,7 @@ var ConnectionI = Class({
}
return ret;
}
-});
+}
// DestructionReason.
ConnectionI.ObjectAdapterDeactivated = 0;
@@ -2079,68 +2093,70 @@ ConnectionI.CommunicatorDestroyed = 1;
Ice.ConnectionI = ConnectionI;
-var OutgoingMessage = Class({
- __init__: function()
+class OutgoingMessage
+{
+ constructor()
{
this.stream = null;
this.outAsync = null;
- this.compress = false;
this.requestId = 0;
this.prepared = false;
- },
- canceled: function()
+ }
+
+ canceled()
{
Debug.assert(this.outAsync !== null);
this.outAsync = null;
- },
- doAdopt: function()
+ }
+
+ doAdopt()
{
if(this.adopt)
{
- var stream = new BasicStream(this.stream.instance, Protocol.currentProtocolEncoding);
+ const stream = new OutputStream(this.stream.instance, Protocol.currentProtocolEncoding);
stream.swap(this.stream);
this.stream = stream;
this.adopt = false;
}
- },
- sent: function()
+ }
+
+ sent()
{
if(this.outAsync !== null)
{
- this.outAsync.__sent();
+ this.outAsync.sent();
}
- },
- completed: function(ex)
+ }
+
+ completed(ex)
{
if(this.outAsync !== null)
{
- this.outAsync.__completedEx(ex);
+ this.outAsync.completedEx(ex);
}
}
-});
-OutgoingMessage.createForStream = function(stream, compress, adopt)
-{
- var m = new OutgoingMessage();
- m.stream = stream;
- m.compress = compress;
- m.adopt = adopt;
- m.isSent = false;
- m.requestId = 0;
- m.outAsync = null;
- return m;
-};
-
-OutgoingMessage.create = function(out, stream, compress, requestId)
-{
- var m = new OutgoingMessage();
- m.stream = stream;
- m.compress = compress;
- m.outAsync = out;
- m.requestId = requestId;
- m.isSent = false;
- m.adopt = false;
- return m;
-};
+ static createForStream(stream, adopt)
+ {
+ const m = new OutgoingMessage();
+ m.stream = stream;
+ m.adopt = adopt;
+ m.isSent = false;
+ m.requestId = 0;
+ m.outAsync = null;
+ return m;
+ }
+
+ static create(out, stream, requestId)
+ {
+ const m = new OutgoingMessage();
+ m.stream = stream;
+ m.outAsync = out;
+ m.requestId = requestId;
+ m.isSent = false;
+ m.adopt = false;
+ return m;
+ }
+}
module.exports.Ice = Ice;
diff --git a/js/src/Ice/ConnectionRequestHandler.js b/js/src/Ice/ConnectionRequestHandler.js
index 3aa1e4e5247..76590808edc 100644
--- a/js/src/Ice/ConnectionRequestHandler.js
+++ b/js/src/Ice/ConnectionRequestHandler.js
@@ -7,21 +7,19 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Promise", "../Ice/Class", "../Ice/ReferenceMode"]);
+const Ice = require("../Ice/ReferenceMode").Ice;
+const ReferenceMode = Ice.ReferenceMode;
-var Promise = Ice.Promise;
-var ReferenceMode = Ice.ReferenceMode;
-
-var ConnectionRequestHandler = Ice.Class({
- __init__: function(ref, connection, compress)
+class ConnectionRequestHandler
+{
+ constructor(ref, connection)
{
this._reference = ref;
this._response = ref.getMode() == ReferenceMode.ModeTwoway;
this._connection = connection;
- this._compress = compress;
- },
- update: function(previousHandler, newHandler)
+ }
+
+ update(previousHandler, newHandler)
{
try
{
@@ -44,24 +42,28 @@ var ConnectionRequestHandler = Ice.Class({
// Ignore
}
return this;
- },
- sendAsyncRequest: function(out)
+ }
+
+ sendAsyncRequest(out)
{
- return out.__invokeRemote(this._connection, this._compress, this._response);
- },
- asyncRequestCanceled: function(out)
+ return out.invokeRemote(this._connection, this._response);
+ }
+
+ asyncRequestCanceled(out)
{
return this._connection.asyncRequestCanceled(out);
- },
- getReference: function()
+ }
+
+ getReference()
{
return this._reference;
- },
- getConnection: function()
+ }
+
+ getConnection()
{
return this._connection;
- },
-});
+ }
+}
Ice.ConnectionRequestHandler = ConnectionRequestHandler;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/Debug.js b/js/src/Ice/Debug.js
index 843c59979d2..5764ba876f8 100644
--- a/js/src/Ice/Debug.js
+++ b/js/src/Ice/Debug.js
@@ -7,25 +7,20 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-var fs = require("fs");
+const Ice = require("../Ice/ModuleRegistry").Ice;
+const fs = require("fs");
-function writeSync(stream, msg)
+class Debug
{
- var data = new Buffer(msg + "\n");
- fs.writeSync(stream.fd, data, 0, data.length, stream.pos);
-}
-
-Ice.Debug =
-{
- assert: function(b, msg)
+ static assert(b, msg)
{
if(!b)
{
- writeSync(process.stderr, msg === undefined ? "assertion failed" : msg);
- writeSync(process.stderr, new Error().stack);
+ fs.writeSync(process.stderr.fd, msg === undefined ? "assertion failed" : msg);
+ fs.writeSync(process.stderr.fd, new Error().stack);
process.exit(1);
}
}
-};
+}
+Ice.Debug = Debug;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/DefaultsAndOverrides.js b/js/src/Ice/DefaultsAndOverrides.js
index 6f137ff08d1..51b1f9a084f 100644
--- a/js/src/Ice/DefaultsAndOverrides.js
+++ b/js/src/Ice/DefaultsAndOverrides.js
@@ -8,137 +8,139 @@
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/FormatType",
- "../Ice/EndpointTypes",
- "../Ice/Protocol",
+ "../Ice/FormatType",
+ "../Ice/EndpointTypes",
+ "../Ice/Protocol",
"../Ice/LocalException"
]);
-var FormatType = Ice.FormatType;
-var EndpointSelectionType = Ice.EndpointSelectionType;
-var Protocol = Ice.Protocol;
+const FormatType = Ice.FormatType;
+const EndpointSelectionType = Ice.EndpointSelectionType;
+const Protocol = Ice.Protocol;
-var DefaultsAndOverrides = function(properties, logger)
+class DefaultsAndOverrides
{
- this.defaultProtocol = properties.getPropertyWithDefault("Ice.Default.Protocol",
- Ice.TcpEndpointFactory !== undefined ? "tcp" : "ws");
+ constructor(properties, logger)
+ {
+ this.defaultProtocol = properties.getPropertyWithDefault("Ice.Default.Protocol",
+ Ice.TcpEndpointFactory !== undefined ? "tcp" : "ws");
- var value = properties.getProperty("Ice.Default.Host");
- this.defaultHost = value.length > 0 ? value : null;
+ let value = properties.getProperty("Ice.Default.Host");
+ this.defaultHost = value.length > 0 ? value : null;
- value = properties.getProperty("Ice.Default.SourceAddress");
- this.defaultSourceAddress = value.length > 0 ? value : null;
+ value = properties.getProperty("Ice.Default.SourceAddress");
+ this.defaultSourceAddress = value.length > 0 ? value : null;
- value = properties.getProperty("Ice.Override.Timeout");
- if(value.length > 0)
- {
- this.overrideTimeout = true;
- this.overrideTimeoutValue = properties.getPropertyAsInt("Ice.Override.Timeout");
- if(this.overrideTimeoutValue < 1 && this.overrideTimeoutValue !== -1)
+ value = properties.getProperty("Ice.Override.Timeout");
+ if(value.length > 0)
+ {
+ this.overrideTimeout = true;
+ this.overrideTimeoutValue = properties.getPropertyAsInt("Ice.Override.Timeout");
+ if(this.overrideTimeoutValue < 1 && this.overrideTimeoutValue !== -1)
+ {
+ this.overrideTimeoutValue = -1;
+ logger.warning("invalid value for Ice.Override.Timeout `" +
+ properties.getProperty("Ice.Override.Timeout") + "': defaulting to -1");
+ }
+ }
+ else
{
+ this.overrideTimeout = false;
this.overrideTimeoutValue = -1;
- logger.warning("invalid value for Ice.Override.Timeout `" +
- properties.getProperty("Ice.Override.Timeout") + "': defaulting to -1");
}
- }
- else
- {
- this.overrideTimeout = false;
- this.overrideTimeoutValue = -1;
- }
- value = properties.getProperty("Ice.Override.ConnectTimeout");
- if(value.length > 0)
- {
- this.overrideConnectTimeout = true;
- this.overrideConnectTimeoutValue = properties.getPropertyAsInt("Ice.Override.ConnectTimeout");
- if(this.overrideConnectTimeoutValue < 1 && this.overrideConnectTimeoutValue !== -1)
+ value = properties.getProperty("Ice.Override.ConnectTimeout");
+ if(value.length > 0)
{
+ this.overrideConnectTimeout = true;
+ this.overrideConnectTimeoutValue = properties.getPropertyAsInt("Ice.Override.ConnectTimeout");
+ if(this.overrideConnectTimeoutValue < 1 && this.overrideConnectTimeoutValue !== -1)
+ {
+ this.overrideConnectTimeoutValue = -1;
+ logger.warning("invalid value for Ice.Override.ConnectTimeout `" +
+ properties.getProperty("Ice.Override.ConnectTimeout") + "': defaulting to -1");
+ }
+ }
+ else
+ {
+ this.overrideConnectTimeout = false;
this.overrideConnectTimeoutValue = -1;
- logger.warning("invalid value for Ice.Override.ConnectTimeout `" +
- properties.getProperty("Ice.Override.ConnectTimeout") + "': defaulting to -1");
}
- }
- else
- {
- this.overrideConnectTimeout = false;
- this.overrideConnectTimeoutValue = -1;
- }
- value = properties.getProperty("Ice.Override.CloseTimeout");
- if(value.length > 0)
- {
- this.overrideCloseTimeout = true;
- this.overrideCloseTimeoutValue = properties.getPropertyAsInt("Ice.Override.CloseTimeout");
- if(this.overrideCloseTimeoutValue < 1 && this.overrideCloseTimeoutValue !== -1)
+ value = properties.getProperty("Ice.Override.CloseTimeout");
+ if(value.length > 0)
{
+ this.overrideCloseTimeout = true;
+ this.overrideCloseTimeoutValue = properties.getPropertyAsInt("Ice.Override.CloseTimeout");
+ if(this.overrideCloseTimeoutValue < 1 && this.overrideCloseTimeoutValue !== -1)
+ {
+ this.overrideCloseTimeoutValue = -1;
+ logger.warning("invalid value for Ice.Override.CloseTimeout `" +
+ properties.getProperty("Ice.Override.CloseTimeout") + "': defaulting to -1");
+ }
+ }
+ else
+ {
+ this.overrideCloseTimeout = false;
this.overrideCloseTimeoutValue = -1;
- logger.warning("invalid value for Ice.Override.CloseTimeout `" +
- properties.getProperty("Ice.Override.CloseTimeout") + "': defaulting to -1");
}
- }
- else
- {
- this.overrideCloseTimeout = false;
- this.overrideCloseTimeoutValue = -1;
- }
- this.overrideCompress = false;
- this.overrideSecure = false;
+ this.overrideSecure = false;
- value = properties.getPropertyWithDefault("Ice.Default.EndpointSelection", "Random");
- if(value === "Random")
- {
- this.defaultEndpointSelection = EndpointSelectionType.Random;
- }
- else if(value === "Ordered")
- {
- this.defaultEndpointSelection = EndpointSelectionType.Ordered;
- }
- else
- {
- var ex = new Ice.EndpointSelectionTypeParseException();
- ex.str = "illegal value `" + value + "'; expected `Random' or `Ordered'";
- throw ex;
- }
+ value = properties.getPropertyWithDefault("Ice.Default.EndpointSelection", "Random");
+ if(value === "Random")
+ {
+ this.defaultEndpointSelection = EndpointSelectionType.Random;
+ }
+ else if(value === "Ordered")
+ {
+ this.defaultEndpointSelection = EndpointSelectionType.Ordered;
+ }
+ else
+ {
+ let ex = new Ice.EndpointSelectionTypeParseException();
+ ex.str = "illegal value `" + value + "'; expected `Random' or `Ordered'";
+ throw ex;
+ }
- this.defaultTimeout = properties.getPropertyAsIntWithDefault("Ice.Default.Timeout", 60000);
- if(this.defaultTimeout < 1 && this.defaultTimeout !== -1)
- {
- this.defaultTimeout = 60000;
- logger.warning("invalid value for Ice.Default.Timeout `" + properties.getProperty("Ice.Default.Timeout") +
- "': defaulting to 60000");
- }
+ this.defaultTimeout = properties.getPropertyAsIntWithDefault("Ice.Default.Timeout", 60000);
+ if(this.defaultTimeout < 1 && this.defaultTimeout !== -1)
+ {
+ this.defaultTimeout = 60000;
+ logger.warning("invalid value for Ice.Default.Timeout `" + properties.getProperty("Ice.Default.Timeout") +
+ "': defaulting to 60000");
+ }
- this.defaultLocatorCacheTimeout = properties.getPropertyAsIntWithDefault("Ice.Default.LocatorCacheTimeout", -1);
- if(this.defaultLocatorCacheTimeout < -1)
- {
- this.defaultLocatorCacheTimeout = -1;
- logger.warning("invalid value for Ice.Default.LocatorCacheTimeout `" +
- properties.getProperty("Ice.Default.LocatorCacheTimeout") + "': defaulting to -1");
- }
+ this.defaultLocatorCacheTimeout = properties.getPropertyAsIntWithDefault("Ice.Default.LocatorCacheTimeout", -1);
+ if(this.defaultLocatorCacheTimeout < -1)
+ {
+ this.defaultLocatorCacheTimeout = -1;
+ logger.warning("invalid value for Ice.Default.LocatorCacheTimeout `" +
+ properties.getProperty("Ice.Default.LocatorCacheTimeout") + "': defaulting to -1");
+ }
- this.defaultInvocationTimeout = properties.getPropertyAsIntWithDefault("Ice.Default.InvocationTimeout", -1);
- if(this.defaultInvocationTimeout < 1 && this.defaultInvocationTimeout !== -1)
- {
- this.defaultInvocationTimeout = -1;
- logger.warning("invalid value for Ice.Default.InvocationTimeout `" +
- properties.getProperty("Ice.Default.InvocationTimeout") + "': defaulting to -1");
- }
+ this.defaultInvocationTimeout = properties.getPropertyAsIntWithDefault("Ice.Default.InvocationTimeout", -1);
+ if(this.defaultInvocationTimeout < 1 && this.defaultInvocationTimeout !== -1)
+ {
+ this.defaultInvocationTimeout = -1;
+ logger.warning("invalid value for Ice.Default.InvocationTimeout `" +
+ properties.getProperty("Ice.Default.InvocationTimeout") + "': defaulting to -1");
+ }
- this.defaultPreferSecure = properties.getPropertyAsIntWithDefault("Ice.Default.PreferSecure", 0) > 0;
+ this.defaultPreferSecure = properties.getPropertyAsIntWithDefault("Ice.Default.PreferSecure", 0) > 0;
- value = properties.getPropertyWithDefault("Ice.Default.EncodingVersion",
- Ice.encodingVersionToString(Protocol.currentEncoding));
- this.defaultEncoding = Ice.stringToEncodingVersion(value);
- Protocol.checkSupportedEncoding(this.defaultEncoding);
+ value = properties.getPropertyWithDefault("Ice.Default.EncodingVersion",
+ Ice.encodingVersionToString(Protocol.currentEncoding));
+ this.defaultEncoding = Ice.stringToEncodingVersion(value);
+ Protocol.checkSupportedEncoding(this.defaultEncoding);
- var slicedFormat = properties.getPropertyAsIntWithDefault("Ice.Default.SlicedFormat", 0) > 0;
- this.defaultFormat = slicedFormat ? FormatType.SlicedFormat : FormatType.CompactFormat;
-};
+ const slicedFormat = properties.getPropertyAsIntWithDefault("Ice.Default.SlicedFormat", 0) > 0;
+ this.defaultFormat = slicedFormat ? FormatType.SlicedFormat : FormatType.CompactFormat;
+ }
+}
Ice.DefaultsAndOverrides = DefaultsAndOverrides;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/EndpointFactoryManager.js b/js/src/Ice/EndpointFactoryManager.js
index bae748e5da1..04e1f6c8f75 100644
--- a/js/src/Ice/EndpointFactoryManager.js
+++ b/js/src/Ice/EndpointFactoryManager.js
@@ -7,12 +7,11 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/StringUtil",
- "../Ice/BasicStream",
+ "../Ice/Stream",
"../Ice/Debug",
"../Ice/OpaqueEndpointI",
"../Ice/Protocol",
@@ -22,66 +21,59 @@ Ice.__M.require(module,
//
// Local aliases.
//
-var Debug = Ice.Debug;
-var BasicStream = Ice.BasicStream;
-var EndpointParseException = Ice.EndpointParseException;
-var OpaqueEndpointI = Ice.OpaqueEndpointI;
-var Protocol = Ice.Protocol;
-var StringUtil = Ice.StringUtil;
+const Debug = Ice.Debug;
+const InputStream = Ice.InputStream;
+const OutputStream = Ice.OutputStream;
+const EndpointParseException = Ice.EndpointParseException;
+const OpaqueEndpointI = Ice.OpaqueEndpointI;
+const Protocol = Ice.Protocol;
+const StringUtil = Ice.StringUtil;
-var EndpointFactoryManager = Ice.Class({
- __init__: function(instance)
+class EndpointFactoryManager
+{
+ constructor(instance)
{
this._instance = instance;
this._factories = [];
- },
- add: function(factory)
- {
- for(var i = 0; i < this._factories.length; ++i)
- {
- Debug.assert(this._factories[i].type() != factory.type());
- }
+ }
+ add(factory)
+ {
+ Debug.assert(this._factories.find(f => factory.type() == f.type()) === undefined);
this._factories.push(factory);
- },
- get: function(type)
+ }
+
+ get(type)
{
- for(var i = 0; i < this._factories.length; ++i)
- {
- if(this._factories[i].type() === type)
- {
- return this._factories[i];
- }
- }
- return null;
- },
- create: function(str, oaEndpoint)
+ return this._factories.find(f => type == f.type()) || null;
+ }
+
+ create(str, oaEndpoint)
{
- var s = str.trim();
+ const s = str.trim();
if(s.length === 0)
{
throw new EndpointParseException("value has no non-whitespace characters");
}
- var arr = StringUtil.splitString(s, " \t\n\r");
+ const arr = StringUtil.splitString(s, " \t\n\r");
if(arr.length === 0)
{
throw new EndpointParseException("value has no non-whitespace characters");
}
- var protocol = arr[0];
+ let protocol = arr[0];
arr.splice(0, 1);
if(protocol === "default")
{
protocol = this._instance.defaultsAndOverrides().defaultProtocol;
}
-
- for(var i = 0, length = this._factories.length; i < length; ++i)
+ for(let i = 0, length = this._factories.length; i < length; ++i)
{
if(this._factories[i].protocol() === protocol)
{
- var e = this._factories[i].create(arr, oaEndpoint);
+ const e = this._factories[i].create(arr, oaEndpoint);
if(arr.length > 0)
{
throw new EndpointParseException("unrecognized argument `" + arr[0] + "' in endpoint `" +
@@ -97,14 +89,14 @@ var EndpointFactoryManager = Ice.Class({
//
if(protocol === "opaque")
{
- var ue = new OpaqueEndpointI();
+ const ue = new OpaqueEndpointI();
ue.initWithOptions(arr);
if(arr.length > 0)
{
throw new EndpointParseException("unrecognized argument `" + arr[0] + "' in endpoint `" + str + "'");
}
- for(i = 0, length = this._factories.length; i < length; ++i)
+ for(let i = 0, length = this._factories.length; i < length; ++i)
{
if(this._factories[i].type() == ue.type())
{
@@ -113,51 +105,50 @@ var EndpointFactoryManager = Ice.Class({
// and ask the factory to read the endpoint data from that stream to create
// the actual endpoint.
//
- var bs = new BasicStream(this._instance, Protocol.currentProtocolEncoding);
- bs.writeShort(ue.type());
- ue.streamWrite(bs);
- bs.pos = 0;
- bs.readShort(); // type
- bs.startReadEncaps();
- var endpoint = this._factories[i].read(bs);
- bs.endReadEncaps();
- return endpoint;
+ const os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
+ os.writeShort(ue.type());
+ ue.streamWrite(os);
+ const is = new InputStream(this._instance, Protocol.currentProtocolEncoding, os.buffer);
+ is.pos = 0;
+ is.readShort(); // type
+ is.startEncapsulation();
+ const e = this._factories[i].read(is);
+ is.endEncapsulation();
+ return e;
}
}
return ue; // Endpoint is opaque, but we don't have a factory for its type.
}
return null;
- },
- read: function(s)
+ }
+
+ read(s)
{
- var e;
- var type = s.readShort();
- for(var i = 0; i < this._factories.length; ++i)
+ const type = s.readShort();
+ for(let i = 0; i < this._factories.length; ++i)
{
if(this._factories[i].type() == type)
{
- s.startReadEncaps();
- e = this._factories[i].read(s);
- s.endReadEncaps();
+ s.startEncapsulation();
+ const e = this._factories[i].read(s);
+ s.endEncapsulation();
return e;
}
}
- s.startReadEncaps();
- e = new OpaqueEndpointI(type);
+ s.startEncapsulation();
+ const e = new OpaqueEndpointI(type);
e.initWithStream(s);
- s.endReadEncaps();
+ s.endEncapsulation();
return e;
- },
- destroy: function()
+ }
+
+ destroy()
{
- for(var i = 0; i < this._factories.length; ++i)
- {
- this._factories[i].destroy();
- }
+ this._factories.forEach(factory => factory.destroy());
this._factories = [];
}
-});
+}
Ice.EndpointFactoryManager = EndpointFactoryManager;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/EndpointI.js b/js/src/Ice/EndpointI.js
index 22f49cc88cb..458bfab371d 100644
--- a/js/src/Ice/EndpointI.js
+++ b/js/src/Ice/EndpointI.js
@@ -7,17 +7,11 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
- [
- "../Ice/Class",
- "../Ice/Endpoint",
- ]);
+const Ice = require("../Ice/Endpoint").Ice;
-var Class = Ice.Class;
-
-var EndpointI = Class(Ice.Endpoint, {
- toString: function()
+class EndpointI
+{
+ toString()
{
//
// WARNING: Certain features, such as proxy validation in Glacier2,
@@ -27,14 +21,14 @@ var EndpointI = Class(Ice.Endpoint, {
// format of proxyToString() before changing this and related code.
//
return this.protocol() + this.options();
- },
- initWithOptions: function(args)
+ }
+
+ initWithOptions(args)
{
- var unknown = [];
+ const unknown = [];
- var i;
- var str = "`" + this.protocol();
- for(i = 0; i < args.length; ++i)
+ let str = "`" + this.protocol();
+ for(let i = 0; i < args.length; ++i)
{
if(args[i].search(/[ \t\n\r]+/) !== -1)
{
@@ -47,17 +41,16 @@ var EndpointI = Class(Ice.Endpoint, {
}
str += "'";
- i = 0;
- while(i < args.length)
+ for(let i = 0; i < args.length;)
{
- var option = args[i++];
+ let option = args[i++];
if(option.length < 2 || option.charAt(0) != '-')
{
unknown.push(option);
continue;
}
- var argument = null;
+ let argument = null;
if(i < args.length && args[i].charAt(0) != '-')
{
argument = args[i++];
@@ -74,27 +67,28 @@ var EndpointI = Class(Ice.Endpoint, {
}
args.length = 0;
- for(i = 0; i < unknown.length; i++)
+ for(let i = 0; i < unknown.length; i++)
{
args.push(unknown[i]);
}
- },
+ }
//
// Compare endpoints for sorting purposes
//
- equals: function(p)
+ equals(p)
{
if(!(p instanceof EndpointI))
{
return false;
}
return this.compareTo(p) === 0;
- },
- checkOption: function()
+ }
+
+ checkOption()
{
return false;
}
-});
+}
Ice.EndpointI = EndpointI;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/EnumBase.js b/js/src/Ice/EnumBase.js
index 4d96e03270a..430b8e45e37 100644
--- a/js/src/Ice/EnumBase.js
+++ b/js/src/Ice/EnumBase.js
@@ -7,98 +7,105 @@
//
// **********************************************************************
-var Ice = require("../Ice/Class").Ice;
+const Ice = require("../Ice/ModuleRegistry").Ice;
//
// Ice.EnumBase
//
-var EnumBase = Ice.Class({
- __init__: function(name, value)
+class EnumBase
+{
+ constructor(name, value)
{
this._name = name;
this._value = value;
- },
- equals: function(rhs)
+ }
+
+ equals(rhs)
{
if(this === rhs)
{
return true;
}
- var proto = Object.getPrototypeOf(this);
- if(!(rhs instanceof proto.constructor))
+ if(!(rhs instanceof Object.getPrototypeOf(this).constructor))
{
return false;
}
return this._value == rhs._value;
- },
- hashCode: function()
+ }
+
+ hashCode()
{
return this._value;
- },
- toString: function()
+ }
+
+ toString()
{
return this._name;
}
-});
+
+ get name()
+ {
+ return this._name;
+ }
+
+ get value()
+ {
+ return this._value;
+ }
+}
Ice.EnumBase = EnumBase;
-var prototype = EnumBase.prototype;
-
-Object.defineProperty(prototype, 'name', {
- enumerable: true,
- get: function() { return this._name; }
-});
-
-Object.defineProperty(prototype, 'value', {
- enumerable: true,
- get: function() { return this._value; }
-});
-
-var EnumHelper = Ice.Class({
- __init__: function(enumType)
+class EnumHelper
+{
+ constructor(enumType)
{
this._enumType = enumType;
- },
- write: function(os, v)
+ }
+
+ write(os, v)
{
- this._enumType.__write(os, v);
- },
- writeOpt: function(os, tag, v)
+ this._enumType._write(os, v);
+ }
+
+ writeOptional(os, tag, v)
{
- this._enumType.__writeOpt(os, tag, v);
- },
- read: function(is)
+ this._enumType._writeOpt(os, tag, v);
+ }
+
+ read(is)
{
- return this._enumType.__read(is);
- },
- readOpt: function(is, tag)
+ return this._enumType._read(is);
+ }
+
+ readOptional(is, tag)
{
- return this._enumType.__readOpt(is, tag);
+ return this._enumType._readOpt(is, tag);
}
-});
+}
Ice.EnumHelper = EnumHelper;
-var Slice = Ice.Slice;
+const Slice = Ice.Slice;
Slice.defineEnum = function(enumerators)
{
- var type = function(n, v)
+ const type = class extends EnumBase
{
- EnumBase.call(this, n, v);
+ constructor(n, v)
+ {
+ super(n, v);
+ }
};
- type.prototype = new EnumBase();
- type.prototype.constructor = type;
-
- var enums = [];
- var maxValue = 0;
- var firstEnum = null;
- for(var idx in enumerators)
+ const enums = [];
+ let maxValue = 0;
+ let firstEnum = null;
+
+ for(let idx in enumerators)
{
- var e = enumerators[idx][0], value = enumerators[idx][1];
- var enumerator = new type(e, value);
+ let e = enumerators[idx][0], value = enumerators[idx][1];
+ let enumerator = new type(e, value);
enums[value] = enumerator;
if(!firstEnum)
{
@@ -118,7 +125,7 @@ Slice.defineEnum = function(enumerators)
get: function(){ return 1; }
});
- type.__write = function(os, v)
+ type._write = function(os, v)
{
if(v)
{
@@ -129,26 +136,26 @@ Slice.defineEnum = function(enumerators)
os.writeEnum(firstEnum);
}
};
- type.__read = function(is)
+ type._read = function(is)
{
return is.readEnum(type);
};
- type.__writeOpt = function(os, tag, v)
+ type._writeOpt = function(os, tag, v)
{
if(v !== undefined)
{
- if(os.writeOpt(tag, Ice.OptionalFormat.Size))
+ if(os.writeOptional(tag, Ice.OptionalFormat.Size))
{
- type.__write(os, v);
+ type._write(os, v);
}
}
};
- type.__readOpt = function(is, tag)
+ type._readOpt = function(is, tag)
{
- return is.readOptEnum(tag, type);
+ return is.readOptionalEnum(tag, type);
};
- type.__helper = new EnumHelper(type);
+ type._helper = new EnumHelper(type);
Object.defineProperty(type, 'valueOf', {
value: function(v) {
diff --git a/js/src/Ice/ExUtil.js b/js/src/Ice/ExUtil.js
index 1d6eea38f7d..83aca3edb28 100644
--- a/js/src/Ice/ExUtil.js
+++ b/js/src/Ice/ExUtil.js
@@ -7,13 +7,13 @@
//
// **********************************************************************
-var Ice = require("../Ice/LocalException").Ice;
+const Ice = require("../Ice/LocalException").Ice;
//
// Local aliases.
//
-var UnexpectedObjectException = Ice.UnexpectedObjectException;
-var MemoryLimitException = Ice.MemoryLimitException;
+const UnexpectedObjectException = Ice.UnexpectedObjectException;
+const MemoryLimitException = Ice.MemoryLimitException;
//
// Exception utilities
@@ -23,7 +23,7 @@ Ice.ExUtil =
{
throwUOE: function(expectedType, v)
{
- var type = v.ice_id();
+ const type = v.ice_id();
throw new UnexpectedObjectException("expected element of type `" + expectedType + "' but received '" +
type, type, expectedType);
},
diff --git a/js/src/Ice/Exception.js b/js/src/Ice/Exception.js
index 960bb47f209..3ad61513fa7 100644
--- a/js/src/Ice/Exception.js
+++ b/js/src/Ice/Exception.js
@@ -7,10 +7,9 @@
//
// **********************************************************************
-var Ice = require("../Ice/Class").Ice;
-var Class = Ice.Class;
+const Ice = require("../Ice/ModuleRegistry").Ice;
-var toString = function(key, object, objectTable, ident)
+const toString = function(key, object, objectTable, ident)
{
ident += " ";
if(object === null)
@@ -35,8 +34,8 @@ var toString = function(key, object, objectTable, ident)
}
objectTable.push(object);
- var s = "\n" + ident + key + ":";
- for(var k in object)
+ let s = "\n" + ident + key + ":";
+ for(let k in object)
{
if(key.indexOf("_") === 0)
{
@@ -55,19 +54,23 @@ var toString = function(key, object, objectTable, ident)
//
// Ice.Exception
//
-var Exception = Class(Error, {
- __init__: function(cause)
+class Exception extends Error
+{
+ constructor(cause)
{
+ super();
if(cause)
{
this.ice_cause = cause;
}
- },
- ice_name: function()
+ }
+
+ ice_name()
{
return "Ice::Exception";
- },
- toString: function()
+ }
+
+ toString()
{
//
// We have a guard here to prevent being re-entered. With some browsers (IE), accessing
@@ -80,8 +83,8 @@ var Exception = Class(Error, {
}
this._inToStringAlready = true;
- var s = this.ice_name();
- for(var key in this)
+ let s = this.ice_name();
+ for(let key in this)
{
if(key != "_inToStringAlready")
{
@@ -89,106 +92,106 @@ var Exception = Class(Error, {
}
}
- if(Ice.__printStackTraces === true && this.stack)
+ if(Ice._printStackTraces === true && this.stack)
{
s += "\n" + this.stack;
}
this._inToStringAlready = false;
return s;
}
-});
-
-Exception.captureStackTrace = function(object)
-{
- var stack = new Error().stack;
- //
- // In IE 10 and greater the stack will be filled once the Error is throw
- // we don't need to do anything.
- //
- if(stack !== undefined)
+
+ static captureStackTrace(object)
{
- Object.defineProperty(object, "stack", {
- get: function(){
- return stack;
- }
- });
+ const stack = new Error().stack;
+ //
+ // In IE 10 and greater the stack will be filled once the Error is throw
+ // we don't need to do anything.
+ //
+ if(stack !== undefined)
+ {
+ Object.defineProperty(object, "stack", {
+ get: function()
+ {
+ return stack;
+ }
+ });
+ }
}
-};
+}
Ice.Exception = Exception;
//
// Ice.LocalException
//
-var LocalException = Class(Exception, {
- __init__: function(cause)
+class LocalException extends Exception
+{
+ constructor(cause)
{
- Exception.call(this, cause);
+ super(cause);
Exception.captureStackTrace(this);
- },
- ice_name: function()
+ }
+
+ ice_name()
{
return "Ice::LocalException";
}
-});
+}
Ice.LocalException = LocalException;
-var Slice = Ice.Slice;
-Slice.defineLocalException = function(constructor, base, name)
-{
- var ex = constructor;
- ex.prototype = new base();
- ex.prototype.constructor = ex;
- ex.prototype.ice_name = function()
- {
- return name;
- };
- return ex;
-};
-
//
// Ice.UserException
//
-var UserException = Class(Exception, {
- __init__: function(cause)
+class UserException extends Exception
+{
+ constructor(cause)
{
- Exception.call(this, cause);
+ super(cause);
Exception.captureStackTrace(this);
- },
- ice_name: function()
+ }
+
+ ice_name()
{
return "Ice::UserException";
- },
- __write: function(os)
+ }
+
+ _write(os)
{
- os.startWriteException(null);
- __writeImpl(this, os, this.__mostDerivedType());
- os.endWriteException();
- },
- __read: function(is)
+ os.startException(null);
+ writeImpl(this, os, this._mostDerivedType());
+ os.endException();
+ }
+
+ _read(is)
{
- is.startReadException();
- __readImpl(this, is, this.__mostDerivedType());
- is.endReadException(false);
- },
- __usesClasses: function()
+ is.startException();
+ readImpl(this, is, this._mostDerivedType());
+ is.endException(false);
+ }
+
+ _usesClasses()
{
return false;
}
-});
+
+ _mostDerivedType()
+ {
+ return Ice.UserException;
+ }
+}
Ice.UserException = UserException;
//
// Private methods
//
-var __writeImpl = function(obj, os, type)
+const writeImpl = function(obj, os, type)
{
//
- // The __writeImpl method is a recursive method that goes down the
+ // The writeImpl method is a recursive method that goes down the
// class hierarchy to marshal each slice of the class using the
- // generated __writeMemberImpl method.
+ // generated _writeMemberImpl method.
//
if(type === undefined || type === UserException)
@@ -196,21 +199,21 @@ var __writeImpl = function(obj, os, type)
return; // Don't marshal anything for Ice.UserException
}
- os.startWriteSlice(type.__id, -1, type.__parent === UserException);
- if(type.prototype.__writeMemberImpl)
+ os.startSlice(type._id, -1, type._parent === UserException);
+ if(type.prototype._writeMemberImpl)
{
- type.prototype.__writeMemberImpl.call(obj, os);
+ type.prototype._writeMemberImpl.call(obj, os);
}
- os.endWriteSlice();
- __writeImpl(obj, os, type.__parent);
+ os.endSlice();
+ writeImpl(obj, os, type._parent);
};
-var __readImpl = function(obj, is, type)
+const readImpl = function(obj, is, type)
{
//
- // The __readImpl method is a recursive method that goes down the
+ // The readImpl method is a recursive method that goes down the
// class hierarchy to marshal each slice of the class using the
- // generated __readMemberImpl method.
+ // generated _readMemberImpl method.
//
if(type === undefined || type === UserException)
@@ -218,66 +221,41 @@ var __readImpl = function(obj, is, type)
return; // Don't marshal anything for UserException
}
- is.startReadSlice();
- if(type.prototype.__readMemberImpl)
+ is.startSlice();
+ if(type.prototype._readMemberImpl)
{
- type.prototype.__readMemberImpl.call(obj, is);
+ type.prototype._readMemberImpl.call(obj, is);
}
- is.endReadSlice();
- __readImpl(obj, is, type.__parent);
+ is.endSlice();
+ readImpl(obj, is, type._parent);
};
-var __writePreserved = function(os)
+const writePreserved = function(os)
{
//
// For Slice exceptions which are marked "preserved", the implementation of this method
- // replaces the Ice.Object.prototype.__write method.
+ // replaces the Ice.UserException.prototype._write method.
//
- os.startWriteException(this.__slicedData);
- __writeImpl(this, os, this.__mostDerivedType());
- os.endWriteException();
+ os.startException(this._slicedData);
+ writeImpl(this, os, this._mostDerivedType());
+ os.endException();
};
-var __readPreserved = function(is)
+const readPreserved = function(is)
{
//
// For Slice exceptions which are marked "preserved", the implementation of this method
- // replaces the Ice.Object.prototype.__read method.
+ // replaces the Ice.UserException.prototype._read method.
//
- is.startReadException();
- __readImpl(this, is, this.__mostDerivedType());
- this.__slicedData = is.endReadException(true);
+ is.startException();
+ readImpl(this, is, this._mostDerivedType());
+ this._slicedData = is.endException(true);
};
-Slice.defineUserException = function(constructor, base, name, writeImpl, readImpl, preserved, usesClasses)
+Ice.Slice.PreservedUserException = function(ex)
{
- var ex = constructor;
- ex.__parent = base;
- ex.prototype = new base();
- ex.__id = "::" + name;
- ex.prototype.ice_name = function()
- {
- return name;
- };
-
- ex.prototype.constructor = ex;
- ex.prototype.__mostDerivedType = function() { return ex; };
- if(preserved)
- {
- ex.prototype.__write = __writePreserved;
- ex.prototype.__read = __readPreserved;
- }
- ex.prototype.__writeMemberImpl = writeImpl;
- ex.prototype.__readMemberImpl = readImpl;
-
- if(usesClasses)
- {
- ex.prototype.__usesClasses = function()
- {
- return true;
- };
- }
-
- return ex;
+ ex.prototype._write = writePreserved;
+ ex.prototype._read = readPreserved;
};
+
module.exports.Ice = Ice;
diff --git a/js/src/Ice/FormatType.js b/js/src/Ice/FormatType.js
index 7130858b6d2..8c16b773c6d 100644
--- a/js/src/Ice/FormatType.js
+++ b/js/src/Ice/FormatType.js
@@ -7,6 +7,6 @@
//
// **********************************************************************
-var Ice = require("../Ice/EnumBase").Ice;
+const Ice = require("../Ice/EnumBase").Ice;
Ice.FormatType = Ice.Slice.defineEnum([['DefaultFormat', 0], ['CompactFormat',1], ['SlicedFormat',2]]);
module.exports.Ice = Ice;
diff --git a/js/src/Ice/HashMap.js b/js/src/Ice/HashMap.js
index 0fafc8165d2..174c9a20eec 100644
--- a/js/src/Ice/HashMap.js
+++ b/js/src/Ice/HashMap.js
@@ -7,17 +7,17 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-var __M = Ice.__M;
-__M.require(module, ["../Ice/Class", "../Ice/StringUtil", "../Ice/UUID"]);
-var StringUtil = Ice.StringUtil;
+const Ice = require("../Ice/ModuleRegistry").Ice;
+const _ModuleRegistry = Ice._ModuleRegistry;
+_ModuleRegistry.require(module, ["../Ice/StringUtil", "../Ice/UUID"]);
+const StringUtil = Ice.StringUtil;
function setInternal(map, key, value, hash, index)
{
//
// Search for an entry with the same key.
//
- for(var e = map._table[index]; e !== null; e = e._nextInBucket)
+ for(let e = map._table[index]; e !== null; e = e._nextInBucket)
{
if(e._hash === hash && map.keysEqual(key, e._key))
{
@@ -54,16 +54,15 @@ function compareIdentity(v1, v2)
return v1 === v2;
}
-var HashMap = Ice.Class({
- __init__: function(arg1, arg2)
+class HashMap
+{
+ constructor(arg1, arg2)
{
//
// The first argument can be a HashMap or the keyComparator, the second
// argument if present is always the value comparator.
//
- var args = arguments;
-
- var h, keyComparator, valueComparator;
+ let h, keyComparator, valueComparator;
if(typeof arg1 == "function")
{
@@ -86,13 +85,11 @@ var HashMap = Ice.Class({
this._keyComparator = (typeof keyComparator == "function") ? keyComparator : compareIdentity;
this._valueComparator = (typeof valueComparator == "function") ? valueComparator : compareIdentity;
- var i, length;
if(h instanceof HashMap && h._size > 0)
{
this._threshold = h._threshold;
- length = h._table.length;
- this._table.length = length;
- for(i = 0; i < length; i++)
+ this._table.length = h._table.length;
+ for(let i = 0; i < h._table.length; i++)
{
this._table[i] = null;
}
@@ -101,42 +98,46 @@ var HashMap = Ice.Class({
else
{
this._threshold = this._initialCapacity * this._loadFactor;
- for(i = 0; i < this._initialCapacity; i++)
+ for(let i = 0; i < this._initialCapacity; i++)
{
this._table[i] = null;
}
}
- },
- set: function(key, value)
+ }
+
+ set(key, value)
{
- var r = this.computeHash(key); // Returns an object with key,hash members.
+ const r = this.computeHash(key); // Returns an object with key,hash members.
- var index = this.hashIndex(r.hash, this._table.length);
+ const index = this.hashIndex(r.hash, this._table.length);
return setInternal(this, r.key, value, r.hash, index);
- },
- get: function(key)
+ }
+
+ get(key)
{
- var r = this.computeHash(key); // Returns an object with key,hash members.
- var e = this.findEntry(r.key, r.hash);
+ const r = this.computeHash(key); // Returns an object with key,hash members.
+ const e = this.findEntry(r.key, r.hash);
return e !== undefined ? e._value : undefined;
- },
- has: function(key)
+ }
+
+ has(key)
{
- var r = this.computeHash(key); // Returns an object with key,hash members.
+ const r = this.computeHash(key); // Returns an object with key,hash members.
return this.findEntry(r.key, r.hash) !== undefined;
- },
- delete: function(key)
+ }
+
+ delete(key)
{
- var r = this.computeHash(key); // Returns an object with key,hash members.
+ const r = this.computeHash(key); // Returns an object with key,hash members.
- var index = this.hashIndex(r.hash, this._table.length);
+ const index = this.hashIndex(r.hash, this._table.length);
//
// Search for an entry with the same key.
//
- var prev = null;
- for(var e = this._table[index]; e !== null; e = e._nextInBucket)
+ let prev = null;
+ for(let e = this._table[index]; e !== null; e = e._nextInBucket)
{
if(e._hash === r.hash && this.keysEqual(r.key, e._key))
{
@@ -181,85 +182,88 @@ var HashMap = Ice.Class({
}
return undefined;
- },
- clear: function()
+ }
+
+ clear()
{
- for(var i = 0; i < this._table.length; ++i)
+ for(let i = 0; i < this._table.length; ++i)
{
this._table[i] = null;
}
this._head = null;
this._size = 0;
- },
- forEach: function(fn, obj)
+ }
+
+ forEach(fn, obj)
{
obj = obj === undefined ? fn : obj;
- for(var e = this._head; e !== null; e = e._next)
+ for(let e = this._head; e !== null; e = e._next)
+ {
+ fn.call(obj, e._value, e._key);
+ }
+ }
+
+ *entries()
+ {
+ for(let e = this._head; e !== null; e = e._next)
{
- fn.call(obj, e._key, e._value);
+ yield [e._key, e._value];
}
- },
- keys: function()
+ }
+
+ *keys()
{
- var k = [];
- var i = 0;
- for(var e = this._head; e !== null; e = e._next)
+ for(let e = this._head; e !== null; e = e._next)
{
- k[i++] = e._key;
+ yield e._key;
}
- return k;
- },
- values: function()
+ }
+
+ *values()
{
- var v = [];
- var i = 0;
- for(var e = this._head; e !== null; e = e._next)
+ for(let e = this._head; e !== null; e = e._next)
{
- v[i++] = e._value;
+ yield e._value;
}
- return v;
- },
- equals: function(other, valuesEqual)
+ }
+
+ equals(other, valuesEqual)
{
if(other === null || !(other instanceof HashMap) || this._size !== other._size)
{
return false;
}
- var self = this;
- var eq = valuesEqual || function(v1, v2)
+ const eq = valuesEqual || ((v1, v2) =>
{
- return self._valueComparator.call(self._valueComparator, v1, v2);
- };
+ return this._valueComparator.call(this._valueComparator, v1, v2);
+ });
- for(var e = this._head; e !== null; e = e._next)
+ for(let e = this._head; e !== null; e = e._next)
{
- var oe = other.findEntry(e._key, e._hash);
+ const oe = other.findEntry(e._key, e._hash);
if(oe === undefined || !eq(e._value, oe._value))
{
return false;
}
}
-
return true;
- },
- clone: function()
- {
- return new HashMap(this);
- },
- merge: function(from)
+ }
+
+ merge(from)
{
- for(var e = from._head; e !== null; e = e._next)
+ for(let e = from._head; e !== null; e = e._next)
{
setInternal(this, e._key, e._value, e._hash, this.hashIndex(e._hash, this._table.length));
}
- },
- add: function(key, value, hash, index)
+ }
+
+ add(key, value, hash, index)
{
//
// Create a new table entry.
//
- var e = Object.create(null, {
+ let e = Object.create(null, {
"key": {
enumerable: true,
get: function() { return this._key; }
@@ -318,37 +322,33 @@ var HashMap = Ice.Class({
{
this.resize(this._table.length * 2);
}
- },
- resize: function(capacity)
- {
- var oldTable = this._table;
+ }
- var newTable = [];
- for(var i = 0; i < capacity; i++)
- {
- newTable[i] = null;
- }
+ resize(capacity)
+ {
+ const newTable = new Array(capacity).fill(null);
//
// Re-assign all entries to buckets.
//
- for(var e = this._head; e !== null; e = e._next)
+ for(let e = this._head; e !== null; e = e._next)
{
- var index = this.hashIndex(e._hash, capacity);
+ let index = this.hashIndex(e._hash, capacity);
e._nextInBucket = newTable[index];
newTable[index] = e;
}
this._table = newTable;
this._threshold = (capacity * this._loadFactor);
- },
- findEntry: function(key, hash)
+ }
+
+ findEntry(key, hash)
{
- var index = this.hashIndex(hash, this._table.length);
+ let index = this.hashIndex(hash, this._table.length);
//
// Search for an entry with the same key.
//
- for(var e = this._table[index]; e !== null; e = e._nextInBucket)
+ for(let e = this._table[index]; e !== null; e = e._nextInBucket)
{
if(e._hash === hash && this.keysEqual(key, e._key))
{
@@ -357,14 +357,15 @@ var HashMap = Ice.Class({
}
return undefined;
- },
- hashIndex: function(hash, len)
+ }
+
+ hashIndex(hash, len)
{
return hash & (len - 1);
- },
- computeHash: function(v)
+ }
+
+ computeHash(v)
{
- var uuid;
if(v === 0 || v === -0)
{
return {key:0, hash:0};
@@ -374,7 +375,7 @@ var HashMap = Ice.Class({
{
if(HashMap._null === null)
{
- uuid = Ice.generateUUID();
+ let uuid = Ice.generateUUID();
HashMap._null = {key:uuid, hash:StringUtil.hashCode(uuid)};
}
return HashMap._null;
@@ -390,7 +391,7 @@ var HashMap = Ice.Class({
return {key:v, hash:v.hashCode()};
}
- var type = typeof(v);
+ const type = typeof(v);
if(type === "string" || v instanceof String)
{
return {key:v, hash:StringUtil.hashCode(v)};
@@ -401,7 +402,7 @@ var HashMap = Ice.Class({
{
if(HashMap._nan === null)
{
- uuid = Ice.generateUUID();
+ let uuid = Ice.generateUUID();
HashMap._nan = {key:uuid, hash:StringUtil.hashCode(uuid)};
}
return HashMap._nan;
@@ -414,12 +415,21 @@ var HashMap = Ice.Class({
}
throw new Error("cannot compute hash for value of type " + type);
- },
- keysEqual: function(k1, k2)
+ }
+
+ keysEqual(k1, k2)
{
return this._keyComparator.call(this._keyComparator, k1, k2);
}
-});
+
+ get size()
+ {
+ return this._size;
+ }
+}
+
+HashMap.prototype[Symbol.iterator] = HashMap.prototype.entries;
+
Ice.HashMap = HashMap;
HashMap.compareEquals = compareEquals;
@@ -427,20 +437,15 @@ HashMap.compareIdentity = compareIdentity;
HashMap._null = null;
HashMap._nan = null;
-var prototype = HashMap.prototype;
-
-Object.defineProperty(prototype, "size", {
- get: function() { return this._size; }
-});
-
-Object.defineProperty(prototype, "entries", {
- get: function() { return this._head; }
-});
+const Slice = Ice.Slice;
-var Slice = Ice.Slice;
-Slice.defineDictionary = function(module, name, helperName, keyHelper, valueHelper, fixed, keysEqual, valueType, valuesEqual)
+Slice.defineDictionary = function(module, name, helperName, keyHelper, valueHelper, fixed, keysEqual, valueType)
{
- if(keysEqual !== undefined || valuesEqual !== undefined)
+ if(keysEqual === undefined)
+ {
+ module[name] = Map;
+ }
+ else
{
//
// Define a constructor function for a dictionary whose key type requires
@@ -449,28 +454,25 @@ Slice.defineDictionary = function(module, name, helperName, keyHelper, valueHelp
//
module[name] = function(h)
{
- return new HashMap(h || keysEqual, valuesEqual);
+ return new HashMap(h || keysEqual);
};
}
- else
- {
- module[name] = HashMap;
- }
-
- var helper = null;
+
+ let helper = null;
Object.defineProperty(module, helperName,
{
get: function()
+ {
+ if(helper === null)
{
- if(helper === null)
- {
- /*jshint -W061 */
- helper = Ice.StreamHelpers.generateDictHelper(__M.type(keyHelper), __M.type(valueHelper), fixed,
- __M.type(valueType), module[name]);
- /*jshint +W061 */
- }
- return helper;
+ helper = Ice.StreamHelpers.generateDictHelper(_ModuleRegistry.type(keyHelper),
+ _ModuleRegistry.type(valueHelper),
+ fixed,
+ _ModuleRegistry.type(valueType),
+ module[name]);
}
+ return helper;
+ }
});
};
module.exports.Ice = Ice;
diff --git a/js/src/Ice/HashUtil.js b/js/src/Ice/HashUtil.js
index 09c8c70e76b..844077bd119 100644
--- a/js/src/Ice/HashUtil.js
+++ b/js/src/Ice/HashUtil.js
@@ -7,45 +7,51 @@
//
// **********************************************************************
-var Ice = require("../Ice/StringUtil").Ice;
-var StringUtil = Ice.StringUtil;
+const Ice = require("../Ice/StringUtil").Ice;
+const StringUtil = Ice.StringUtil;
-Ice.HashUtil =
+class HashUtil
{
- addBoolean: function(h, b)
+ static addBoolean(h, b)
{
return ((h << 5) + h) ^ (b ? 0 : 1);
- },
- addString: function(h, str)
+ }
+
+ static addString(h, str)
{
if(str !== undefined && str !== null)
{
h = ((h << 5) + h) ^ StringUtil.hashCode(str);
}
return h;
- },
- addNumber: function(h, num)
+ }
+
+ static addNumber(h, num)
{
return ((h << 5) + h) ^ num;
- },
- addHashable: function(h, obj)
+ }
+
+ static addHashable(h, obj)
{
if(obj !== undefined && obj !== null)
{
h = ((h << 5) + h) ^ obj.hashCode();
}
return h;
- },
- addArray: function(h, arr, hashCode)
+ }
+
+ static addArray(h, arr, hashCode)
{
if(arr !== undefined && arr !== null)
{
- for(var i = 0; i < arr.length; ++i)
+ for(let i = 0; i < arr.length; ++i)
{
h = hashCode(h, arr[i]);
}
}
return h;
}
-};
+}
+
+Ice.HashUtil = HashUtil;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/IPEndpointI.js b/js/src/Ice/IPEndpointI.js
index 2a1eae43ccd..0bfbe3f1989 100644
--- a/js/src/Ice/IPEndpointI.js
+++ b/js/src/Ice/IPEndpointI.js
@@ -7,10 +7,9 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/Address",
"../Ice/HashUtil",
"../Ice/StringUtil",
@@ -18,65 +17,73 @@ Ice.__M.require(module,
"../Ice/LocalException"
]);
-var Address = Ice.Address;
-var HashUtil = Ice.HashUtil;
-var StringUtil = Ice.StringUtil;
-var Class = Ice.Class;
-var EndpointParseException = Ice.EndpointParseException;
+const Address = Ice.Address;
+const HashUtil = Ice.HashUtil;
+const StringUtil = Ice.StringUtil;
+const EndpointParseException = Ice.EndpointParseException;
-var IPEndpointI = Class(Ice.EndpointI, {
- __init__: function(instance, ho, po, sa, conId)
+class IPEndpointI extends Ice.EndpointI
+{
+ constructor(instance, ho, po, sa, conId)
{
+ super();
this._instance = instance;
this._host = ho === undefined ? null : ho;
this._port = po === undefined ? null : po;
this._sourceAddr = sa === undefined ? null : sa;
this._connectionId = conId === undefined ? "" : conId;
- },
+ }
+
//
// Marshal the endpoint
//
- streamWrite: function(s)
+ streamWrite(s)
{
- s.startWriteEncaps();
+ s.startEncapsulation();
this.streamWriteImpl(s);
- s.endWriteEncaps();
- },
- getInfo: function()
+ s.endEncapsulation();
+ }
+
+ getInfo()
{
- var info = new Ice.IPEndpointInfo();
+ const info = new Ice.IPEndpointInfo();
this.fillEndpointInfo(info);
return info;
- },
+ }
+
//
// Return the endpoint type
//
- type: function()
+ type()
{
return this._instance.type();
- },
+ }
+
//
// Return the protocol string
//
- protocol: function()
+ protocol()
{
return this._instance.protocol();
- },
+ }
+
//
// Return true if the endpoint is secure.
//
- secure: function()
+ secure()
{
return this._instance.secure();
- },
- connectionId: function()
+ }
+
+ connectionId()
{
return this._connectionId;
- },
+ }
+
//
// Return a new endpoint with a different connection id.
//
- changeConnectionId: function(connectionId)
+ changeConnectionId(connectionId)
{
if(connectionId === this._connectionId)
{
@@ -86,19 +93,21 @@ var IPEndpointI = Class(Ice.EndpointI, {
{
return this.createEndpoint(this._host, this._port, connectionId);
}
- },
+ }
+
//
// Return the endpoint information.
//
- hashCode: function()
+ hashCode()
{
if(this._hashCode === undefined)
{
this._hashCode = this.hashInit(5381);
}
return this._hashCode;
- },
- options: function()
+ }
+
+ options()
{
//
// WARNING: Certain features, such as proxy validation in Glacier2,
@@ -107,12 +116,12 @@ var IPEndpointI = Class(Ice.EndpointI, {
// these features. Please review for all features that depend on the
// format of proxyToString() before changing this and related code.
//
- var s = "";
+ let s = "";
if(this._host !== null && this._host.length > 0)
{
s += " -h ";
- var addQuote = this._host.indexOf(':') != -1;
+ const addQuote = this._host.indexOf(':') != -1;
if(addQuote)
{
s += "\"";
@@ -131,8 +140,9 @@ var IPEndpointI = Class(Ice.EndpointI, {
s += " --sourceAddr " + this._sourceAddr;
}
return s;
- },
- compareTo: function(p)
+ }
+
+ compareTo(p)
{
if(this === p)
{
@@ -174,24 +184,28 @@ var IPEndpointI = Class(Ice.EndpointI, {
}
return 0;
- },
- getAddress: function()
+ }
+
+ getAddress()
{
return new Address(this._host, this._port);
- },
+ }
+
//
// Convert the endpoint to its Connector string form
//
- toConnectorString: function()
+ toConnectorString()
{
return this._host + ":" + this._port;
- },
- streamWriteImpl: function(s)
+ }
+
+ streamWriteImpl(s)
{
s.writeString(this._host);
s.writeInt(this._port);
- },
- hashInit: function(h)
+ }
+
+ hashInit(h)
{
h = HashUtil.addNumber(h, this.type());
h = HashUtil.addString(h, this._host);
@@ -199,20 +213,21 @@ var IPEndpointI = Class(Ice.EndpointI, {
h = HashUtil.addString(h, this._sourceAddr);
h = HashUtil.addString(h, this._connectionId);
return h;
- },
- fillEndpointInfo: function(info)
+ }
+
+ fillEndpointInfo(info)
{
- var self = this;
- info.type = function() { return self.type(); };
- info.datagram = function() { return self.datagram(); };
- info.secure = function() { return self.secure(); };
+ info.type = () => this.type();
+ info.datagram = () => this.datagram();
+ info.secure = () => this.secure();
info.host = this._host;
info.port = this._port;
info.sourceAddress = this._sourceAddr;
- },
- initWithOptions: function(args, oaEndpoint)
+ }
+
+ initWithOptions(args, oaEndpoint)
{
- Ice.EndpointI.prototype.initWithOptions.call(this, args);
+ super.initWithOptions(args);
if(this._host === null || this._host.length === 0)
{
@@ -246,13 +261,15 @@ var IPEndpointI = Class(Ice.EndpointI, {
{
throw new EndpointParseException("`--sourceAddress not valid for object adapter endpoint `" + this + "'");
}
- },
- initWithStream: function(s)
+ }
+
+ initWithStream(s)
{
this._host = s.readString();
this._port = s.readInt();
- },
- checkOption: function(option, argument, str)
+ }
+
+ checkOption(option, argument, str)
{
if(option === "-h")
{
@@ -299,8 +316,7 @@ var IPEndpointI = Class(Ice.EndpointI, {
}
return true;
}
-});
+}
Ice.IPEndpointI = IPEndpointI;
module.exports.Ice = Ice;
-
diff --git a/js/src/Ice/Ice.js b/js/src/Ice/Ice.js
index 5d8fe0cbea9..56057f11bbd 100644
--- a/js/src/Ice/Ice.js
+++ b/js/src/Ice/Ice.js
@@ -8,14 +8,15 @@
// **********************************************************************
-var __M = require("../Ice/ModuleRegistry").Ice.__M;
+const _ModuleRegistry = require("../Ice/ModuleRegistry").Ice._ModuleRegistry;
-module.exports.Ice = __M.require(module,
+module.exports.Ice = _ModuleRegistry.require(module,
[
"../Ice/Initialize",
"../Ice/Communicator",
"../Ice/HashMap",
"../Ice/Object",
+ "../Ice/Value",
"../Ice/Long",
"../Ice/Logger",
"../Ice/ObjectPrx",
@@ -34,11 +35,12 @@ module.exports.Ice = __M.require(module,
"../Ice/Locator",
"../Ice/Router",
"../Ice/Version",
- "../Ice/ObjectFactory",
"../Ice/Buffer",
"../Ice/ArrayUtil",
- "../Ice/UnknownSlicedObject",
- "../Ice/Process"
+ "../Ice/UnknownSlicedValue",
+ "../Ice/Process",
+ "../Ice/MapUtil",
+ "../Ice/ToStringMode"
]).Ice;
module.exports.IceMX = require("../Ice/Metrics").IceMX;
diff --git a/js/src/Ice/IdentityUtil.js b/js/src/Ice/IdentityUtil.js
index 6cd908388b4..b6652d0d7fc 100644
--- a/js/src/Ice/IdentityUtil.js
+++ b/js/src/Ice/IdentityUtil.js
@@ -7,12 +7,12 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, [ "../Ice/StringUtil", "../Ice/Identity", "../Ice/LocalException"]);
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module, [ "../Ice/StringUtil", "../Ice/Identity", "../Ice/LocalException"]);
-var StringUtil = Ice.StringUtil;
-var Identity = Ice.Identity;
-var IdentityParseException = Ice.IdentityParseException;
+const StringUtil = Ice.StringUtil;
+const Identity = Ice.Identity;
+const IdentityParseException = Ice.IdentityParseException;
/**
* Converts a string to an object identity.
@@ -23,17 +23,17 @@ var IdentityParseException = Ice.IdentityParseException;
**/
Ice.stringToIdentity = function(s)
{
- var ident = new Identity();
+ const ident = new Identity();
//
// Find unescaped separator; note that the string may contain an escaped
// backslash before the separator.
//
- var slash = -1;
- var pos = 0;
+ let slash = -1;
+ let pos = 0;
while((pos = s.indexOf('/', pos)) !== -1)
{
- var escapes = 0;
+ let escapes = 0;
while(pos - escapes > 0 && s.charAt(pos - escapes - 1) == '\\')
{
escapes++;
@@ -53,9 +53,7 @@ Ice.stringToIdentity = function(s)
//
// Extra unescaped slash found.
//
- var ex = new IdentityParseException();
- ex.str = "unescaped backslash in identity `" + s + "'";
- throw ex;
+ throw new IdentityParseException(`unescaped backslash in identity \`${s}'`);
}
}
pos++;
@@ -66,38 +64,32 @@ Ice.stringToIdentity = function(s)
ident.category = "";
try
{
- ident.name = StringUtil.unescapeString(s);
+ ident.name = StringUtil.unescapeString(s, 0, s.length, "/");
}
catch(e)
{
- var ex = new IdentityParseException();
- ex.str = "invalid identity name `" + s + "': " + ex.toString();
- throw ex;
+ throw new IdentityParseException(`invalid identity name \`${s}': ${e.toString()}`);
}
}
else
{
try
{
- ident.category = StringUtil.unescapeString(s, 0, slash);
+ ident.category = StringUtil.unescapeString(s, 0, slash, "/");
}
catch(e)
{
- var ex = new IdentityParseException();
- ex.str = "invalid category in identity `" + s + "': " + ex.toString();
- throw ex;
+ throw new IdentityParseException(`invalid category in identity \`${s}': ${e.toString()}`);
}
if(slash + 1 < s.length)
{
try
{
- ident.name = StringUtil.unescapeString(s, slash + 1, s.length);
+ ident.name = StringUtil.unescapeString(s, slash + 1, s.length, "/");
}
catch(e)
{
- var ex = new IdentityParseException();
- ex.str = "invalid name in identity `" + s + "': " + ex.toString();
- throw ex;
+ throw new IdentityParseException(`invalid name in identity \`${s}': ${e.toString()}`);
}
}
else
@@ -114,17 +106,19 @@ Ice.stringToIdentity = function(s)
*
* @param ident The object identity to convert.
*
+* @param toStringMode Specifies if and how non-printable ASCII characters are escaped in the result.
+*
* @return The string representation of the object identity.
**/
-Ice.identityToString = function(ident)
+Ice.identityToString = function(ident, toStringMode = Ice.ToStringMode.Unicode)
{
if(ident.category === null || ident.category.length === 0)
{
- return StringUtil.escapeString(ident.name, "/");
+ return StringUtil.escapeString(ident.name, "/", toStringMode);
}
else
{
- return StringUtil.escapeString(ident.category, "/") + '/' + StringUtil.escapeString(ident.name, "/");
+ return StringUtil.escapeString(ident.category, "/", toStringMode) + '/' + StringUtil.escapeString(ident.name, "/", toStringMode);
}
};
@@ -157,14 +151,10 @@ Ice.proxyIdentityCompare = function(lhs, rhs)
}
else
{
- var lhsIdentity = lhs.ice_getIdentity();
- var rhsIdentity = rhs.ice_getIdentity();
- var n;
- if((n = lhsIdentity.name.localeCompare(rhsIdentity.name)) !== 0)
- {
- return n;
- }
- return lhsIdentity.category.localeCompare(rhsIdentity.category);
+ const lhsIdentity = lhs.ice_getIdentity();
+ const rhsIdentity = rhs.ice_getIdentity();
+ const n = lhsIdentity.name.localeCompare(rhsIdentity.name);
+ return (n !== 0) ? n : lhsIdentity.category.localeCompare(rhsIdentity.category);
}
};
@@ -197,20 +187,21 @@ Ice.proxyIdentityAndFacetCompare = function(lhs, rhs)
}
else
{
- var lhsIdentity = lhs.ice_getIdentity();
- var rhsIdentity = rhs.ice_getIdentity();
- var n;
- if((n = lhsIdentity.name.localeCompare(rhsIdentity.name)) !== 0)
+ const lhsIdentity = lhs.ice_getIdentity();
+ const rhsIdentity = rhs.ice_getIdentity();
+ let n = lhsIdentity.name.localeCompare(rhsIdentity.name);
+ if(n !== 0)
{
return n;
}
- if((n = lhsIdentity.category.localeCompare(rhsIdentity.category)) !== 0)
+ n = lhsIdentity.category.localeCompare(rhsIdentity.category);
+ if(n !== 0)
{
return n;
}
- var lhsFacet = lhs.ice_getFacet();
- var rhsFacet = rhs.ice_getFacet();
+ const lhsFacet = lhs.ice_getFacet();
+ const rhsFacet = rhs.ice_getFacet();
if(lhsFacet === null && rhsFacet === null)
{
return 0;
diff --git a/js/src/Ice/ImplicitContextI.js b/js/src/Ice/ImplicitContextI.js
index 79faff8b797..f210af98790 100644
--- a/js/src/Ice/ImplicitContextI.js
+++ b/js/src/Ice/ImplicitContextI.js
@@ -7,25 +7,28 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/LocalException", "../Ice/Current", "../Ice/Class"]);
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module, ["../Ice/LocalException", "../Ice/Current"]);
-var Context = Ice.Context;
-var InitializationException = Ice.InitializationException;
+const Context = Ice.Context;
+const InitializationException = Ice.InitializationException;
//
// The base class for all ImplicitContext implementations
//
-var ImplicitContextI = Ice.Class({
- __init__: function()
+class ImplicitContextI
+{
+ constructor()
{
this._context = new Context();
- },
- getContext: function()
+ }
+
+ getContext()
{
return new Context(this._context);
- },
- setContext: function(context)
+ }
+
+ setContext(context)
{
if(context !== null && context.size > 0)
{
@@ -35,8 +38,9 @@ var ImplicitContextI = Ice.Class({
{
this._context.clear();
}
- },
- containsKey: function(key)
+ }
+
+ containsKey(key)
{
if(key === null)
{
@@ -44,23 +48,25 @@ var ImplicitContextI = Ice.Class({
}
return this._context.has(key);
- },
- get: function(key)
+ }
+
+ get(key)
{
if(key === null)
{
key = "";
}
- var val = this._context.get(key);
+ let val = this._context.get(key);
if(val === null)
{
val = "";
}
return val;
- },
- put: function(key, value)
+ }
+
+ put(key, value)
{
if(key === null)
{
@@ -71,7 +77,7 @@ var ImplicitContextI = Ice.Class({
value = "";
}
- var oldVal = this._context.get(key);
+ let oldVal = this._context.get(key);
if(oldVal === null)
{
oldVal = "";
@@ -80,15 +86,16 @@ var ImplicitContextI = Ice.Class({
this._context.set(key, value);
return oldVal;
- },
- remove: function(key)
+ }
+
+ remove(key)
{
if(key === null)
{
key = "";
}
- var val = this._context.get(key);
+ let val = this._context.get(key);
this._context.delete(key);
if(val === null)
@@ -96,8 +103,9 @@ var ImplicitContextI = Ice.Class({
val = "";
}
return val;
- },
- write: function(prxContext, os)
+ }
+
+ write(prxContext, os)
{
if(prxContext.size === 0)
{
@@ -105,7 +113,7 @@ var ImplicitContextI = Ice.Class({
}
else
{
- var ctx = null;
+ let ctx = null;
if(this._context.size === 0)
{
ctx = prxContext;
@@ -113,27 +121,31 @@ var ImplicitContextI = Ice.Class({
else
{
ctx = new Context(this._context);
- ctx.merge(prxContext);
+ for(let [key, value] of prxContext)
+ {
+ ctx.set(key, value);
+ }
}
Ice.ContextHelper.write(os, ctx);
}
}
-});
-
-ImplicitContextI.create = function(kind)
-{
- if(kind.length === 0 || kind === "None")
- {
- return null;
- }
- else if(kind === "Shared")
+
+ static create(kind)
{
- return new ImplicitContextI();
- }
- else
- {
- throw new InitializationException("'" + kind + "' is not a valid value for Ice.ImplicitContext");
+ if(kind.length === 0 || kind === "None")
+ {
+ return null;
+ }
+ else if(kind === "Shared")
+ {
+ return new ImplicitContextI();
+ }
+ else
+ {
+ throw new InitializationException("'" + kind + "' is not a valid value for Ice.ImplicitContext");
+ }
}
-};
+}
+
Ice.ImplicitContextI = ImplicitContextI;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/IncomingAsync.js b/js/src/Ice/IncomingAsync.js
index 899f2095509..76e4a29666b 100644
--- a/js/src/Ice/IncomingAsync.js
+++ b/js/src/Ice/IncomingAsync.js
@@ -7,16 +7,14 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
- "../Ice/BasicStream",
+ "../Ice/Stream",
"../Ice/BuiltinSequences",
"../Ice/Connection",
"../Ice/Current",
"../Ice/Debug",
- "../Ice/DispatchStatus",
"../Ice/Exception",
"../Ice/Identity",
"../Ice/LocalException",
@@ -24,26 +22,23 @@ Ice.__M.require(module,
"../Ice/StringUtil"
]);
-var BasicStream = Ice.BasicStream;
-var Current = Ice.Current;
-var Debug = Ice.Debug;
-var FormatType = Ice.FormatType;
-var Context = Ice.Context;
-var Identity = Ice.Identity;
-var Protocol = Ice.Protocol;
-var StringUtil = Ice.StringUtil;
-
-var IncomingAsync = Ice.Class({
- __init__: function(instance, connection, adapter, response, compress, requestId)
+const OutputStream = Ice.OutputStream;
+const Current = Ice.Current;
+const Debug = Ice.Debug;
+const FormatType = Ice.FormatType;
+const Context = Ice.Context;
+const Identity = Ice.Identity;
+const Protocol = Ice.Protocol;
+const StringUtil = Ice.StringUtil;
+
+class IncomingAsync
+{
+ constructor(instance, connection, adapter, response, requestId)
{
this._instance = instance;
this._response = response;
- this._compress = compress;
- if(this._response)
- {
- this._os = new BasicStream(instance, Protocol.currentProtocolEncoding);
- }
this._connection = connection;
+ this._format = Ice.FormatType.DefaultFormat;
this._current = new Current();
this._current.id = new Identity();
@@ -55,99 +50,91 @@ var IncomingAsync = Ice.Class({
this._locator = null;
this._cookie = { value: null };
- //
- // Prepare the response if necessary.
- //
- if(response)
- {
- this._os.writeBlob(Protocol.replyHdr);
-
- //
- // Add the request ID.
- //
- this._os.writeInt(requestId);
- }
-
+ this._os = null;
this._is = null;
+ }
- this._cb = null;
- this._active = true;
- },
- __startWriteParams: function(format)
+ startWriteParams()
{
if(!this._response)
{
throw new Ice.MarshalException("can't marshal out parameters for oneway dispatch");
}
- Debug.assert(this._os.size == Protocol.headerSize + 4); // Reply status position.
Debug.assert(this._current.encoding !== null); // Encoding for reply is known.
+ this._os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
+ this._os.writeBlob(Protocol.replyHdr);
+ this._os.writeInt(this._current.requestId);
this._os.writeByte(0);
- this._os.startWriteEncaps(this._current.encoding, format);
+ this._os.startEncapsulation(this._current.encoding, this._format);
return this._os;
- },
- __endWriteParams: function(ok)
+ }
+
+ endWriteParams()
{
if(this._response)
{
- var save = this._os.pos;
- this._os.pos = Protocol.headerSize + 4; // Reply status position.
- this._os.writeByte(ok ? Protocol.replyOK : Protocol.replyUserException);
- this._os.pos = save;
- this._os.endWriteEncaps();
+ this._os.endEncapsulation();
}
- },
- __writeEmptyParams: function()
+ }
+
+ writeEmptyParams()
{
if(this._response)
{
- Debug.assert(this._os.size === Protocol.headerSize + 4); // Reply status position.
Debug.assert(this._current.encoding !== null); // Encoding for reply is known.
+ this._os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
+ this._os.writeBlob(Protocol.replyHdr);
+ this._os.writeInt(this._current.requestId);
this._os.writeByte(Protocol.replyOK);
- this._os.writeEmptyEncaps(this._current.encoding);
+ this._os.writeEmptyEncapsulation(this._current.encoding);
}
- },
- __writeParamEncaps: function(v, ok)
+ }
+
+ writeParamEncaps(v, ok)
{
if(this._response)
{
- Debug.assert(this._os.size === Protocol.headerSize + 4); // Reply status position.
Debug.assert(this._current.encoding !== null); // Encoding for reply is known.
+ this._os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
+ this._os.writeBlob(Protocol.replyHdr);
+ this._os.writeInt(this._current.requestId);
this._os.writeByte(ok ? Protocol.replyOK : Protocol.replyUserException);
if(v === null || v.length === 0)
{
- this._os.writeEmptyEncaps(this._current.encoding);
+ this._os.writeEmptyEncapsulation(this._current.encoding);
}
else
{
- this._os.writeEncaps(v);
+ this._os.writeEncapsulation(v);
}
}
- },
- __writeUserException: function(ex, format)
+ }
+
+ setFormat(format)
{
- var os = this.__startWriteParams(format);
- os.writeUserException(ex);
- this.__endWriteParams(false);
- },
- __warning: function(ex)
+ this._format = format;
+ }
+
+ warning(ex)
{
Debug.assert(this._instance !== null);
- var s = [];
+ const s = [];
s.push("dispatch exception:");
- s.push("\nidentity: " + this._instance.identityToString(this._current.id));
- s.push("\nfacet: " + StringUtil.escapeString(this._current.facet, ""));
+ s.push("\nidentity: " + Ice.identityToString(this._current.id, this._instance.toStringMode()));
+ s.push("\nfacet: " + StringUtil.escapeString(this._current.facet, "", this._instance.toStringMode()));
s.push("\noperation: " + this._current.operation);
if(this._connection !== null)
{
try
{
- var connInfo = this._connection.getInfo();
- if(connInfo instanceof Ice.IPConnectionInfo)
+ for(let p = this._connection.getInfo(); p; p = p.underlying)
{
- var ipConnInfo = connInfo;
- s.push("\nremote host: " + ipConnInfo.remoteAddress + " remote port: " + ipConnInfo.remotePort);
+ if(p instanceof Ice.IPConnectionInfo)
+ {
+ s.push("\nremote host: " + p.remoteAddress + " remote port: " + p.remotePort);
+ }
}
}
catch(exc)
@@ -161,8 +148,9 @@ var IncomingAsync = Ice.Class({
s.push(ex.stack);
}
this._instance.initializationData().logger.warning(s.join(""));
- },
- __servantLocatorFinished: function()
+ }
+
+ servantLocatorFinished()
{
Debug.assert(this._locator !== null && this._servant !== null);
try
@@ -172,42 +160,16 @@ var IncomingAsync = Ice.Class({
}
catch(ex)
{
- if(ex instanceof Ice.UserException)
- {
- Debug.assert(this._connection !== null);
-
- //
- // The operation may have already marshaled a reply; we must overwrite that reply.
- //
- if(this._response)
- {
- this._os.resize(Protocol.headerSize + 4); // Reply status position.
- this._os.writeByte(Protocol.replyUserException);
- this._os.startWriteEncaps();
- this._os.writeUserException(ex);
- this._os.endWriteEncaps();
- this._connection.sendResponse(this._os, this._compress);
- }
- else
- {
- this._connection.sendNoResponse();
- }
-
- this._connection = null;
- }
- else
- {
- this.__handleException(ex);
- }
- return false;
+ this.handleException(ex);
}
- },
- __handleException: function(ex)
+ return false;
+ }
+
+ handleException(ex)
{
Debug.assert(this._connection !== null);
- var props = this._instance.initializationData().properties;
- var s;
+ const props = this._instance.initializationData().properties;
if(ex instanceof Ice.RequestFailedException)
{
if(ex.id === null)
@@ -227,12 +189,14 @@ var IncomingAsync = Ice.Class({
if(props.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 1)
{
- this.__warning(ex);
+ this.warning(ex);
}
if(this._response)
{
- this._os.resize(Protocol.headerSize + 4); // Reply status position.
+ this._os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
+ this._os.writeBlob(Protocol.replyHdr);
+ this._os.writeInt(this._current.requestId);
if(ex instanceof Ice.ObjectNotExistException)
{
this._os.writeByte(Protocol.replyObjectNotExist);
@@ -249,7 +213,7 @@ var IncomingAsync = Ice.Class({
{
Debug.assert(false);
}
- ex.id.__write(this._os);
+ ex.id._write(this._os);
//
// For compatibility with the old FacetPath.
@@ -265,7 +229,7 @@ var IncomingAsync = Ice.Class({
this._os.writeString(ex.operation);
- this._connection.sendResponse(this._os, this._compress);
+ this._connection.sendResponse(this._os);
}
else
{
@@ -276,15 +240,17 @@ var IncomingAsync = Ice.Class({
{
if(props.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0)
{
- this.__warning(ex);
+ this.warning(ex);
}
if(this._response)
{
- this._os.resize(Protocol.headerSize + 4); // Reply status position.
+ this._os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
+ this._os.writeBlob(Protocol.replyHdr);
+ this._os.writeInt(this._current.requestId);
this._os.writeByte(Protocol.replyUnknownLocalException);
this._os.writeString(ex.unknown);
- this._connection.sendResponse(this._os, this._compress);
+ this._connection.sendResponse(this._os);
}
else
{
@@ -295,15 +261,17 @@ var IncomingAsync = Ice.Class({
{
if(props.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0)
{
- this.__warning(ex);
+ this.warning(ex);
}
if(this._response)
{
- this._os.resize(Protocol.headerSize + 4); // Reply status position.
+ this._os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
+ this._os.writeBlob(Protocol.replyHdr);
+ this._os.writeInt(this._current.requestId);
this._os.writeByte(Protocol.replyUnknownUserException);
this._os.writeString(ex.unknown);
- this._connection.sendResponse(this._os, this._compress);
+ this._connection.sendResponse(this._os);
}
else
{
@@ -314,15 +282,17 @@ var IncomingAsync = Ice.Class({
{
if(props.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0)
{
- this.__warning(ex);
+ this.warning(ex);
}
if(this._response)
{
- this._os.resize(Protocol.headerSize + 4); // Reply status position.
+ this._os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
+ this._os.writeBlob(Protocol.replyHdr);
+ this._os.writeInt(this._current.requestId);
this._os.writeByte(Protocol.replyUnknownException);
this._os.writeString(ex.unknown);
- this._connection.sendResponse(this._os, this._compress);
+ this._connection.sendResponse(this._os);
}
else
{
@@ -333,22 +303,24 @@ var IncomingAsync = Ice.Class({
{
if(props.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0)
{
- this.__warning(ex);
+ this.warning(ex);
}
if(this._response)
{
- this._os.resize(Protocol.headerSize + 4); // Reply status position.
+ this._os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
+ this._os.writeBlob(Protocol.replyHdr);
+ this._os.writeInt(this._current.requestId);
this._os.writeByte(Protocol.replyUnknownLocalException);
//this._os.writeString(ex.toString());
- s = [ ex.ice_name() ];
+ let s = [ ex.ice_name() ];
if(ex.stack)
{
s.push("\n");
s.push(ex.stack);
}
this._os.writeString(s.join(""));
- this._connection.sendResponse(this._os, this._compress);
+ this._connection.sendResponse(this._os);
}
else
{
@@ -357,24 +329,16 @@ var IncomingAsync = Ice.Class({
}
else if(ex instanceof Ice.UserException)
{
- if(props.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0)
- {
- this.__warning(ex);
- }
-
if(this._response)
{
- this._os.resize(Protocol.headerSize + 4); // Reply status position.
- this._os.writeByte(Protocol.replyUnknownUserException);
- //this._os.writeString(ex.toString());
- s = [ ex.ice_name() ];
- if(ex.stack)
- {
- s.push("\n");
- s.push(ex.stack);
- }
- this._os.writeString(s.join(""));
- this._connection.sendResponse(this._os, this._compress);
+ this._os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
+ this._os.writeBlob(Protocol.replyHdr);
+ this._os.writeInt(this._current.requestId);
+ this._os.writeByte(Protocol.replyUserException);
+ this._os.startEncapsulation(this._current.encoding, this._format);
+ this._os.writeUserException(ex);
+ this._os.endEncapsulation();
+ this._connection.sendResponse(this._os);
}
else
{
@@ -385,16 +349,18 @@ var IncomingAsync = Ice.Class({
{
if(props.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0)
{
- this.__warning(ex);
+ this.warning(ex);
}
if(this._response)
{
- this._os.resize(Protocol.headerSize + 4); // Reply status position.
+ this._os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
+ this._os.writeBlob(Protocol.replyHdr);
+ this._os.writeInt(this._current.requestId);
this._os.writeByte(Protocol.replyUnknownException);
//this._os.writeString(ex.toString());
- this._os.writeString(ex.stack ? ex.stack : "");
- this._connection.sendResponse(this._os, this._compress);
+ this._os.writeString(ex.toString() + (ex.stack ? "\n" + ex.stack : ""));
+ this._connection.sendResponse(this._os);
}
else
{
@@ -403,22 +369,21 @@ var IncomingAsync = Ice.Class({
}
this._connection = null;
- },
- invoke: function(servantManager, stream)
+ }
+
+ invoke(servantManager, stream)
{
this._is = stream;
- var start = this._is.pos;
-
//
// Read the current.
//
- this._current.id.__read(this._is);
+ this._current.id._read(this._is);
//
// For compatibility with the old FacetPath.
//
- var facetPath = Ice.StringSeqHelper.read(this._is);
+ const facetPath = Ice.StringSeqHelper.read(this._is);
if(facetPath.length > 0)
{
if(facetPath.length > 1)
@@ -435,12 +400,10 @@ var IncomingAsync = Ice.Class({
this._current.operation = this._is.readString();
this._current.mode = Ice.OperationMode.valueOf(this._is.readByte());
this._current.ctx = new Context();
- var sz = this._is.readSize();
+ let sz = this._is.readSize();
while(sz-- > 0)
{
- var first = this._is.readString();
- var second = this._is.readString();
- this._current.ctx.set(first, second);
+ this._current.ctx.set(this._is.readString(), this._is.readString());
}
//
@@ -448,7 +411,6 @@ var IncomingAsync = Ice.Class({
// in the code above are considered fatal, and must propagate to
// the caller of this operation.
//
-
if(servantManager !== null)
{
this._servant = servantManager.findServant(this._current.id, this._current.facet);
@@ -468,134 +430,93 @@ var IncomingAsync = Ice.Class({
}
catch(ex)
{
- if(ex instanceof Ice.UserException)
- {
- var encoding = this._is.skipEncaps(); // Required for batch requests.
-
- if(this._response)
- {
- this._os.writeByte(Protocol.replyUserException);
- this._os.startWriteEncaps(encoding, FormatType.DefaultFormat);
- this._os.writeUserException(ex);
- this._os.endWriteEncaps();
- this._connection.sendResponse(this._os, this._compress);
- }
- else
- {
- this._connection.sendNoResponse();
- }
-
- this._connection = null;
- return;
- }
- else
- {
- this._is.skipEncaps(); // Required for batch requests.
- this.__handleException(ex);
- return;
- }
+ this.skipReadParams(); // Required for batch requests.
+ this.handleException(ex);
+ return;
}
}
}
}
- try
+ if(this._servant === null)
{
- if(this._servant !== null)
- {
- //
- // DispatchAsync is a "pseudo dispatch status", used internally only
- // to indicate async dispatch.
- //
- if(this._servant.__dispatch(this, this._current) === Ice.DispatchStatus.DispatchAsync)
- {
- //
- // If this was an asynchronous dispatch, we're done here.
- //
- return;
- }
-
- if(this._locator !== null && !this.__servantLocatorFinished())
- {
- return;
- }
- }
- else
+ try
{
- //
- // Skip the input parameters, this is required for reading
- // the next batch request if dispatching batch requests.
- //
- this._is.skipEncaps();
-
if(servantManager !== null && servantManager.hasServant(this._current.id))
{
throw new Ice.FacetNotExistException(this._current.id, this._current.facet,
- this._current.operation);
+ this._current.operation);
}
else
{
throw new Ice.ObjectNotExistException(this._current.id, this._current.facet,
- this._current.operation);
+ this._current.operation);
}
+
}
- }
- catch(ex)
- {
- if(this._servant !== null && this._locator !== null && !this.__servantLocatorFinished())
+ catch(ex)
{
+ this.skipReadParams(); // Required for batch requests.
+ this.handleException(ex);
return;
}
- this.__handleException(ex);
- return;
}
- //
- // Don't put the code below into the try block above. Exceptions
- // in the code below are considered fatal, and must propagate to
- // the caller of this operation.
- //
-
- Debug.assert(this._connection !== null);
-
- if(this._response)
+ try
{
- this._connection.sendResponse(this._os, this._compress);
+ Debug.assert(this._servant !== null);
+ let promise = this._servant._iceDispatch(this, this._current);
+ if(promise !== null)
+ {
+ promise.then(() => this.response(), (ex) => this.exception(ex));
+ return;
+ }
+
+ Debug.assert(!this._response || this._os !== null);
+ this.response();
}
- else
+ catch(ex)
{
- this._connection.sendNoResponse();
+ this.exception(ex);
}
+ }
- this._connection = null;
- },
- startReadParams: function()
+ startReadParams()
{
//
// Remember the encoding used by the input parameters, we'll
// encode the response parameters with the same encoding.
//
- this._current.encoding = this._is.startReadEncaps();
+ this._current.encoding = this._is.startEncapsulation();
return this._is;
- },
- endReadParams: function()
+ }
+
+ endReadParams()
{
- this._is.endReadEncaps();
- },
- readEmptyParams: function()
+ this._is.endEncapsulation();
+ }
+
+ readEmptyParams()
{
- this._current.encoding = this._is.skipEmptyEncaps();
- },
- readParamEncaps: function()
+ this._current.encoding = this._is.skipEmptyEncapsulation();
+ }
+
+ readParamEncaps()
{
this._current.encoding = new Ice.EncodingVersion();
- return this._is.readEncaps(this._current.encoding);
- },
- __response: function()
+ return this._is.readEncapsulation(this._current.encoding);
+ }
+
+ skipReadParams()
+ {
+ this._current.encoding = this._is.skipEncapsulation();
+ }
+
+ response()
{
try
{
- if(this._locator !== null && !this.__servantLocatorFinished())
+ if(this._locator !== null && !this.servantLocatorFinished())
{
return;
}
@@ -604,69 +525,36 @@ var IncomingAsync = Ice.Class({
if(this._response)
{
- this._connection.sendResponse(this._os, this._compress);
+ this._connection.sendResponse(this._os);
}
else
{
this._connection.sendNoResponse();
}
-
- this._connection = null;
}
catch(ex)
{
this._connection.invokeException(ex, 1);
}
- },
- __exception: function(exc)
+ this._connection = null;
+ }
+
+ exception(exc)
{
try
{
- if(this._locator !== null && !this.__servantLocatorFinished())
+ if(this._locator !== null && !this.servantLocatorFinished())
{
return;
}
-
- this.__handleException(exc);
+ this.handleException(exc);
}
catch(ex)
{
this._connection.invokeException(ex, 1);
}
- },
- __validateResponse: function(ok)
- {
- if(!this._active)
- {
- return false;
- }
- this._active = false;
- return true;
- },
- ice_exception: function(ex)
- {
- if(!this._active)
- {
- return;
- }
- this._active = false;
-
- if(this._connection !== null)
- {
- this.__exception(ex);
- }
- else
- {
- //
- // Response has already been sent.
- //
- if(this._instance.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0)
- {
- this.__warning(ex);
- }
- }
}
-});
+}
Ice.IncomingAsync = IncomingAsync;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/Initialize.js b/js/src/Ice/Initialize.js
index b090de83791..8b21588973f 100644
--- a/js/src/Ice/Initialize.js
+++ b/js/src/Ice/Initialize.js
@@ -7,8 +7,8 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
"../Ice/Protocol",
"../Ice/LocalException",
@@ -16,7 +16,7 @@ Ice.__M.require(module,
"../Ice/Properties"
]);
-var Protocol = Ice.Protocol;
+const Protocol = Ice.Protocol;
//
// Ice.InitializationData
@@ -25,13 +25,15 @@ Ice.InitializationData = function()
{
this.properties = null;
this.logger = null;
+ this.valueFactoryManager = null;
};
Ice.InitializationData.prototype.clone = function()
{
- var r = new Ice.InitializationData();
+ const r = new Ice.InitializationData();
r.properties = this.properties;
r.logger = this.logger;
+ r.valueFactoryManager = this.valueFactoryManager;
return r;
};
@@ -40,8 +42,8 @@ Ice.InitializationData.prototype.clone = function()
//
Ice.initialize = function(arg1, arg2)
{
- var args = null;
- var initData = null;
+ let args = null;
+ let initData = null;
if(arg1 instanceof Array)
{
@@ -78,7 +80,7 @@ Ice.initialize = function(arg1, arg2)
}
initData.properties = Ice.createProperties(args, initData.properties);
- var result = new Ice.Communicator(initData);
+ const result = new Ice.Communicator(initData);
result.finishSetup(null);
return result;
};
@@ -101,4 +103,14 @@ Ice.currentEncoding = function()
return Protocol.currentEncoding.clone();
};
+Ice.stringVersion = function()
+{
+ return "3.7a4"; // "A.B.C", with A=major, B=minor, C=patch
+};
+
+Ice.intVersion = function()
+{
+ return 30754; // AABBCC, with AA=major, BB=minor, CC=patch
+};
+
module.exports.Ice = Ice;
diff --git a/js/src/Ice/Instance.js b/js/src/Ice/Instance.js
index 08f7b1424c6..863ac578055 100644
--- a/js/src/Ice/Instance.js
+++ b/js/src/Ice/Instance.js
@@ -7,21 +7,19 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/AsyncResultBase",
"../Ice/Debug",
"../Ice/DefaultsAndOverrides",
"../Ice/EndpointFactoryManager",
- "../Ice/HashMap",
"../Ice/ImplicitContextI",
"../Ice/IdentityUtil",
"../Ice/LocatorManager",
"../Ice/Logger",
"../Ice/ObjectAdapterFactory",
- "../Ice/ObjectFactoryManager",
+ "../Ice/ValueFactoryManagerI",
"../Ice/OutgoingConnectionFactory",
"../Ice/Promise",
"../Ice/Properties",
@@ -38,42 +36,42 @@ Ice.__M.require(module,
"../Ice/LocalException",
"../Ice/Exception",
"../Ice/ProcessLogger",
- "../Ice/ACM"
+ "../Ice/ACM",
+ "../Ice/ToStringMode"
]);
-var IceSSL = Ice.__M.require(module, ["../Ice/EndpointInfo"]).IceSSL;
-
-var AsyncResultBase = Ice.AsyncResultBase;
-var Debug = Ice.Debug;
-var DefaultsAndOverrides = Ice.DefaultsAndOverrides;
-var EndpointFactoryManager = Ice.EndpointFactoryManager;
-var HashMap = Ice.HashMap;
-var ImplicitContextI = Ice.ImplicitContextI;
-var LocatorManager = Ice.LocatorManager;
-var Logger = Ice.Logger;
-var ObjectAdapterFactory = Ice.ObjectAdapterFactory;
-var ObjectFactoryManager = Ice.ObjectFactoryManager;
-var OutgoingConnectionFactory = Ice.OutgoingConnectionFactory;
-var Promise = Ice.Promise;
-var Properties = Ice.Properties;
-var ProxyFactory = Ice.ProxyFactory;
-var RetryQueue = Ice.RetryQueue;
-var RouterManager = Ice.RouterManager;
-var Timer = Ice.Timer;
-var TraceLevels = Ice.TraceLevels;
-var ReferenceFactory = Ice.ReferenceFactory;
-var RequestHandlerFactory = Ice.RequestHandlerFactory;
-var ACMConfig = Ice.ACMConfig;
-
-var StateActive = 0;
-var StateDestroyInProgress = 1;
-var StateDestroyed = 2;
+const IceSSL = Ice._ModuleRegistry.require(module, ["../Ice/EndpointInfo"]).IceSSL;
+
+const AsyncResultBase = Ice.AsyncResultBase;
+const Debug = Ice.Debug;
+const DefaultsAndOverrides = Ice.DefaultsAndOverrides;
+const EndpointFactoryManager = Ice.EndpointFactoryManager;
+const ImplicitContextI = Ice.ImplicitContextI;
+const LocatorManager = Ice.LocatorManager;
+const Logger = Ice.Logger;
+const ObjectAdapterFactory = Ice.ObjectAdapterFactory;
+const ValueFactoryManagerI = Ice.ValueFactoryManagerI;
+const OutgoingConnectionFactory = Ice.OutgoingConnectionFactory;
+const Properties = Ice.Properties;
+const ProxyFactory = Ice.ProxyFactory;
+const RetryQueue = Ice.RetryQueue;
+const RouterManager = Ice.RouterManager;
+const Timer = Ice.Timer;
+const TraceLevels = Ice.TraceLevels;
+const ReferenceFactory = Ice.ReferenceFactory;
+const RequestHandlerFactory = Ice.RequestHandlerFactory;
+const ACMConfig = Ice.ACMConfig;
+
+const StateActive = 0;
+const StateDestroyInProgress = 1;
+const StateDestroyed = 2;
//
// Instance - only for use by Communicator
//
-var Instance = Ice.Class({
- __init__: function(initData)
+class Instance
+{
+ constructor(initData)
{
this._state = StateActive;
this._initData = initData;
@@ -83,6 +81,7 @@ var Instance = Ice.Class({
this._messageSizeMax = 0;
this._batchAutoFlushSize = 0;
this._clientACM = null;
+ this._toStringMode = Ice.ToStringMode.Unicode;
this._implicitContext = null;
this._routerManager = null;
this._locatorManager = null;
@@ -90,13 +89,14 @@ var Instance = Ice.Class({
this._requestHandlerFactory = null;
this._proxyFactory = null;
this._outgoingConnectionFactory = null;
- this._servantFactoryManager = null;
this._objectAdapterFactory = null;
this._retryQueue = null;
this._endpointHostResolver = null;
this._endpointFactoryManager = null;
- },
- initializationData: function()
+ this._objectFactoryMap = null;
+ }
+
+ initializationData()
{
//
// No check for destruction. It must be possible to access the
@@ -105,20 +105,23 @@ var Instance = Ice.Class({
// This value is immutable.
//
return this._initData;
- },
- traceLevels: function()
+ }
+
+ traceLevels()
{
// This value is immutable.
Debug.assert(this._traceLevels !== null);
return this._traceLevels;
- },
- defaultsAndOverrides: function()
+ }
+
+ defaultsAndOverrides()
{
// This value is immutable.
Debug.assert(this._defaultsAndOverrides !== null);
return this._defaultsAndOverrides;
- },
- routerManager: function()
+ }
+
+ routerManager()
{
if(this._state === StateDestroyed)
{
@@ -127,8 +130,9 @@ var Instance = Ice.Class({
Debug.assert(this._routerManager !== null);
return this._routerManager;
- },
- locatorManager: function()
+ }
+
+ locatorManager()
{
if(this._state === StateDestroyed)
{
@@ -137,8 +141,9 @@ var Instance = Ice.Class({
Debug.assert(this._locatorManager !== null);
return this._locatorManager;
- },
- referenceFactory: function()
+ }
+
+ referenceFactory()
{
if(this._state === StateDestroyed)
{
@@ -147,8 +152,9 @@ var Instance = Ice.Class({
Debug.assert(this._referenceFactory !== null);
return this._referenceFactory;
- },
- requestHandlerFactory: function()
+ }
+
+ requestHandlerFactory()
{
if(this._state === StateDestroyed)
{
@@ -157,8 +163,9 @@ var Instance = Ice.Class({
Debug.assert(this._requestHandlerFactory !== null);
return this._requestHandlerFactory;
- },
- proxyFactory: function()
+ }
+
+ proxyFactory()
{
if(this._state === StateDestroyed)
{
@@ -167,8 +174,9 @@ var Instance = Ice.Class({
Debug.assert(this._proxyFactory !== null);
return this._proxyFactory;
- },
- outgoingConnectionFactory: function()
+ }
+
+ outgoingConnectionFactory()
{
if(this._state === StateDestroyed)
{
@@ -177,18 +185,9 @@ var Instance = Ice.Class({
Debug.assert(this._outgoingConnectionFactory !== null);
return this._outgoingConnectionFactory;
- },
- servantFactoryManager: function()
- {
- if(this._state === StateDestroyed)
- {
- throw new Ice.CommunicatorDestroyedException();
- }
+ }
- Debug.assert(this._servantFactoryManager !== null);
- return this._servantFactoryManager;
- },
- objectAdapterFactory: function()
+ objectAdapterFactory()
{
if(this._state === StateDestroyed)
{
@@ -197,8 +196,9 @@ var Instance = Ice.Class({
Debug.assert(this._objectAdapterFactory !== null);
return this._objectAdapterFactory;
- },
- retryQueue: function()
+ }
+
+ retryQueue()
{
if(this._state === StateDestroyed)
{
@@ -207,8 +207,9 @@ var Instance = Ice.Class({
Debug.assert(this._retryQueue !== null);
return this._retryQueue;
- },
- timer: function()
+ }
+
+ timer()
{
if(this._state === StateDestroyed)
{
@@ -217,8 +218,9 @@ var Instance = Ice.Class({
Debug.assert(this._timer !== null);
return this._timer;
- },
- endpointFactoryManager: function()
+ }
+
+ endpointFactoryManager()
{
if(this._state === StateDestroyed)
{
@@ -227,36 +229,38 @@ var Instance = Ice.Class({
Debug.assert(this._endpointFactoryManager !== null);
return this._endpointFactoryManager;
- },
- messageSizeMax: function()
+ }
+
+ messageSizeMax()
{
// This value is immutable.
return this._messageSizeMax;
- },
- batchAutoFlushSize: function()
+ }
+
+ batchAutoFlushSize()
{
// This value is immutable.
return this._batchAutoFlushSize;
- },
- clientACM: function()
+ }
+
+ clientACM()
{
// This value is immutable.
return this._clientACM;
- },
- getImplicitContext: function()
- {
- return this._implicitContext;
- },
- stringToIdentity: function(s)
+ }
+
+ toStringMode()
{
- return Ice.stringToIdentity(s);
- },
- identityToString: function(ident)
+ // this value is immutable
+ return this._toStringMode;
+ }
+
+ getImplicitContext()
{
- return Ice.identityToString(ident);
- },
+ return this._implicitContext;
+ }
- setDefaultLocator: function(locator)
+ setDefaultLocator(locator)
{
if(this._state == StateDestroyed)
{
@@ -264,8 +268,9 @@ var Instance = Ice.Class({
}
this._referenceFactory = this._referenceFactory.setDefaultLocator(locator);
- },
- setDefaultRouter: function(router)
+ }
+
+ setDefaultRouter(router)
{
if(this._state == StateDestroyed)
{
@@ -273,18 +278,19 @@ var Instance = Ice.Class({
}
this._referenceFactory = this._referenceFactory.setDefaultRouter(router);
- },
- setLogger: function(logger)
+ }
+
+ setLogger(logger)
{
this._initData.logger = logger;
- },
- finishSetup: function(communicator, promise)
+ }
+
+ finishSetup(communicator, promise)
{
//
// If promise == null, it means the caller is requesting a synchronous setup.
// Otherwise, we resolve the promise after all initialization is complete.
//
-
try
{
if(this._initData.properties === null)
@@ -292,12 +298,12 @@ var Instance = Ice.Class({
this._initData.properties = Properties.createProperties();
}
- if(Ice.__oneOfDone === undefined)
+ if(Ice._oneOfDone === undefined)
{
- Ice.__printStackTraces =
+ Ice._printStackTraces =
this._initData.properties.getPropertyAsIntWithDefault("Ice.PrintStackTraces", 0) > 0;
- Ice.__oneOfDone = true;
+ Ice._oneOfDone = true;
}
if(this._initData.logger === null)
@@ -309,8 +315,8 @@ var Instance = Ice.Class({
this._defaultsAndOverrides = new DefaultsAndOverrides(this._initData.properties, this._initData.logger);
- var defMessageSizeMax = 1024;
- var num = this._initData.properties.getPropertyAsIntWithDefault("Ice.MessageSizeMax", defMessageSizeMax);
+ const defMessageSizeMax = 1024;
+ let num = this._initData.properties.getPropertyAsIntWithDefault("Ice.MessageSizeMax", defMessageSizeMax);
if(num < 1 || num > 0x7fffffff / 1024)
{
this._messageSizeMax = 0x7fffffff;
@@ -349,6 +355,21 @@ var Instance = Ice.Class({
new ACMConfig(this._initData.properties, this._initData.logger,
"Ice.ACM", new ACMConfig()));
+
+ const toStringModeStr = this._initData.properties.getPropertyWithDefault("Ice.ToStringMode", "Unicode");
+ if(toStringModeStr === "ASCII")
+ {
+ _toStringMode = Ice.ToStringMode.ASCII;
+ }
+ else if(toStringModeStr === "Compat")
+ {
+ _toStringMode = Ice.ToStringMode.Compat;
+ }
+ else if(toStringModeStr !== "Unicode")
+ {
+ throw new Ice.InitializationException("The value for Ice.ToStringMode must be Unicode, ASCII or Compat");
+ }
+
this._implicitContext =
ImplicitContextI.create(this._initData.properties.getProperty("Ice.ImplicitContext"));
@@ -364,37 +385,41 @@ var Instance = Ice.Class({
this._endpointFactoryManager = new EndpointFactoryManager(this);
- var tcpInstance = new Ice.ProtocolInstance(this, Ice.TCPEndpointType, "tcp", false);
- var tcpEndpointFactory = new Ice.TcpEndpointFactory(tcpInstance);
+ const tcpInstance = new Ice.ProtocolInstance(this, Ice.TCPEndpointType, "tcp", false);
+ const tcpEndpointFactory = new Ice.TcpEndpointFactory(tcpInstance);
this._endpointFactoryManager.add(tcpEndpointFactory);
- var wsInstance = new Ice.ProtocolInstance(this, Ice.WSEndpointType, "ws", false);
- var wsEndpointFactory = new Ice.WSEndpointFactory(wsInstance, tcpEndpointFactory.clone(wsInstance));
+ const wsInstance = new Ice.ProtocolInstance(this, Ice.WSEndpointType, "ws", false);
+ const wsEndpointFactory = new Ice.WSEndpointFactory(wsInstance, tcpEndpointFactory.clone(wsInstance));
this._endpointFactoryManager.add(wsEndpointFactory);
- var sslInstance = new Ice.ProtocolInstance(this, IceSSL.EndpointType, "ssl", true);
- var sslEndpointFactory = new Ice.TcpEndpointFactory(sslInstance);
+ const sslInstance = new Ice.ProtocolInstance(this, Ice.SSLEndpointType, "ssl", true);
+ const sslEndpointFactory = new Ice.TcpEndpointFactory(sslInstance);
this._endpointFactoryManager.add(sslEndpointFactory);
- var wssInstance = new Ice.ProtocolInstance(this, Ice.WSSEndpointType, "wss", true);
- var wssEndpointFactory = new Ice.WSEndpointFactory(wssInstance, sslEndpointFactory.clone(wssInstance));
+ const wssInstance = new Ice.ProtocolInstance(this, Ice.WSSEndpointType, "wss", true);
+ const wssEndpointFactory = new Ice.WSEndpointFactory(wssInstance, sslEndpointFactory.clone(wssInstance));
this._endpointFactoryManager.add(wssEndpointFactory);
this._outgoingConnectionFactory = new OutgoingConnectionFactory(communicator, this);
- this._servantFactoryManager = new ObjectFactoryManager();
+
+ if(this._initData.valueFactoryManager === null)
+ {
+ this._initData.valueFactoryManager = new ValueFactoryManagerI();
+ }
this._objectAdapterFactory = new ObjectAdapterFactory(this, communicator);
this._retryQueue = new RetryQueue(this);
this._timer = new Timer(this._initData.logger);
- var router = Ice.RouterPrx.uncheckedCast(this._proxyFactory.propertyToProxy("Ice.Default.Router"));
+ const router = Ice.RouterPrx.uncheckedCast(this._proxyFactory.propertyToProxy("Ice.Default.Router"));
if(router !== null)
{
this._referenceFactory = this._referenceFactory.setDefaultRouter(router);
}
- var loc = Ice.LocatorPrx.uncheckedCast(this._proxyFactory.propertyToProxy("Ice.Default.Locator"));
+ const loc = Ice.LocatorPrx.uncheckedCast(this._proxyFactory.propertyToProxy("Ice.Default.Locator"));
if(loc !== null)
{
this._referenceFactory = this._referenceFactory.setDefaultLocator(loc);
@@ -402,7 +427,7 @@ var Instance = Ice.Class({
if(promise !== null)
{
- promise.succeed(communicator);
+ promise.resolve(communicator);
}
}
catch(ex)
@@ -411,14 +436,11 @@ var Instance = Ice.Class({
{
if(ex instanceof Ice.LocalException)
{
- this.destroy().finally(function()
- {
- promise.fail(ex);
- });
+ this.destroy().finally(() => promise.reject(ex));
}
else
{
- promise.fail(ex);
+ promise.reject(ex);
}
}
else
@@ -430,13 +452,14 @@ var Instance = Ice.Class({
throw ex;
}
}
- },
+ }
+
//
// Only for use by Ice.CommunicatorI
//
- destroy: function()
+ destroy()
{
- var promise = new AsyncResultBase(null, "destroy", null, this, null);
+ const promise = new AsyncResultBase(null, "destroy", null, this, null);
//
// If destroy is in progress, wait for it to be done. This is
@@ -458,122 +481,131 @@ var Instance = Ice.Class({
// Shutdown and destroy all the incoming and outgoing Ice
// connections and wait for the connections to be finished.
//
- var self = this;
- Ice.Promise.try(
- function()
+ Ice.Promise.try(() =>
{
- if(self._objectAdapterFactory)
+ if(this._objectAdapterFactory)
{
- return self._objectAdapterFactory.shutdown();
+ return this._objectAdapterFactory.shutdown();
}
}
- ).then(
- function()
+ ).then(() =>
{
- if(self._outgoingConnectionFactory !== null)
+ if(this._outgoingConnectionFactory !== null)
{
- self._outgoingConnectionFactory.destroy();
+ this._outgoingConnectionFactory.destroy();
}
- if(self._objectAdapterFactory !== null)
+ if(this._objectAdapterFactory !== null)
{
- return self._objectAdapterFactory.destroy();
+ return this._objectAdapterFactory.destroy();
}
}
- ).then(
- function()
+ ).then(() =>
{
- if(self._outgoingConnectionFactory !== null)
+ if(this._outgoingConnectionFactory !== null)
{
- return self._outgoingConnectionFactory.waitUntilFinished();
+ return this._outgoingConnectionFactory.waitUntilFinished();
}
}
- ).then(
- function()
+ ).then(() =>
{
- if(self._retryQueue)
+ if(this._retryQueue)
{
- self._retryQueue.destroy();
+ this._retryQueue.destroy();
}
- if(self._timer)
+ if(this._timer)
{
- self._timer.destroy();
+ this._timer.destroy();
}
- if(self._servantFactoryManager)
+ if(this._objectFactoryMap !== null)
{
- self._servantFactoryManager.destroy();
+ this._objectFactoryMap.forEach(factory => factory.destroy());
+ this._objectFactoryMap.clear();
}
- if(self._routerManager)
+
+ if(this._routerManager)
{
- self._routerManager.destroy();
+ this._routerManager.destroy();
}
- if(self._locatorManager)
+ if(this._locatorManager)
{
- self._locatorManager.destroy();
+ this._locatorManager.destroy();
}
- if(self._endpointFactoryManager)
+ if(this._endpointFactoryManager)
{
- self._endpointFactoryManager.destroy();
+ this._endpointFactoryManager.destroy();
}
- var i;
- if(self._initData.properties.getPropertyAsInt("Ice.Warn.UnusedProperties") > 0)
+ if(this._initData.properties.getPropertyAsInt("Ice.Warn.UnusedProperties") > 0)
{
- var unusedProperties = self._initData.properties.getUnusedProperties();
+ const unusedProperties = this._initData.properties.getUnusedProperties();
if(unusedProperties.length > 0)
{
- var message = [];
+ const message = [];
message.push("The following properties were set but never read:");
- for(i = 0; i < unusedProperties.length; ++i)
- {
- message.push("\n ");
- message.push(unusedProperties[i]);
- }
- self._initData.logger.warning(message.join(""));
+ unusedProperties.forEach(p => message.push("\n ", p));
+ this._initData.logger.warning(message.join(""));
}
}
- self._objectAdapterFactory = null;
- self._outgoingConnectionFactory = null;
- self._retryQueue = null;
- self._timer = null;
+ this._objectAdapterFactory = null;
+ this._outgoingConnectionFactory = null;
+ this._retryQueue = null;
+ this._timer = null;
- self._servantFactoryManager = null;
- self._referenceFactory = null;
- self._requestHandlerFactory = null;
- self._proxyFactory = null;
- self._routerManager = null;
- self._locatorManager = null;
- self._endpointFactoryManager = null;
+ this._referenceFactory = null;
+ this._requestHandlerFactory = null;
+ this._proxyFactory = null;
+ this._routerManager = null;
+ this._locatorManager = null;
+ this._endpointFactoryManager = null;
- self._state = StateDestroyed;
+ this._state = StateDestroyed;
if(this._destroyPromises)
{
- for(i = 0; i < this._destroyPromises.length; ++i)
- {
- this._destroyPromises[i].succeed(this._destroyPromises[i]);
- }
+ this._destroyPromises.forEach(p => p.resolve());
}
- promise.succeed(promise);
+ promise.resolve();
}
- ).exception(
- function(ex)
+ ).catch(ex =>
{
if(this._destroyPromises)
{
- for(var i = 0; i < this._destroyPromises.length; ++i)
- {
- this._destroyPromises[i].fail(ex, this._destroyPromises[i]);
- }
+ this._destroyPromises.forEach(p => p.reject(ex));
}
- promise.fail(ex, promise);
- }
- );
+ promise.reject(ex);
+ });
return promise;
- },
-});
+ }
+
+ addObjectFactory(factory, id)
+ {
+ //
+ // Create a ValueFactory wrapper around the given ObjectFactory and register the wrapper
+ // with the value factory manager. This may raise AlreadyRegisteredException.
+ //
+ this._initData.valueFactoryManager.add(typeId => factory.create(typeId), id);
+
+ if(this._objectFactoryMap === null)
+ {
+ this._objectFactoryMap = new Map();
+ }
+
+ this._objectFactoryMap.set(id, factory);
+ }
+
+ findObjectFactory(id)
+ {
+ let factory = null;
+ if(this._objectFactoryMap !== null)
+ {
+ factory = this._objectFactoryMap.get(id);
+ }
+ return factory !== undefined ? factory : null;
+ }
+}
Ice.Instance = Instance;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/LocatorInfo.js b/js/src/Ice/LocatorInfo.js
index 8d2e615e75a..de4554506b4 100644
--- a/js/src/Ice/LocatorInfo.js
+++ b/js/src/Ice/LocatorInfo.js
@@ -7,44 +7,44 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/Debug",
- "../Ice/HashMap",
"../Ice/Promise",
"../Ice/Protocol",
"../Ice/Locator",
"../Ice/LocalException",
- "../Ice/Exception"
+ "../Ice/Exception",
+ "../Ice/HashMap",
+ "../Ice/IdentityUtil"
]);
-var Debug = Ice.Debug;
-var HashMap = Ice.HashMap;
-var Promise = Ice.Promise;
-var Protocol = Ice.Protocol;
-var LocatorRegistryPrx = Ice.LocatorRegisterPrx;
+const Debug = Ice.Debug;
+const Protocol = Ice.Protocol;
+const LocatorRegistryPrx = Ice.LocatorRegisterPrx;
+const HashMap = Ice.HashMap;
-var Class = Ice.Class;
-
-var LocatorInfo = Class({
- __init__: function(locator, table, background)
+class LocatorInfo
+{
+ constructor(locator, table, background)
{
this._locator = locator;
this._locatorRegistry = null;
this._table = table;
this._background = background;
- this._adapterRequests = new HashMap(); // Map<String, Request>
+ this._adapterRequests = new Map(); // Map<String, Request>
this._objectRequests = new HashMap(HashMap.compareEquals); // Map<Ice.Identity, Request>
- },
- destroy: function()
+ }
+
+ destroy()
{
this._locatorRegistry = null;
this._table.clear();
- },
- equals: function(rhs)
+ }
+
+ equals(rhs)
{
if(this === rhs)
{
@@ -57,43 +57,45 @@ var LocatorInfo = Class({
}
return false;
- },
- hashCode: function()
+ }
+
+ hashCode()
{
return this._locator.hashCode();
- },
- getLocator: function()
+ }
+
+ getLocator()
{
return this._locator;
- },
- getLocatorRegistry: function()
+ }
+
+ getLocatorRegistry()
{
if(this._locatorRegistry !== null)
{
- return new Promise().succeed(this._locatorRegistry);
+ return Ice.Promise.resolve(this._locatorRegistry);
}
- var self = this;
- return this._locator.getRegistry().then(
- function(reg)
+ return this._locator.getRegistry().then(reg =>
{
//
// The locator registry can't be located. We use ordered
// endpoint selection in case the locator returned a proxy
// with some endpoints which are prefered to be tried first.
//
- self._locatorRegistry = LocatorRegistryPrx.uncheckedCast(reg.ice_locator(null).ice_endpointSelection(
+ this._locatorRegistry = LocatorRegistryPrx.uncheckedCast(reg.ice_locator(null).ice_endpointSelection(
Ice.EndpointSelectionType.Ordered));
- return self._locatorRegistry;
+ return this._locatorRegistry;
});
- },
- getEndpoints: function(ref, wellKnownRef, ttl, p)
+ }
+
+ getEndpoints(ref, wellKnownRef, ttl, p)
{
- var promise = p || new Promise(); // success callback receives (endpoints, cached)
+ const promise = p || new Ice.Promise(); // success callback receives (endpoints, cached)
Debug.assert(ref.isIndirect());
- var endpoints = null;
- var cached = { value: false };
+ let endpoints = null;
+ const cached = { value: false };
if(!ref.isWellKnown())
{
endpoints = this._table.getAdapterEndpoints(ref.getAdapterId(), ttl, cached);
@@ -112,7 +114,7 @@ var LocatorInfo = Class({
}
else
{
- var r = this._table.getObjectReference(ref.getIdentity(), ttl, cached);
+ const r = this._table.getObjectReference(ref.getIdentity(), ttl, cached);
if(!cached.value)
{
if(this._background && r !== null)
@@ -142,17 +144,18 @@ var LocatorInfo = Class({
{
this.getEndpointsTrace(ref, endpoints, true);
}
- promise.succeed(endpoints, true);
+ promise.resolve([endpoints, true]);
return promise;
- },
- clearCache: function(ref)
+ }
+
+ clearCache(ref)
{
Debug.assert(ref.isIndirect());
if(!ref.isWellKnown())
{
- var endpoints = this._table.removeAdapterEndpoints(ref.getAdapterId());
+ const endpoints = this._table.removeAdapterEndpoints(ref.getAdapterId());
if(endpoints !== null && ref.getInstance().traceLevels().location >= 2)
{
@@ -161,7 +164,7 @@ var LocatorInfo = Class({
}
else
{
- var r = this._table.removeObjectReference(ref.getIdentity());
+ const r = this._table.removeObjectReference(ref.getIdentity());
if(r !== null)
{
if(!r.isIndirect())
@@ -177,12 +180,13 @@ var LocatorInfo = Class({
}
}
}
- },
- trace: function(msg, ref, endpoints)
+ }
+
+ trace(msg, ref, endpoints)
{
Debug.assert(ref.isIndirect());
- var s = [];
+ const s = [];
s.push(msg);
s.push("\n");
if(!ref.isWellKnown())
@@ -194,28 +198,20 @@ var LocatorInfo = Class({
else
{
s.push("object = ");
- s.push(ref.getInstance().identityToString(ref.getIdentity()));
+ s.push(Ice.identityToString(ref.getIdentity(), ref.getInstance().toStringMode()));
s.push("\n");
}
s.push("endpoints = ");
- for(var i = 0; i < endpoints.length; i++)
- {
- s.push(endpoints[i].toString());
- if(i + 1 < endpoints.length)
- {
- s.push(":");
- }
- }
-
+ s.push(endpoints.map(e => e.toString()).join(":"));
ref.getInstance().initializationData().logger.trace(ref.getInstance().traceLevels().locationCat, s.join(""));
- },
- getEndpointsException: function(ref, exc)
+ }
+
+ getEndpointsException(ref, exc)
{
Debug.assert(ref.isIndirect());
- var instance = ref.getInstance();
- var s, e;
+ const instance = ref.getInstance();
try
{
throw exc;
@@ -226,14 +222,14 @@ var LocatorInfo = Class({
{
if(instance.traceLevels().location >= 1)
{
- s = [];
+ const s = [];
s.push("adapter not found\n");
s.push("adapter = ");
s.push(ref.getAdapterId());
instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.join(""));
}
- e = new Ice.NotRegisteredException();
+ const e = new Ice.NotRegisteredException();
e.kindOfObject = "object adapter";
e.id = ref.getAdapterId();
throw e;
@@ -242,16 +238,16 @@ var LocatorInfo = Class({
{
if(instance.traceLevels().location >= 1)
{
- s = [];
+ const s = [];
s.push("object not found\n");
s.push("object = ");
- s.push(instance.identityToString(ref.getIdentity()));
+ s.push(Ice.identityToString(ref.getIdentity(), instance.toStringMode()));
instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.join(""));
}
- e = new Ice.NotRegisteredException();
+ const e = new Ice.NotRegisteredException();
e.kindOfObject = "object";
- e.id = instance.identityToString(ref.getIdentity());
+ e.id = Ice.identityToString(ref.getIdentity(), instance.toStringMode());
throw e;
}
else if(ex instanceof Ice.NotRegisteredException)
@@ -262,7 +258,7 @@ var LocatorInfo = Class({
{
if(instance.traceLevels().location >= 1)
{
- s = [];
+ const s = [];
s.push("couldn't contact the locator to retrieve adapter endpoints\n");
if(ref.getAdapterId().length > 0)
{
@@ -273,7 +269,7 @@ var LocatorInfo = Class({
else
{
s.push("object = ");
- s.push(instance.identityToString(ref.getIdentity()));
+ s.push(Ice.identityToString(ref.getIdentity(), instance.toStringMode()));
s.push("\n");
}
s.push("reason = " + ex.toString());
@@ -286,8 +282,9 @@ var LocatorInfo = Class({
Debug.assert(false);
}
}
- },
- getEndpointsTrace: function(ref, endpoints, cached)
+ }
+
+ getEndpointsTrace(ref, endpoints, cached)
{
if(endpoints !== null && endpoints.length > 0)
{
@@ -302,8 +299,8 @@ var LocatorInfo = Class({
}
else
{
- var instance = ref.getInstance();
- var s = [];
+ const instance = ref.getInstance();
+ const s = [];
s.push("no endpoints configured for ");
if(ref.getAdapterId().length > 0)
{
@@ -316,25 +313,26 @@ var LocatorInfo = Class({
{
s.push("object\n");
s.push("object = ");
- s.push(instance.identityToString(ref.getIdentity()));
+ s.push(Ice.identityToString(ref.getIdentity(), instance.toStringMode()));
s.push("\n");
}
instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.join(""));
}
- },
- getAdapterRequest: function(ref)
+ }
+
+ getAdapterRequest(ref)
{
if(ref.getInstance().traceLevels().location >= 1)
{
- var instance = ref.getInstance();
- var s = [];
+ const instance = ref.getInstance();
+ const s = [];
s.push("searching for adapter by id\n");
s.push("adapter = ");
s.push(ref.getAdapterId());
instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.join(""));
}
- var request = this._adapterRequests.get(ref.getAdapterId());
+ let request = this._adapterRequests.get(ref.getAdapterId());
if(request !== undefined)
{
return request;
@@ -342,20 +340,21 @@ var LocatorInfo = Class({
request = new AdapterRequest(this, ref);
this._adapterRequests.set(ref.getAdapterId(), request);
return request;
- },
- getObjectRequest: function(ref)
+ }
+
+ getObjectRequest(ref)
{
if(ref.getInstance().traceLevels().location >= 1)
{
- var instance = ref.getInstance();
- var s = [];
+ const instance = ref.getInstance();
+ const s = [];
s.push("searching for object by id\n");
s.push("object = ");
- s.push(instance.identityToString(ref.getIdentity()));
+ s.push(Ice.identityToString(ref.getIdentity(), instance.toStringMode()));
instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.join(""));
}
- var request = this._objectRequests.get(ref.getIdentity());
+ let request = this._objectRequests.get(ref.getIdentity());
if(request !== undefined)
{
return request;
@@ -363,16 +362,17 @@ var LocatorInfo = Class({
request = new ObjectRequest(this, ref);
this._objectRequests.set(ref.getIdentity(), request);
return request;
- },
- finishRequest: function(ref, wellKnownRefs, proxy, notRegistered)
+ }
+
+ finishRequest(ref, wellKnownRefs, proxy, notRegistered)
{
- if(proxy === null || proxy.__reference().isIndirect())
+ if(proxy === null || proxy._getReference().isIndirect())
{
//
// Remove the cached references of well-known objects for which we tried
// to resolved the endpoints if these endpoints are empty.
//
- for(var i = 0; i < wellKnownRefs.length; ++i)
+ for(let i = 0; i < wellKnownRefs.length; ++i)
{
this._table.removeObjectReference(wellKnownRefs[i].getIdentity());
}
@@ -380,10 +380,10 @@ var LocatorInfo = Class({
if(!ref.isWellKnown())
{
- if(proxy !== null && !proxy.__reference().isIndirect())
+ if(proxy !== null && !proxy._getReference().isIndirect())
{
// Cache the adapter endpoints.
- this._table.addAdapterEndpoints(ref.getAdapterId(), proxy.__reference().getEndpoints());
+ this._table.addAdapterEndpoints(ref.getAdapterId(), proxy._getReference().getEndpoints());
}
else if(notRegistered) // If the adapter isn't registered anymore, remove it from the cache.
{
@@ -395,10 +395,10 @@ var LocatorInfo = Class({
}
else
{
- if(proxy !== null && !proxy.__reference().isWellKnown())
+ if(proxy !== null && !proxy._getReference().isWellKnown())
{
// Cache the well-known object reference.
- this._table.addObjectReference(ref.getIdentity(), proxy.__reference());
+ this._table.addObjectReference(ref.getIdentity(), proxy._getReference());
}
else if(notRegistered) // If the well-known object isn't registered anymore, remove it from the cache.
{
@@ -409,23 +409,25 @@ var LocatorInfo = Class({
this._objectRequests.delete(ref.getIdentity());
}
}
-});
+}
Ice.LocatorInfo = LocatorInfo;
-var RequestCallback = Class({
- __init__: function(ref, ttl, promise)
+class RequestCallback
+{
+ constructor(ref, ttl, promise)
{
this._ref = ref;
this._ttl = ttl;
this._promise = promise;
- },
- response: function(locatorInfo, proxy)
+ }
+
+ response(locatorInfo, proxy)
{
- var endpoints = null;
+ let endpoints = null;
if(proxy !== null)
{
- var r = proxy.__reference();
+ let r = proxy._getReference();
if(this._ref.isWellKnown() && !Protocol.isSupported(this._ref.getEncoding(), r.getEncoding()))
{
//
@@ -445,20 +447,19 @@ var RequestCallback = Class({
// by the locator is an indirect proxy. We now need to resolve the endpoints
// of this indirect proxy.
//
- var self = this;
locatorInfo.getEndpoints(r, this._ref, this._ttl).then(
- function(endpts, b)
+ values =>
{
- if(self._promise !== null)
+ if(this._promise !== null)
{
- self._promise.succeed(endpts, b);
+ this._promise.resolve(values);
}
},
- function(ex)
+ ex =>
{
- if(self._promise !== null)
+ if(this._promise !== null)
{
- self._promise.fail(ex);
+ this._promise.reject(ex);
}
});
return;
@@ -472,10 +473,11 @@ var RequestCallback = Class({
if(this._promise !== null)
{
- this._promise.succeed(endpoints === null ? [] : endpoints, false);
+ this._promise.resolve(endpoints === null ? [[], false] : [endpoints, false]);
}
- },
- exception: function(locatorInfo, exc)
+ }
+
+ exception(locatorInfo, exc)
{
try
{
@@ -485,14 +487,15 @@ var RequestCallback = Class({
{
if(this._promise !== null)
{
- this._promise.fail(ex);
+ this._promise.reject(ex);
}
}
}
-});
+}
-var Request = Class({
- __init__: function(locatorInfo, ref)
+class Request
+{
+ constructor(locatorInfo, ref)
{
this._locatorInfo = locatorInfo;
this._ref = ref;
@@ -503,10 +506,11 @@ var Request = Class({
this._response = false;
this._proxy = null;
this._exception = null;
- },
- addCallback: function(ref, wellKnownRef, ttl, promise)
+ }
+
+ addCallback(ref, wellKnownRef, ttl, promise)
{
- var callback = new RequestCallback(ref, ttl, promise);
+ const callback = new RequestCallback(ref, ttl, promise);
if(this._response)
{
callback.response(this._locatorInfo, this._proxy);
@@ -528,82 +532,74 @@ var Request = Class({
this.send();
}
}
- },
- response: function(proxy)
+ }
+
+ response(proxy)
{
this._locatorInfo.finishRequest(this._ref, this._wellKnownRefs, proxy, false);
this._response = true;
this._proxy = proxy;
- for(var i = 0; i < this._callbacks.length; ++i)
+ for(let i = 0; i < this._callbacks.length; ++i)
{
this._callbacks[i].response(this._locatorInfo, proxy);
}
- },
- exception: function(ex)
+ }
+
+ exception(ex)
{
this._locatorInfo.finishRequest(this._ref, this._wellKnownRefs, null, ex instanceof Ice.UserException);
this._exception = ex;
- for(var i = 0; i < this._callbacks.length; ++i)
+ for(let i = 0; i < this._callbacks.length; ++i)
{
this._callbacks[i].exception(this._locatorInfo, ex);
}
}
-});
+}
-var ObjectRequest = Class(Request, {
- __init__: function(locatorInfo, reference)
+class ObjectRequest extends Request
+{
+ constructor(locatorInfo, reference)
{
- Request.call(this, locatorInfo, reference);
+ super(locatorInfo, reference);
Debug.assert(reference.isWellKnown());
- },
- send: function()
+ }
+
+ send()
{
try
{
- var self = this;
this._locatorInfo.getLocator().findObjectById(this._ref.getIdentity()).then(
- function(proxy)
- {
- self.response(proxy);
- },
- function(ex)
- {
- self.exception(ex);
- });
+ proxy => this.response(proxy),
+ ex => this.exception(ex));
}
catch(ex)
{
this.exception(ex);
}
}
-});
+}
-var AdapterRequest = Class(Request, {
- __init__: function(locatorInfo, reference)
+class AdapterRequest extends Request
+{
+ constructor(locatorInfo, reference)
{
- Request.call(this, locatorInfo, reference);
+ super(locatorInfo, reference);
Debug.assert(reference.isIndirect());
- },
- send: function()
+ }
+
+ send()
{
try
{
- var self = this;
this._locatorInfo.getLocator().findAdapterById(this._ref.getAdapterId()).then(
- function(proxy)
- {
- self.response(proxy);
- },
- function(ex)
- {
- self.exception(ex);
- });
+ proxy => this.response(proxy),
+ ex => this.exception(ex));
}
catch(ex)
{
this.exception(ex);
}
}
-});
+}
module.exports.Ice = Ice;
diff --git a/js/src/Ice/LocatorManager.js b/js/src/Ice/LocatorManager.js
index 1eacd35e994..d1631df20b8 100644
--- a/js/src/Ice/LocatorManager.js
+++ b/js/src/Ice/LocatorManager.js
@@ -7,43 +7,44 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/HashMap",
"../Ice/LocatorInfo",
"../Ice/LocatorTable",
"../Ice/Locator"
]);
-var HashMap = Ice.HashMap;
-var LocatorInfo = Ice.LocatorInfo;
-var LocatorTable = Ice.LocatorTable;
-var LocatorPrx = Ice.LocatorPrx;
+const HashMap = Ice.HashMap;
+const LocatorInfo = Ice.LocatorInfo;
+const LocatorTable = Ice.LocatorTable;
+const LocatorPrx = Ice.LocatorPrx;
-var LocatorManager = Ice.Class({
- __init__: function(properties)
+class LocatorManager
+{
+ constructor(properties)
{
this._background = properties.getPropertyAsInt("Ice.BackgroundLocatorCacheUpdates") > 0;
-
this._table = new HashMap(HashMap.compareEquals); // Map<Ice.LocatorPrx, LocatorInfo>
this._locatorTables = new HashMap(HashMap.compareEquals); // Map<Ice.Identity, LocatorTable>
- },
- destroy: function()
+ }
+
+ destroy()
{
- for(var e = this._table.entries; e !== null; e = e.next)
+ for(let locator of this._table.values())
{
- e.value.destroy();
+ locator.destroy();
}
this._table.clear();
this._locatorTables.clear();
- },
+ }
+
//
// Returns locator info for a given locator. Automatically creates
// the locator info if it doesn't exist yet.
//
- find: function(loc)
+ find(loc)
{
if(loc === null)
{
@@ -53,13 +54,12 @@ var LocatorManager = Ice.Class({
//
// The locator can't be located.
//
- var locator = LocatorPrx.uncheckedCast(loc.ice_locator(null));
+ const locator = LocatorPrx.uncheckedCast(loc.ice_locator(null));
//
// TODO: reap unused locator info objects?
//
-
- var info = this._table.get(locator);
+ let info = this._table.get(locator);
if(info === undefined)
{
//
@@ -67,7 +67,7 @@ var LocatorManager = Ice.Class({
// have only one table per locator (not one per locator
// proxy).
//
- var table = this._locatorTables.get(locator.ice_getIdentity());
+ let table = this._locatorTables.get(locator.ice_getIdentity());
if(table === undefined)
{
table = new LocatorTable();
@@ -80,7 +80,7 @@ var LocatorManager = Ice.Class({
return info;
}
-});
+}
Ice.LocatorManager = LocatorManager;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/LocatorTable.js b/js/src/Ice/LocatorTable.js
index fe6e93d1ea9..4f7e9f646c1 100644
--- a/js/src/Ice/LocatorTable.js
+++ b/js/src/Ice/LocatorTable.js
@@ -7,24 +7,45 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Class", "../Ice/HashMap", "../Ice/Debug"]);
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module, ["../Ice/HashMap", "../Ice/Debug", "../Ice/IdentityUtil"]);
-var HashMap = Ice.HashMap;
-var Debug = Ice.Debug;
+const HashMap = Ice.HashMap;
+const Debug = Ice.Debug;
-var LocatorTable = Ice.Class({
- __init__: function()
+class EndpointTableEntry
+{
+ constructor(time, endpoints)
+ {
+ this.time = time;
+ this.endpoints = endpoints;
+ }
+}
+
+class ReferenceTableEntry
+{
+ constructor(time, reference)
+ {
+ this.time = time;
+ this.reference = reference;
+ }
+}
+
+class LocatorTable
+{
+ constructor()
{
- this._adapterEndpointsTable = new HashMap(); // Map<String, EndpointTableEntry>
+ this._adapterEndpointsTable = new Map(); // Map<String, EndpointTableEntry>
this._objectTable = new HashMap(HashMap.compareEquals); // Map<Ice.Identity, ReferenceTableEntry>
- },
- clear: function()
+ }
+
+ clear()
{
this._adapterEndpointsTable.clear();
this._objectTable.clear();
- },
- getAdapterEndpoints: function(adapter, ttl, cached)
+ }
+
+ getAdapterEndpoints(adapter, ttl, cached)
{
if(ttl === 0) // Locator cache disabled.
{
@@ -32,7 +53,7 @@ var LocatorTable = Ice.Class({
return null;
}
- var entry = this._adapterEndpointsTable.get(adapter);
+ const entry = this._adapterEndpointsTable.get(adapter);
if(entry !== undefined)
{
cached.value = this.checkTTL(entry.time, ttl);
@@ -40,18 +61,21 @@ var LocatorTable = Ice.Class({
}
cached.value = false;
return null;
- },
- addAdapterEndpoints: function(adapter, endpoints)
+ }
+
+ addAdapterEndpoints(adapter, endpoints)
{
this._adapterEndpointsTable.set(adapter, new EndpointTableEntry(Date.now(), endpoints));
- },
- removeAdapterEndpoints: function(adapter)
+ }
+
+ removeAdapterEndpoints(adapter)
{
- var entry = this._adapterEndpointsTable.get(adapter);
+ const entry = this._adapterEndpointsTable.get(adapter);
this._adapterEndpointsTable.delete(adapter);
return entry !== undefined ? entry.endpoints : null;
- },
- getObjectReference: function(id, ttl, cached)
+ }
+
+ getObjectReference(id, ttl, cached)
{
if(ttl === 0) // Locator cache disabled.
{
@@ -59,7 +83,7 @@ var LocatorTable = Ice.Class({
return null;
}
- var entry = this._objectTable.get(id);
+ const entry = this._objectTable.get(id);
if(entry !== undefined)
{
cached.value = this.checkTTL(entry.time, ttl);
@@ -67,18 +91,21 @@ var LocatorTable = Ice.Class({
}
cached.value = false;
return null;
- },
- addObjectReference: function(id, ref)
+ }
+
+ addObjectReference(id, ref)
{
this._objectTable.set(id, new ReferenceTableEntry(Date.now(), ref));
- },
- removeObjectReference: function(id)
+ }
+
+ removeObjectReference(id)
{
- var entry = this._objectTable.get(id);
+ const entry = this._objectTable.get(id);
this._objectTable.delete(id);
return entry !== undefined ? entry.reference : null;
- },
- checkTTL: function(time, ttl)
+ }
+
+ checkTTL(time, ttl)
{
Debug.assert(ttl !== 0);
if(ttl < 0) // TTL = infinite
@@ -90,19 +117,8 @@ var LocatorTable = Ice.Class({
return Date.now() - time <= (ttl * 1000);
}
}
-});
+}
Ice.LocatorTable = LocatorTable;
module.exports.Ice = Ice;
-var EndpointTableEntry = function(time, endpoints)
-{
- this.time = time;
- this.endpoints = endpoints;
-};
-
-var ReferenceTableEntry = function(time, reference)
-{
- this.time = time;
- this.reference = reference;
-};
diff --git a/js/src/Ice/Logger.js b/js/src/Ice/Logger.js
index 31b3c554415..10ac279fc08 100644
--- a/js/src/Ice/Logger.js
+++ b/js/src/Ice/Logger.js
@@ -7,10 +7,11 @@
//
// **********************************************************************
-var Ice = require("../Ice/Class").Ice;
-
-var Logger = Ice.Class({
- __init__: function(prefix)
+const Ice = require("../Ice/ModuleRegistry").Ice;
+
+class Logger
+{
+ constructor(prefix)
{
if(prefix !== undefined && prefix.length > 0)
{
@@ -20,6 +21,7 @@ var Logger = Ice.Class({
{
this._prefix = "";
}
+
this._dateformat =
{
year: 'numeric',
@@ -30,15 +32,17 @@ var Logger = Ice.Class({
second: 'numeric',
hour12: false
};
- },
- print: function(message)
+ }
+
+ print(message)
{
this.write(message, false);
- },
- trace: function(category, message)
+ }
+
+ trace(category, message)
{
- var s = [];
- var d = new Date();
+ const s = [];
+ const d = new Date();
s.push("-- ");
s.push(this.timestamp());
s.push(' ');
@@ -47,11 +51,12 @@ var Logger = Ice.Class({
s.push(": ");
s.push(message);
this.write(s.join(""), true);
- },
- warning: function(message)
+ }
+
+ warning(message)
{
- var s = [];
- var d = new Date();
+ const s = [];
+ const d = new Date();
s.push("-! ");
s.push(this.timestamp());
s.push(' ');
@@ -59,11 +64,12 @@ var Logger = Ice.Class({
s.push("warning: ");
s.push(message);
this.write(s.join(""), true);
- },
- error: function(message)
+ }
+
+ error(message)
{
- var s = [];
- var d = new Date();
+ const s = [];
+ const d = new Date();
s.push("!! ");
s.push(this.timestamp());
s.push(' ');
@@ -71,12 +77,14 @@ var Logger = Ice.Class({
s.push("error: ");
s.push(message);
this.write(s.join(""), true);
- },
- cloneWithPrefix: function(prefix)
+ }
+
+ cloneWithPrefix(prefix)
{
return new Logger(prefix);
- },
- write: function(message, indent)
+ }
+
+ write(message, indent)
{
if(indent)
{
@@ -84,12 +92,14 @@ var Logger = Ice.Class({
}
console.log(message);
- },
- timestamp: function()
+ }
+
+ timestamp()
{
- var d = new Date();
+ const d = new Date();
return d.toLocaleString("en-US", this._dateformat) + "." + d.getMilliseconds();
}
-});
+}
+
Ice.Logger = Logger;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/Long.js b/js/src/Ice/Long.js
index b474f6893d3..cf748c8c4ba 100644
--- a/js/src/Ice/Long.js
+++ b/js/src/Ice/Long.js
@@ -7,33 +7,62 @@
//
// **********************************************************************
-var Ice = require("../Ice/Class").Ice;
+const Ice = require("../Ice/ModuleRegistry").Ice;
//
// The Long type represents a signed 64-bit integer as two 32-bit values
// corresponding to the high and low words.
//
-
-var Long = Ice.Class({
- __init__: function(high, low)
+class Long
+{
+ //
+ // If only one argument is provide we assume it is a JavaScript Number,
+ // and we convert it to two 32 bit words to fit in the Ice.Long internal
+ // representation.
+ //
+ // If two arguments are provided we asume these are the high and low words
+ // respectively.
+ //
+ constructor(high = 0, low)
{
- if(low < 0 || low > Long.MAX_UINT32)
+ if(!Number.isSafeInteger(high))
{
- throw new RangeError("Low word must be between 0 and 0xFFFFFFFF");
+ throw new RangeError(low === undefined ?
+ "Number must be a safe integer" :
+ "High word must be a safe integer");
}
- if(high < 0 || high > Long.MAX_UINT32)
+
+ if(low === undefined)
{
- throw new RangeError("High word must be between 0 and 0xFFFFFFFF");
+ this.low = high % Long.HIGH_MASK;
+ this.high = Math.floor(high / Long.HIGH_MASK);
}
-
- this.high = high;
- this.low = low;
- },
- hashCode: function()
+ else
+ {
+ if(!Number.isSafeInteger(low))
+ {
+ throw new RangeError("Low word must be a safe integer");
+ }
+ if(low < 0 || low > Long.MAX_UINT32)
+ {
+ throw new RangeError("Low word must be between 0 and 0xFFFFFFFF");
+ }
+ if(high < 0 || high > Long.MAX_UINT32)
+ {
+ throw new RangeError("High word must be between 0 and 0xFFFFFFFF");
+ }
+
+ this.high = high;
+ this.low = low;
+ }
+ }
+
+ hashCode()
{
return this.low;
- },
- equals: function(rhs)
+ }
+
+ equals(rhs)
{
if(this === rhs)
{
@@ -44,14 +73,15 @@ var Long = Ice.Class({
return false;
}
return this.high === rhs.high && this.low === rhs.low;
- },
- toString: function()
+ }
+
+ toString()
{
return this.high + ":" + this.low;
- },
- toNumber: function()
- {
+ }
+ toNumber()
+ {
if((this.high & Long.SIGN_MASK) !== 0)
{
const l = (~this.low) >>> 0;
@@ -71,7 +101,7 @@ var Long = Ice.Class({
return (this.high * Long.HIGH_MASK) + this.low;
}
}
-});
+}
//
// 2^32
diff --git a/js/src/Ice/MapUtil.js b/js/src/Ice/MapUtil.js
new file mode 100644
index 00000000000..d8511839085
--- /dev/null
+++ b/js/src/Ice/MapUtil.js
@@ -0,0 +1,51 @@
+// **********************************************************************
+//
+// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
+//
+// This copy of Ice is licensed to you under the terms described in the
+// ICE_LICENSE file included in this distribution.
+//
+// **********************************************************************
+
+const Ice = require("../Ice/ModuleRegistry").Ice;
+
+class MapUtil
+{
+ static equals(m1, m2)
+ {
+ if(m1 === m2)
+ {
+ return true;
+ }
+ else if(m1.size != m2.size)
+ {
+ return false;
+ }
+ else
+ {
+ for(let [key, value] of m1)
+ {
+ if(value === undefined)
+ {
+ if(!m2.has(key))
+ {
+ return false;
+ }
+ else if(m2.get(key) !== value)
+ {
+ return false;
+ }
+ }
+ else if(m2.get(key) !== value)
+ {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+}
+
+Ice.MapUtil = MapUtil;
+
+module.exports.Ice = Ice;
diff --git a/js/src/Ice/ModuleRegistry.js b/js/src/Ice/ModuleRegistry.js
index b7a4fb014d9..37c2add25fe 100644
--- a/js/src/Ice/ModuleRegistry.js
+++ b/js/src/Ice/ModuleRegistry.js
@@ -7,39 +7,42 @@
//
// **********************************************************************
-var __modules__ = {};
+const modules = {};
-var __M =
+class _ModuleRegistry
{
- module: function(name)
+ static module(name)
{
- var m = __modules__[name];
+ let m = modules[name];
if(m === undefined)
{
m = {};
- __modules__[name] = m;
+ modules[name] = m;
}
return m;
- },
- require: function(m, paths)
+ }
+
+ static require(m, paths)
{
- var i = 0, length = paths.length, o;
- for(; i < length; ++i)
- {
- o = m.require(paths[i]);
- }
+ let o;
+ paths.forEach(path =>
+ {
+ o = m.require(path);
+ });
return o;
- },
- type: function(scoped)
+ }
+
+ static type(scoped)
{
if(scoped === undefined)
{
return undefined;
}
- var components = scoped.split(".");
- var T = __modules__;
- for(var i = 0, length = components.length; i < length; ++i)
+ const components = scoped.split(".");
+ let T = modules;
+
+ for(let i = 0; i < components.length; ++i)
{
T = T[components[i]];
if(T === undefined)
@@ -49,9 +52,9 @@ var __M =
}
return T;
}
-};
+}
-var Ice = __M.module("Ice");
+const Ice = _ModuleRegistry.module("Ice");
Ice.Slice = Ice.Slice || {};
-Ice.__M = __M;
+Ice._ModuleRegistry = _ModuleRegistry;
exports.Ice = Ice;
diff --git a/js/src/Ice/Object.js b/js/src/Ice/Object.js
index fd0d2f59fb5..9b9e990fe57 100644
--- a/js/src/Ice/Object.js
+++ b/js/src/Ice/Object.js
@@ -12,301 +12,68 @@
//
// Using IceObject in this file to avoid collisions with the native Object.
//
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
- "../Ice/DispatchStatus",
"../Ice/Exception",
"../Ice/FormatType",
"../Ice/StreamHelpers",
"../Ice/OptionalFormat"
]);
-var Class = Ice.Class;
+const ids = ["::Ice::Object"];
-var nextAddress = 0;
-
-var IceObject = Class({
- __init__: function()
- {
- // Fake Address used as the hashCode for this object instance.
- this.__address = nextAddress++;
- },
- hashCode: function()
- {
- return this.__address;
- },
- ice_isA: function(s, current)
- {
- return this.__mostDerivedType().__ids.indexOf(s) >= 0;
- },
- ice_ping: function(current)
- {
- },
- ice_ids: function(current)
- {
- return this.__mostDerivedType().__ids;
- },
- ice_id: function(current)
- {
- return this.__mostDerivedType().__id;
- },
- toString: function()
- {
- return "[object " + this.ice_id() + "]";
- },
- ice_preMarshal: function()
- {
- },
- ice_postUnmarshal: function()
- {
- },
- __write: function(os)
- {
- os.startWriteObject(null);
- __writeImpl(this, os, this.__mostDerivedType());
- os.endWriteObject();
- },
- __read: function(is)
- {
- is.startReadObject();
- __readImpl(this, is, this.__mostDerivedType());
- is.endReadObject(false);
- },
- ice_instanceof: function(T)
- {
- if(T)
- {
- if(this instanceof T)
- {
- return true;
- }
- return this.__mostDerivedType().__instanceof(T);
- }
- return false;
- },
- //
- // __mostDerivedType returns the the most derived Ice generated class. This is
- // necessary because the user might extend Slice generated classes. The user
- // class extensions don't have __id, __ids, __instanceof etc static members so
- // the implementation of ice_id, ice_ids and ice_instanceof would fail trying
- // to access those members of the user defined class. Instead, ice_id, ice_ids
- // and ice_instanceof call __mostDerivedType to get the most derived Ice class.
- //
- // The __mostDerivedType is overriden by each Slice generated class, see the
- // Slice.defineObject method implementation for details.
- //
- __mostDerivedType: function()
- {
- return IceObject;
- },
- //
- // The default implementation of equals compare references.
- //
- equals: function(other)
- {
- return this === other;
- }
-});
-
-//
-// These methods are used for object parameters.
-//
-IceObject.write = function(os, v)
-{
- os.writeObject(v);
-};
-
-IceObject.writeOpt = function(os, tag, v)
-{
- os.writeOptObject(tag, v);
-};
-
-IceObject.read = function(is)
-{
- var v = { value: null };
- is.readObject(function(o) { v.value = o; }, IceObject);
- return v;
-};
-
-IceObject.readOpt = function(is, tag)
-{
- var v = { value: undefined };
- is.readOptObject(tag, function(o) { v.value = o; }, IceObject);
- return v;
-};
-
-IceObject.ice_staticId = function()
+Ice.Object = class
{
- return IceObject.__id;
-};
-
-IceObject.__instanceof = function(T)
-{
- if(T === this)
+ ice_isA(s, current)
{
- return true;
+ return this._iceMostDerivedType()._iceIds.indexOf(s) >= 0;
}
- for(var i in this.__implements)
+ ice_ping(current)
{
- if(this.__implements[i].__instanceof(T))
- {
- return true;
- }
}
- if(this.__parent)
+ ice_ids(current)
{
- return this.__parent.__instanceof(T);
+ return this._iceMostDerivedType()._iceIds;
}
- return false;
-};
-IceObject.__ids = ["::Ice::Object"];
-IceObject.__id = IceObject.__ids[0];
-IceObject.__compactId = -1;
-IceObject.__preserved = false;
-
-//
-// Private methods
-//
-
-var __writeImpl = function(obj, os, type)
-{
- //
- // The __writeImpl method is a recursive method that goes down the
- // class hierarchy to marshal each slice of the class using the
- // generated __writeMemberImpl method.
- //
-
- if(type === undefined || type === IceObject)
+ ice_id(current)
{
- return; // Don't marshal anything for IceObject
+ return this._iceMostDerivedType()._iceId;
}
- os.startWriteSlice(type.__id, type.__compactId, type.__parent === IceObject);
- if(type.prototype.__writeMemberImpl)
+ toString()
{
- type.prototype.__writeMemberImpl.call(obj, os);
+ return "[object " + this.ice_id() + "]";
}
- os.endWriteSlice();
- __writeImpl(obj, os, type.__parent);
-};
-var __readImpl = function(obj, is, type)
-{
//
- // The __readImpl method is a recursive method that goes down the
- // class hierarchy to marshal each slice of the class using the
- // generated __readMemberImpl method.
+ // _iceMostDerivedType returns the the most derived Ice generated class. This is
+ // necessary because the user might extend Slice generated classes. The user
+ // class extensions don't have _iceId, _iceIds, etc static members so the implementation
+ // of ice_id and ice_ids would fail trying to access those members of the user
+ // defined class. Instead, ice_id, ice_ids and ice_instanceof call _iceMostDerivedType
+ // to get the most derived Ice class.
//
-
- if(type === undefined || type === IceObject)
+ _iceMostDerivedType()
{
- return; // Don't marshal anything for IceObject
+ return Ice.Object;
}
- is.startReadSlice();
- if(type.prototype.__readMemberImpl)
- {
- type.prototype.__readMemberImpl.call(obj, is);
- }
- is.endReadSlice();
- __readImpl(obj, is, type.__parent);
-};
-
-var __writePreserved = function(os)
-{
- //
- // For Slice classes which are marked "preserved", the implementation of this method
- // replaces the Ice.Object.prototype.__write method.
//
- os.startWriteObject(this.__slicedData);
- __writeImpl(this, os, this.__mostDerivedType());
- os.endWriteObject();
-};
-
-var __readPreserved = function(is)
-{
- //
- // For Slice classes which are marked "preserved", the implementation of this method
- // replaces the Ice.Object.prototype.__read method.
+ // The default implementation of equals compare references.
//
- is.startReadObject();
- __readImpl(this, is, this.__mostDerivedType());
- this.__slicedData = is.endReadObject(true);
-};
-
-Ice.Object = IceObject;
-
-var Slice = Ice.Slice;
-Slice.defineLocalObject = function(constructor, base)
-{
- var obj = constructor || function(){};
-
- if(base !== undefined)
+ equals(other)
{
- obj.prototype = new base();
- obj.__parent = base;
- obj.prototype.constructor = constructor;
+ return this === other;
}
- return obj;
-};
-
-Slice.defineObject = function(constructor, base, intfs, scope, ids, compactId, writeImpl, readImpl, preserved)
-{
- var obj = constructor || function(){};
-
- obj.prototype = new base();
- obj.__parent = base;
- obj.__ids = ids;
- obj.__id = ids[scope];
- obj.__compactId = compactId;
- obj.__instanceof = IceObject.__instanceof;
- obj.__implements = intfs;
-
- //
- // These methods are used for object parameters.
- //
- obj.write = function(os, v)
- {
- os.writeObject(v);
- };
- obj.writeOpt = function(os, tag, v)
+ static get _iceImplements()
{
- os.writeOptObject(tag, v);
- };
- obj.read = function(is)
- {
- var v = { value: null };
- is.readObject(function(o) { v.value = o; }, obj);
- return v;
- };
- obj.readOpt = function(is, tag)
- {
- var v = { value: undefined };
- is.readOptObject(tag, function(o) { v.value = o; }, obj);
- return v;
- };
-
- obj.ice_staticId = function()
- {
- return ids[scope];
- };
-
- obj.prototype.constructor = obj;
- obj.prototype.__mostDerivedType = function() { return obj; };
- if(preserved)
- {
- obj.prototype.__write = __writePreserved;
- obj.prototype.__read = __readPreserved;
+ return [];
}
- obj.prototype.__writeMemberImpl = writeImpl;
- obj.prototype.__readMemberImpl = readImpl;
-
- return obj;
};
+
module.exports.Ice = Ice;
diff --git a/js/src/Ice/ObjectAdapterFactory.js b/js/src/Ice/ObjectAdapterFactory.js
index e034797abee..2115358984a 100644
--- a/js/src/Ice/ObjectAdapterFactory.js
+++ b/js/src/Ice/ObjectAdapterFactory.js
@@ -7,10 +7,9 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/AsyncResultBase",
"../Ice/LocalException",
"../Ice/ObjectAdapterI",
@@ -18,23 +17,25 @@ Ice.__M.require(module,
"../Ice/UUID"
]);
-var AsyncResultBase = Ice.AsyncResultBase;
-var ObjectAdapterI = Ice.ObjectAdapterI;
-var Promise = Ice.Promise;
+const AsyncResultBase = Ice.AsyncResultBase;
+const ObjectAdapterI = Ice.ObjectAdapterI;
+const _Promise = Ice.Promise;
//
// Only for use by Instance.
//
-var ObjectAdapterFactory = Ice.Class({
- __init__: function(instance, communicator)
+class ObjectAdapterFactory
+{
+ constructor(instance, communicator)
{
this._instance = instance;
this._communicator = communicator;
this._adapters = [];
this._adapterNamesInUse = [];
- this._shutdownPromise = new Promise();
- },
- shutdown: function()
+ this._shutdownPromise = new _Promise();
+ }
+
+ shutdown()
{
//
// Ignore shutdown requests if the object adapter factory has
@@ -47,55 +48,39 @@ var ObjectAdapterFactory = Ice.Class({
this._instance = null;
this._communicator = null;
- this._shutdownPromise = Promise.all(
- this._adapters.map(function(adapter)
- {
- return adapter.deactivate();
- }));
+ this._shutdownPromise = _Promise.all(this._adapters.map(adapter => adapter.deactivate()));
return this._shutdownPromise;
- },
- waitForShutdown: function()
+ }
+
+ waitForShutdown()
{
- var self = this;
- return this._shutdownPromise.then(
- function()
- {
- return Promise.all(self._adapters.map(function(adapter)
- {
- return adapter.waitForDeactivate();
- }));
- });
- },
- isShutdown: function()
+ return this._shutdownPromise.then(() => _Promise.all(this._adapters.map(adapter => adapter.waitForDeactivate())));
+ }
+
+ isShutdown()
{
return this._instance === null;
- },
- destroy: function()
+ }
+
+ destroy()
{
- var self = this;
- return this.waitForShutdown().then(
- function()
- {
- return Promise.all(self._adapters.map(function(adapter)
- {
- return adapter.destroy();
- }));
- });
- },
- createObjectAdapter: function(name, router, promise)
+ return this.waitForShutdown().then(() => _Promise.all(this._adapters.map(adapter => adapter.destroy())));
+ }
+
+ createObjectAdapter(name, router, promise)
{
if(this._instance === null)
{
throw new Ice.ObjectAdapterDeactivatedException();
}
- var adapter = null;
+ let adapter = null;
try
{
if(name.length === 0)
{
- var uuid = Ice.generateUUID();
- adapter = new ObjectAdapterI(this._instance, this._communicator, this, uuid, null, true, promise);
+ adapter = new ObjectAdapterI(this._instance, this._communicator, this, Ice.generateUUID(), null, true,
+ promise);
}
else
{
@@ -110,17 +95,18 @@ var ObjectAdapterFactory = Ice.Class({
}
catch(ex)
{
- promise.fail(ex, promise);
+ promise.reject(ex);
}
- },
- removeObjectAdapter: function(adapter)
+ }
+
+ removeObjectAdapter(adapter)
{
if(this._instance === null)
{
return;
}
- var n = this._adapters.indexOf(adapter);
+ let n = this._adapters.indexOf(adapter);
if(n !== -1)
{
this._adapters.splice(n, 1);
@@ -132,7 +118,7 @@ var ObjectAdapterFactory = Ice.Class({
this._adapterNamesInUse.splice(n, 1);
}
}
-});
+}
Ice.ObjectAdapterFactory = ObjectAdapterFactory;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/ObjectAdapterI.js b/js/src/Ice/ObjectAdapterI.js
index 58191e56078..fe371687b5a 100644
--- a/js/src/Ice/ObjectAdapterI.js
+++ b/js/src/Ice/ObjectAdapterI.js
@@ -7,15 +7,13 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/AsyncResultBase",
"../Ice/Debug",
"../Ice/Identity",
"../Ice/LocalException",
- "../Ice/Promise",
"../Ice/PropertyNames",
"../Ice/Router",
"../Ice/ServantManager",
@@ -23,15 +21,14 @@ Ice.__M.require(module,
"../Ice/UUID"
]);
-var AsyncResultBase = Ice.AsyncResultBase;
-var Debug = Ice.Debug;
-var Identity = Ice.Identity;
-var Promise = Ice.Promise;
-var PropertyNames = Ice.PropertyNames;
-var ServantManager = Ice.ServantManager;
-var StringUtil = Ice.StringUtil;
+const AsyncResultBase = Ice.AsyncResultBase;
+const Debug = Ice.Debug;
+const Identity = Ice.Identity;
+const PropertyNames = Ice.PropertyNames;
+const ServantManager = Ice.ServantManager;
+const StringUtil = Ice.StringUtil;
-var _suffixes =
+const _suffixes =
[
"ACM",
"AdapterId",
@@ -69,19 +66,20 @@ var _suffixes =
"ThreadPool.Serialize"
];
-var StateUninitialized = 0; // Just constructed.
-//var StateHeld = 1;
-//var StateWaitActivate = 2;
-//var StateActive = 3;
-//var StateDeactivating = 4;
-var StateDeactivated = 5;
-var StateDestroyed = 6;
+const StateUninitialized = 0; // Just constructed.
+//const StateHeld = 1;
+//const StateWaitActivate = 2;
+//const StateActive = 3;
+//const StateDeactivating = 4;
+const StateDeactivated = 5;
+const StateDestroyed = 6;
//
// Only for use by IceInternal.ObjectAdapterFactory
//
-var ObjectAdapterI = Ice.Class({
- __init__: function(instance, communicator, objectAdapterFactory, name, router, noConfig, promise)
+class ObjectAdapterI
+{
+ constructor(instance, communicator, objectAdapterFactory, name, router, noConfig, promise)
{
this._instance = instance;
this._communicator = communicator;
@@ -97,24 +95,21 @@ var ObjectAdapterI = Ice.Class({
{
this._reference = this._instance.referenceFactory().createFromString("dummy -t", "");
this._messageSizeMax = this._instance.messageSizeMax();
- promise.succeed(this, promise);
+ promise.resolve(this);
return;
}
- var properties = this._instance.initializationData().properties;
- var unknownProps = [];
- var noProps = this.filterProperties(unknownProps);
+ const properties = this._instance.initializationData().properties;
+ const unknownProps = [];
+ const noProps = this.filterProperties(unknownProps);
//
// Warn about unknown object adapter properties.
//
if(unknownProps.length !== 0 && properties.getPropertyAsIntWithDefault("Ice.Warn.UnknownProperties", 1) > 0)
{
- var message = ["found unknown properties for object adapter `" + name + "':"];
- for(var i = 0; i < unknownProps.length; ++i)
- {
- message.push("\n " + unknownProps[i]);
- }
+ const message = ["found unknown properties for object adapter `" + name + "':"];
+ unknownProps.forEach(unknownProp => message.push("\n " + unknownProp));
this._instance.initializationData().logger.warning(message.join(""));
}
@@ -123,16 +118,14 @@ var ObjectAdapterI = Ice.Class({
//
if(router === null && noProps)
{
- var ex = new Ice.InitializationException();
- ex.reason = "object adapter `" + this._name + "' requires configuration";
- throw ex;
+ throw new Ice.InitializationException(`object adapter \`${this._name}' requires configuration`);
}
//
// Setup a reference to be used to get the default proxy options
// when creating new proxies. By default, create twoway proxies.
//
- var proxyOptions = properties.getPropertyWithDefault(this._name + ".ProxyOptions", "-t");
+ const proxyOptions = properties.getPropertyWithDefault(this._name + ".ProxyOptions", "-t");
try
{
this._reference = this._instance.referenceFactory().createFromString("dummy " + proxyOptions, "");
@@ -141,9 +134,8 @@ var ObjectAdapterI = Ice.Class({
{
if(e instanceof Ice.ProxyParseException)
{
- var ex = new Ice.InitializationException();
- ex.reason = "invalid proxy options `" + proxyOptions + "' for object adapter `" + name + "'";
- throw ex;
+ throw new Ice.InitializationException(
+ `invalid proxy options \`${proxyOptions}' for object adapter \`${name}'`);
}
else
{
@@ -152,8 +144,8 @@ var ObjectAdapterI = Ice.Class({
}
{
- var defaultMessageSizeMax = this._instance.messageSizeMax() / 1024;
- var num = properties.getPropertyAsIntWithDefault(this._name + ".MessageSizeMax", defaultMessageSizeMax);
+ const defaultMessageSizeMax = this._instance.messageSizeMax() / 1024;
+ const num = properties.getPropertyAsIntWithDefault(this._name + ".MessageSizeMax", defaultMessageSizeMax);
if(num < 1 || num > 0x7fffffff / 1024)
{
this._messageSizeMax = 0x7fffffff;
@@ -184,40 +176,28 @@ var ObjectAdapterI = Ice.Class({
{
throw new Ice.AlreadyRegisteredException(
"object adapter with router",
- this._instance.identityToString(router.ice_getIdentity()));
+ Ice.identityToString(router.ice_getIdentity(), this._instance.toStringMode()));
}
//
// Add the router's server proxy endpoints to this object
// adapter.
//
- var self = this;
this._routerInfo.getServerEndpoints().then(
- function(endpoints)
+ (endpoints) =>
{
- var i;
-
- for(i = 0; i < endpoints.length; ++i)
- {
- self._routerEndpoints.push(endpoints[i]);
- }
- self._routerEndpoints.sort( // Must be sorted.
- function(e1, e2)
- {
- return e1.compareTo(e2);
- });
+ endpoints.forEach(endpoint => this._routerEndpoints.push(endpoint));
+ this._routerEndpoints.sort((e1, e2) => e1.compareTo(e2)); // Must be sorted.
//
// Remove duplicate endpoints, so we have a list of unique
// endpoints.
//
- for(i = 0; i < self._routerEndpoints.length - 1;)
+ for(let i = 0; i < this._routerEndpoints.length - 1;)
{
- var e1 = self._routerEndpoints[i];
- var e2 = self._routerEndpoints[i + 1];
- if(e1.equals(e2))
+ if(this._routerEndpoints[i].equals(this._routerEndpoints[i + 1]))
{
- self._routerEndpoints.splice(i, 1);
+ this._routerEndpoints.splice(i, 1);
}
else
{
@@ -230,33 +210,25 @@ var ObjectAdapterI = Ice.Class({
// new outgoing connections to the router's client proxy will
// use this object adapter for callbacks.
//
- self._routerInfo.setAdapter(self);
+ this._routerInfo.setAdapter(this);
//
// Also modify all existing outgoing connections to the
// router's client proxy to use this object adapter for
// callbacks.
//
- return self._instance.outgoingConnectionFactory().setRouterInfo(self._routerInfo);
+ return this._instance.outgoingConnectionFactory().setRouterInfo(this._routerInfo);
}
- ).then(
- function()
- {
- promise.succeed(self, promise);
- },
- function(ex)
- {
- promise.fail(ex, promise);
- });
+ ).then(() => promise.resolve(this), promise.reject);
}
else
{
- var endpoints = properties.getProperty(this._name + ".Endpoints");
+ const endpoints = properties.getProperty(this._name + ".Endpoints");
if(endpoints.length > 0)
{
throw new Ice.FeatureNotSupportedException("object adapter endpoints not supported");
}
- promise.succeed(this, promise);
+ promise.resolve(this);
}
}
catch(ex)
@@ -264,75 +236,81 @@ var ObjectAdapterI = Ice.Class({
this.destroy();
throw ex;
}
- },
- getName: function()
+ }
+
+ getName()
{
//
// No mutex lock necessary, _name is immutable.
//
return this._noConfig ? "" : this._name;
- },
- getCommunicator: function()
+ }
+
+ getCommunicator()
{
return this._communicator;
- },
- activate: function()
+ }
+
+ activate()
{
- },
- hold: function()
+ }
+
+ hold()
{
this.checkForDeactivation();
- },
- waitForHold: function()
+ }
+
+ waitForHold()
{
- var promise = new AsyncResultBase(this._communicator, "waitForHold", null, null, this);
- if(this.checkForDeactivation(promise))
- {
- return promise;
- }
- return promise.succeed(promise);
- },
- deactivate: function()
+ const promise = new AsyncResultBase(this._communicator, "waitForHold", null, null, this);
+ return this.checkForDeactivation(promise) ? promise : promise.resolve();
+ }
+
+ deactivate()
{
- var promise = new AsyncResultBase(this._communicator, "deactivate", null, null, this);
+ const promise = new AsyncResultBase(this._communicator, "deactivate", null, null, this);
if(this._state < StateDeactivated)
{
this._state = StateDeactivated;
this._instance.outgoingConnectionFactory().removeAdapter(this);
}
- return promise.succeed(promise);
- },
- waitForDeactivate: function()
+ promise.resolve();
+ return promise;
+ }
+
+ waitForDeactivate()
{
- var promise = new AsyncResultBase(this._communicator, "deactivate", null, null, this);
- return promise.succeed(promise);
- },
- isDeactivated: function()
+ return new AsyncResultBase(this._communicator, "deactivate", null, null, this).resolve();
+ }
+
+ isDeactivated()
{
return this._state >= StateDeactivated;
- },
- destroy: function()
+ }
+
+ destroy()
{
- var promise = new AsyncResultBase(this._communicator, "destroy", null, null, this);
- var self = this;
- var destroyInternal = function()
+ const promise = new AsyncResultBase(this._communicator, "destroy", null, null, this);
+ const destroyInternal = () =>
{
- if(self._state < StateDestroyed)
+ if(this._state < StateDestroyed)
{
- self._state = StateDestroyed;
- self._servantManager.destroy();
- self._objectAdapterFactory.removeObjectAdapter(self);
+ this._state = StateDestroyed;
+ this._servantManager.destroy();
+ this._objectAdapterFactory.removeObjectAdapter(this);
}
- return promise.succeed(promise);
+ return promise.resolve();
};
return this._state < StateDeactivated ? this.deactivate().then(destroyInternal) : destroyInternal();
- },
- add: function(object, ident)
+ }
+
+ add(object, ident)
{
return this.addFacet(object, ident, "");
- },
- addFacet: function(object, ident, facet)
+ }
+
+ addFacet(object, ident, facet)
{
this.checkForDeactivation();
this.checkIdentity(ident);
@@ -342,172 +320,189 @@ var ObjectAdapterI = Ice.Class({
// Create a copy of the Identity argument, in case the caller
// reuses it.
//
- var id = ident.clone();
+ const id = ident.clone();
this._servantManager.addServant(object, id, facet);
return this.newProxy(id, facet);
- },
- addWithUUID: function(object)
+ }
+
+ addWithUUID(object)
{
return this.addFacetWithUUID(object, "");
- },
- addFacetWithUUID: function(object, facet)
+ }
+
+ addFacetWithUUID(object, facet)
{
return this.addFacet(object, new Identity(Ice.generateUUID(), ""), facet);
- },
- addDefaultServant: function(servant, category)
+ }
+
+ addDefaultServant(servant, category)
{
this.checkServant(servant);
this.checkForDeactivation();
this._servantManager.addDefaultServant(servant, category);
- },
- remove: function(ident)
+ }
+
+ remove(ident)
{
return this.removeFacet(ident, "");
- },
- removeFacet: function(ident, facet)
+ }
+
+ removeFacet(ident, facet)
{
this.checkForDeactivation();
this.checkIdentity(ident);
return this._servantManager.removeServant(ident, facet);
- },
- removeAllFacets: function(ident)
+ }
+
+ removeAllFacets(ident)
{
this.checkForDeactivation();
this.checkIdentity(ident);
return this._servantManager.removeAllFacets(ident);
- },
- removeDefaultServant: function(category)
+ }
+
+ removeDefaultServant(category)
{
this.checkForDeactivation();
return this._servantManager.removeDefaultServant(category);
- },
- find: function(ident)
+ }
+
+ find(ident)
{
return this.findFacet(ident, "");
- },
- findFacet: function(ident, facet)
+ }
+
+ findFacet(ident, facet)
{
this.checkForDeactivation();
this.checkIdentity(ident);
-
return this._servantManager.findServant(ident, facet);
- },
- findAllFacets: function(ident)
+ }
+
+ findAllFacets(ident)
{
this.checkForDeactivation();
this.checkIdentity(ident);
-
return this._servantManager.findAllFacets(ident);
- },
- findByProxy: function(proxy)
+ }
+
+ findByProxy(proxy)
{
this.checkForDeactivation();
-
- var ref = proxy.__reference();
+ const ref = proxy._getReference();
return this.findFacet(ref.getIdentity(), ref.getFacet());
- },
- findDefaultServant: function(category)
+ }
+
+ findDefaultServant(category)
{
this.checkForDeactivation();
-
return this._servantManager.findDefaultServant(category);
- },
- addServantLocator: function(locator, prefix)
+ }
+
+ addServantLocator(locator, prefix)
{
this.checkForDeactivation();
-
this._servantManager.addServantLocator(locator, prefix);
- },
- removeServantLocator: function(prefix)
+ }
+
+ removeServantLocator(prefix)
{
this.checkForDeactivation();
-
return this._servantManager.removeServantLocator(prefix);
- },
- findServantLocator: function(prefix)
+ }
+
+ findServantLocator(prefix)
{
this.checkForDeactivation();
-
return this._servantManager.findServantLocator(prefix);
- },
- createProxy: function(ident)
+ }
+
+ createProxy(ident)
{
this.checkForDeactivation();
this.checkIdentity(ident);
-
return this.newProxy(ident, "");
- },
- createDirectProxy: function(ident)
+ }
+
+ createDirectProxy(ident)
{
return this.createProxy(ident);
- },
- createIndirectProxy: function(ident)
+ }
+
+ createIndirectProxy(ident)
{
- throw new Ice.FeatureNotSupportedException("setLocator not supported");
- },
- setLocator: function(locator)
+ throw new Ice.FeatureNotSupportedException("createIndirectProxy not supported");
+ }
+
+ setLocator(locator)
{
throw new Ice.FeatureNotSupportedException("setLocator not supported");
- },
- refreshPublishedEndpoints: function()
+ }
+
+ getEndpoints()
+ {
+ return [];
+ }
+
+ refreshPublishedEndpoints()
{
throw new Ice.FeatureNotSupportedException("refreshPublishedEndpoints not supported");
- },
- getEndpoints: function()
+ }
+
+ getPublishedEndpoints()
{
return [];
- },
- getPublishedEndpoints: function()
+ }
+
+ setPublishedEndpoints(newEndpoints)
{
- return [];
- },
- getServantManager: function()
+ throw new Ice.FeatureNotSupportedException("setPublishedEndpoints not supported");
+ }
+
+ getServantManager()
{
//
// _servantManager is immutable.
//
return this._servantManager;
- },
- messageSizeMax: function()
+ }
+
+ messageSizeMax()
{
return this._messageSizeMax;
- },
- newProxy: function(ident, facet)
- {
- var endpoints = [];
+ }
+ newProxy(ident, facet)
+ {
//
// Now we also add the endpoints of the router's server proxy, if
// any. This way, object references created by this object adapter
// will also point to the router's server proxy endpoints.
//
- for(var i = 0; i < this._routerEndpoints.length; ++i)
- {
- endpoints.push(this._routerEndpoints[i]);
- }
-
//
// Create a reference and return a proxy for this reference.
//
- var ref = this._instance.referenceFactory().create(ident, facet, this._reference, endpoints);
- return this._instance.proxyFactory().referenceToProxy(ref);
- },
- checkForDeactivation: function(promise)
+ return this._instance.proxyFactory().referenceToProxy(
+ this._instance.referenceFactory().create(ident, facet, this._reference,
+ Array.from(this._routerEndpoints)));
+ }
+
+ checkForDeactivation(promise)
{
if(this._state >= StateDeactivated)
{
- var ex = new Ice.ObjectAdapterDeactivatedException();
+ const ex = new Ice.ObjectAdapterDeactivatedException();
ex.name = this.getName();
if(promise !== undefined)
{
- promise.fail(ex, promise);
+ promise.reject(ex);
return true;
}
else
@@ -517,8 +512,9 @@ var ObjectAdapterI = Ice.Class({
}
return false;
- },
- checkIdentity: function(ident)
+ }
+
+ checkIdentity(ident)
{
if(ident.name === undefined || ident.name === null || ident.name.length === 0)
{
@@ -529,22 +525,24 @@ var ObjectAdapterI = Ice.Class({
{
ident.category = "";
}
- },
- checkServant: function(servant)
+ }
+
+ checkServant(servant)
{
if(servant === undefined || servant === null)
{
throw new Ice.IllegalServantException("cannot add null servant to Object Adapter");
}
- },
- filterProperties: function(unknownProps)
+ }
+
+ filterProperties(unknownProps)
{
//
// Do not create unknown properties list if Ice prefix, i.e., Ice, Glacier2, etc.
//
- var addUnknown = true, i;
- var prefix = this._name + ".";
- for(i = 0; i < PropertyNames.clPropNames.length; ++i)
+ let addUnknown = true;
+ const prefix = this._name + ".";
+ for(let i = 0; i < PropertyNames.clPropNames.length; ++i)
{
if(prefix.indexOf(PropertyNames.clPropNames[i] + ".") === 0)
{
@@ -553,14 +551,14 @@ var ObjectAdapterI = Ice.Class({
}
}
- var noProps = true;
- var props = this._instance.initializationData().properties.getPropertiesForPrefix(prefix);
- for(var e = props.entries; e !== null; e = e.next)
+ let noProps = true;
+ let props = this._instance.initializationData().properties.getPropertiesForPrefix(prefix);
+ for(let [key, value] of props)
{
- var valid = false;
- for(i = 0; i < _suffixes.length; ++i)
+ let valid = false;
+ for(let i = 0; i < _suffixes.length; ++i)
{
- if(e.key === prefix + _suffixes[i])
+ if(key === prefix + _suffixes[i])
{
noProps = false;
valid = true;
@@ -570,13 +568,13 @@ var ObjectAdapterI = Ice.Class({
if(!valid && addUnknown)
{
- unknownProps.push(e.key);
+ unknownProps.push(key);
}
}
return noProps;
}
-});
+}
Ice.ObjectAdapterI = ObjectAdapterI;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/ObjectFactory.js b/js/src/Ice/ObjectFactory.js
deleted file mode 100644
index 178954b9f08..00000000000
--- a/js/src/Ice/ObjectFactory.js
+++ /dev/null
@@ -1,21 +0,0 @@
-// **********************************************************************
-//
-// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
-//
-// This copy of Ice is licensed to you under the terms described in the
-// ICE_LICENSE file included in this distribution.
-//
-// **********************************************************************
-
-var Ice = require("../Ice/Class").Ice;
-Ice.ObjectFactory = Ice.Class({
- create: function(type)
- {
- throw new Error("not implemented");
- },
- destroy: function()
- {
- throw new Error("not implemented");
- }
-});
-module.exports.Ice = Ice;
diff --git a/js/src/Ice/ObjectFactoryManager.js b/js/src/Ice/ObjectFactoryManager.js
deleted file mode 100644
index 1b394397e9d..00000000000
--- a/js/src/Ice/ObjectFactoryManager.js
+++ /dev/null
@@ -1,71 +0,0 @@
-// **********************************************************************
-//
-// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
-//
-// This copy of Ice is licensed to you under the terms described in the
-// ICE_LICENSE file included in this distribution.
-//
-// **********************************************************************
-
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Class", "../Ice/HashMap", "../Ice/LocalException"]);
-
-var HashMap = Ice.HashMap;
-var AlreadyRegisteredException = Ice.AlreadyRegisteredException;
-var NotRegisteredException = Ice.NotRegisteredException;
-
-//
-// Only for use by Instance
-//
-var ObjectFactoryManager = Ice.Class({
- __init__: function()
- {
- this._factoryMap = new HashMap(); // Map<String, ObjectFactory>
- },
- add: function(factory, id)
- {
- var o, ex;
- o = this._factoryMap.get(id);
- if(o !== undefined)
- {
- ex = new AlreadyRegisteredException();
- ex.id = id;
- ex.kindOfObject = "object factory";
- throw ex;
- }
- this._factoryMap.set(id, factory);
- },
- remove: function(id)
- {
- var factory, ex;
- factory = this._factoryMap.get(id);
- if(factory === undefined)
- {
- ex = new NotRegisteredException();
- ex.id = id;
- ex.kindOfObject = "object factory";
- throw ex;
- }
- this._factoryMap.delete(id);
- factory.destroy();
- },
- find: function(id)
- {
- return this._factoryMap.get(id);
- },
- destroy: function()
- {
- var oldMap = this._factoryMap,
- e = oldMap.entries;
- this._factoryMap = new HashMap(); // Map<String, ObjectFactory>
-
- while(e !== null)
- {
- e.value.destroy();
- e = e.next;
- }
- }
-});
-
-Ice.ObjectFactoryManager = ObjectFactoryManager;
-module.exports.Ice = Ice;
diff --git a/js/src/Ice/ObjectPrx.js b/js/src/Ice/ObjectPrx.js
index 4d0c5e1328c..51bf7bf466a 100644
--- a/js/src/Ice/ObjectPrx.js
+++ b/js/src/Ice/ObjectPrx.js
@@ -7,15 +7,13 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/ArrayUtil",
"../Ice/AsyncResult",
"../Ice/Debug",
"../Ice/FormatType",
- "../Ice/HashMap",
"../Ice/OutgoingAsync",
"../Ice/ReferenceMode",
"../Ice/Current",
@@ -25,44 +23,49 @@ Ice.__M.require(module,
"../Ice/Object"
]);
-var ArrayUtil = Ice.ArrayUtil;
-var AsyncResultBase = Ice.AsyncResultBase;
-var AsyncResult = Ice.AsyncResult;
-var Debug = Ice.Debug;
-var FormatType = Ice.FormatType;
-var HashMap = Ice.HashMap;
-var OutgoingAsync = Ice.OutgoingAsync;
-var ProxyFlushBatch = Ice.ProxyFlushBatch;
-var ProxyGetConnection = Ice.ProxyGetConnection;
-var RefMode = Ice.ReferenceMode;
-var OperationMode = Ice.OperationMode;
+const ArrayUtil = Ice.ArrayUtil;
+const AsyncResultBase = Ice.AsyncResultBase;
+const AsyncResult = Ice.AsyncResult;
+const Debug = Ice.Debug;
+const FormatType = Ice.FormatType;
+const OutgoingAsync = Ice.OutgoingAsync;
+const ProxyFlushBatch = Ice.ProxyFlushBatch;
+const ProxyGetConnection = Ice.ProxyGetConnection;
+const RefMode = Ice.ReferenceMode;
+const OperationMode = Ice.OperationMode;
//
// Ice.ObjectPrx
//
-var ObjectPrx = Ice.Class({
- __init__: function()
+class ObjectPrx
+{
+ constructor()
{
this._reference = null;
this._requestHandler = null;
- },
- hashCode: function(r)
+ }
+
+ hashCode(r)
{
return this._reference.hashCode();
- },
- ice_getCommunicator: function()
+ }
+
+ ice_getCommunicator()
{
return this._reference.getCommunicator();
- },
- toString: function()
+ }
+
+ toString()
{
return this._reference.toString();
- },
- ice_getIdentity: function()
+ }
+
+ ice_getIdentity()
{
return this._reference.getIdentity().clone();
- },
- ice_identity: function(newIdentity)
+ }
+
+ ice_identity(newIdentity)
{
if(newIdentity === undefined || newIdentity === null || newIdentity.name.length === 0)
{
@@ -74,24 +77,28 @@ var ObjectPrx = Ice.Class({
}
else
{
- var proxy = new ObjectPrx();
- proxy.__setup(this._reference.changeIdentity(newIdentity));
+ const proxy = new ObjectPrx();
+ proxy._setup(this._reference.changeIdentity(newIdentity));
return proxy;
}
- },
- ice_getContext: function()
+ }
+
+ ice_getContext()
{
- return new HashMap(this._reference.getContext());
- },
- ice_context: function(newContext)
+ return new Map(this._reference.getContext());
+ }
+
+ ice_context(newContext)
{
- return this.__newInstance(this._reference.changeContext(newContext));
- },
- ice_getFacet: function()
+ return this._newInstance(this._reference.changeContext(newContext));
+ }
+
+ ice_getFacet()
{
return this._reference.getFacet();
- },
- ice_facet: function(newFacet)
+ }
+
+ ice_facet(newFacet)
{
if(newFacet === undefined || newFacet === null)
{
@@ -104,16 +111,18 @@ var ObjectPrx = Ice.Class({
}
else
{
- var proxy = new ObjectPrx();
- proxy.__setup(this._reference.changeFacet(newFacet));
+ const proxy = new ObjectPrx();
+ proxy._setup(this._reference.changeFacet(newFacet));
return proxy;
}
- },
- ice_getAdapterId: function()
+ }
+
+ ice_getAdapterId()
{
return this._reference.getAdapterId();
- },
- ice_adapterId: function(newAdapterId)
+ }
+
+ ice_adapterId(newAdapterId)
{
if(newAdapterId === undefined || newAdapterId === null)
{
@@ -126,14 +135,16 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changeAdapterId(newAdapterId));
+ return this._newInstance(this._reference.changeAdapterId(newAdapterId));
}
- },
- ice_getEndpoints: function()
+ }
+
+ ice_getEndpoints()
{
return ArrayUtil.clone(this._reference.getEndpoints());
- },
- ice_endpoints: function(newEndpoints)
+ }
+
+ ice_endpoints(newEndpoints)
{
if(newEndpoints === undefined || newEndpoints === null)
{
@@ -146,14 +157,16 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changeEndpoints(newEndpoints));
+ return this._newInstance(this._reference.changeEndpoints(newEndpoints));
}
- },
- ice_getLocatorCacheTimeout: function()
+ }
+
+ ice_getLocatorCacheTimeout()
{
return this._reference.getLocatorCacheTimeout();
- },
- ice_locatorCacheTimeout: function(newTimeout)
+ }
+
+ ice_locatorCacheTimeout(newTimeout)
{
if(newTimeout < -1)
{
@@ -165,14 +178,16 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changeLocatorCacheTimeout(newTimeout));
+ return this._newInstance(this._reference.changeLocatorCacheTimeout(newTimeout));
}
- },
- ice_getInvocationTimeout: function()
+ }
+
+ ice_getInvocationTimeout()
{
return this._reference.getInvocationTimeout();
- },
- ice_invocationTimeout: function(newTimeout)
+ }
+
+ ice_invocationTimeout(newTimeout)
{
if(newTimeout < 1 && newTimeout !== -1)
{
@@ -184,14 +199,16 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changeInvocationTimeout(newTimeout));
+ return this._newInstance(this._reference.changeInvocationTimeout(newTimeout));
}
- },
- ice_isConnectionCached: function()
+ }
+
+ ice_isConnectionCached()
{
return this._reference.getCacheConnection();
- },
- ice_connectionCached: function(newCache)
+ }
+
+ ice_connectionCached(newCache)
{
if(newCache === this._reference.getCacheConnection())
{
@@ -199,14 +216,16 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changeCacheConnection(newCache));
+ return this._newInstance(this._reference.changeCacheConnection(newCache));
}
- },
- ice_getEndpointSelection: function()
+ }
+
+ ice_getEndpointSelection()
{
return this._reference.getEndpointSelection();
- },
- ice_endpointSelection: function(newType)
+ }
+
+ ice_endpointSelection(newType)
{
if(newType === this._reference.getEndpointSelection())
{
@@ -214,14 +233,16 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changeEndpointSelection(newType));
+ return this._newInstance(this._reference.changeEndpointSelection(newType));
}
- },
- ice_isSecure: function()
+ }
+
+ ice_isSecure()
{
return this._reference.getSecure();
- },
- ice_secure: function(b)
+ }
+
+ ice_secure(b)
{
if(b === this._reference.getSecure())
{
@@ -229,14 +250,16 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changeSecure(b));
+ return this._newInstance(this._reference.changeSecure(b));
}
- },
- ice_getEncodingVersion: function()
+ }
+
+ ice_getEncodingVersion()
{
return this._reference.getEncoding().clone();
- },
- ice_encodingVersion: function(e)
+ }
+
+ ice_encodingVersion(e)
{
if(e.equals(this._reference.getEncoding()))
{
@@ -244,14 +267,16 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changeEncoding(e));
+ return this._newInstance(this._reference.changeEncoding(e));
}
- },
- ice_isPreferSecure: function()
+ }
+
+ ice_isPreferSecure()
{
return this._reference.getPreferSecure();
- },
- ice_preferSecure: function(b)
+ }
+
+ ice_preferSecure(b)
{
if(b === this._reference.getPreferSecure())
{
@@ -259,48 +284,54 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changePreferSecure(b));
+ return this._newInstance(this._reference.changePreferSecure(b));
}
- },
- ice_getRouter: function()
+ }
+
+ ice_getRouter()
{
- var ri = this._reference.getRouterInfo();
+ const ri = this._reference.getRouterInfo();
return ri !== null ? ri.getRouter() : null;
- },
- ice_router: function(router)
+ }
+
+ ice_router(router)
{
- var ref = this._reference.changeRouter(router);
+ const ref = this._reference.changeRouter(router);
if(ref.equals(this._reference))
{
return this;
}
else
{
- return this.__newInstance(ref);
+ return this._newInstance(ref);
}
- },
- ice_getLocator: function()
+ }
+
+ ice_getLocator()
{
- var ri = this._reference.getLocatorInfo();
+ const ri = this._reference.getLocatorInfo();
return ri !== null ? ri.getLocator() : null;
- },
- ice_locator: function(locator)
+ }
+
+ ice_locator(locator)
{
- var ref = this._reference.changeLocator(locator);
+ const ref = this._reference.changeLocator(locator);
if(ref.equals(this._reference))
{
return this;
}
else
{
- return this.__newInstance(ref);
+ return this._newInstance(ref);
}
- },
- ice_isTwoway: function()
+ }
+
+ ice_isTwoway()
{
return this._reference.getMode() === RefMode.ModeTwoway;
- },
- ice_twoway: function()
+ }
+
+ ice_twoway()
{
if(this._reference.getMode() === RefMode.ModeTwoway)
{
@@ -308,14 +339,16 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changeMode(RefMode.ModeTwoway));
+ return this._newInstance(this._reference.changeMode(RefMode.ModeTwoway));
}
- },
- ice_isOneway: function()
+ }
+
+ ice_isOneway()
{
return this._reference.getMode() === RefMode.ModeOneway;
- },
- ice_oneway: function()
+ }
+
+ ice_oneway()
{
if(this._reference.getMode() === RefMode.ModeOneway)
{
@@ -323,14 +356,16 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changeMode(RefMode.ModeOneway));
+ return this._newInstance(this._reference.changeMode(RefMode.ModeOneway));
}
- },
- ice_isBatchOneway: function()
+ }
+
+ ice_isBatchOneway()
{
return this._reference.getMode() === RefMode.ModeBatchOneway;
- },
- ice_batchOneway: function()
+ }
+
+ ice_batchOneway()
{
if(this._reference.getMode() === RefMode.ModeBatchOneway)
{
@@ -338,14 +373,16 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changeMode(RefMode.ModeBatchOneway));
+ return this._newInstance(this._reference.changeMode(RefMode.ModeBatchOneway));
}
- },
- ice_isDatagram: function()
+ }
+
+ ice_isDatagram()
{
return this._reference.getMode() === RefMode.ModeDatagram;
- },
- ice_datagram: function()
+ }
+
+ ice_datagram()
{
if(this._reference.getMode() === RefMode.ModeDatagram)
{
@@ -353,14 +390,16 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changeMode(RefMode.ModeDatagram));
+ return this._newInstance(this._reference.changeMode(RefMode.ModeDatagram));
}
- },
- ice_isBatchDatagram: function()
+ }
+
+ ice_isBatchDatagram()
{
return this._reference.getMode() === RefMode.ModeBatchDatagram;
- },
- ice_batchDatagram: function()
+ }
+
+ ice_batchDatagram()
{
if(this._reference.getMode() === RefMode.ModeBatchDatagram)
{
@@ -368,84 +407,79 @@ var ObjectPrx = Ice.Class({
}
else
{
- return this.__newInstance(this._reference.changeMode(RefMode.ModeBatchDatagram));
- }
- },
- ice_compress: function(co)
- {
- var ref = this._reference.changeCompress(co);
- if(ref.equals(this._reference))
- {
- return this;
- }
- else
- {
- return this.__newInstance(ref);
+ return this._newInstance(this._reference.changeMode(RefMode.ModeBatchDatagram));
}
- },
- ice_timeout: function(t)
+ }
+
+ ice_timeout(t)
{
if(t < 1 && t !== -1)
{
throw new Error("invalid value passed to ice_timeout: " + t);
}
- var ref = this._reference.changeTimeout(t);
+ const ref = this._reference.changeTimeout(t);
if(ref.equals(this._reference))
{
return this;
}
else
{
- return this.__newInstance(ref);
+ return this._newInstance(ref);
}
- },
- ice_getConnectionId: function()
+ }
+
+ ice_getConnectionId()
{
return this._reference.getConnectionId();
- },
- ice_connectionId: function(id)
+ }
+
+ ice_connectionId(id)
{
- var ref = this._reference.changeConnectionId(id);
+ const ref = this._reference.changeConnectionId(id);
if(ref.equals(this._reference))
{
return this;
}
else
{
- return this.__newInstance(ref);
+ return this._newInstance(ref);
}
- },
- ice_getConnection: function()
+ }
+
+ ice_getConnection()
{
- var r = new ProxyGetConnection(this, "ice_getConnection");
+ const r = new ProxyGetConnection(this, "ice_getConnection");
try
{
- r.__invoke();
+ r.invoke();
}
catch(ex)
{
- r.__abort(ex);
+ r.abort(ex);
}
return r;
- },
- ice_getCachedConnection: function()
+ }
+
+ ice_getCachedConnection()
{
return this._requestHandler ? this._requestHandler.getConnection() : null;
- },
- ice_flushBatchRequests: function()
+ }
+
+ ice_flushBatchRequests()
{
- var r = new ProxyFlushBatch(this, "ice_flushBatchRequests");
+ const r = new ProxyFlushBatch(this, "ice_flushBatchRequests");
try
{
- r.__invoke();
+ r.invoke();
}
catch(ex)
{
- r.__abort(ex);
+ r.abort(ex);
}
return r;
- },
- equals: function(r)
+ }
+
+ equals(r)
{
if(this === r)
{
@@ -458,22 +492,31 @@ var ObjectPrx = Ice.Class({
}
return false;
- },
- __reference: function()
+ }
+
+ _write(os)
+ {
+ this._reference.getIdentity()._write(os);
+ this._reference.streamWrite(os);
+ }
+
+ _getReference()
{
return this._reference;
- },
- __copyFrom: function(from)
+ }
+
+ _copyFrom(from)
{
Debug.assert(this._reference === null);
Debug.assert(this._requestHandler === null);
this._reference = from._reference;
this._requestHandler = from._requestHandler;
- },
- __handleException: function(ex, handler, mode, sent, sleep, cnt)
+ }
+
+ _handleException(ex, handler, mode, sent, sleep, cnt)
{
- this.__updateRequestHandler(handler, null); // Clear the request handler
+ this._updateRequestHandler(handler, null); // Clear the request handler
//
// We only retry local exception, system exceptions aren't retried.
@@ -521,15 +564,17 @@ var ObjectPrx = Ice.Class({
{
throw ex;
}
- },
- __checkAsyncTwowayOnly: function(name)
+ }
+
+ _checkAsyncTwowayOnly(name)
{
if(!this.ice_isTwoway())
{
throw new Error("`" + name + "' can only be called with a twoway proxy");
}
- },
- __getRequestHandler: function()
+ }
+
+ _getRequestHandler()
{
if(this._reference.getCacheConnection())
{
@@ -539,16 +584,18 @@ var ObjectPrx = Ice.Class({
}
}
return this._reference.getRequestHandler(this);
- },
- __getBatchRequestQueue: function()
+ }
+
+ _getBatchRequestQueue()
{
if(!this._batchRequestQueue)
{
this._batchRequestQueue = this._reference.getBatchRequestQueue();
}
return this._batchRequestQueue;
- },
- __setRequestHandler: function(handler)
+ }
+
+ _setRequestHandler(handler)
{
if(this._reference.getCacheConnection())
{
@@ -559,8 +606,9 @@ var ObjectPrx = Ice.Class({
return this._requestHandler;
}
return handler;
- },
- __updateRequestHandler: function(previous, handler)
+ }
+
+ _updateRequestHandler(previous, handler)
{
if(this._reference.getCacheConnection() && previous !== null)
{
@@ -569,23 +617,26 @@ var ObjectPrx = Ice.Class({
this._requestHandler = this._requestHandler.update(previous, handler);
}
}
- },
+ }
+
//
// Only for use by IceInternal.ProxyFactory
//
- __setup: function(ref)
+ _setup(ref)
{
Debug.assert(this._reference === null);
this._reference = ref;
- },
- __newInstance: function(ref)
+ }
+
+ _newInstance(ref)
{
- var proxy = new this.constructor();
- proxy.__setup(ref);
+ const proxy = new this.constructor();
+ proxy._setup(ref);
return proxy;
- },
- ice_instanceof: function(T)
+ }
+
+ ice_instanceof(T)
{
if(T)
{
@@ -593,351 +644,238 @@ var ObjectPrx = Ice.Class({
{
return true;
}
- return this.constructor.__instanceof(T);
+ return this.constructor._instanceof(T);
}
return false;
}
-});
-//
-// Generic invocation for operations that have input parameters.
-//
-ObjectPrx.__invoke = function(p, name, mode, fmt, ctx, marshalFn, unmarshalFn, userEx, args)
-{
- if(unmarshalFn !== null || userEx.length > 0)
+ //
+ // Generic invocation for operations that have input parameters.
+ //
+ static _invoke(p, name, mode, fmt, ctx, marshalFn, unmarshalFn, userEx, args)
{
- p.__checkAsyncTwowayOnly(name);
- }
-
- var __r = new OutgoingAsync(p, name,
- function(__res)
+ if(unmarshalFn !== null || userEx.length > 0)
{
- ObjectPrx.__completed(__res, unmarshalFn, userEx);
- });
+ p._checkAsyncTwowayOnly(name);
+ }
- try
- {
- __r.__prepare(name, mode, ctx);
- if(marshalFn === null)
+ const r = new OutgoingAsync(p, name,
+ res =>
+ {
+ this._completed(res, unmarshalFn, userEx);
+ });
+
+ try
{
- __r.__writeEmptyParams();
+ r.prepare(name, mode, ctx);
+ if(marshalFn === null)
+ {
+ r.writeEmptyParams();
+ }
+ else
+ {
+ const ostr = r.startWriteParams(fmt);
+ marshalFn.call(null, ostr, args);
+ r.endWriteParams();
+ }
+ r.invoke();
}
- else
+ catch(ex)
{
- var __os = __r.__startWriteParams(fmt);
- marshalFn.call(null, __os, args);
- __r.__endWriteParams();
+ r.abort(ex);
}
- __r.__invoke();
- }
- catch(ex)
- {
- __r.__abort(ex);
+ return r;
}
- return __r;
-};
-//
-// Handles the completion of an invocation.
-//
-ObjectPrx.__completed = function(__r, unmarshalFn, userEx)
-{
- if(!ObjectPrx.__check(__r, userEx))
+ //
+ // Handles the completion of an invocation.
+ //
+ static _completed(r, unmarshalFn, userEx)
{
- return;
- }
+ if(!this._check(r, userEx))
+ {
+ return;
+ }
- try
- {
- if(unmarshalFn === null)
+ try
{
- __r.__readEmptyParams();
- __r.succeed(__r);
+ if(unmarshalFn === null)
+ {
+ r.readEmptyParams();
+ r.resolve();
+ }
+ else
+ {
+ r.resolve(unmarshalFn(r));
+ }
}
- else
+ catch(ex)
{
- var results = unmarshalFn(__r);
- __r.succeed.apply(__r, results);
+ this.dispatchLocalException(r, ex);
+ return;
}
}
- catch(ex)
- {
- ObjectPrx.__dispatchLocalException(__r, ex);
- return;
- }
-};
-
-//
-// Unmarshal callback for operations that return a bool as the only result.
-//
-ObjectPrx.__returns_bool = function(__is, __results)
-{
- __results.push(__is.readBool());
-};
-//
-// Unmarshal callback for operations that return a byte as the only result.
-//
-ObjectPrx.__returns_byte = function(__is, __results)
-{
- __results.push(__is.readByte());
-};
-
-//
-// Unmarshal callback for operations that return a short as the only result.
-//
-ObjectPrx.__returns_short = function(__is, __results)
-{
- __results.push(__is.readShort());
-};
-
-//
-// Unmarshal callback for operations that return an int as the only result.
-//
-ObjectPrx.__returns_int = function(__is, __results)
-{
- __results.push(__is.readInt());
-};
-
-//
-// Unmarshal callback for operations that return a long as the only result.
-//
-ObjectPrx.__returns_long = function(__is, __results)
-{
- __results.push(__is.readLong());
-};
-
-//
-// Unmarshal callback for operations that return a float as the only result.
-//
-ObjectPrx.__returns_float = function(__is, __results)
-{
- __results.push(__is.readFloat());
-};
-
-//
-// Unmarshal callback for operations that return a double as the only result.
-//
-ObjectPrx.__returns_double = function(__is, __results)
-{
- __results.push(__is.readDouble());
-};
-
-//
-// Unmarshal callback for operations that return a string as the only result.
-//
-ObjectPrx.__returns_string = function(__is, __results)
-{
- __results.push(__is.readString());
-};
-
-//
-// Unmarshal callback for operations that return a proxy as the only result.
-//
-ObjectPrx.__returns_ObjectPrx = function(__is, __results)
-{
- __results.push(__is.readProxy());
-};
-
-//
-// Unmarshal callback for operations that return an object as the only result.
-//
-ObjectPrx.__returns_Object = function(__is, __results)
-{
- __is.readObject(function(obj){ __results.push(obj); }, Ice.Object);
- __is.readPendingObjects();
-};
-
-//
-// Handles user exceptions.
-//
-ObjectPrx.__check = function(__r, __uex)
-{
//
- // If __uex is non-null, it must be an array of exception types.
+ // Handles user exceptions.
//
- try
- {
- __r.__throwUserException();
- }
- catch(ex)
+ static _check(r, uex)
{
- if(ex instanceof Ice.UserException)
+ //
+ // If uex is non-null, it must be an array of exception types.
+ //
+ try
{
- if(__uex !== null)
+ r.throwUserException();
+ }
+ catch(ex)
+ {
+ if(ex instanceof Ice.UserException)
{
- for(var i = 0; i < __uex.length; ++i)
+ if(uex !== null)
{
- if(ex instanceof __uex[i])
+ for(let i = 0; i < uex.length; ++i)
{
- __r.fail(ex, __r);
- return false;
+ if(ex instanceof uex[i])
+ {
+ r.reject(ex);
+ return false;
+ }
}
}
+ r.reject(new Ice.UnknownUserException(ex.ice_name()));
+ return false;
+ }
+ else
+ {
+ r.reject(ex);
+ return false;
}
- __r.fail(new Ice.UnknownUserException(ex.ice_name()), __r);
- return false;
- }
- else
- {
- __r.fail(ex, __r);
- return false;
}
- }
- return true;
-};
-
-ObjectPrx.__dispatchLocalException = function(__r, __ex)
-{
- __r.fail(__ex, __r);
-};
-
-ObjectPrx.ice_staticId = Ice.Object.ice_staticId;
-
-ObjectPrx.checkedCast = function(prx, facet, ctx)
-{
- var __r = null;
+ return true;
+ }
- if(prx === undefined || prx === null)
+ static dispatchLocalException(r, ex)
{
- __r = new AsyncResultBase(null, "checkedCast", null, null, null);
- __r.succeed(null, __r);
+ r.reject(ex);
}
- else
+
+ static checkedCast(prx, facet, ctx)
{
- if(facet !== undefined)
+ let r = null;
+
+ if(prx === undefined || prx === null)
{
- prx = prx.ice_facet(facet);
+ r = new AsyncResultBase(null, "checkedCast", null, null, null);
+ r.resolve(null);
}
-
- var self = this;
- __r = new AsyncResultBase(prx.ice_getCommunicator(), "checkedCast", null, prx, null);
- prx.ice_isA(this.ice_staticId(), ctx).then(
- function(__res, __ret)
+ else
+ {
+ if(facet !== undefined)
{
- if(__ret)
- {
- var __h = new self();
- __h.__copyFrom(prx);
- __r.succeed(__h, __r);
- }
- else
- {
- __r.succeed(null, __r);
- }
- }).exception(
- function(__ex)
+ prx = prx.ice_facet(facet);
+ }
+
+ r = new AsyncResultBase(prx.ice_getCommunicator(), "checkedCast", null, prx, null);
+ prx.ice_isA(this.ice_staticId(), ctx).then(
+ ret =>
{
- if(__ex instanceof Ice.FacetNotExistException)
+ if(ret)
{
- __r.succeed(null, __r);
+ const h = new this();
+ h._copyFrom(prx);
+ r.resolve(h);
}
else
{
- __r.fail(__ex, __r);
+ r.resolve(null);
}
- });
- }
+ }).catch(
+ ex =>
+ {
+ if(ex instanceof Ice.FacetNotExistException)
+ {
+ r.resolve(null);
+ }
+ else
+ {
+ r.reject(ex);
+ }
+ });
+ }
- return __r;
-};
+ return r;
+ }
-ObjectPrx.uncheckedCast = function(prx, facet)
-{
- var r = null;
- if(prx !== undefined && prx !== null)
+ static uncheckedCast(prx, facet)
{
- r = new this();
- if(facet !== undefined)
+ let r = null;
+ if(prx !== undefined && prx !== null)
{
- prx = prx.ice_facet(facet);
+ r = new this();
+ if(facet !== undefined)
+ {
+ prx = prx.ice_facet(facet);
+ }
+ r._copyFrom(prx);
}
- r.__copyFrom(prx);
+ return r;
}
- return r;
-};
-
-Object.defineProperty(ObjectPrx, "minWireSize", {
- get: function(){ return 2; }
-});
-ObjectPrx.write = function(os, v)
-{
- os.writeProxy(v);
-};
+ static get minWireSize()
+ {
+ return 2;
+ }
-ObjectPrx.read = function(is)
-{
- return is.readProxy(this);
-};
+ static write(os, v)
+ {
+ os.writeProxy(v);
+ }
-ObjectPrx.writeOpt = function(os, tag, v)
-{
- os.writeOptProxy(tag, v);
-};
+ static read(is)
+ {
+ return is.readProxy(this);
+ }
-ObjectPrx.readOpt = function(is, tag)
-{
- return is.readOptProxy(tag, this);
-};
+ static writeOptional(os, tag, v)
+ {
+ os.writeOptionalProxy(tag, v);
+ }
-ObjectPrx.__instanceof = function(T)
-{
- if(T === this)
+ static readOptional(is, tag)
{
- return true;
+ return is.readOptionalProxy(tag, this);
}
- for(var i in this.__implements)
+ static _instanceof(T)
{
- if(this.__implements[i].__instanceof(T))
+ if(T === this)
{
return true;
}
+
+ for(let i in this._implements)
+ {
+ if(this._implements[i]._instanceof(T))
+ {
+ return true;
+ }
+ }
+
+ return false;
}
- if(this.__parent)
+ static ice_staticId()
{
- return this.__parent.__instanceof(T);
+ return this._id;
}
- return false;
-};
-var Slice = Ice.Slice;
-Slice.defineProxy = function(base, staticId, prxInterfaces)
-{
- var prx = function()
+ static get _implements()
{
- base.call(this);
- };
- prx.__parent = base;
- prx.__implements = prxInterfaces;
-
- // All generated proxies inherit from ObjectPrx
- prx.prototype = new base();
- prx.prototype.constructor = prx;
-
- // Static methods
- prx.ice_staticId = staticId;
-
- // Copy static methods inherited from ObjectPrx
- prx.checkedCast = ObjectPrx.checkedCast;
- prx.uncheckedCast = ObjectPrx.uncheckedCast;
- prx.write = ObjectPrx.write;
- prx.writeOpt = ObjectPrx.writeOpt;
- prx.read = ObjectPrx.read;
- prx.readOpt = ObjectPrx.readOpt;
-
- prx.__instanceof = ObjectPrx.__instanceof;
-
- // Static properties
- Object.defineProperty(prx, "minWireSize", {
- get: function(){ return 2; }
- });
-
- return prx;
-};
+ return [];
+ }
+}
Ice.ObjectPrx = ObjectPrx;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/OpaqueEndpointI.js b/js/src/Ice/OpaqueEndpointI.js
index 1dd8d853c52..3d9da5efc97 100644
--- a/js/src/Ice/OpaqueEndpointI.js
+++ b/js/src/Ice/OpaqueEndpointI.js
@@ -7,10 +7,9 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/Base64",
"../Ice/Debug",
"../Ice/FormatType",
@@ -21,111 +20,124 @@ Ice.__M.require(module,
"../Ice/LocalException"
]);
-var Base64 = Ice.Base64;
-var Debug = Ice.Debug;
-var HashUtil = Ice.HashUtil;
-var Protocol = Ice.Protocol;
-var StringUtil = Ice.StringUtil;
-var EndpointParseException = Ice.EndpointParseException;
+const Base64 = Ice.Base64;
+const Debug = Ice.Debug;
+const HashUtil = Ice.HashUtil;
+const Protocol = Ice.Protocol;
+const StringUtil = Ice.StringUtil;
+const EndpointParseException = Ice.EndpointParseException;
-var Class = Ice.Class;
-
-var OpaqueEndpointI = Class(Ice.EndpointI, {
- __init__: function(type)
+class OpaqueEndpointI extends Ice.EndpointI
+{
+ constructor(type)
{
+ super();
this._rawEncoding = Ice.Encoding_1_0;
this._type = type === undefined ? -1 : type;
this._rawBytes = null;
- },
+ }
+
//
// Marshal the endpoint
//
- streamWrite: function(s)
+ streamWrite(s)
{
- s.startWriteEncaps(this._rawEncoding, Ice.FormatType.DefaultFormat);
+ s.startEncapsulation(this._rawEncoding, Ice.FormatType.DefaultFormat);
s.writeBlob(this._rawBytes);
- s.endWriteEncaps();
- },
+ s.endEncapsulation();
+ }
+
//
// Return the endpoint information.
//
- getInfo: function()
+ getInfo()
{
- return new OpaqueEndpointInfoI(-1, false, this._rawEncoding, this._rawBytes, this._type);
- },
+ return new OpaqueEndpointInfoI(null, -1, false, this._rawEncoding, this._rawBytes, this._type);
+ }
+
//
// Return the endpoint type
//
- type: function()
+ type()
{
return this._type;
- },
- protocol: function()
+ }
+
+ protocol()
{
return "opaque";
- },
+ }
+
//
// Return the timeout for the endpoint in milliseconds. 0 means
// non-blocking, -1 means no timeout.
//
- timeout: function()
+ timeout()
{
return -1;
- },
+ }
+
//
// Return a new endpoint with a different timeout value, provided
// that timeouts are supported by the endpoint. Otherwise the same
// endpoint is returned.
//
- changeTimeout: function(t)
+ changeTimeout(t)
{
return this;
- },
+ }
+
//
// Return a new endpoint with a different connection id.
//
- changeConnectionId: function(connectionId)
+ changeConnectionId(connectionId)
{
return this;
- },
+ }
+
//
// Return true if the endpoints support bzip2 compress, or false
// otherwise.
//
- compress: function()
+ compress()
{
return false;
- },
+ }
+
//
// Return a new endpoint with a different compression value,
// provided that compression is supported by the
// endpoint. Otherwise the same endpoint is returned.
//
- changeCompress: function(compress)
+ changeCompress(compress)
{
return this;
- },
+ }
+
//
// Return true if the endpoint is datagram-based.
//
- datagram: function()
+ datagram()
{
return false;
- },
+ }
+
//
// Return true if the endpoint is secure.
//
- secure: function()
+ secure()
{
return false;
- },
+ }
+
//
// Get the encoded endpoint.
//
- rawBytes: function()
+ rawBytes()
{
return this._rawBytes; // Returns a Uint8Array
- },
+ }
+
//
// Return a server side transceiver for this endpoint, or null if a
// transceiver can only be created by an acceptor. In case a
@@ -133,11 +145,12 @@ var OpaqueEndpointI = Class(Ice.EndpointI, {
// "effective" endpoint, which might differ from this endpoint,
// for example, if a dynamic port number is assigned.
//
- transceiver: function(endpoint)
+ transceiver(endpoint)
{
endpoint.value = null;
return null;
- },
+ }
+
//
// Return an acceptor for this endpoint, or null if no acceptors
// is available. In case an acceptor is created, this operation
@@ -145,39 +158,43 @@ var OpaqueEndpointI = Class(Ice.EndpointI, {
// from this endpoint, for example, if a dynamic port number is
// assigned.
//
- acceptor: function(endpoint, adapterName)
+ acceptor(endpoint, adapterName)
{
endpoint.value = this;
return null;
- },
- connect: function()
+ }
+
+ connect()
{
return null;
- },
- hashCode: function()
+ }
+
+ hashCode()
{
if(this._hashCode === undefined)
{
- var h = 5381;
+ let h = 5381;
h = HashUtil.addNumber(h, this._type);
h = HashUtil.addHashable(h, this._rawEncoding);
h = HashUtil.addArray(h, this._rawBytes, HashUtil.addNumber);
this._hashCode = h;
}
return this._hashCode;
- },
- options: function()
+ }
+
+ options()
{
- var s = "";
- s+= " -t " + this._type;
+ let s = "";
+ s += " -t " + this._type;
s += " -e " + Ice.encodingVersionToString(this._rawEncoding);
s += " -v " + Base64.encode(this._rawBytes);
return s;
- },
+ }
+
//
// Compare endpoints for sorting purposes
//
- equals: function(p)
+ equals(p)
{
if(!(p instanceof OpaqueEndpointI))
{
@@ -203,7 +220,7 @@ var OpaqueEndpointI = Class(Ice.EndpointI, {
{
return false;
}
- for(var i = 0; i < this._rawBytes.length; i++)
+ for(let i = 0; i < this._rawBytes.length; i++)
{
if(this._rawBytes[i] !== p._rawBytes[i])
{
@@ -212,8 +229,9 @@ var OpaqueEndpointI = Class(Ice.EndpointI, {
}
return true;
- },
- compareTo: function(p)
+ }
+
+ compareTo(p)
{
if(this === p)
{
@@ -265,7 +283,7 @@ var OpaqueEndpointI = Class(Ice.EndpointI, {
{
return 1;
}
- for(var i = 0; i < this._rawBytes.length; i++)
+ for(let i = 0; i < this._rawBytes.length; i++)
{
if(this._rawBytes[i] < p._rawBytes[i])
{
@@ -278,8 +296,9 @@ var OpaqueEndpointI = Class(Ice.EndpointI, {
}
return 0;
- },
- checkOption: function(option, argument, endpoint)
+ }
+
+ checkOption(option, argument, endpoint)
{
switch(option.charAt(1))
{
@@ -294,7 +313,7 @@ var OpaqueEndpointI = Class(Ice.EndpointI, {
throw new EndpointParseException("no argument provided for -t option in endpoint " + endpoint);
}
- var type;
+ let type;
try
{
@@ -325,13 +344,13 @@ var OpaqueEndpointI = Class(Ice.EndpointI, {
{
throw new EndpointParseException("no argument provided for -v option in endpoint " + endpoint);
}
- for(var j = 0; j < argument.length; ++j)
+ for(let i = 0; i < argument.length; ++i)
{
- if(!Base64.isBase64(argument.charAt(j)))
+ if(!Base64.isBase64(argument.charAt(i)))
{
- throw new EndpointParseException("invalid base64 character `" + argument.charAt(j) +
- "' (ordinal " + argument.charCodeAt(j) +
- ") in endpoint " + endpoint);
+ throw new EndpointParseException("invalid base64 character `" + argument.charAt(i) +
+ "' (ordinal " + argument.charCodeAt(i) +
+ ") in endpoint " + endpoint);
}
}
this._rawBytes = Base64.decode(argument);
@@ -361,10 +380,11 @@ var OpaqueEndpointI = Class(Ice.EndpointI, {
return false;
}
}
- },
- initWithOptions: function(args)
+ }
+
+ initWithOptions(args)
{
- Ice.EndpointI.prototype.initWithOptions.call(this, args);
+ super.initWithOptions(args);
Debug.assert(this._rawEncoding);
if(this._type < 0)
@@ -375,34 +395,38 @@ var OpaqueEndpointI = Class(Ice.EndpointI, {
{
throw new EndpointParseException("no -v option in endpoint `" + this + "'");
}
- },
- initWithStream: function(s)
+ }
+
+ initWithStream(s)
{
- this._rawEncoding = s.getReadEncoding();
- var sz = s.getReadEncapsSize();
- this._rawBytes = s.readBlob(sz);
+ this._rawEncoding = s.getEncoding();
+ this._rawBytes = s.readBlob(s.getEncapsulationSize());
}
-});
+}
-var OpaqueEndpointInfoI = Class(Ice.OpaqueEndpointInfo, {
- __init__: function(timeout, compress, rawEncoding, rawBytes, type)
+class OpaqueEndpointInfoI extends Ice.OpaqueEndpointInfo
+{
+ constructor(timeout, compress, rawEncoding, rawBytes, type)
{
- Ice.OpaqueEndpointInfo.call(this, -1, false, rawEncoding, rawBytes);
+ super(-1, false, rawEncoding, rawBytes);
this._type = type;
- },
- type: function()
+ }
+
+ type()
{
return this._type;
- },
- datagram: function()
+ }
+
+ datagram()
{
return false;
- },
- secure: function()
+ }
+
+ secure()
{
return false;
}
-});
+}
Ice.OpaqueEndpointI = OpaqueEndpointI;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/Operation.js b/js/src/Ice/Operation.js
index 5df6f506211..399eab97377 100644
--- a/js/src/Ice/Operation.js
+++ b/js/src/Ice/Operation.js
@@ -8,13 +8,11 @@
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-var __M = Ice.__M;
-__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+const _ModuleRegistry = Ice._ModuleRegistry;
+_ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/Current",
- "../Ice/DispatchStatus",
"../Ice/Exception",
"../Ice/FormatType",
"../Ice/Object",
@@ -23,9 +21,7 @@ __M.require(module,
"../Ice/StreamHelpers"
]);
-var Class = Ice.Class;
-
-var builtinHelpers =
+const builtinHelpers =
[
Ice.ByteHelper,
Ice.BoolHelper,
@@ -35,23 +31,21 @@ var builtinHelpers =
Ice.FloatHelper,
Ice.DoubleHelper,
Ice.StringHelper,
- Ice.Object,
+ Ice.Value,
Ice.ObjectPrx
];
function parseParam(p)
{
- var type = p[0];
- var t = typeof(type);
+ let type = p[0];
+ const t = typeof(type);
if(t === 'number')
{
type = builtinHelpers[p[0]];
}
else if(t === 'string')
{
- /*jshint -W061 */
- type = __M.type(type);
- /*jshint +W061 */
+ type = _ModuleRegistry.type(type);
}
return {
@@ -69,51 +63,39 @@ function parseParam(p)
// otherwise an empty string
// 1: mode (undefined == Normal or int)
// 2: sendMode (undefined == Normal or int)
-// 3: amd (undefined or 1)
-// 4: format (undefined == Default or int)
-// 5: return type (undefined if void, or [type, tag])
-// 6: in params (undefined if none, or array of [type, tag])
-// 7: out params (undefined if none, or array of [type, tag])
-// 8: exceptions (undefined if none, or array of types)
-// 9: sends classes (true or undefined)
-// 10: returns classes (true or undefined)
+// 3: format (undefined == Default or int)
+// 4: return type (undefined if void, or [type, tag])
+// 5: in params (undefined if none, or array of [type, tag])
+// 6: out params (undefined if none, or array of [type, tag])
+// 7: exceptions (undefined if none, or array of types)
+// 8: sends classes (true or undefined)
+// 9: returns classes (true or undefined)
//
function parseOperation(name, arr)
{
- var r = {};
- var i;
- var p;
+ const r = {};
r.name = name;
+ r.servantMethod = arr[0] ? arr[0] : name;
r.mode = arr[1] ? Ice.OperationMode.valueOf(arr[1]) : Ice.OperationMode.Normal;
r.sendMode = arr[2] ? Ice.OperationMode.valueOf(arr[2]) : Ice.OperationMode.Normal;
- r.amd = arr[3] ? true : false;
- r.format = arr[4] ? Ice.FormatType.valueOf(arr[4]) : Ice.FormatType.DefaultFormat;
+ r.format = arr[3] ? Ice.FormatType.valueOf(arr[3]) : Ice.FormatType.DefaultFormat;
- if(r.amd)
- {
- r.servantMethod = name + "_async";
- }
- else
+ let ret;
+ if(arr[4])
{
- r.servantMethod = arr[0] ? arr[0] : name;
- }
-
- var ret;
- if(arr[5])
- {
- ret = parseParam(arr[5]);
+ ret = parseParam(arr[4]);
ret.pos = 0;
}
r.returns = ret;
- var inParams = [];
- var inParamsOpt = [];
- if(arr[6])
+ const inParams = [];
+ const inParamsOpt = [];
+ if(arr[5])
{
- for(i = 0; i < arr[6].length; ++i)
+ for(let i = 0; i < arr[5].length; ++i)
{
- p = parseParam(arr[6][i]);
+ let p = parseParam(arr[5][i]);
p.pos = i;
inParams.push(p);
if(p.tag)
@@ -126,14 +108,14 @@ function parseOperation(name, arr)
r.inParams = inParams;
r.inParamsOpt = inParamsOpt;
- var outParams = [];
- var outParamsOpt = [];
- if(arr[7])
+ const outParams = [];
+ const outParamsOpt = [];
+ if(arr[6])
{
- var offs = ret ? 1 : 0;
- for(i = 0; i < arr[7].length; ++i)
+ const offs = ret ? 1 : 0;
+ for(let i = 0; i < arr[6].length; ++i)
{
- p = parseParam(arr[7][i]);
+ let p = parseParam(arr[6][i]);
p.pos = i + offs;
outParams.push(p);
if(p.tag)
@@ -150,34 +132,36 @@ function parseOperation(name, arr)
r.outParams = outParams;
r.outParamsOpt = outParamsOpt;
- var exceptions = [];
- if(arr[8])
+ const exceptions = [];
+ if(arr[7])
{
- for(i = 0; i < arr[8].length; ++i)
+ for(let i = 0; i < arr[7].length; ++i)
{
- exceptions.push(arr[8][i]);
+ exceptions.push(arr[7][i]);
}
}
r.exceptions = exceptions;
- r.sendsClasses = arr[9] === true;
- r.returnsClasses = arr[10] === true;
+ r.sendsClasses = arr[8] === true;
+ r.returnsClasses = arr[9] === true;
return r;
}
-var OpTable = Class({
- __init__: function(ops)
+class OpTable
+{
+ constructor(ops)
{
this.raw = ops;
this.parsed = {};
- },
- find: function(name)
+ }
+
+ find(name)
{
//
// Check if we've already parsed the operation.
//
- var op = this.parsed[name];
+ let op = this.parsed[name];
if(op === undefined && this.raw[name] !== undefined)
{
//
@@ -188,21 +172,44 @@ var OpTable = Class({
}
return op;
}
-});
+}
function unmarshalParams(is, retvalInfo, allParamInfo, optParamInfo, usesClasses, params, offset)
{
- var i, p, v;
+ const readParam = (p, optional) =>
+ {
+ if(optional)
+ {
+ if(p.isObject)
+ {
+ is.readOptionalValue(p.tag, obj => params[p.pos + offset] = obj, p.type);
+ }
+ else
+ {
+ params[p.pos + offset] = p.type.readOptional(is, p.tag);
+ }
+ }
+ else
+ {
+ if(p.isObject)
+ {
+ is.readValue(obj => params[p.pos + offset] = obj, p.type);
+ }
+ else
+ {
+ params[p.pos + offset] = p.type.read(is);
+ }
+ }
+ };
+
//
// First read all required params.
//
- for(i = 0; i < allParamInfo.length; ++i)
+ for(let i = 0; i < allParamInfo.length; ++i)
{
- p = allParamInfo[i];
- if(!p.tag)
+ if(!allParamInfo[i].tag)
{
- v = p.type.read(is);
- params[p.pos + offset] = v;
+ readParam(allParamInfo[i], false);
}
}
@@ -211,36 +218,31 @@ function unmarshalParams(is, retvalInfo, allParamInfo, optParamInfo, usesClasses
//
if(retvalInfo)
{
- v = retvalInfo.type.read(is);
- params[retvalInfo.pos + offset] = v;
+ readParam(retvalInfo, false);
}
//
// Then read all optional params.
//
- for(i = 0; i < optParamInfo.length; ++i)
+ for(let i = 0; i < optParamInfo.length; ++i)
{
- p = optParamInfo[i];
- v = p.type.readOpt(is, p.tag);
- params[p.pos + offset] = v;
+ readParam(optParamInfo[i], true);
}
if(usesClasses)
{
- is.readPendingObjects();
+ is.readPendingValues();
}
}
function marshalParams(os, params, retvalInfo, paramInfo, optParamInfo, usesClasses)
{
- var i, p;
-
//
// Write the required params.
//
- for(i = 0; i < paramInfo.length; ++i)
+ for(let i = 0; i < paramInfo.length; ++i)
{
- p = paramInfo[i];
+ let p = paramInfo[i];
if(!p.tag)
{
p.type.write(os, params[p.pos]);
@@ -258,236 +260,104 @@ function marshalParams(os, params, retvalInfo, paramInfo, optParamInfo, usesClas
//
// Write the optional params.
//
- for(i = 0; i < optParamInfo.length; ++i)
+ for(let i = 0; i < optParamInfo.length; ++i)
{
- p = optParamInfo[i];
- p.type.writeOpt(os, p.tag, params[p.pos]);
+ let p = optParamInfo[i];
+ p.type.writeOptional(os, p.tag, params[p.pos]);
}
if(usesClasses)
{
- os.writePendingObjects();
+ os.writePendingValues();
}
}
-var Upcall = Class({
- __init__: function(incomingAsync, op)
- {
- this.incomingAsync = incomingAsync;
- this.op = op;
- },
- ice_response: function()
- {
- var args = arguments;
-
- if(this.incomingAsync.__validateResponse(true))
- {
- try
- {
- this.__sendResponse(args);
- this.incomingAsync.__response();
- }
- catch(ex)
- {
- this.incomingAsync.__exception(ex);
- }
- }
- },
- ice_exception: function(ex)
- {
- if(this.__checkException(ex))
- {
- if(this.incomingAsync.__validateResponse(false))
- {
- this.__sendException(ex);
- this.incomingAsync.__response();
- }
- }
- else
- {
- this.incomingAsync.ice_exception(ex);
- }
- },
- __sendResponse: function(results)
- {
- if(this.op.returns === undefined && this.op.outParams.length === 0)
- {
- if(results && results.length > 0)
- {
- //
- // No results expected.
- //
- throw new Error("ice_response called with invalid arguments");
- }
- else
- {
- this.incomingAsync.__writeEmptyParams();
- }
- }
- else
- {
- var __os = this.incomingAsync.__startWriteParams(this.op.format);
- var retvalInfo;
- if(this.op.returns && !this.op.returns.tag)
- {
- retvalInfo = this.op.returns;
- }
- marshalParams(__os, results, retvalInfo, this.op.outParams, this.op.outParamsOpt,
- this.op.returnsClasses);
- this.incomingAsync.__endWriteParams(true);
- }
- },
- __checkException: function(ex)
- {
- //
- // Make sure the given exception is an instance of one of the declared user exceptions
- // for this operation.
- //
- for(var i = 0; i < this.op.exceptions.length; ++i)
- {
- if(ex instanceof this.op.exceptions[i])
- {
- //
- // User exception is valid.
- //
- return true;
- }
- }
-
- return false;
- },
- __sendException: function(ex)
- {
- //
- // User exception is valid, now marshal it.
- //
- this.incomingAsync.__writeUserException(ex, this.op.format);
- }
-});
-
-var __dispatchImpl = function(servant, op, incomingAsync, current)
+function dispatchImpl(servant, op, incomingAsync, current)
{
//
// Check to make sure the servant implements the operation.
//
- var method = servant[op.servantMethod];
+ const method = servant[op.servantMethod];
if(method === undefined || typeof(method) !== "function")
{
- var comm = current.adapter.getCommunicator();
- var msg = "servant for identity " + comm.identityToString(current.id) +
- " does not define operation `" + op.servantMethod + "'";
- throw new Ice.UnknownException(msg);
+ throw new Ice.UnknownException("servant for identity " + current.adapter.getCommunicator().identityToString(current.id) +
+ " does not define operation `" + op.servantMethod + "'");
}
- var up = new Upcall(incomingAsync, op);
+ //
+ // Unmarshal the in params (if any).
+ //
+ const params = [];
+ if(op.inParams.length === 0)
+ {
+ incomingAsync.readEmptyParams();
+ }
+ else
+ {
+ const is = incomingAsync.startReadParams();
+ unmarshalParams(is, undefined, op.inParams, op.inParamsOpt, op.sendsClasses, params, 0);
+ incomingAsync.endReadParams();
+ }
+
+ params.push(current);
+
+ incomingAsync.setFormat(op.format);
- try
+ let marshalFn = function(params)
{
- //
- // Unmarshal the in params (if any).
- //
- var params = op.amd ? [null] : [];
- if(op.inParams.length === 0)
+ let numExpectedResults = op.outParams.length + (op.returns ? 1 : 0);
+ if(numExpectedResults > 1 && !(params instanceof Array))
{
- incomingAsync.readEmptyParams();
+ throw new Ice.MarshalException("operation `" + op.servantMethod + "' should return an array");
}
- else
+ else if(numExpectedResults === 1)
{
- var __is = incomingAsync.startReadParams();
- var offset = op.amd ? 1 : 0;
- unmarshalParams(__is, undefined, op.inParams, op.inParamsOpt, op.sendsClasses, params, offset);
- incomingAsync.endReadParams();
-
- //
- // When unmarshaling objects, the ObjectHelper returns a wrapper object
- // and eventually stores the unmarshaled object into its "value" member.
- // Here we scan the parameter array and replace the wrappers with the
- // actual object references.
- //
- if(op.inParams.length > 0 && (op.sendsClasses || op.inParamsOpt.length > 0))
- {
- for(var i = 0; i < op.inParams.length; ++i)
- {
- var p = op.inParams[i];
- //
- // Optional parameters may be undefined.
- //
- if(p.isObject && params[p.pos + offset] !== undefined)
- {
- params[p.pos + offset] = params[p.pos + offset].value;
- }
- }
- }
+ params = [params]; // Wrap a single out parameter in an array.
}
- params.push(current);
-
- if(op.amd)
+ if(op.returns === undefined && op.outParams.length === 0)
{
- params[0] = up; // The AMD callback object.
- try
+ if(params && params.length > 0)
{
- method.apply(servant, params);
+ throw new Ice.MarshalException("operation `" + op.servantMethod + "' shouldn't return any value");
}
- catch(ex)
+ else
{
- up.ice_exception(ex);
+ incomingAsync.writeEmptyParams();
}
- return Ice.DispatchStatus.DispatchAsync;
}
else
{
- //
- // Determine how many out parameters to expect.
- //
- var numExpectedResults = op.outParams.length;
- if(op.returns)
+ let retvalInfo;
+ if(op.returns && !op.returns.tag)
{
- ++numExpectedResults;
+ retvalInfo = op.returns;
}
- var results = method.apply(servant, params);
-
- //
- // Complain if we expect more than out parameter and the servant doesn't return an array.
- //
- if(numExpectedResults > 1 && !(results instanceof Array))
- {
- throw new Ice.MarshalException("operation `" + op.servantMethod +
- "' should return an array of length " + numExpectedResults);
- }
- else if(numExpectedResults === 1)
- {
- //
- // Wrap a single out parameter in an array.
- //
- results = [results];
- }
-
- up.__sendResponse(results);
- return Ice.DispatchStatus.DispatchOK;
+ const os = incomingAsync.startWriteParams();
+ marshalParams(os, params, retvalInfo, op.outParams, op.outParamsOpt, op.returnsClasses);
+ incomingAsync.endWriteParams();
}
+ };
+
+ let results = method.apply(servant, params);
+ if(results instanceof Promise)
+ {
+ return results.then(marshalFn);
}
- catch(ex)
+ else
{
- if(up.__checkException(ex))
- {
- up.__sendException(ex);
- return Ice.DispatchStatus.DispatchUserException;
- }
- else
- {
- throw ex;
- }
+ marshalFn(results);
+ return null;
}
-};
+}
function getServantMethodFromInterfaces(interfaces, methodName, all)
{
- var method;
- for(var i = 0; method === undefined && i < interfaces.length; ++i)
+ let method;
+ for(let i = 0; method === undefined && i < interfaces.length; ++i)
{
- var intf = interfaces[i];
+ let intf = interfaces[i];
method = intf[methodName];
if(method === undefined)
{
@@ -495,30 +365,30 @@ function getServantMethodFromInterfaces(interfaces, methodName, all)
{
all.push(intf);
}
- if(intf.__implements)
+ if(intf._iceImplements)
{
- method = getServantMethodFromInterfaces(intf.__implements, methodName, all);
+ method = getServantMethodFromInterfaces(intf._iceImplements, methodName, all);
}
}
}
return method;
}
-var dispatchPrefix = "__op_";
+const dispatchPrefix = "_iceD_";
function getServantMethod(servantType, name)
{
//
- // The dispatch method is named __op_<Slice name> and is stored in the type (not the prototype).
+ // The dispatch method is named _iceD_<Slice name> and is stored in the type (not the prototype).
//
- var methodName = dispatchPrefix + name;
+ const methodName = dispatchPrefix + name;
//
// First check the servant type.
//
- var method = servantType[methodName];
+ let method = servantType[methodName];
- var allInterfaces;
+ let allInterfaces;
if(method === undefined)
{
@@ -527,14 +397,14 @@ function getServantMethod(servantType, name)
//
// Now check the prototypes of the implemented interfaces.
//
- var curr = servantType;
+ let curr = servantType;
while(curr && method === undefined)
{
- if(curr.__implements)
+ if(curr._iceImplements)
{
- method = getServantMethodFromInterfaces(curr.__implements, methodName, allInterfaces);
+ method = getServantMethodFromInterfaces(curr._iceImplements, methodName, allInterfaces);
}
- curr = curr.__parent;
+ curr = Object.getPrototypeOf(curr);
}
if(method !== undefined)
@@ -551,40 +421,40 @@ function getServantMethod(servantType, name)
//
// Next check the op table for the servant's type.
//
- var op;
- if(servantType.__ops)
+ let op;
+ if(servantType._iceOps)
{
- op = servantType.__ops.find(name);
+ op = servantType._iceOps.find(name);
}
- var source;
+ let source;
if(op === undefined)
{
//
// Now check the op tables of the base types.
//
- var parent = servantType.__parent;
+ let parent = Object.getPrototypeOf(servantType);
while(op === undefined && parent)
{
- if(parent.__ops)
+ if(parent._iceOps)
{
- if((op = parent.__ops.find(name)) !== undefined)
+ if((op = parent._iceOps.find(name)) !== undefined)
{
source = parent;
}
}
- parent = parent.__parent;
+ parent = Object.getPrototypeOf(parent);
}
//
// Now check the op tables of all base interfaces.
//
- for(var i = 0; op === undefined && i < allInterfaces.length; ++i)
+ for(let i = 0; op === undefined && i < allInterfaces.length; ++i)
{
- var intf = allInterfaces[i];
- if(intf.__ops)
+ let intf = allInterfaces[i];
+ if(intf._iceOps)
{
- if((op = intf.__ops.find(name)) !== undefined)
+ if((op = intf._iceOps.find(name)) !== undefined)
{
source = intf;
}
@@ -596,7 +466,7 @@ function getServantMethod(servantType, name)
{
method = function(servant, incomingAsync, current)
{
- return __dispatchImpl(servant, op, incomingAsync, current);
+ return dispatchImpl(servant, op, incomingAsync, current);
};
//
@@ -619,13 +489,13 @@ function getServantMethod(servantType, name)
function addProxyOperation(proxyType, name, data)
{
- var method = data[0] ? data[0] : name;
+ let method = data[0] ? data[0] : name;
- var op = null;
+ let op = null;
proxyType.prototype[method] = function()
{
- var args = arguments;
+ let args = arguments;
//
// Parse the operation data on the first invocation of a proxy method.
@@ -635,22 +505,20 @@ function addProxyOperation(proxyType, name, data)
op = parseOperation(name, data);
}
- var ctx = args[op.inParams.length]; // The request context is the last argument (if present).
+ let ctx = args[op.inParams.length]; // The request context is the last argument (if present).
- var marshalFn = null;
+ let marshalFn = null;
if(op.inParams.length > 0)
{
marshalFn = function(os, params)
{
- var i, p, v;
-
//
// Validate the parameters.
//
- for(i = 0; i < op.inParams.length; ++i)
+ for(let i = 0; i < op.inParams.length; ++i)
{
- p = op.inParams[i];
- v = params[p.pos];
+ let p = op.inParams[i];
+ let v = params[p.pos];
if(!p.tag || v !== undefined)
{
if(typeof p.type.validate === "function")
@@ -668,7 +536,7 @@ function addProxyOperation(proxyType, name, data)
};
}
- var unmarshalFn = null;
+ let unmarshalFn = null;
if(op.returns || op.outParams.length > 0)
{
unmarshalFn = function(asyncResult)
@@ -678,68 +546,38 @@ function addProxyOperation(proxyType, name, data)
//
// [retval, out1, out2, ..., asyncResult]
//
- var results = [];
-
- var is = asyncResult.__startReadParams();
+ let results = [];
- var retvalInfo;
+ let is = asyncResult.startReadParams();
+ let retvalInfo;
if(op.returns && !op.returns.tag)
{
retvalInfo = op.returns;
}
unmarshalParams(is, retvalInfo, op.outParams, op.outParamsOpt, op.returnsClasses, results, 0);
-
- asyncResult.__endReadParams();
-
- //
- // When unmarshaling objects, the ObjectHelper returns a wrapper object
- // and eventually stores the unmarshaled object into its "value" member.
- // Here we scan the results array and replace the wrappers with the
- // actual object references.
- //
- if(op.returnsClasses || op.outParamsOpt.length > 0)
- {
- var offset = 0; // Skip asyncResult in results.
- if(op.returns && op.returns.isObject && results[op.returns.pos + offset] !== undefined)
- {
- results[op.returns.pos + offset] = results[op.returns.pos + offset].value;
- }
- for(var i = 0; i < op.outParams.length; ++i)
- {
- var p = op.outParams[i];
- //
- // Optional parameters may be undefined.
- //
- if(p.isObject && results[p.pos + offset] !== undefined)
- {
- results[p.pos + offset] = results[p.pos + offset].value;
- }
- }
- }
- results.push(asyncResult);
- return results;
+ asyncResult.endReadParams();
+ return results.length == 1 ? results[0] : results;
};
}
-
- return Ice.ObjectPrx.__invoke(this, op.name, op.sendMode, op.format, ctx, marshalFn, unmarshalFn,
- op.exceptions, Array.prototype.slice.call(args));
+ return Ice.ObjectPrx._invoke(this, op.name, op.sendMode, op.format, ctx, marshalFn, unmarshalFn,
+ op.exceptions, Array.prototype.slice.call(args));
};
}
-var Slice = Ice.Slice;
-Slice.defineOperations = function(classType, proxyType, ops)
+const Slice = Ice.Slice;
+Slice.defineOperations = function(classType, proxyType, ids, pos, ops)
{
if(ops)
{
- classType.__ops = new OpTable(ops);
+ classType._iceOps = new OpTable(ops);
}
- classType.prototype.__dispatch = function(incomingAsync, current)
+ classType.prototype._iceDispatch = function(incomingAsync, current)
{
//
// Retrieve the dispatch method for this operation.
//
- var method = getServantMethod(classType, current.operation);
+ const method = getServantMethod(classType, current.operation);
if(method === undefined || typeof(method) !== 'function')
{
@@ -749,42 +587,67 @@ Slice.defineOperations = function(classType, proxyType, ops)
return method.call(method, this, incomingAsync, current);
};
- if(ops)
+ classType.prototype._iceMostDerivedType = function()
+ {
+ return classType;
+ };
+
+ Object.defineProperty(classType, "_iceIds", {
+ get: function(){ return ids; }
+ });
+
+ Object.defineProperty(classType, "_iceId", {
+ get: function(){ return ids[pos]; }
+ });
+
+ classType.ice_staticId = function()
{
- for(var name in ops)
+ return classType._iceId;
+ };
+
+ if(proxyType !== undefined)
+ {
+ if(ops)
{
- addProxyOperation(proxyType, name, ops[name]);
+ for(let name in ops)
+ {
+ addProxyOperation(proxyType, name, ops[name]);
+ }
}
- }
- //
- // Copy proxy methods from super-interfaces.
- //
- if(proxyType.__implements)
- {
- for(var intf in proxyType.__implements)
+ //
+ // Copy proxy methods from super-interfaces.
+ //
+ if(proxyType._implements)
{
- var proto = proxyType.__implements[intf].prototype;
- for(var f in proto)
+ for(let intf in proxyType._implements)
{
- if(typeof proto[f] == "function" && proxyType.prototype[f] === undefined)
+ let proto = proxyType._implements[intf].prototype;
+ for(let f in proto)
{
- proxyType.prototype[f] = proto[f];
+ if(typeof proto[f] == "function" && proxyType.prototype[f] === undefined)
+ {
+ proxyType.prototype[f] = proto[f];
+ }
}
}
}
+
+ Object.defineProperty(proxyType, "_id", {
+ get: function(){ return ids[pos]; }
+ });
}
};
//
// Define the "built-in" operations for all Ice objects.
//
-Slice.defineOperations(Ice.Object, Ice.ObjectPrx,
+Slice.defineOperations(Ice.Object, Ice.ObjectPrx, ["::Ice::Object"], 0,
{
- "ice_ping": [, 1, 1, , , , , , ],
- "ice_isA": [, 1, 1, , , [1], [[7]], , ],
- "ice_id": [, 1, 1, , , [7], , , ],
- "ice_ids": [, 1, 1, , , ["Ice.StringSeqHelper"], , , ]
+ "ice_ping": [, 1, 1, , , , , ],
+ "ice_isA": [, 1, 1, , [1], [[7]], , ],
+ "ice_id": [, 1, 1, , [7], , , ],
+ "ice_ids": [, 1, 1, , ["Ice.StringSeqHelper"], , , ]
});
module.exports.Ice = Ice;
diff --git a/js/src/Ice/OptionalFormat.js b/js/src/Ice/OptionalFormat.js
index 16a439e5e23..847f4de8e22 100644
--- a/js/src/Ice/OptionalFormat.js
+++ b/js/src/Ice/OptionalFormat.js
@@ -7,6 +7,6 @@
//
// **********************************************************************
-var Ice = require("../Ice/EnumBase").Ice;
+const Ice = require("../Ice/EnumBase").Ice;
Ice.OptionalFormat = Ice.Slice.defineEnum([['F1', 0], ['F2', 1], ['F4', 2], ['F8', 3], ['Size', 4], ['VSize', 5], ['FSize', 6], ['Class', 7]]);
module.exports.Ice = Ice;
diff --git a/js/src/Ice/OutgoingAsync.js b/js/src/Ice/OutgoingAsync.js
index a4d72fe38b2..1e7f70c006e 100644
--- a/js/src/Ice/OutgoingAsync.js
+++ b/js/src/Ice/OutgoingAsync.js
@@ -7,15 +7,13 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/AsyncStatus",
"../Ice/AsyncResult",
- "../Ice/BasicStream",
+ "../Ice/Stream",
"../Ice/Debug",
- "../Ice/HashMap",
"../Ice/RetryException",
"../Ice/Current",
"../Ice/Protocol",
@@ -25,105 +23,99 @@ Ice.__M.require(module,
"../Ice/Identity"
]);
-var AsyncStatus = Ice.AsyncStatus;
-var AsyncResult = Ice.AsyncResult;
-var BasicStream = Ice.BasicStream;
-var Debug = Ice.Debug;
-var HashMap = Ice.HashMap;
-var RetryException = Ice.RetryException;
-var OperationMode = Ice.OperationMode;
-var Protocol = Ice.Protocol;
-var Identity = Ice.Identity;
+const AsyncStatus = Ice.AsyncStatus;
+const AsyncResult = Ice.AsyncResult;
+const InputStream = Ice.InputStream;
+const OutputStream = Ice.OutputStream;
+const Debug = Ice.Debug;
+const RetryException = Ice.RetryException;
+const OperationMode = Ice.OperationMode;
+const Protocol = Ice.Protocol;
+const Identity = Ice.Identity;
+
+class OutgoingAsyncBase extends AsyncResult
+{
+ constructor(communicator, operation, connection, proxy, adapter)
+ {
+ super(communicator, operation, connection, proxy, adapter);
+ this._os = new OutputStream(this._instance, Protocol.currentProtocolEncoding);
+ }
-var OutgoingAsyncBase = Ice.Class(AsyncResult, {
- __init__ : function(communicator, operation, connection, proxy, adapter)
- {
- if(communicator !== undefined)
- {
- AsyncResult.call(this, communicator, operation, connection, proxy, adapter);
- this._os = new BasicStream(this._instance, Protocol.currentProtocolEncoding);
- }
- else
- {
- AsyncResult.call(this);
- }
- },
- __os: function()
+ getOs()
{
return this._os;
- },
- __sent: function()
- {
- this.__markSent(true);
- },
- __completedEx: function(ex)
+ }
+
+ sent()
{
- this.__markFinishedEx(ex);
+ this.markSent(true);
}
-});
+ completedEx(ex)
+ {
+ this.markFinishedEx(ex);
+ }
+}
-var ProxyOutgoingAsyncBase = Ice.Class(OutgoingAsyncBase, {
- __init__ : function(prx, operation)
+class ProxyOutgoingAsyncBase extends OutgoingAsyncBase
+{
+ constructor(prx, operation)
{
- if(prx !== undefined)
- {
- OutgoingAsyncBase.call(this, prx.ice_getCommunicator(), operation, null, prx, null);
- this._mode = null;
- this._cnt = 0;
- this._sent = false;
- this._handler = null;
- }
- else
- {
- AsyncResult.call(this);
- }
- },
- __completedEx: function(ex)
+ super(prx.ice_getCommunicator(), operation, null, prx, null);
+ this._mode = null;
+ this._cnt = 0;
+ this._sent = false;
+ this._handler = null;
+ }
+
+ completedEx(ex)
{
try
{
- this._instance.retryQueue().add(this, this.__handleException(ex));
+ this._instance.retryQueue().add(this, this.handleException(ex));
}
catch(ex)
{
- this.__markFinishedEx(ex);
+ this.markFinishedEx(ex);
}
- },
- __retryException: function(ex)
+ }
+
+ retryException(ex)
{
try
{
- this._proxy.__updateRequestHandler(this._handler, null); // Clear request handler and always retry.
+ this._proxy._updateRequestHandler(this._handler, null); // Clear request handler and always retry.
this._instance.retryQueue().add(this, 0);
}
catch(ex)
{
- this.__completedEx(ex);
+ this.completedEx(ex);
}
- },
- __retry: function()
+ }
+
+ retry()
{
- this.__invokeImpl(false);
- },
- __abort: function(ex)
+ this.invokeImpl(false);
+ }
+
+ abort(ex)
{
- this.__markFinishedEx(ex);
- },
- __invokeImpl: function(userThread)
+ this.markFinishedEx(ex);
+ }
+
+ invokeImpl(userThread)
{
try
{
if(userThread)
{
- var invocationTimeout = this._proxy.__reference().getInvocationTimeout();
+ const invocationTimeout = this._proxy._getReference().getInvocationTimeout();
if(invocationTimeout > 0)
{
- var self = this;
this._timeoutToken = this._instance.timer().schedule(
- function()
+ () =>
{
- self.__cancel(new Ice.InvocationTimeoutException());
+ this.cancelWithException(new Ice.InvocationTimeoutException());
},
invocationTimeout);
}
@@ -134,9 +126,8 @@ var ProxyOutgoingAsyncBase = Ice.Class(OutgoingAsyncBase, {
try
{
this._sent = false;
- this._handler = this._proxy.__getRequestHandler();
- var status = this._handler.sendAsyncRequest(this);
- if((status & AsyncStatus.Sent) > 0)
+ this._handler = this._proxy._getRequestHandler();
+ if((this._handler.sendAsyncRequest(this) & AsyncStatus.Sent) > 0)
{
if(userThread)
{
@@ -150,11 +141,11 @@ var ProxyOutgoingAsyncBase = Ice.Class(OutgoingAsyncBase, {
if(ex instanceof RetryException)
{
// Clear request handler and always retry
- this._proxy.__updateRequestHandler(this._handler, null);
+ this._proxy._updateRequestHandler(this._handler, null);
}
else
{
- var interval = this.__handleException(ex);
+ const interval = this.handleException(ex);
if(interval > 0)
{
this._instance.retryQueue().add(this, interval);
@@ -166,10 +157,11 @@ var ProxyOutgoingAsyncBase = Ice.Class(OutgoingAsyncBase, {
}
catch(ex)
{
- this.__markFinishedEx(ex);
+ this.markFinishedEx(ex);
}
- },
- __markSent: function(done)
+ }
+
+ markSent(done)
{
this._sent = true;
if(done)
@@ -179,45 +171,38 @@ var ProxyOutgoingAsyncBase = Ice.Class(OutgoingAsyncBase, {
this._instance.timer().cancel(this._timeoutToken);
}
}
- OutgoingAsyncBase.prototype.__markSent.call(this, done);
- },
- __markFinishedEx: function(ex)
+ super.markSent.call(this, done);
+ }
+
+ markFinishedEx(ex)
{
if(this._timeoutToken)
{
this._instance.timer().cancel(this._timeoutToken);
}
- OutgoingAsyncBase.prototype.__markFinishedEx.call(this, ex);
- },
- __handleException: function(ex)
+ super.markFinishedEx.call(this, ex);
+ }
+
+ handleException(ex)
{
- var interval = { value: 0 };
- this._cnt = this._proxy.__handleException(ex, this._handler, this._mode, this._sent, interval, this._cnt);
+ const interval = { value: 0 };
+ this._cnt = this._proxy._handleException(ex, this._handler, this._mode, this._sent, interval, this._cnt);
return interval.value;
}
-});
+}
-var OutgoingAsync = Ice.Class(ProxyOutgoingAsyncBase, {
- __init__: function(prx, operation, completed)
+class OutgoingAsync extends ProxyOutgoingAsyncBase
+{
+ constructor(prx, operation, completed)
{
- //
- // OutgoingAsync can be constructed by a sub-type's prototype, in which case the
- // arguments are undefined.
- //
- if(prx !== undefined)
- {
- ProxyOutgoingAsyncBase.call(this, prx, operation);
- this._encoding = Protocol.getCompatibleEncoding(this._proxy.__reference().getEncoding());
- this._completed = completed;
- }
- else
- {
- ProxyOutgoingAsyncBase.call(this);
- }
- },
- __prepare: function(op, mode, ctx)
+ super(prx, operation);
+ this._encoding = Protocol.getCompatibleEncoding(this._proxy._getReference().getEncoding());
+ this._completed = completed;
+ }
+
+ prepare(op, mode, ctx)
{
- Protocol.checkSupportedProtocol(Protocol.getCompatibleProtocol(this._proxy.__reference().getProtocol()));
+ Protocol.checkSupportedProtocol(Protocol.getCompatibleProtocol(this._proxy._getReference().getProtocol()));
this._mode = mode;
if(ctx === null)
@@ -227,21 +212,21 @@ var OutgoingAsync = Ice.Class(ProxyOutgoingAsyncBase, {
if(this._proxy.ice_isBatchOneway() || this._proxy.ice_isBatchDatagram())
{
- this._proxy.__getBatchRequestQueue().prepareBatchRequest(this._os);
+ this._proxy._getBatchRequestQueue().prepareBatchRequest(this._os);
}
else
{
this._os.writeBlob(Protocol.requestHdr);
}
- var ref = this._proxy.__reference();
+ const ref = this._proxy._getReference();
- ref.getIdentity().__write(this._os);
+ ref.getIdentity()._write(this._os);
//
// For compatibility with the old FacetPath.
//
- var facet = ref.getFacet();
+ const facet = ref.getFacet();
if(facet === null || facet.length === 0)
{
Ice.StringSeqHelper.write(this._os, null);
@@ -257,9 +242,9 @@ var OutgoingAsync = Ice.Class(ProxyOutgoingAsyncBase, {
if(ctx !== undefined)
{
- if(ctx !== null && !(ctx instanceof HashMap))
+ if(ctx !== null && !(ctx instanceof Map))
{
- throw new Error("illegal context value, expecting null or HashMap");
+ throw new Error("illegal context value, expecting null or Map");
}
//
@@ -272,8 +257,8 @@ var OutgoingAsync = Ice.Class(ProxyOutgoingAsyncBase, {
//
// Implicit context
//
- var implicitContext = ref.getInstance().getImplicitContext();
- var prxContext = ref.getContext();
+ const implicitContext = ref.getInstance().getImplicitContext();
+ const prxContext = ref.getContext();
if(implicitContext === null)
{
@@ -284,30 +269,34 @@ var OutgoingAsync = Ice.Class(ProxyOutgoingAsyncBase, {
implicitContext.write(prxContext, this._os);
}
}
- },
- __sent: function()
+ }
+
+ sent()
{
- this.__markSent(!this._proxy.ice_isTwoway());
- },
- __invokeRemote: function(connection, compress, response)
+ this.markSent(!this._proxy.ice_isTwoway());
+ }
+
+ invokeRemote(connection, response)
{
- return connection.sendAsyncRequest(this, compress, response, 0);
- },
- __abort: function(ex)
+ return connection.sendAsyncRequest(this, response, 0);
+ }
+
+ abort(ex)
{
if(this._proxy.ice_isBatchOneway() || this._proxy.ice_isBatchDatagram())
{
- this._proxy.__getBatchRequestQueue().abortBatchRequest(this._os);
+ this._proxy._getBatchRequestQueue().abortBatchRequest(this._os);
}
- ProxyOutgoingAsyncBase.prototype.__abort.call(this, ex);
- },
- __invoke: function()
+ super.abort(ex);
+ }
+
+ invoke()
{
if(this._proxy.ice_isBatchOneway() || this._proxy.ice_isBatchDatagram())
{
this._sentSynchronously = true;
- this._proxy.__getBatchRequestQueue().finishBatchRequest(this._os, this._proxy, this._operation);
- this.__markFinished(true);
+ this._proxy._getBatchRequestQueue().finishBatchRequest(this._os, this._proxy, this._operation);
+ this.markFinished(true);
return;
}
@@ -316,18 +305,19 @@ var OutgoingAsync = Ice.Class(ProxyOutgoingAsyncBase, {
// try block with the catch block calling abort() in case of an
// exception.
//
- this.__invokeImpl(true); // userThread = true
- },
- __completed: function(istr)
+ this.invokeImpl(true); // userThread = true
+ }
+
+ completed(istr)
{
Debug.assert(this._proxy.ice_isTwoway()); // Can only be called for twoways.
- var replyStatus;
+ let replyStatus;
try
{
if(this._is === null) // _is can already be initialized if the invocation is retried
{
- this._is = new BasicStream(this._instance, Protocol.currentProtocolEncoding);
+ this._is = new InputStream(this._instance, Protocol.currentProtocolEncoding);
}
this._is.swap(istr);
replyStatus = this._is.readByte();
@@ -344,14 +334,14 @@ var OutgoingAsync = Ice.Class(ProxyOutgoingAsyncBase, {
case Protocol.replyFacetNotExist:
case Protocol.replyOperationNotExist:
{
- var id = new Identity();
- id.__read(this._is);
+ const id = new Identity();
+ id._read(this._is);
//
// For compatibility with the old FacetPath.
//
- var facetPath = Ice.StringSeqHelper.read(this._is);
- var facet;
+ const facetPath = Ice.StringSeqHelper.read(this._is);
+ let facet;
if(facetPath.length > 0)
{
if(facetPath.length > 1)
@@ -365,9 +355,9 @@ var OutgoingAsync = Ice.Class(ProxyOutgoingAsyncBase, {
facet = "";
}
- var operation = this._is.readString();
+ const operation = this._is.readString();
- var rfe = null;
+ let rfe = null;
switch(replyStatus)
{
case Protocol.replyObjectNotExist:
@@ -405,9 +395,9 @@ var OutgoingAsync = Ice.Class(ProxyOutgoingAsyncBase, {
case Protocol.replyUnknownLocalException:
case Protocol.replyUnknownUserException:
{
- var unknown = this._is.readString();
+ const unknown = this._is.readString();
- var ue = null;
+ let ue = null;
switch(replyStatus)
{
case Protocol.replyUnknownException:
@@ -445,143 +435,168 @@ var OutgoingAsync = Ice.Class(ProxyOutgoingAsyncBase, {
}
}
- this.__markFinished(replyStatus == Protocol.replyOK, this._completed);
+ this.markFinished(replyStatus == Protocol.replyOK, this._completed);
}
catch(ex)
{
- this.__completedEx(ex);
+ this.completedEx(ex);
}
- },
- __startWriteParams: function(format)
+ }
+
+ startWriteParams(format)
{
- this._os.startWriteEncaps(this._encoding, format);
+ this._os.startEncapsulation(this._encoding, format);
return this._os;
- },
- __endWriteParams: function()
- {
- this._os.endWriteEncaps();
- },
- __writeEmptyParams: function()
- {
- this._os.writeEmptyEncaps(this._encoding);
- },
- __writeParamEncaps: function(encaps)
+ }
+
+ endWriteParams()
{
- if(encaps === null || encaps.length === 0)
- {
- this._os.writeEmptyEncaps(this._encoding);
- }
- else
- {
- this._os.writeEncaps(encaps);
- }
- },
- __is: function()
+ this._os.endEncapsulation();
+ }
+
+ writeEmptyParams()
{
- return this._is;
- },
- __startReadParams: function()
+ this._os.writeEmptyEncapsulation(this._encoding);
+ }
+
+ startReadParams()
{
- this._is.startReadEncaps();
+ this._is.startEncapsulation();
return this._is;
- },
- __endReadParams: function()
- {
- this._is.endReadEncaps();
- },
- __readEmptyParams: function()
+ }
+
+ endReadParams()
{
- this._is.skipEmptyEncaps();
- },
- __readParamEncaps: function()
+ this._is.endEncapsulation();
+ }
+
+ readEmptyParams()
{
- return this._is.readEncaps(null);
- },
- __throwUserException: function()
+ this._is.skipEmptyEncapsulation();
+ }
+
+ throwUserException()
{
Debug.assert((this._state & AsyncResult.Done) !== 0);
if((this._state & AsyncResult.OK) === 0)
{
try
{
- this._is.startReadEncaps();
+ this._is.startEncapsulation();
this._is.throwException();
}
catch(ex)
{
if(ex instanceof Ice.UserException)
{
- this._is.endReadEncaps();
+ this._is.endEncapsulation();
}
throw ex;
}
}
- },
-});
-OutgoingAsync._emptyContext = new HashMap();
+ }
+}
-var ProxyFlushBatch = Ice.Class(ProxyOutgoingAsyncBase, {
- __init__ : function(prx, operation)
+OutgoingAsync._emptyContext = new Map(); // Map<string, string>
+
+class ProxyFlushBatch extends ProxyOutgoingAsyncBase
+{
+ constructor(prx, operation)
{
- ProxyOutgoingAsyncBase.call(this, prx, operation);
- this._batchRequestNum = prx.__getBatchRequestQueue().swap(this._os);
- },
- __invokeRemote: function(connection, compress, response)
+ super(prx, operation);
+ this._batchRequestNum = prx._getBatchRequestQueue().swap(this._os);
+ }
+
+ invokeRemote(connection, response)
{
if(this._batchRequestNum === 0)
{
- this.__sent();
+ this.sent();
return AsyncStatus.Sent;
}
- return connection.sendAsyncRequest(this, compress, response, this._batchRequestNum);
- },
- __invoke: function()
- {
- Protocol.checkSupportedProtocol(Protocol.getCompatibleProtocol(this._proxy.__reference().getProtocol()));
- this.__invokeImpl(true); // userThread = true
- },
-});
-
-var ProxyGetConnection = Ice.Class(ProxyOutgoingAsyncBase, {
- __init__ : function(prx, operation)
- {
- ProxyOutgoingAsyncBase.call(this, prx, operation);
- },
- __invokeRemote: function(connection, compress, response)
- {
- this.__markFinished(true,
- function(r)
- {
- r.succeed(connection);
- });
+ return connection.sendAsyncRequest(this, response, this._batchRequestNum);
+ }
+
+ invoke()
+ {
+ Protocol.checkSupportedProtocol(Protocol.getCompatibleProtocol(this._proxy._getReference().getProtocol()));
+ this.invokeImpl(true); // userThread = true
+ }
+}
+
+class ProxyGetConnection extends ProxyOutgoingAsyncBase
+{
+ constructor(prx, operation)
+ {
+ super(prx, operation);
+ }
+
+ invokeRemote(connection, response)
+ {
+ this.markFinished(true, r => r.resolve(connection));
return AsyncStatus.Sent;
- },
- __invoke: function()
+ }
+
+ invoke()
{
- this.__invokeImpl(true); // userThread = true
+ this.invokeImpl(true); // userThread = true
}
-});
+}
-var ConnectionFlushBatch = Ice.Class(OutgoingAsyncBase, {
- __init__: function(con, communicator, operation)
+class ConnectionFlushBatch extends OutgoingAsyncBase
+{
+ constructor(con, communicator, operation)
{
- OutgoingAsyncBase.call(this, communicator, operation, con, null, null);
- },
- __invoke: function()
+ super(communicator, operation, con, null, null);
+ }
+
+ invoke()
{
try
{
- var batchRequestNum = this._connection.getBatchRequestQueue().swap(this._os);
- var status;
+ const batchRequestNum = this._connection.getBatchRequestQueue().swap(this._os);
+ let status;
if(batchRequestNum === 0)
{
- this.__sent();
+ this.sent();
status = AsyncStatus.Sent;
}
else
{
- status = this._connection.sendAsyncRequest(this, false, false, batchRequestNum);
+ status = this._connection.sendAsyncRequest(this, false, batchRequestNum);
+ }
+
+ if((status & AsyncStatus.Sent) > 0)
+ {
+ this._sentSynchronously = true;
}
+ }
+ catch(ex)
+ {
+ this.completedEx(ex);
+ }
+ }
+}
+
+class HeartbeatAsync extends OutgoingAsyncBase
+{
+ constructor(con, communicator)
+ {
+ super(communicator, "heartbeat", con, null, null);
+ }
+
+ invoke()
+ {
+ try
+ {
+ this._os.writeBlob(Protocol.magic);
+ Protocol.currentProtocol._write(this._os);
+ Protocol.currentProtocolEncoding._write(this._os);
+ this._os.writeByte(Protocol.validateConnectionMsg);
+ this._os.writeByte(0);
+ this._os.writeInt(Protocol.headerSize); // Message size.
+
+ let status = this._connection.sendAsyncRequest(this, false, 0);
if((status & AsyncStatus.Sent) > 0)
{
@@ -590,14 +605,15 @@ var ConnectionFlushBatch = Ice.Class(OutgoingAsyncBase, {
}
catch(ex)
{
- this.__completedEx(ex);
+ this.completedEx(ex);
}
}
-});
+}
Ice.OutgoingAsync = OutgoingAsync;
Ice.ProxyFlushBatch = ProxyFlushBatch;
Ice.ProxyGetConnection = ProxyGetConnection;
Ice.ConnectionFlushBatch = ConnectionFlushBatch;
+Ice.HeartbeatAsync = HeartbeatAsync;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/OutgoingConnectionFactory.js b/js/src/Ice/OutgoingConnectionFactory.js
index 27fc576e1d7..83e58447172 100644
--- a/js/src/Ice/OutgoingConnectionFactory.js
+++ b/js/src/Ice/OutgoingConnectionFactory.js
@@ -7,10 +7,9 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/ArrayUtil",
"../Ice/AsyncResultBase",
"../Ice/ConnectionI",
@@ -23,22 +22,21 @@ Ice.__M.require(module,
"../Ice/ACM"
]);
-var ArrayUtil = Ice.ArrayUtil;
-var AsyncResultBase = Ice.AsyncResultBase;
-var ConnectionI = Ice.ConnectionI;
-var ConnectionReaper = Ice.ConnectionReaper;
-var Debug = Ice.Debug;
-var HashMap = Ice.HashMap;
-var Promise = Ice.Promise;
-var EndpointSelectionType = Ice.EndpointSelectionType;
-var FactoryACMMonitor = Ice.FactoryACMMonitor;
-var Class = Ice.Class;
+const ArrayUtil = Ice.ArrayUtil;
+const AsyncResultBase = Ice.AsyncResultBase;
+const ConnectionI = Ice.ConnectionI;
+const ConnectionReaper = Ice.ConnectionReaper;
+const Debug = Ice.Debug;
+const HashMap = Ice.HashMap;
+const EndpointSelectionType = Ice.EndpointSelectionType;
+const FactoryACMMonitor = Ice.FactoryACMMonitor;
//
// Only for use by Instance.
//
-var OutgoingConnectionFactory = Class({
- __init__: function(communicator, instance)
+class OutgoingConnectionFactory
+{
+ constructor(communicator, instance)
{
this._communicator = communicator;
this._instance = instance;
@@ -51,75 +49,72 @@ var OutgoingConnectionFactory = Class({
this._pendingConnectCount = 0;
this._waitPromise = null;
- },
- destroy: function()
+ }
+
+ destroy()
{
if(this._destroyed)
{
return;
}
- this._connectionsByEndpoint.forEach(function(connection)
- {
- connection.destroy(ConnectionI.CommunicatorDestroyed);
- });
+ this._connectionsByEndpoint.forEach(connection => connection.destroy(ConnectionI.CommunicatorDestroyed));
this._destroyed = true;
this._communicator = null;
this.checkFinished();
- },
- waitUntilFinished: function()
+ }
+
+ waitUntilFinished()
{
- this._waitPromise = new Promise();
+ this._waitPromise = new Ice.Promise();
this.checkFinished();
return this._waitPromise;
- },
+ }
+
//
- // Returns a promise, success callback receives (connection, compress)
+ // Returns a promise, success callback receives the connection
//
- create: function(endpts, hasMore, selType)
+ create(endpts, hasMore, selType)
{
Debug.assert(endpts.length > 0);
//
// Apply the overrides.
//
- var endpoints = this.applyOverrides(endpts);
+ const endpoints = this.applyOverrides(endpts);
//
// Try to find a connection to one of the given endpoints.
//
try
{
- var compress = { value: false };
- var connection = this.findConnectionByEndpoint(endpoints, compress);
+ const connection = this.findConnectionByEndpoint(endpoints);
if(connection !== null)
{
- return new Promise().succeed(connection, compress.value);
+ return Ice.Promise.resolve(connection);
}
}
catch(ex)
{
- return new Promise().fail(ex);
+ return Ice.Promise.reject(ex);
}
- var cb = new ConnectCallback(this, endpoints, hasMore, selType);
- return cb.start();
- },
- setRouterInfo: function(routerInfo)
+ return new ConnectCallback(this, endpoints, hasMore, selType).start();
+ }
+
+ setRouterInfo(routerInfo)
{
- var self = this;
- return Ice.Promise.try(
- function()
+ return Ice.Promise.try(() =>
{
- if(self._destroyed)
+ if(this._destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
return routerInfo.getClientEndpoints();
}
).then(
- function(endpoints)
+ endpoints =>
{
//
// Search for connections to the router's client proxy
@@ -127,12 +122,10 @@ var OutgoingConnectionFactory = Class({
// connections, so that callbacks from the router can be
// received over such connections.
//
- var adapter = routerInfo.getAdapter();
- var defaultsAndOverrides = self._instance.defaultsAndOverrides();
- for(var i = 0; i < endpoints.length; ++i)
+ const adapter = routerInfo.getAdapter();
+ const defaultsAndOverrides = this._instance.defaultsAndOverrides();
+ endpoints.forEach(endpoint =>
{
- var endpoint = endpoints[i];
-
//
// Modify endpoints with overrides.
//
@@ -152,48 +145,49 @@ var OutgoingConnectionFactory = Class({
//
endpoint = endpoint.changeCompress(false);
- self._connectionsByEndpoint.forEach(function(connection)
+ this._connectionsByEndpoint.forEach(connection =>
{
if(connection.endpoint().equals(endpoint))
{
connection.setAdapter(adapter);
}
});
- }
- }
- );
- },
- removeAdapter: function(adapter)
+ });
+ });
+ }
+
+ removeAdapter(adapter)
{
if(this._destroyed)
{
return;
}
- this._connectionsByEndpoint.forEach(function(connection)
+ this._connectionsByEndpoint.forEach(connection =>
{
if(connection.getAdapter() === adapter)
{
connection.setAdapter(null);
}
});
- },
- flushAsyncBatchRequests: function()
+ }
+
+ flushAsyncBatchRequests()
{
- var promise = new AsyncResultBase(this._communicator, "flushBatchRequests", null, null, null);
+ const promise = new AsyncResultBase(this._communicator, "flushBatchRequests", null, null, null);
if(this._destroyed)
{
- promise.succeed();
+ promise.resolve();
return;
}
- Promise.all(
+ Ice.Promise.all(
this._connectionsByEndpoint.map(
- function(connection)
+ connection =>
{
if(connection.isActiveOrHolding())
{
- return connection.flushBatchRequests().exception(
- function(ex)
+ return connection.flushBatchRequests().catch(
+ ex =>
{
if(ex instanceof Ice.LocalException)
{
@@ -205,87 +199,61 @@ var OutgoingConnectionFactory = Class({
}
});
}
- })
- ).then(
- function()
- {
- promise.succeed(promise);
- },
- function(ex)
- {
- promise.fail(ex, promise);
- }
- );
+ })).then(promise.resolve, promise.reject);
return promise;
- },
- applyOverrides: function(endpts)
- {
- var defaultsAndOverrides = this._instance.defaultsAndOverrides();
- var endpoints = [];
- for(var i = 0; i < endpts.length; ++i)
- {
- var endpoint = endpts[i];
+ }
- //
- // Modify endpoints with overrides.
- //
- if(defaultsAndOverrides.overrideTimeout)
- {
- endpoints.push(endpoint.changeTimeout(defaultsAndOverrides.overrideTimeoutValue));
- }
- else
+ applyOverrides(endpts)
+ {
+ const defaultsAndOverrides = this._instance.defaultsAndOverrides();
+ return endpts.map(endpoint =>
{
- endpoints.push(endpoint);
- }
- }
+ //
+ // Modify endpoints with overrides.
+ //
+ return defaultsAndOverrides.overrideTimeout ?
+ endpoint.changeTimeout(defaultsAndOverrides.overrideTimeoutValue) : endpoint;
+ });
+ }
- return endpoints;
- },
- findConnectionByEndpoint: function(endpoints, compress)
+ findConnectionByEndpoint(endpoints)
{
if(this._destroyed)
{
throw new Ice.CommunicatorDestroyedException();
}
- var defaultsAndOverrides = this._instance.defaultsAndOverrides();
+ const defaultsAndOverrides = this._instance.defaultsAndOverrides();
Debug.assert(endpoints.length > 0);
- for(var i = 0; i < endpoints.length; ++i)
+ for(let i = 0; i < endpoints.length; ++i)
{
- var endpoint = endpoints[i];
+ const endpoint = endpoints[i];
if(this._pending.has(endpoint))
{
continue;
}
- var connectionList = this._connectionsByEndpoint.get(endpoint);
+ const connectionList = this._connectionsByEndpoint.get(endpoint);
if(connectionList === undefined)
{
continue;
}
- for(var j = 0; j < connectionList.length; ++j)
+ for(let j = 0; j < connectionList.length; ++j)
{
if(connectionList[j].isActiveOrHolding()) // Don't return destroyed or un-validated connections
{
- if(defaultsAndOverrides.overrideCompress)
- {
- compress.value = defaultsAndOverrides.overrideCompressValue;
- }
- else
- {
- compress.value = endpoint.compress();
- }
return connectionList[j];
}
}
}
return null;
- },
- incPendingConnectCount: function()
+ }
+
+ incPendingConnectCount()
{
//
// Keep track of the number of pending connects. The outgoing connection factory
@@ -300,8 +268,9 @@ var OutgoingConnectionFactory = Class({
throw new Ice.CommunicatorDestroyedException();
}
++this._pendingConnectCount;
- },
- decPendingConnectCount: function()
+ }
+
+ decPendingConnectCount()
{
--this._pendingConnectCount;
Debug.assert(this._pendingConnectCount >= 0);
@@ -309,8 +278,9 @@ var OutgoingConnectionFactory = Class({
{
this.checkFinished();
}
- },
- getConnection: function(endpoints, cb, compress)
+ }
+
+ getConnection(endpoints, cb)
{
if(this._destroyed)
{
@@ -320,15 +290,14 @@ var OutgoingConnectionFactory = Class({
//
// Reap closed connections
//
- var cons = this._monitor.swapReapedConnections();
+ const cons = this._monitor.swapReapedConnections();
if(cons !== null)
{
- for(var i = 0; i < cons.length; ++i)
- {
- var c = cons[i];
- this._connectionsByEndpoint.removeConnection(c.endpoint(), c);
- this._connectionsByEndpoint.removeConnection(c.endpoint().changeCompress(true), c);
- }
+ cons.forEach(c =>
+ {
+ this._connectionsByEndpoint.removeConnection(c.endpoint(), c);
+ this._connectionsByEndpoint.removeConnection(c.endpoint().changeCompress(true), c);
+ });
}
//
@@ -344,7 +313,7 @@ var OutgoingConnectionFactory = Class({
//
// Search for a matching connection. If we find one, we're done.
//
- var connection = this.findConnectionByEndpoint(endpoints, compress);
+ const connection = this.findConnectionByEndpoint(endpoints);
if(connection !== null)
{
return connection;
@@ -377,8 +346,9 @@ var OutgoingConnectionFactory = Class({
cb.nextEndpoint();
return null;
- },
- createConnection: function(transceiver, endpoint)
+ }
+
+ createConnection(transceiver, endpoint)
{
Debug.assert(this._pending.has(endpoint) && transceiver !== null);
@@ -387,7 +357,7 @@ var OutgoingConnectionFactory = Class({
// is necessary to support the interruption of the connection initialization and validation
// in case the communicator is destroyed.
//
- var connection = null;
+ let connection = null;
try
{
if(this._destroyed)
@@ -396,7 +366,7 @@ var OutgoingConnectionFactory = Class({
}
connection = new ConnectionI(this._communicator, this._instance, this._monitor, transceiver,
- endpoint.changeCompress(false), false, null);
+ endpoint.changeCompress(false), false, null);
}
catch(ex)
{
@@ -417,172 +387,132 @@ var OutgoingConnectionFactory = Class({
this._connectionsByEndpoint.set(connection.endpoint(), connection);
this._connectionsByEndpoint.set(connection.endpoint().changeCompress(true), connection);
return connection;
- },
- finishGetConnection: function(endpoints, endpoint, connection, cb)
+ }
+
+ finishGetConnection(endpoints, endpoint, connection, cb)
{
// cb is-a ConnectCallback
- var connectionCallbacks = [];
+ const connectionCallbacks = [];
if(cb !== null)
{
connectionCallbacks.push(cb);
}
- var i;
- var cc;
- var callbacks = [];
- for(i = 0; i < endpoints.length; ++i)
- {
- var endpt = endpoints[i];
- var cbs = this._pending.get(endpt);
- if(cbs !== undefined)
+ let callbacks = [];
+ endpoints.forEach(endpt =>
{
- this._pending.delete(endpt);
- for(var j = 0; j < cbs.length; ++j)
+ let cbs = this._pending.get(endpt);
+ if(cbs !== undefined)
{
- cc = cbs[j];
- if(cc.hasEndpoint(endpoint))
- {
- if(connectionCallbacks.indexOf(cc) === -1)
+ this._pending.delete(endpt);
+ cbs.forEach(cc =>
{
- connectionCallbacks.push(cc);
- }
- }
- else
- {
- if(callbacks.indexOf(cc) === -1)
- {
- callbacks.push(cc);
- }
- }
+ if(cc.hasEndpoint(endpoint))
+ {
+ if(connectionCallbacks.indexOf(cc) === -1)
+ {
+ connectionCallbacks.push(cc);
+ }
+ }
+ else
+ {
+ if(callbacks.indexOf(cc) === -1)
+ {
+ callbacks.push(cc);
+ }
+ }
+ });
}
- }
- }
+ });
- for(i = 0; i < connectionCallbacks.length; ++i)
- {
- cc = connectionCallbacks[i];
- cc.removeFromPending();
- var idx = callbacks.indexOf(cc);
- if(idx !== -1)
+ connectionCallbacks.forEach(cc =>
{
- callbacks.splice(idx, 1);
- }
- }
- for(i = 0; i < callbacks.length; ++i)
- {
- cc = callbacks[i];
- cc.removeFromPending();
- }
+ cc.removeFromPending();
+ let idx = callbacks.indexOf(cc);
+ if(idx !== -1)
+ {
+ callbacks.splice(idx, 1);
+ }
+ });
- var compress;
- var defaultsAndOverrides = this._instance.defaultsAndOverrides();
- if(defaultsAndOverrides.overrideCompress)
- {
- compress = defaultsAndOverrides.overrideCompressValue;
- }
- else
- {
- compress = endpoint.compress();
- }
+ callbacks.forEach(cc => cc.removeFromPending());
- for(i = 0; i < callbacks.length; ++i)
- {
- cc = callbacks[i];
- cc.getConnection();
- }
- for(i = 0; i < connectionCallbacks.length; ++i)
- {
- cc = connectionCallbacks[i];
- cc.setConnection(connection, compress);
- }
+ callbacks.forEach(cc => cc.getConnection());
+ connectionCallbacks.forEach(cc => cc.setConnection(connection));
this.checkFinished();
- },
- finishGetConnectionEx: function(endpoints, ex, cb)
+ }
+
+ finishGetConnectionEx(endpoints, ex, cb)
{
// cb is-a ConnectCallback
- var failedCallbacks = [];
+ const failedCallbacks = [];
if(cb !== null)
{
failedCallbacks.push(cb);
}
- var i;
- var cc;
- var callbacks = [];
- for(i = 0; i < endpoints.length; ++i)
- {
- var endpt = endpoints[i];
- var cbs = this._pending.get(endpt);
- if(cbs !== undefined)
+
+ const callbacks = [];
+ endpoints.forEach(endpt =>
{
- this._pending.delete(endpt);
- for(var j = 0; j < cbs.length; ++j)
+ const cbs = this._pending.get(endpt);
+ if(cbs !== undefined)
{
- cc = cbs[j];
- if(cc.removeEndpoints(endpoints))
- {
- if(failedCallbacks.indexOf(cc) === -1)
- {
- failedCallbacks.push(cc);
- }
- }
- else
- {
- if(callbacks.indexOf(cc) === -1)
+ this._pending.delete(endpt);
+ cbs.forEach(cc =>
{
- callbacks.push(cc);
- }
- }
+ if(cc.removeEndpoints(endpoints))
+ {
+ if(failedCallbacks.indexOf(cc) === -1)
+ {
+ failedCallbacks.push(cc);
+ }
+ }
+ else
+ {
+ if(callbacks.indexOf(cc) === -1)
+ {
+ callbacks.push(cc);
+ }
+ }
+ });
}
- }
- }
+ });
- for(i = 0; i < callbacks.length; ++i)
- {
- cc = callbacks[i];
- Debug.assert(failedCallbacks.indexOf(cc) === -1);
- cc.removeFromPending();
- }
+ callbacks.forEach(cc =>
+ {
+ Debug.assert(failedCallbacks.indexOf(cc) === -1);
+ cc.removeFromPending();
+ });
this.checkFinished();
+ callbacks.forEach(cc => cc.getConnection());
+ failedCallbacks.forEach(cc => cc.setException(ex));
+ }
- for(i = 0; i < callbacks.length; ++i)
- {
- cc = callbacks[i];
- cc.getConnection();
- }
- for(i = 0; i < failedCallbacks.length; ++i)
- {
- cc = failedCallbacks[i];
- cc.setException(ex);
- }
- },
- addToPending: function(cb, endpoints)
+ addToPending(cb, endpoints)
{
// cb is-a ConnectCallback
//
// Add the callback to each pending list.
//
- var found = false;
- var p;
- var i;
+ let found = false;
if(cb !== null)
{
- for(i = 0; i < endpoints.length; ++i)
- {
- p = endpoints[i];
- var cbs = this._pending.get(p);
- if(cbs !== undefined)
+ endpoints.forEach(p =>
{
- found = true;
- if(cbs.indexOf(cb) === -1)
+ const cbs = this._pending.get(p);
+ if(cbs !== undefined)
{
- cbs.push(cb); // Add the callback to each pending endpoint.
+ found = true;
+ if(cbs.indexOf(cb) === -1)
+ {
+ cbs.push(cb); // Add the callback to each pending endpoint.
+ }
}
- }
- }
+ });
}
if(found)
@@ -595,41 +525,40 @@ var OutgoingConnectionFactory = Class({
// responsible for its establishment. We add empty pending lists,
// other callbacks to the same endpoints will be queued.
//
- for(i = 0; i < endpoints.length; ++i)
- {
- p = endpoints[i];
- if(!this._pending.has(p))
+ endpoints.forEach(p =>
{
- this._pending.set(p, []);
- }
- }
+ if(!this._pending.has(p))
+ {
+ this._pending.set(p, []);
+ }
+ });
return false;
- },
- removeFromPending: function(cb, endpoints)
+ }
+
+ removeFromPending(cb, endpoints)
{
// cb is-a ConnectCallback
-
- for(var i = 0; i < endpoints.length; ++i)
- {
- var p = endpoints[i];
- var cbs = this._pending.get(p);
- if(cbs !== undefined)
+ endpoints.forEach(p =>
{
- var idx = cbs.indexOf(cb);
- if(idx !== -1)
+ const cbs = this._pending.get(p);
+ if(cbs !== undefined)
{
- cbs.splice(idx, 1);
+ const idx = cbs.indexOf(cb);
+ if(idx !== -1)
+ {
+ cbs.splice(idx, 1);
+ }
}
- }
- }
- },
- handleConnectionException: function(ex, hasMore)
+ });
+ }
+
+ handleConnectionException(ex, hasMore)
{
- var traceLevels = this._instance.traceLevels();
+ const traceLevels = this._instance.traceLevels();
if(traceLevels.retry >= 2)
{
- var s = [];
+ const s = [];
s.push("connection to endpoint failed");
if(ex instanceof Ice.CommunicatorDestroyedException)
{
@@ -649,13 +578,14 @@ var OutgoingConnectionFactory = Class({
s.push(ex.toString());
this._instance.initializationData().logger.trace(traceLevels.retryCat, s.join(""));
}
- },
- handleException: function(ex, hasMore)
+ }
+
+ handleException(ex, hasMore)
{
- var traceLevels = this._instance.traceLevels();
+ const traceLevels = this._instance.traceLevels();
if(traceLevels.retry >= 2)
{
- var s = [];
+ const s = [];
s.push("couldn't resolve endpoint host");
if(ex instanceof Ice.CommunicatorDestroyedException)
{
@@ -675,8 +605,9 @@ var OutgoingConnectionFactory = Class({
s.push(ex.toString());
this._instance.initializationData().logger.trace(traceLevels.retryCat, s.join(""));
}
- },
- checkFinished: function()
+ }
+
+ checkFinished()
{
//
// Can't continue until the factory is destroyed and there are no pending connections.
@@ -686,50 +617,37 @@ var OutgoingConnectionFactory = Class({
return;
}
- var self = this;
- Promise.all(
- self._connectionsByEndpoint.map(
- function(connection)
- {
- return connection.waitUntilFinished().exception(function(ex)
- {
- Debug.assert(false);
- });
- }
- )
+ Ice.Promise.all(
+ this._connectionsByEndpoint.map(
+ connection => connection.waitUntilFinished().catch(ex => Debug.assert(false)))
).then(
- function()
+ () =>
{
- var cons = self._monitor.swapReapedConnections();
+ const cons = this._monitor.swapReapedConnections();
if(cons !== null)
{
- var arr = [];
- for(var e = self._connectionsByEndpoint.entries; e !== null; e = e.next)
+ const arr = [];
+ this._connectionsByEndpoint.forEach(connection =>
{
- var connectionList = e.value;
- for(var i = 0; i < connectionList.length; ++i)
+ if(arr.indexOf(connection) === -1)
{
- if(arr.indexOf(connectionList[i]) === -1)
- {
- arr.push(connectionList[i]);
- }
+ arr.push(connection);
}
- }
+ });
Debug.assert(cons.length === arr.length);
- self._connectionsByEndpoint.clear();
+ this._connectionsByEndpoint.clear();
}
else
{
- Debug.assert(self._connectionsByEndpoint.size === 0);
+ Debug.assert(this._connectionsByEndpoint.size === 0);
}
- Debug.assert(self._waitPromise !== null);
- self._waitPromise.succeed();
- self._monitor.destroy();
- }
- );
+ Debug.assert(this._waitPromise !== null);
+ this._waitPromise.resolve();
+ this._monitor.destroy();
+ });
}
-});
+}
Ice.OutgoingConnectionFactory = OutgoingConnectionFactory;
module.exports.Ice = Ice;
@@ -737,130 +655,135 @@ module.exports.Ice = Ice;
//
// Value is a Vector<Ice.ConnectionI>
//
-var ConnectionListMap = Class(HashMap, {
- __init__: function(h)
+class ConnectionListMap extends HashMap
+{
+ constructor(h)
{
- HashMap.call(this, h || HashMap.compareEquals);
- },
- set: function(key, value)
+ super(h || HashMap.compareEquals);
+ }
+
+ set(key, value)
{
- var list = this.get(key);
+ let list = this.get(key);
if(list === undefined)
{
list = [];
- HashMap.prototype.set.call(this, key, list);
+ super.set(key, list);
}
Debug.assert(value instanceof ConnectionI);
list.push(value);
return undefined;
- },
- removeConnection: function(key, conn)
+ }
+
+ removeConnection(key, conn)
{
- var list = this.get(key);
+ const list = this.get(key);
Debug.assert(list !== null);
- var idx = list.indexOf(conn);
+ const idx = list.indexOf(conn);
Debug.assert(idx !== -1);
list.splice(idx, 1);
if(list.length === 0)
{
this.delete(key);
}
- },
- map: function(fn)
+ }
+
+ map(fn)
{
- var arr = [];
- this.forEach(function(c) { arr.push(fn(c)); });
+ const arr = [];
+ this.forEach(c => arr.push(fn(c)));
return arr;
- },
- forEach: function(fn)
+ }
+
+ forEach(fn)
{
- for(var e = this._head; e !== null; e = e._next)
+ for(let connections of this.values())
{
- for(var i = 0; i < e.value.length; ++i)
- {
- fn(e.value[i]);
- }
+ connections.forEach(fn);
}
}
-});
+}
-var ConnectCallback = Class({
- __init__: function(f, endpoints, more, selType)
+class ConnectCallback
+{
+ constructor(f, endpoints, more, selType)
{
this._factory = f;
this._endpoints = endpoints;
this._hasMore = more;
this._selType = selType;
- this._promise = new Promise();
+ this._promise = new Ice.Promise();
this._index = 0;
this._current = null;
- },
+ }
+
//
// Methods from ConnectionI_StartCallback
//
- connectionStartCompleted: function(connection)
+ connectionStartCompleted(connection)
{
connection.activate();
this._factory.finishGetConnection(this._endpoints, this._current, connection, this);
- },
- connectionStartFailed: function(connection, ex)
+ }
+
+ connectionStartFailed(connection, ex)
{
Debug.assert(this._current !== null);
if(this.connectionStartFailedImpl(ex))
{
this.nextEndpoint();
}
- },
- setConnection: function(connection, compress)
+ }
+
+ setConnection(connection)
{
//
// Callback from the factory: the connection to one of the callback
// connectors has been established.
//
- this._promise.succeed(connection, compress);
+ this._promise.resolve(connection);
this._factory.decPendingConnectCount(); // Must be called last.
- },
- setException: function(ex)
+ }
+
+ setException(ex)
{
//
// Callback from the factory: connection establishment failed.
//
- this._promise.fail(ex);
+ this._promise.reject(ex);
this._factory.decPendingConnectCount(); // Must be called last.
- },
- hasEndpoint: function(endpt)
+ }
+
+ hasEndpoint(endpoint)
{
- return this.findEndpoint(endpt) !== -1;
- },
- findEndpoint: function(endpt)
+ return this.findEndpoint(endpoint) !== -1;
+ }
+
+ findEndpoint(endpoint)
{
- for(var index = 0; index < this._endpoints.length; ++index)
- {
- if(endpt.equals(this._endpoints[index]))
- {
- return index;
- }
- }
- return -1;
- },
- removeEndpoints: function(endpoints)
+ return this._endpoints.findIndex(value => endpoint.equals(value));
+ }
+
+ removeEndpoints(endpoints)
{
- for(var i = 0; i < endpoints.length; ++i)
- {
- var idx = this.findEndpoint(endpoints[i]);
- if(idx !== -1)
+ endpoints.forEach(endpoint =>
{
- this._endpoints.splice(idx, 1);
- }
- }
+ let idx = this.findEndpoint(endpoint);
+ if(idx !== -1)
+ {
+ this._endpoints.splice(idx, 1);
+ }
+ });
this._index = 0;
return this._endpoints.length === 0;
- },
- removeFromPending: function()
+ }
+
+ removeFromPending()
{
this._factory.removeFromPending(this, this._endpoints);
- },
- start: function()
+ }
+
+ start()
{
try
{
@@ -873,22 +796,22 @@ var ConnectCallback = Class({
}
catch(ex)
{
- this._promise.fail(ex);
+ this._promise.reject(ex);
return;
}
this.getConnection();
return this._promise;
- },
- getConnection: function()
+ }
+
+ getConnection()
{
try
{
//
// Ask the factory to get a connection.
//
- var compress = { value: false };
- var connection = this._factory.getConnection(this._endpoints, this, compress);
+ const connection = this._factory.getConnection(this._endpoints, this);
if(connection === null)
{
//
@@ -900,20 +823,21 @@ var ConnectCallback = Class({
return;
}
- this._promise.succeed(connection, compress.value);
+ this._promise.resolve(connection);
this._factory.decPendingConnectCount(); // Must be called last.
}
catch(ex)
{
- this._promise.fail(ex);
+ this._promise.reject(ex);
this._factory.decPendingConnectCount(); // Must be called last.
}
- },
- nextEndpoint: function()
+ }
+
+ nextEndpoint()
{
while(true)
{
- var traceLevels = this._factory._instance.traceLevels();
+ const traceLevels = this._factory._instance.traceLevels();
try
{
Debug.assert(this._index < this._endpoints.length);
@@ -921,7 +845,7 @@ var ConnectCallback = Class({
if(traceLevels.network >= 2)
{
- var s = [];
+ let s = [];
s.push("trying to establish ");
s.push(this._current.protocol());
s.push(" connection to ");
@@ -929,23 +853,22 @@ var ConnectCallback = Class({
this._factory._instance.initializationData().logger.trace(traceLevels.networkCat, s.join(""));
}
- var connection = this._factory.createConnection(this._current.connect(), this._current);
- var self = this;
+ const connection = this._factory.createConnection(this._current.connect(), this._current);
connection.start().then(
- function()
+ () =>
{
- self.connectionStartCompleted(connection);
+ this.connectionStartCompleted(connection);
},
- function(ex)
+ ex =>
{
- self.connectionStartFailed(connection, ex);
+ this.connectionStartFailed(connection, ex);
});
}
catch(ex)
{
if(traceLevels.network >= 2)
{
- var s = [];
+ let s = [];
s.push("failed to establish ");
s.push(this._current.protocol());
s.push(" connection to ");
@@ -962,8 +885,9 @@ var ConnectCallback = Class({
}
break;
}
- },
- connectionStartFailedImpl: function(ex)
+ }
+
+ connectionStartFailedImpl(ex)
{
if(ex instanceof Ice.LocalException)
{
@@ -987,4 +911,4 @@ var ConnectCallback = Class({
}
return false;
}
-});
+}
diff --git a/js/src/Ice/ProcessLogger.js b/js/src/Ice/ProcessLogger.js
index 9935e34dd8e..675cf838f02 100644
--- a/js/src/Ice/ProcessLogger.js
+++ b/js/src/Ice/ProcessLogger.js
@@ -8,10 +8,10 @@
//
// **********************************************************************
-var Ice = require("../Ice/Logger").Ice;
-var Logger = Ice.Logger;
+const Ice = require("../Ice/Logger").Ice;
+const Logger = Ice.Logger;
-var processLogger = null;
+let processLogger = null;
Ice.getProcessLogger = function()
{
diff --git a/js/src/Ice/Promise.js b/js/src/Ice/Promise.js
index 3a3fc93da66..27472db0926 100644
--- a/js/src/Ice/Promise.js
+++ b/js/src/Ice/Promise.js
@@ -7,291 +7,58 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
- [
- "../Ice/Class",
- "../Ice/TimerUtil"
- ]);
+const Ice = require("../Ice/Timer").Ice;
+const Timer = Ice.Timer;
-var Timer = Ice.Timer;
-
-//
-// Promise State
-//
-var State = {Pending: 0, Success: 1, Failed: 2};
-
-var resolveImp = function(self, listener)
+class P extends Promise
{
- var callback = self.__state === State.Success ? listener.onResponse : listener.onException;
- try
+ constructor(cb)
{
- if(typeof callback !== "function")
- {
- listener.promise.setState(self.__state, self._args);
- }
- else
- {
- var result = callback.apply(null, self._args);
-
- //
- // Callback can return a new promise.
- //
- if(result && typeof result.then == "function")
+ let res, rej;
+ super((resolve, reject) =>
{
- result.then(
- function()
- {
- var args = arguments;
- listener.promise.succeed.apply(listener.promise, args);
- },
- function()
- {
- var args = arguments;
- listener.promise.fail.apply(listener.promise, args);
- });
- }
- else
- {
- listener.promise.succeed(result);
- }
- }
- }
- catch(e)
- {
- listener.promise.fail.call(listener.promise, e);
- }
-};
+ res = resolve;
+ rej = reject;
-var Promise = Ice.Class({
- __init__: function()
- {
- this.__state = State.Pending;
- this.__listeners = [];
- },
- then: function(onResponse, onException)
- {
- var promise = new Promise();
- var self = this;
- //
- // Use setImmediate so the listeners are not resolved until the call stack is empty.
- //
- Timer.setImmediate(
- function()
- {
- self.__listeners.push(
- {
- promise:promise,
- onResponse:onResponse,
- onException:onException
- });
- self.resolve();
- });
- return promise;
- },
- exception: function(onException)
- {
- return this.then(null, onException);
- },
- finally: function(cb)
- {
- var p = new Promise();
- var self = this;
-
- var finallyHandler = function(method)
- {
- return function()
- {
- var args = arguments;
- try
- {
- var result = cb.apply(null, args);
- if(result && typeof result.then == "function")
- {
- var handler = function(){ method.apply(p, args); };
- result.then(handler).exception(handler);
- }
- else
- {
- method.apply(p, args);
- }
- }
- catch(e)
+ if(cb !== undefined)
{
- method.apply(p, args);
+ cb(resolve, reject);
}
- };
- };
-
- Timer.setImmediate(
- function(){
- self.then(finallyHandler(p.succeed), finallyHandler(p.fail));
});
- return p;
- },
- delay: function(ms)
- {
- var p = new Promise();
-
- var self = this;
-
- var delayHandler = function(promise, method)
- {
- return function()
- {
- var args = arguments;
- Timer.setTimeout(
- function()
- {
- method.apply(promise, args);
- },
- ms);
- };
- };
-
- Timer.setImmediate(function()
- {
- self.then(delayHandler(p, p.succeed), delayHandler(p, p.fail));
- });
- return p;
- },
- resolve: function()
- {
- if(this.__state === State.Pending)
- {
- return;
- }
- var obj;
- while((obj = this.__listeners.pop()))
- {
- //
- // We use a separate function here to capture the listeners
- // in the loop.
- //
- resolveImp(this, obj);
- }
- },
- setState: function(state, args)
- {
- if(this.__state === State.Pending && state !== State.Pending)
- {
- this.__state = state;
- this._args = args;
- //
- // Use setImmediate so the listeners are not resolved until the call stack is empty.
- //
- var self = this;
- Timer.setImmediate(function(){ self.resolve(); });
- }
- },
- succeed: function()
- {
- var args = arguments;
- this.setState(State.Success, args);
- return this;
- },
- fail: function()
- {
- var args = arguments;
- this.setState(State.Failed, args);
- return this;
- },
- succeeded: function()
- {
- return this.__state === State.Success;
- },
- failed: function()
- {
- return this.__state === State.Failed;
- },
- completed: function()
- {
- return this.__state !== State.Pending;
+ this.resolve = res;
+ this.reject = rej;
}
-});
-//
-// Create a new promise object that is fulfilled when all the promise arguments
-// are fulfilled or is rejected when one of the promises is rejected.
-//
-Promise.all = function()
-{
- // If only one argument is provided, check if the argument is an array
- if(arguments.length === 1 && arguments[0] instanceof Array)
+ finally(cb)
{
- return Promise.all.apply(this, arguments[0]);
+ return this.then(
+ (value) => P.resolve(cb()).then(() => value),
+ (reason) => P.resolve(cb()).then(() => { throw reason; }));
}
- var promise = new Promise();
- var promises = Array.prototype.slice.call(arguments);
- var results = new Array(arguments.length);
-
- var pending = promises.length;
- if(pending === 0)
+ delay(ms)
{
- promise.succeed.apply(promise, results);
+ return this.then(
+ value => new P((resolve, reject) => Timer.setTimeout(() => resolve(value), ms)),
+ reason => new P((resolve, reject) => Timer.setTiemout(() => reject(reason), ms)));
}
- for(var i = 0; i < promises.length; ++i)
+
+ static get [Symbol.species]()
{
- //
- // Create an anonymous function to capture the loop index
- //
-
- /*jshint -W083 */
- (function(j)
- {
- if(promises[j] && typeof promises[j].then == "function")
- {
- promises[j].then(
- function()
- {
- results[j] = arguments;
- pending--;
- if(pending === 0)
- {
- promise.succeed.apply(promise, results);
- }
- },
- function()
- {
- promise.fail.apply(promise, arguments);
- });
- }
- else
- {
- results[j] = promises[j];
- pending--;
- if(pending === 0)
- {
- promise.succeed.apply(promise, results);
- }
- }
- }(i));
- /*jshint +W083 */
+ return P;
}
- return promise;
-};
-
-Promise.try = function(onResponse)
-{
- return new Promise().succeed().then(onResponse);
-};
-Promise.delay = function(ms)
-{
- if(arguments.length > 1)
+ static delay(ms, value)
{
- var p = new Promise();
- var args = Array.prototype.slice.call(arguments);
- ms = args.pop();
- return p.succeed.apply(p, args).delay(ms);
+ return new P(resolve => Timer.setTimeout(() => resolve(value), ms));
}
- else
+
+ static try(cb)
{
- return new Promise().succeed().delay(ms);
+ return P.resolve().then(cb);
}
-};
+}
-Ice.Promise = Promise;
+Ice.Promise = P;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/Properties.js b/js/src/Ice/Properties.js
index 74759e4375b..ab9e6f8015d 100644
--- a/js/src/Ice/Properties.js
+++ b/js/src/Ice/Properties.js
@@ -8,13 +8,10 @@
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/StringUtil",
- "../Ice/HashMap",
- "../Ice/Promise",
"../Ice/PropertyNames",
"../Ice/Debug",
"../Ice/ProcessLogger",
@@ -22,24 +19,23 @@ Ice.__M.require(module,
"../Ice/LocalException"
]);
-var StringUtil = Ice.StringUtil;
-var HashMap = Ice.HashMap;
-var Promise = Ice.Promise;
-var PropertyNames = Ice.PropertyNames;
-var Debug = Ice.Debug;
-var ProcessLogger = Ice.ProcessLogger;
-var getProcessLogger = Ice.getProcessLogger;
-var InitializationException = Ice.InitializationException;
-
-var ParseStateKey = 0;
-var ParseStateValue = 1;
+const StringUtil = Ice.StringUtil;
+const PropertyNames = Ice.PropertyNames;
+const Debug = Ice.Debug;
+const ProcessLogger = Ice.ProcessLogger;
+const getProcessLogger = Ice.getProcessLogger;
+const InitializationException = Ice.InitializationException;
+
+const ParseStateKey = 0;
+const ParseStateValue = 1;
//
// Ice.Properties
//
-var Properties = Ice.Class({
- __init__: function(args, defaults)
+class Properties
+{
+ constructor(args, defaults)
{
- this._properties = new HashMap();
+ this._properties = new Map();
if(defaults !== undefined && defaults !== null)
{
@@ -47,30 +43,32 @@ var Properties = Ice.Class({
// NOTE: we can't just do a shallow copy of the map as the map values
// would otherwise be shared between the two PropertiesI object.
//
- //_properties = new HashMap(pi._properties);
- for(var e = defaults._properties.entries; e !== null; e = e.next)
+ //_properties = new Map(pi._properties);
+ for(let [key, property] of defaults._properties)
{
- this._properties.set(e.key, { 'value': e.value.value, 'used': false });
+ this._properties.set(key, { 'value': property.value, 'used': false });
}
}
if(args !== undefined && args !== null)
{
- var v = this.parseIceCommandLineOptions(args);
+ let v = this.parseIceCommandLineOptions(args);
args.length = 0;
- for(var i = 0; i < v.length; ++i)
+ for(let i = 0; i < v.length; ++i)
{
args.push(v[i]);
}
}
- },
- getProperty: function(key)
+ }
+
+ getProperty(key)
{
return this.getPropertyWithDefault(key, "");
- },
- getPropertyWithDefault: function(key, value)
+ }
+
+ getPropertyWithDefault(key, value)
{
- var pv = this._properties.get(key);
+ const pv = this._properties.get(key);
if(pv !== undefined)
{
pv.used = true;
@@ -80,14 +78,16 @@ var Properties = Ice.Class({
{
return value;
}
- },
- getPropertyAsInt: function(key)
+ }
+
+ getPropertyAsInt(key)
{
return this.getPropertyAsIntWithDefault(key, 0);
- },
- getPropertyAsIntWithDefault: function(key, value)
+ }
+
+ getPropertyAsIntWithDefault(key, value)
{
- var pv = this._properties.get(key);
+ const pv = this._properties.get(key);
if(pv !== undefined)
{
pv.used = true;
@@ -97,24 +97,26 @@ var Properties = Ice.Class({
{
return value;
}
- },
- getPropertyAsList: function(key)
+ }
+
+ getPropertyAsList(key)
{
return this.getPropertyAsListWithDefault(key, 0);
- },
- getPropertyAsListWithDefault: function(key, value)
+ }
+
+ getPropertyAsListWithDefault(key, value)
{
if(value === undefined || value === null)
{
value = [];
}
- var pv = this._properties.get(key);
+ const pv = this._properties.get(key);
if(pv !== undefined)
{
pv.used = true;
- var result = StringUtil.splitString(pv.value, ", \t\r\n");
+ let result = StringUtil.splitString(pv.value, ", \t\r\n");
if(result === null)
{
getProcessLogger().warning("mismatched quotes in property " + key + "'s value, returning default value");
@@ -130,26 +132,28 @@ var Properties = Ice.Class({
{
return value;
}
- },
- getPropertiesForPrefix: function(prefix)
+ }
+
+ getPropertiesForPrefix(prefix = "")
{
- var result = new HashMap();
- for(var e = this._properties.entries; e !== null; e = e.next)
- {
- if(prefix === undefined || prefix === null || e.key.indexOf(prefix) === 0)
+ const result = new Map();
+ this._properties.forEach((property, key) =>
{
- e.value.used = true;
- result.set(e.key, e.value.value);
- }
- }
+ if(key.indexOf(prefix) === 0)
+ {
+ property.used = true;
+ result.set(key, property.value);
+ }
+ });
return result;
- },
- setProperty: function(key, value)
+ }
+
+ setProperty(key = "", value = "")
{
//
// Trim whitespace
//
- if(key !== null && key !== undefined)
+ if(key !== null)
{
key = key.trim();
}
@@ -157,38 +161,37 @@ var Properties = Ice.Class({
//
// Check if the property is legal.
//
- var logger = getProcessLogger();
- if(key === null || key === undefined || key.length === 0)
+ const logger = getProcessLogger();
+ if(key === null || key.length === 0)
{
throw new InitializationException("Attempt to set property with empty key");
}
- var dotPos = key.indexOf(".");
+ let dotPos = key.indexOf(".");
if(dotPos !== -1)
{
- var prefix = key.substr(0, dotPos);
- for(var i = 0; i < PropertyNames.validProps.length; ++i)
+ const prefix = key.substr(0, dotPos);
+ for(let i = 0; i < PropertyNames.validProps.length; ++i)
{
- var pattern = PropertyNames.validProps[i][0].pattern;
+ let pattern = PropertyNames.validProps[i][0].pattern;
dotPos = pattern.indexOf(".");
//
// Each top level prefix describes a non-empty namespace. Having a string without a
// prefix followed by a dot is an error.
//
Debug.assert(dotPos != -1);
- var propPrefix = pattern.substring(0, dotPos - 1);
- if(propPrefix != prefix)
+ if(pattern.substring(0, dotPos - 1) != prefix)
{
continue;
}
- var found = false;
- var mismatchCase = false;
- var otherKey;
- for(var j = 0; j < PropertyNames.validProps[i][j].length && !found; ++j)
+ let found = false;
+ let mismatchCase = false;
+ let otherKey;
+ for(let j = 0; j < PropertyNames.validProps[i][j].length && !found; ++j)
{
pattern = PropertyNames.validProps[i][j].pattern();
- var pComp = new RegExp(pattern);
+ let pComp = new RegExp(pattern);
found = pComp.test(key);
if(found && PropertyNames.validProps[i][j].deprecated)
@@ -233,9 +236,9 @@ var Properties = Ice.Class({
//
// Set or clear the property.
//
- if(value !== undefined && value !== null && value.length > 0)
+ if(value !== null && value.length > 0)
{
- var pv = this._properties.get(key);
+ let pv = this._properties.get(key);
if(pv !== undefined)
{
pv.value = value;
@@ -249,17 +252,19 @@ var Properties = Ice.Class({
{
this._properties.delete(key);
}
- },
- getCommandLineOptions: function()
+ }
+
+ getCommandLineOptions()
{
- var result = [];
- for(var e = this._properties.entries; e !== null; e = e.next)
- {
- result.push("--" + e.key + "=" + e.pv.value);
- }
+ const result = [];
+ this._properties.forEach((property, key) =>
+ {
+ result.push("--" + key + "=" + property.value);
+ });
return result;
- },
- parseCommandLineOptions: function(pfx, options)
+ }
+
+ parseCommandLineOptions(pfx, options)
{
if(pfx.length > 0 && pfx.charAt(pfx.length - 1) != ".")
{
@@ -267,11 +272,9 @@ var Properties = Ice.Class({
}
pfx = "--" + pfx;
- var result = [];
+ const result = [];
- var self = this;
- options.forEach(
- function(opt)
+ options.forEach(opt =>
{
if(opt.indexOf(pfx) === 0)
{
@@ -280,7 +283,7 @@ var Properties = Ice.Class({
opt += "=1";
}
- self.parseLine(opt.substring(2));
+ this.parseLine(opt.substring(2));
}
else
{
@@ -288,41 +291,37 @@ var Properties = Ice.Class({
}
});
return result;
- },
- parseIceCommandLineOptions: function(options)
+ }
+
+ parseIceCommandLineOptions(options)
{
- var args = options.slice();
- for(var i = 0; i < PropertyNames.clPropNames.length; ++i)
+ let args = options.slice();
+ for(let i = 0; i < PropertyNames.clPropNames.length; ++i)
{
args = this.parseCommandLineOptions(PropertyNames.clPropNames[i], args);
}
return args;
- },
- parse: function(data)
+ }
+
+ parse(data)
{
- var lines = data.match(/[^\r\n]+/g);
-
- var line;
-
- while((line = lines.shift()))
- {
- this.parseLine(line);
- }
- },
- parseLine: function(line)
+ data.match(/[^\r\n]+/g).forEach(line => this.parseLine(line));
+ }
+
+ parseLine(line)
{
- var key = "";
- var value = "";
+ let key = "";
+ let value = "";
- var state = ParseStateKey;
+ let state = ParseStateKey;
- var whitespace = "";
- var escapedspace = "";
- var finished = false;
+ let whitespace = "";
+ let escapedspace = "";
+ let finished = false;
- for(var i = 0; i < line.length; ++i)
+ for(let i = 0; i < line.length; ++i)
{
- var c = line.charAt(i);
+ let c = line.charAt(i);
switch(state)
{
case ParseStateKey:
@@ -465,7 +464,7 @@ var Properties = Ice.Class({
value += escapedspace;
if((state === ParseStateKey && key.length !== 0) ||
- (state == ParseStateValue && key.length === 0))
+ (state == ParseStateValue && key.length === 0))
{
getProcessLogger().warning("invalid config file entry: \"" + line + "\"");
return;
@@ -476,29 +475,31 @@ var Properties = Ice.Class({
}
this.setProperty(key, value);
- },
- clone: function()
+ }
+
+ clone()
{
return new Properties(null, this);
- },
- getUnusedProperties: function()
+ }
+
+ getUnusedProperties()
{
- var unused = [];
- for(var e = this._properties.entries; e !== null; e = e.next)
- {
- if(!e.pv.used)
+ const unused = [];
+ this._properties.forEach((property, key) =>
{
- unused.push(e.key);
- }
- }
+ if(!property.used)
+ {
+ unused.push(key);
+ }
+ });
return unused;
}
-});
-
-Properties.createProperties = function(args, defaults)
-{
- return new Properties(args, defaults);
-};
+
+ static createProperties(args, defaults)
+ {
+ return new Properties(args, defaults);
+ }
+}
Ice.Properties = Properties;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/Property.js b/js/src/Ice/Property.js
index f7a2695e3b4..5402eff23c6 100644
--- a/js/src/Ice/Property.js
+++ b/js/src/Ice/Property.js
@@ -7,25 +7,31 @@
//
// **********************************************************************
-var Property = function Property(pattern, deprecated, deprecatedBy)
-{
- this._pattern = pattern;
- this._deprecated = deprecated;
- this._deprecatedBy = deprecatedBy;
-};
+const Ice = require("../Ice/ModuleRegistry").Ice;
-Object.defineProperty(Property.prototype, "pattern",{
- get: function() { return this._pattern; }
-});
+Ice.Property = class
+{
+ constructor(pattern, deprecated, deprecatedBy)
+ {
+ this._pattern = pattern;
+ this._deprecated = deprecated;
+ this._deprecatedBy = deprecatedBy;
+ }
+
+ get pattern()
+ {
+ return this._pattern;
+ }
-Object.defineProperty(Property.prototype, "deprecated",{
- get: function() { return this._deprecated; }
-});
+ get deprecated()
+ {
+ return this._deprecated;
+ }
-Object.defineProperty(Property.prototype, "deprecatedBy",{
- get: function() { return this._deprecatedBy; }
-});
+ get deprecatedBy()
+ {
+ return this._deprecatedBy;
+ }
+};
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.Property = Property;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/PropertyNames.js b/js/src/Ice/PropertyNames.js
index 19c71f574ec..429a637d692 100644
--- a/js/src/Ice/PropertyNames.js
+++ b/js/src/Ice/PropertyNames.js
@@ -6,13 +6,13 @@
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
-// Generated by makeprops.py from file ./config/PropertyNames.xml, Wed Nov 2 09:46:48 2016
+// Generated by makeprops.py from file ../config/PropertyNames.xml, Fri Feb 10 17:05:23 2017
// IMPORTANT: Do not edit this file -- any edits made here will be lost!
-var Ice = require("../Ice/Property").Ice;
-var PropertyNames = {};
-var Property = Ice.Property;
+const Ice = require("../Ice/Property").Ice;
+const PropertyNames = {};
+const Property = Ice.Property;
/* jshint -W044*/
PropertyNames.IceProps =
@@ -166,6 +166,7 @@ PropertyNames.IceProps =
new Property("/^Ice\.ThreadPool\.Server\.ThreadIdleTime/", false, null),
new Property("/^Ice\.ThreadPool\.Server\.ThreadPriority/", false, null),
new Property("/^Ice\.ThreadPriority/", false, null),
+ new Property("/^Ice\.ToStringMode/", false, null),
new Property("/^Ice\.Trace\.Admin\.Properties/", false, null),
new Property("/^Ice\.Trace\.Admin\.Logger/", false, null),
new Property("/^Ice\.Trace\.Locator/", false, null),
diff --git a/js/src/Ice/Protocol.js b/js/src/Ice/Protocol.js
index 43e6874f940..032e5bea36b 100644
--- a/js/src/Ice/Protocol.js
+++ b/js/src/Ice/Protocol.js
@@ -7,8 +7,8 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
"../Ice/StringUtil",
"../Ice/LocalException",
@@ -16,9 +16,9 @@ Ice.__M.require(module,
"../Ice/Buffer"
]);
-var StringUtil = Ice.StringUtil;
+const StringUtil = Ice.StringUtil;
-var Protocol = {};
+const Protocol = {};
Ice.Encoding_1_0 = new Ice.EncodingVersion(1, 0);
Ice.Encoding_1_1 = new Ice.EncodingVersion(1, 1);
@@ -253,61 +253,62 @@ Ice.encodingVersionToString = function(v)
return majorMinorToString(v.major, v.minor);
};
+Protocol.OPTIONAL_END_MARKER = 0xFF;
+Protocol.FLAG_HAS_TYPE_ID_STRING = (1<<0);
+Protocol.FLAG_HAS_TYPE_ID_INDEX = (1<<1);
+Protocol.FLAG_HAS_TYPE_ID_COMPACT = (1<<1 | 1<<0);
+Protocol.FLAG_HAS_OPTIONAL_MEMBERS = (1<<2);
+Protocol.FLAG_HAS_INDIRECTION_TABLE = (1<<3);
+Protocol.FLAG_HAS_SLICE_SIZE = (1<<4);
+Protocol.FLAG_IS_LAST_SLICE = (1<<5);
+
Ice.Protocol = Protocol;
module.exports.Ice = Ice;
function stringToMajor(str)
{
- var pos = str.indexOf('.');
+ const pos = str.indexOf('.');
if(pos === -1)
{
throw new Ice.VersionParseException("malformed version value `" + str + "'");
}
-
- var majStr = str.substring(0, pos);
- var majVersion;
+
try
{
- majVersion = StringUtil.toInt(majStr);
+ const majVersion = StringUtil.toInt(str.substring(0, pos));
+ if(majVersion < 1 || majVersion > 255)
+ {
+ throw new Ice.VersionParseException("range error in version `" + str + "'");
+ }
+ return majVersion;
}
catch(ex)
{
throw new Ice.VersionParseException("invalid version value `" + str + "'");
}
-
- if(majVersion < 1 || majVersion > 255)
- {
- throw new Ice.VersionParseException("range error in version `" + str + "'");
- }
-
- return majVersion;
}
function stringToMinor(str)
{
- var pos = str.indexOf('.');
+ const pos = str.indexOf('.');
if(pos === -1)
{
throw new Ice.VersionParseException("malformed version value `" + str + "'");
}
-
- var minStr = str.substring(pos + 1);
- var minVersion;
+
try
{
- minVersion = StringUtil.toInt(minStr);
+ const minVersion = StringUtil.toInt(str.substring(pos + 1));
+ if(minVersion < 0 || minVersion > 255)
+ {
+ throw new Ice.VersionParseException("range error in version `" + str + "'");
+ }
+ return minVersion;
}
catch(ex)
{
throw new Ice.VersionParseException("invalid version value `" + str + "'");
}
-
- if(minVersion < 0 || minVersion > 255)
- {
- throw new Ice.VersionParseException("range error in version `" + str + "'");
- }
-
- return minVersion;
}
function majorMinorToString(major, minor)
diff --git a/js/src/Ice/ProtocolInstance.js b/js/src/Ice/ProtocolInstance.js
index 76237f3ee57..e0554b24001 100644
--- a/js/src/Ice/ProtocolInstance.js
+++ b/js/src/Ice/ProtocolInstance.js
@@ -7,8 +7,7 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Class"]);
+const Ice = require("../Ice/ModuleRegistry").Ice;
//
// NOTE: the protocol instance class is a bit different from other
@@ -23,8 +22,9 @@ Ice.__M.require(module, ["../Ice/Class"]);
// endpoint and suppress the secure member of the protocol instance
// class bellow.
//
-var ProtocolInstance = Ice.Class({
- __init__: function(instance, type, protocol, secure)
+class ProtocolInstance
+{
+ constructor(instance, type, protocol, secure)
{
this._instance = instance;
this._traceLevel = instance.traceLevels().network;
@@ -34,58 +34,68 @@ var ProtocolInstance = Ice.Class({
this._type = type;
this._protocol = protocol;
this._secure = secure;
- },
- traceLevel: function()
+ }
+
+ traceLevel()
{
return this._traceLevel;
- },
- traceCategory: function()
+ }
+
+ traceCategory()
{
return this._traceCategory;
- },
- logger: function()
+ }
+
+ logger()
{
return this._logger;
- },
- protocol: function()
+ }
+
+ protocol()
{
return this._protocol;
- },
- type: function()
+ }
+
+ type()
{
return this._type;
- },
- secure: function()
+ }
+
+ secure()
{
return this._secure;
- },
- properties: function()
+ }
+
+ properties()
{
return this._properties;
- },
- defaultHost: function()
+ }
+
+ defaultHost()
{
return this._instance.defaultsAndOverrides().defaultHost;
- },
- defaultSourceAddress: function()
+ }
+
+ defaultSourceAddress()
{
return this._instance.defaultsAndOverrides().defaultSourceAddress;
- },
- defaultEncoding: function()
+ }
+
+ defaultEncoding()
{
return this._instance.defaultsAndOverrides().defaultEncoding;
- },
- defaultTimeout: function()
+ }
+
+ defaultTimeout()
{
return this._instance.defaultsAndOverrides().defaultTimeout;
- },
- messageSizeMax: function()
+ }
+
+ messageSizeMax()
{
return this._instance.messageSizeMax();
}
-});
+}
Ice.ProtocolInstance = ProtocolInstance;
module.exports.Ice = Ice;
-
-
diff --git a/js/src/Ice/ProxyFactory.js b/js/src/Ice/ProxyFactory.js
index 1aa3cc05209..2a72f40acd9 100644
--- a/js/src/Ice/ProxyFactory.js
+++ b/js/src/Ice/ProxyFactory.js
@@ -7,12 +7,10 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/Debug",
- "../Ice/HashMap",
"../Ice/ObjectPrx",
"../Ice/StringUtil",
"../Ice/Identity",
@@ -20,29 +18,29 @@ Ice.__M.require(module,
"../Ice/LocalException"
]);
-var Debug = Ice.Debug;
-var HashMap = Ice.HashMap;
-var ObjectPrx = Ice.ObjectPrx;
-var StringUtil = Ice.StringUtil;
-var Identity = Ice.Identity;
+const Debug = Ice.Debug;
+const ObjectPrx = Ice.ObjectPrx;
+const StringUtil = Ice.StringUtil;
+const Identity = Ice.Identity;
//
// Only for use by Instance.
//
-var ProxyFactory = Ice.Class({
- __init__: function(instance)
+class ProxyFactory
+{
+ constructor(instance)
{
this._instance = instance;
- var arr = this._instance.initializationData().properties.getPropertyAsList("Ice.RetryIntervals");
+ const arr = this._instance.initializationData().properties.getPropertyAsList("Ice.RetryIntervals");
if(arr.length > 0)
{
this._retryIntervals = [];
- for(var i = 0; i < arr.length; i++)
+ for(let i = 0; i < arr.length; i++)
{
- var v;
+ let v;
try
{
@@ -68,79 +66,55 @@ var ProxyFactory = Ice.Class({
{
this._retryIntervals = [ 0 ];
}
- },
- stringToProxy: function(str)
+ }
+
+ stringToProxy(str)
{
- var ref = this._instance.referenceFactory().createFromString(str, null);
- return this.referenceToProxy(ref);
- },
- proxyToString: function(proxy)
+ return this.referenceToProxy(this._instance.referenceFactory().createFromString(str, null));
+ }
+
+ proxyToString(proxy)
{
- if(proxy !== null)
- {
- return proxy.__reference().toString();
- }
- else
- {
- return "";
- }
- },
- propertyToProxy: function(prefix)
+ return proxy === null ? "" : proxy._getReference().toString();
+ }
+
+ propertyToProxy(prefix)
{
- var proxy = this._instance.initializationData().properties.getProperty(prefix);
- var ref = this._instance.referenceFactory().createFromString(proxy, prefix);
+ const proxy = this._instance.initializationData().properties.getProperty(prefix);
+ const ref = this._instance.referenceFactory().createFromString(proxy, prefix);
return this.referenceToProxy(ref);
- },
- proxyToProperty: function(proxy, prefix)
+ }
+
+ proxyToProperty(proxy, prefix)
{
- if(proxy !== null)
- {
- return proxy.__reference().toProperty(prefix);
- }
- else
- {
- return new HashMap();
- }
- },
- streamToProxy: function(s, type)
+ return proxy === null ? new Map() : proxy._getReference().toProperty(prefix);
+ }
+
+ streamToProxy(s, type)
{
- var ident = new Identity();
- ident.__read(s);
+ const ident = new Identity();
+ ident._read(s);
+ return this.referenceToProxy(this._instance.referenceFactory().createFromStream(ident, s), type);
+ }
- var ref = this._instance.referenceFactory().createFromStream(ident, s);
- return this.referenceToProxy(ref, type);
- },
- referenceToProxy: function(ref, type)
+ referenceToProxy(ref, type)
{
if(ref !== null)
{
- var proxy = type ? new type() : new ObjectPrx();
- proxy.__setup(ref);
+ const proxy = type ? new type() : new ObjectPrx();
+ proxy._setup(ref);
return proxy;
}
else
{
return null;
}
- },
- proxyToStream: function(proxy, s)
- {
- if(proxy !== null)
- {
- var ref = proxy.__reference();
- ref.getIdentity().__write(s);
- ref.streamWrite(s);
- }
- else
- {
- var ident = new Identity("", "");
- ident.__write(s);
- }
- },
- checkRetryAfterException: function(ex, ref, sleepInterval, cnt)
+ }
+
+ checkRetryAfterException(ex, ref, sleepInterval, cnt)
{
- var traceLevels = this._instance.traceLevels();
- var logger = this._instance.initializationData().logger;
+ const traceLevels = this._instance.traceLevels();
+ const logger = this._instance.initializationData().logger;
//
// We don't retry batch requests because the exception might have caused
@@ -154,9 +128,7 @@ var ProxyFactory = Ice.Class({
if(ex instanceof Ice.ObjectNotExistException)
{
- var one = ex;
-
- if(ref.getRouterInfo() !== null && one.operation === "ice_add_proxy")
+ if(ref.getRouterInfo() !== null && ex.operation === "ice_add_proxy")
{
//
// If we have a router, an ObjectNotExistException with an
@@ -172,7 +144,7 @@ var ProxyFactory = Ice.Class({
if(traceLevels.retry >= 1)
{
logger.trace(traceLevels.retryCat, "retrying operation call to add proxy to router\n" +
- ex.toString());
+ ex.toString());
}
if(sleepInterval !== null)
@@ -190,7 +162,7 @@ var ProxyFactory = Ice.Class({
if(ref.isWellKnown())
{
- var li = ref.getLocatorInfo();
+ const li = ref.getLocatorInfo();
if(li !== null)
{
li.clearCache(ref);
@@ -241,10 +213,12 @@ var ProxyFactory = Ice.Class({
}
//
- // Don't retry if the communicator is destroyed or object adapter
- // deactivated.
+ // Don't retry if the communicator is destroyed, object adapter is deactivated,
+ // or connection is manually closed.
//
- if(ex instanceof Ice.CommunicatorDestroyedException || ex instanceof Ice.ObjectAdapterDeactivatedException)
+ if(ex instanceof Ice.CommunicatorDestroyedException ||
+ ex instanceof Ice.ObjectAdapterDeactivatedException ||
+ ex instanceof Ice.ConnectionManuallyClosedException)
{
throw ex;
}
@@ -260,7 +234,7 @@ var ProxyFactory = Ice.Class({
++cnt;
Debug.assert(cnt > 0);
- var interval;
+ let interval;
if(cnt === (this._retryIntervals.length + 1) && ex instanceof Ice.CloseConnectionException)
{
//
@@ -274,7 +248,7 @@ var ProxyFactory = Ice.Class({
if(traceLevels.retry >= 1)
{
logger.trace(traceLevels.retryCat,
- "cannot retry operation call because retry limit has been exceeded\n" + ex.toString());
+ "cannot retry operation call because retry limit has been exceeded\n" + ex.toString());
}
throw ex;
}
@@ -285,7 +259,7 @@ var ProxyFactory = Ice.Class({
if(traceLevels.retry >= 1)
{
- var msg = "retrying operation call";
+ let msg = "retrying operation call";
if(interval > 0)
{
msg += " in " + interval + "ms";
@@ -299,7 +273,7 @@ var ProxyFactory = Ice.Class({
return cnt;
}
-});
+}
Ice.ProxyFactory = ProxyFactory;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/Reference.js b/js/src/Ice/Reference.js
index 88bb2025854..855417c97a1 100644
--- a/js/src/Ice/Reference.js
+++ b/js/src/Ice/Reference.js
@@ -7,14 +7,12 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/ArrayUtil",
"../Ice/BatchRequestQueue",
"../Ice/Debug",
- "../Ice/HashMap",
"../Ice/HashUtil",
"../Ice/OpaqueEndpointI",
"../Ice/Promise",
@@ -30,29 +28,27 @@ Ice.__M.require(module,
"../Ice/Version",
"../Ice/PropertyNames",
"../Ice/ConnectionRequestHandler",
+ "../Ice/MapUtil"
]);
-var ArrayUtil = Ice.ArrayUtil;
-var Debug = Ice.Debug;
-var BatchRequestQueue = Ice.BatchRequestQueue;
-var HashMap = Ice.HashMap;
-var HashUtil = Ice.HashUtil;
-var OpaqueEndpointI = Ice.OpaqueEndpointI;
-var Promise = Ice.Promise;
-var Protocol = Ice.Protocol;
-var RefMode = Ice.ReferenceMode;
-var StringUtil = Ice.StringUtil;
-var StringSeqHelper = Ice.StringSeqHelper;
-var EndpointSelectionType = Ice.EndpointSelectionType;
-var Identity = Ice.Identity;
-var RouterPrx = Ice.RouterPrx;
-var LocatorPrx = Ice.LocatorPrx;
-var PropertyNames = Ice.PropertyNames;
-var ConnectionRequestHandler = Ice.ConnectionRequestHandler;
-
-var Class = Ice.Class;
-
-var suffixes =
+const ArrayUtil = Ice.ArrayUtil;
+const Debug = Ice.Debug;
+const BatchRequestQueue = Ice.BatchRequestQueue;
+const HashUtil = Ice.HashUtil;
+const OpaqueEndpointI = Ice.OpaqueEndpointI;
+const Protocol = Ice.Protocol;
+const RefMode = Ice.ReferenceMode;
+const StringUtil = Ice.StringUtil;
+const StringSeqHelper = Ice.StringSeqHelper;
+const EndpointSelectionType = Ice.EndpointSelectionType;
+const Identity = Ice.Identity;
+const RouterPrx = Ice.RouterPrx;
+const LocatorPrx = Ice.LocatorPrx;
+const PropertyNames = Ice.PropertyNames;
+const ConnectionRequestHandler = Ice.ConnectionRequestHandler;
+const MapUtil = Ice.MapUtil;
+
+const suffixes =
[
"EndpointSelection",
"ConnectionCached",
@@ -68,15 +64,17 @@ var suffixes =
//
// Only for use by Instance
//
-var ReferenceFactory = Class({
- __init__: function(instance, communicator)
+class ReferenceFactory
+{
+ constructor(instance, communicator)
{
this._instance = instance;
this._communicator = communicator;
this._defaultRouter = null;
this._defaultLocator = null;
- },
- create: function(ident, facet, tmpl, endpoints)
+ }
+
+ create(ident, facet, tmpl, endpoints)
{
if(ident.name.length === 0 && ident.category.length === 0)
{
@@ -84,9 +82,10 @@ var ReferenceFactory = Class({
}
return this.createImpl(ident, facet, tmpl.getMode(), tmpl.getSecure(), tmpl.getProtocol(), tmpl.getEncoding(),
- endpoints, null, null);
- },
- createWithAdapterId: function(ident, facet, tmpl, adapterId)
+ endpoints, null, null);
+ }
+
+ createWithAdapterId(ident, facet, tmpl, adapterId)
{
if(ident.name.length === 0 && ident.category.length === 0)
{
@@ -94,9 +93,10 @@ var ReferenceFactory = Class({
}
return this.createImpl(ident, facet, tmpl.getMode(), tmpl.getSecure(), tmpl.getProtocol(), tmpl.getEncoding(),
- null, adapterId, null);
- },
- createFixed: function(ident, fixedConnection)
+ null, adapterId, null);
+ }
+
+ createFixed(ident, fixedConnection)
{
if(ident.name.length === 0 && ident.category.length === 0)
{
@@ -106,7 +106,7 @@ var ReferenceFactory = Class({
//
// Create new reference
//
- var ref = new FixedReference(
+ return new FixedReference(
this._instance,
this._communicator,
ident,
@@ -115,30 +115,29 @@ var ReferenceFactory = Class({
fixedConnection.endpoint().secure(),
this._instance.defaultsAndOverrides().defaultEncoding,
fixedConnection);
- return ref;
- },
- copy: function(r)
+ }
+
+ copy(r)
{
- var ident = r.getIdentity();
+ const ident = r.getIdentity();
if(ident.name.length === 0 && ident.category.length === 0)
{
return null;
}
return r.clone();
- },
- createFromString: function(s, propertyPrefix)
+ }
+
+ createFromString(s, propertyPrefix)
{
if(s === undefined || s === null || s.length === 0)
{
return null;
}
- var delim = " \t\n\r";
-
- var beg;
- var end = 0;
+ const delim = " \t\n\r";
- beg = StringUtil.findFirstNotOf(s, delim, end);
+ let end = 0;
+ let beg = StringUtil.findFirstNotOf(s, delim, end);
if(beg == -1)
{
throw new Ice.ProxyParseException("no non-whitespace characters found in `" + s + "'");
@@ -148,7 +147,7 @@ var ReferenceFactory = Class({
// Extract the identity, which may be enclosed in single
// or double quotation marks.
//
- var idstr = null;
+ let idstr = null;
end = StringUtil.checkQuote(s, beg);
if(end === -1)
{
@@ -178,7 +177,7 @@ var ReferenceFactory = Class({
//
// Parsing the identity may raise IdentityParseException.
//
- var ident = this._instance.stringToIdentity(idstr);
+ const ident = Ice.stringToIdentity(idstr);
if(ident.name.length === 0)
{
@@ -206,12 +205,12 @@ var ReferenceFactory = Class({
}
}
- var facet = "";
- var mode = RefMode.ModeTwoway;
- var secure = false;
- var encoding = this._instance.defaultsAndOverrides().defaultEncoding;
- var protocol = Ice.Protocol_1_0;
- var adapter = "";
+ let facet = "";
+ let mode = RefMode.ModeTwoway;
+ let secure = false;
+ let encoding = this._instance.defaultsAndOverrides().defaultEncoding;
+ let protocol = Ice.Protocol_1_0;
+ let adapter = "";
while(true)
{
@@ -237,7 +236,7 @@ var ReferenceFactory = Class({
break;
}
- var option = s.substring(beg, end);
+ const option = s.substring(beg, end);
if(option.length != 2 || option.charAt(0) != '-')
{
throw new Ice.ProxyParseException("expected a proxy option but found `" + option + "' in `" + s + "'");
@@ -248,11 +247,11 @@ var ReferenceFactory = Class({
// argument may be enclosed in single or double
// quotation marks.
//
- var argument = null;
- var argumentBeg = StringUtil.findFirstNotOf(s, delim, end);
+ let argument = null;
+ let argumentBeg = StringUtil.findFirstNotOf(s, delim, end);
if(argumentBeg != -1)
{
- var ch = s.charAt(argumentBeg);
+ let ch = s.charAt(argumentBeg);
if(ch != "@" && ch != ":" && ch != "-")
{
beg = argumentBeg;
@@ -260,7 +259,7 @@ var ReferenceFactory = Class({
if(end == -1)
{
throw new Ice.ProxyParseException("mismatched quotes around value for " + option +
- " option in `" + s + "'");
+ " option in `" + s + "'");
}
else if(end === 0)
{
@@ -310,7 +309,7 @@ var ReferenceFactory = Class({
if(argument !== null)
{
throw new Ice.ProxyParseException("unexpected argument `" + argument +
- "' provided for -t option in `" + s + "'");
+ "' provided for -t option in `" + s + "'");
}
mode = RefMode.ModeTwoway;
break;
@@ -321,7 +320,7 @@ var ReferenceFactory = Class({
if(argument !== null)
{
throw new Ice.ProxyParseException("unexpected argument `" + argument +
- "' provided for -o option in `" + s + "'");
+ "' provided for -o option in `" + s + "'");
}
mode = RefMode.ModeOneway;
break;
@@ -332,7 +331,7 @@ var ReferenceFactory = Class({
if(argument !== null)
{
throw new Ice.ProxyParseException("unexpected argument `" + argument +
- "' provided for -O option in `" + s + "'");
+ "' provided for -O option in `" + s + "'");
}
mode = RefMode.ModeBatchOneway;
break;
@@ -343,7 +342,7 @@ var ReferenceFactory = Class({
if(argument !== null)
{
throw new Ice.ProxyParseException("unexpected argument `" + argument +
- "' provided for -d option in `" + s + "'");
+ "' provided for -d option in `" + s + "'");
}
mode = RefMode.ModeDatagram;
break;
@@ -354,7 +353,7 @@ var ReferenceFactory = Class({
if(argument !== null)
{
throw new Ice.ProxyParseException("unexpected argument `" + argument +
- "' provided for -D option in `" + s + "'");
+ "' provided for -D option in `" + s + "'");
}
mode = RefMode.ModeBatchDatagram;
break;
@@ -365,7 +364,7 @@ var ReferenceFactory = Class({
if(argument !== null)
{
throw new Ice.ProxyParseException("unexpected argument `" + argument +
- "' provided for -s option in `" + s + "'");
+ "' provided for -s option in `" + s + "'");
}
secure = true;
break;
@@ -385,7 +384,7 @@ var ReferenceFactory = Class({
catch(e) // VersionParseException
{
throw new Ice.ProxyParseException("invalid encoding version `" + argument + "' in `" + s +
- "':\n" + e.str);
+ "':\n" + e.str);
}
break;
}
@@ -404,7 +403,7 @@ var ReferenceFactory = Class({
catch(e) // VersionParseException
{
throw new Ice.ProxyParseException("invalid protocol version `" + argument + "' in `" + s +
- "':\n" + e.str);
+ "':\n" + e.str);
}
break;
}
@@ -421,11 +420,11 @@ var ReferenceFactory = Class({
return this.createImpl(ident, facet, mode, secure, protocol, encoding, null, null, propertyPrefix);
}
- var endpoints = [];
+ let endpoints = [];
if(s.charAt(beg) == ':')
{
- var unknownEndpoints = [];
+ let unknownEndpoints = [];
end = beg;
while(end < s.length && s.charAt(end) == ':')
@@ -443,8 +442,8 @@ var ReferenceFactory = Class({
}
else
{
- var quoted = false;
- var quote = beg;
+ let quoted = false;
+ let quote = beg;
while(true)
{
quote = s.indexOf("\"", quote);
@@ -475,8 +474,8 @@ var ReferenceFactory = Class({
}
}
- var es = s.substring(beg, end);
- var endp = this._instance.endpointFactoryManager().create(es, false);
+ let es = s.substring(beg, end);
+ let endp = this._instance.endpointFactoryManager().create(es, false);
if(endp !== null)
{
endpoints.push(endp);
@@ -492,16 +491,16 @@ var ReferenceFactory = Class({
throw new Ice.EndpointParseException("invalid endpoint `" + unknownEndpoints[0] + "' in `" + s + "'");
}
else if(unknownEndpoints.length !== 0 &&
- this._instance.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Endpoints", 1) > 0)
+ this._instance.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Endpoints", 1) > 0)
{
- var msg = [];
+ const msg = [];
msg.push("Proxy contains unknown endpoints:");
- for(var i = 0; i < unknownEndpoints.length; ++i)
- {
- msg.push(" `");
- msg.push(unknownEndpoints[i]);
- msg.push("'");
- }
+ unknownEndpoints.forEach(unknownEndpoint =>
+ {
+ msg.push(" `");
+ msg.push(unknownEndpoint);
+ msg.push("'");
+ });
this._instance.initializationData().logger.warning(msg.join(""));
}
@@ -515,7 +514,7 @@ var ReferenceFactory = Class({
throw new Ice.ProxyParseException("missing adapter id in `" + s + "'");
}
- var adapterstr = null;
+ let adapterstr = null;
end = StringUtil.checkQuote(s, beg);
if(end === -1)
{
@@ -559,8 +558,9 @@ var ReferenceFactory = Class({
}
throw new Ice.ProxyParseException("malformed proxy `" + s + "'");
- },
- createFromStream: function(ident, s)
+ }
+
+ createFromStream(ident, s)
{
//
// Don't read the identity here. Operations calling this
@@ -575,8 +575,8 @@ var ReferenceFactory = Class({
//
// For compatibility with the old FacetPath.
//
- var facetPath = StringSeqHelper.read(s); // String[]
- var facet;
+ const facetPath = StringSeqHelper.read(s); // String[]
+ let facet;
if(facetPath.length > 0)
{
if(facetPath.length > 1)
@@ -590,22 +590,22 @@ var ReferenceFactory = Class({
facet = "";
}
- var mode = s.readByte();
+ const mode = s.readByte();
if(mode < 0 || mode > RefMode.ModeLast)
{
throw new Ice.ProxyUnmarshalException();
}
- var secure = s.readBool();
+ const secure = s.readBool();
- var protocol = null;
- var encoding = null;
- if(!s.getReadEncoding().equals(Ice.Encoding_1_0))
+ let protocol = null;
+ let encoding = null;
+ if(!s.getEncoding().equals(Ice.Encoding_1_0))
{
protocol = new Ice.ProtocolVersion();
- protocol.__read(s);
+ protocol._read(s);
encoding = new Ice.EncodingVersion();
- encoding.__read(s);
+ encoding._read(s);
}
else
{
@@ -613,14 +613,14 @@ var ReferenceFactory = Class({
encoding = Ice.Encoding_1_0;
}
- var endpoints = null; // EndpointI[]
- var adapterId = null;
+ let endpoints = null; // EndpointI[]
+ let adapterId = null;
- var sz = s.readSize();
+ const sz = s.readSize();
if(sz > 0)
{
endpoints = [];
- for(var i = 0; i < sz; i++)
+ for(let i = 0; i < sz; i++)
{
endpoints[i] = this._instance.endpointFactoryManager().read(s);
}
@@ -631,46 +631,51 @@ var ReferenceFactory = Class({
}
return this.createImpl(ident, facet, mode, secure, protocol, encoding, endpoints, adapterId, null);
- },
- setDefaultRouter: function(defaultRouter)
+ }
+
+ setDefaultRouter(defaultRouter)
{
if(this._defaultRouter === null ? defaultRouter === null : this._defaultRouter.equals(defaultRouter))
{
return this;
}
- var factory = new ReferenceFactory(this._instance, this._communicator);
+ const factory = new ReferenceFactory(this._instance, this._communicator);
factory._defaultLocator = this._defaultLocator;
factory._defaultRouter = defaultRouter;
return factory;
- },
- getDefaultRouter: function()
+ }
+
+ getDefaultRouter()
{
return this._defaultRouter;
- },
- setDefaultLocator: function(defaultLocator)
+ }
+
+ setDefaultLocator(defaultLocator)
{
if(this._defaultLocator === null ? defaultLocator === null : this._defaultLocator.equals(defaultLocator))
{
return this;
}
- var factory = new ReferenceFactory(this._instance, this._communicator);
+ const factory = new ReferenceFactory(this._instance, this._communicator);
factory._defaultRouter = this._defaultRouter;
factory._defaultLocator = defaultLocator;
return factory;
- },
- getDefaultLocator: function()
+ }
+
+ getDefaultLocator()
{
return this._defaultLocator;
- },
- checkForUnknownProperties: function(prefix)
+ }
+
+ checkForUnknownProperties(prefix)
{
- var unknownProps = [], i, length;
+ const unknownProps = [];
//
// Do not warn about unknown properties for Ice prefixes (Ice, Glacier2, etc.)
//
- for(i = 0; i < PropertyNames.clPropNames.length; ++i)
+ for(let i = 0; i < PropertyNames.clPropNames.length; ++i)
{
if(prefix.indexOf(PropertyNames.clPropNames[i] + ".") === 0)
{
@@ -678,50 +683,37 @@ var ReferenceFactory = Class({
}
}
- var props = this._instance.initializationData().properties.getPropertiesForPrefix(prefix + ".");
- for(var e = props.entries; e !== null; e = e.next)
+ let properties = this._instance.initializationData().properties.getPropertiesForPrefix(prefix + ".");
+ for(let key of properties.keys())
{
- var valid = false;
- for(i = 0, length = suffixes.length; i < length; ++i)
- {
- if(e.key === prefix + "." + suffixes[i])
- {
- valid = true;
- break;
- }
- }
-
- if(!valid)
+ if(!suffixes.some(suffix => key === (prefix + "." + suffix)))
{
- unknownProps.push(e.key);
+ unknownProps.push(key);
}
}
if(unknownProps.length > 0)
{
- var message = [];
+ let message = [];
message.push("found unknown properties for proxy '");
message.push(prefix);
message.push("':");
- for(i = 0, length = unknownProps.length; i < length; ++i)
- {
- message.push("\n ");
- message.push(unknownProps[i]);
- }
+ unknownProps.forEach(unknownProp => message.push("\n ", unknownProp));
this._instance.initializationData().logger.warning(message.join(""));
}
- },
- createImpl: function(ident, facet, mode, secure, protocol, encoding, endpoints, adapterId, propertyPrefix)
+ }
+
+ createImpl(ident, facet, mode, secure, protocol, encoding, endpoints, adapterId, propertyPrefix)
{
- var defaultsAndOverrides = this._instance.defaultsAndOverrides();
+ const defaultsAndOverrides = this._instance.defaultsAndOverrides();
//
// Default local proxy options.
//
- var locatorInfo = null;
+ let locatorInfo = null;
if(this._defaultLocator !== null)
{
- if(!this._defaultLocator.__reference().getEncoding().equals(encoding))
+ if(!this._defaultLocator._getReference().getEncoding().equals(encoding))
{
locatorInfo = this._instance.locatorManager().find(
this._defaultLocator.ice_encodingVersion(encoding));
@@ -731,19 +723,19 @@ var ReferenceFactory = Class({
locatorInfo = this._instance.locatorManager().find(this._defaultLocator);
}
}
- var routerInfo = this._instance.routerManager().find(this._defaultRouter);
- var cacheConnection = true;
- var preferSecure = defaultsAndOverrides.defaultPreferSecure;
- var endpointSelection = defaultsAndOverrides.defaultEndpointSelection;
- var locatorCacheTimeout = defaultsAndOverrides.defaultLocatorCacheTimeout;
- var invocationTimeout = defaultsAndOverrides.defaultInvocationTimeout;
+ let routerInfo = this._instance.routerManager().find(this._defaultRouter);
+ let cacheConnection = true;
+ let preferSecure = defaultsAndOverrides.defaultPreferSecure;
+ let endpointSelection = defaultsAndOverrides.defaultEndpointSelection;
+ let locatorCacheTimeout = defaultsAndOverrides.defaultLocatorCacheTimeout;
+ let invocationTimeout = defaultsAndOverrides.defaultInvocationTimeout;
//
// Override the defaults with the proxy properties if a property prefix is defined.
//
if(propertyPrefix !== null && propertyPrefix.length > 0)
{
- var properties = this._instance.initializationData().properties;
+ const properties = this._instance.initializationData().properties;
//
// Warn about unknown properties.
@@ -753,13 +745,11 @@ var ReferenceFactory = Class({
this.checkForUnknownProperties(propertyPrefix);
}
- var property;
-
- property = propertyPrefix + ".Locator";
- var locator = LocatorPrx.uncheckedCast(this._communicator.propertyToProxy(property));
+ let property = propertyPrefix + ".Locator";
+ const locator = LocatorPrx.uncheckedCast(this._communicator.propertyToProxy(property));
if(locator !== null)
{
- if(!locator.__reference().getEncoding().equals(encoding))
+ if(!locator._getReference().getEncoding().equals(encoding))
{
locatorInfo = this._instance.locatorManager().find(locator.ice_encodingVersion(encoding));
}
@@ -770,15 +760,15 @@ var ReferenceFactory = Class({
}
property = propertyPrefix + ".Router";
- var router = RouterPrx.uncheckedCast(this._communicator.propertyToProxy(property));
+ const router = RouterPrx.uncheckedCast(this._communicator.propertyToProxy(property));
if(router !== null)
{
- var match = ".Router";
+ const match = ".Router";
if(propertyPrefix.lastIndexOf(match) == propertyPrefix.length - match.length)
{
- var s = "`" + property + "=" + properties.getProperty(property) +
- "': cannot set a router on a router; setting ignored";
- this._instance.initializationData().logger.warning(s);
+ this._instance.initializationData().logger.warning(
+ "`" + property + "=" + properties.getProperty(property) +
+ "': cannot set a router on a router; setting ignored");
}
else
{
@@ -795,7 +785,7 @@ var ReferenceFactory = Class({
property = propertyPrefix + ".EndpointSelection";
if(properties.getProperty(property).length > 0)
{
- var type = properties.getProperty(property);
+ const type = properties.getProperty(property);
if(type == "Random")
{
endpointSelection = EndpointSelectionType.Random;
@@ -807,12 +797,12 @@ var ReferenceFactory = Class({
else
{
throw new Ice.EndpointSelectionTypeParseException("illegal value `" + type +
- "'; expected `Random' or `Ordered'");
+ "'; expected `Random' or `Ordered'");
}
}
property = propertyPrefix + ".LocatorCacheTimeout";
- var value = properties.getProperty(property);
+ let value = properties.getProperty(property);
if(value.length !== 0)
{
locatorCacheTimeout = properties.getPropertyAsIntWithDefault(property, locatorCacheTimeout);
@@ -861,12 +851,13 @@ var ReferenceFactory = Class({
locatorCacheTimeout,
invocationTimeout);
}
-});
+}
Ice.ReferenceFactory = ReferenceFactory;
-var Reference = Class({
- __init__: function(instance, communicator, identity, facet, mode, secure, protocol, encoding, invocationTimeout)
+class Reference
+{
+ constructor(instance, communicator, identity, facet, mode, secure, protocol, encoding, invocationTimeout)
{
//
// Validate string arguments.
@@ -886,281 +877,300 @@ var Reference = Class({
this._encoding = encoding;
this._invocationTimeout = invocationTimeout;
this._hashInitialized = false;
- this._overrideCompress = false;
- this._compress = false; // Only used if _overrideCompress == true
- },
- getMode: function()
+ }
+
+ getMode()
{
return this._mode;
- },
- getSecure: function()
+ }
+
+ getSecure()
{
return this._secure;
- },
- getProtocol: function()
+ }
+
+ getProtocol()
{
return this._protocol;
- },
- getEncoding: function()
+ }
+
+ getEncoding()
{
return this._encoding;
- },
- getIdentity: function()
+ }
+
+ getIdentity()
{
return this._identity;
- },
- getFacet: function()
+ }
+
+ getFacet()
{
return this._facet;
- },
- getInstance: function()
+ }
+
+ getInstance()
{
return this._instance;
- },
- getContext: function()
+ }
+
+ getContext()
{
- return this._context; // HashMap
- },
- getInvocationTimeout: function()
+ return this._context; // Map
+ }
+
+ getInvocationTimeout()
{
return this._invocationTimeout;
- },
- getCommunicator: function()
+ }
+
+ getCommunicator()
{
return this._communicator;
- },
- getEndpoints: function()
+ }
+
+ getEndpoints()
{
// Abstract
Debug.assert(false);
return null;
- },
- getAdapterId: function()
+ }
+
+ getAdapterId()
{
// Abstract
Debug.assert(false);
return "";
- },
- getRouterInfo: function()
+ }
+
+ getRouterInfo()
{
// Abstract
Debug.assert(false);
return null;
- },
- getLocatorInfo: function()
+ }
+
+ getLocatorInfo()
{
// Abstract
Debug.assert(false);
return null;
- },
- getCacheConnection: function()
+ }
+
+ getCacheConnection()
{
// Abstract
Debug.assert(false);
return false;
- },
- getPreferSecure: function()
+ }
+
+ getPreferSecure()
{
// Abstract
Debug.assert(false);
return false;
- },
- getEndpointSelection: function()
+ }
+
+ getEndpointSelection()
{
// Abstract
Debug.assert(false);
return null;
- },
- getLocatorCacheTimeout: function()
+ }
+
+ getLocatorCacheTimeout()
{
// Abstract
Debug.assert(false);
return 0;
- },
- getConnectionId: function()
+ }
+
+ getConnectionId()
{
// Abstract
Debug.assert(false);
return "";
- },
+ }
+
//
// The change* methods (here and in derived classes) create
// a new reference based on the existing one, with the
// corresponding value changed.
//
- changeContext: function(newContext)
+ changeContext(newContext)
{
if(newContext === undefined || newContext === null)
{
newContext = Reference._emptyContext;
}
- var r = this._instance.referenceFactory().copy(this);
+ const r = this._instance.referenceFactory().copy(this);
if(newContext.size === 0)
{
r._context = Reference._emptyContext;
}
else
{
- r._context = new HashMap(newContext);
+ r._context = new Map(newContext);
}
return r;
- },
- changeMode: function(newMode)
+ }
+
+ changeMode(newMode)
{
if(newMode === this._mode)
{
return this;
}
- var r = this._instance.referenceFactory().copy(this);
+ const r = this._instance.referenceFactory().copy(this);
r._mode = newMode;
return r;
- },
- changeSecure: function(newSecure)
+ }
+
+ changeSecure(newSecure)
{
if(newSecure === this._secure)
{
return this;
}
- var r = this._instance.referenceFactory().copy(this);
+ const r = this._instance.referenceFactory().copy(this);
r._secure = newSecure;
return r;
- },
- changeIdentity: function(newIdentity)
+ }
+
+ changeIdentity(newIdentity)
{
if(newIdentity.equals(this._identity))
{
return this;
}
- var r = this._instance.referenceFactory().copy(this);
+ const r = this._instance.referenceFactory().copy(this);
r._identity = new Identity(newIdentity.name, newIdentity.category);
return r;
- },
- changeFacet: function(newFacet)
+ }
+
+ changeFacet(newFacet)
{
if(newFacet === this._facet)
{
return this;
}
- var r = this._instance.referenceFactory().copy(this);
+ const r = this._instance.referenceFactory().copy(this);
r._facet = newFacet;
return r;
- },
- changeInvocationTimeout: function(newInvocationTimeout)
+ }
+
+ changeInvocationTimeout(newInvocationTimeout)
{
if(newInvocationTimeout === this._invocationTimeout)
{
return this;
}
- var r = this._instance.referenceFactory().copy(this);
+ const r = this._instance.referenceFactory().copy(this);
r._invocationTimeout = newInvocationTimeout;
return r;
- },
- changeEncoding: function(newEncoding)
+ }
+
+ changeEncoding(newEncoding)
{
if(newEncoding.equals(this._encoding))
{
return this;
}
- var r = this._instance.referenceFactory().copy(this);
+ const r = this._instance.referenceFactory().copy(this);
r._encoding = newEncoding;
return r;
- },
- changeCompress: function(newCompress)
- {
- if(this._overrideCompress && this._compress === newCompress)
- {
- return this;
- }
- var r = this._instance.referenceFactory().copy(this);
- r._compress = newCompress;
- r._overrideCompress = true;
- return r;
- },
- changeAdapterId: function(newAdapterId)
+ }
+
+ changeAdapterId(newAdapterId)
{
// Abstract
Debug.assert(false);
return null;
- },
- changeEndpoints: function(newEndpoints)
+ }
+
+ changeEndpoints(newEndpoints)
{
// Abstract
Debug.assert(false);
return null;
- },
- changeLocator: function(newLocator)
+ }
+
+ changeLocator(newLocator)
{
// Abstract
Debug.assert(false);
return null;
- },
- changeRouter: function(newRouter)
+ }
+
+ changeRouter(newRouter)
{
// Abstract
Debug.assert(false);
return null;
- },
- changeCacheConnection: function(newCache)
+ }
+
+ changeCacheConnection(newCache)
{
// Abstract
Debug.assert(false);
return null;
- },
- changePreferSecure: function(newPreferSecure)
+ }
+
+ changePreferSecure(newPreferSecure)
{
// Abstract
Debug.assert(false);
return null;
- },
- changeEndpointSelection: function(newType)
+ }
+
+ changeEndpointSelection(newType)
{
// Abstract
Debug.assert(false);
return null;
- },
- changeLocatorCacheTimeout: function(newTimeout)
+ }
+
+ changeLocatorCacheTimeout(newTimeout)
{
// Abstract
Debug.assert(false);
return null;
- },
- changeTimeout: function(newTimeout)
+ }
+
+ changeTimeout(newTimeout)
{
// Abstract
Debug.assert(false);
return null;
- },
- changeConnectionId: function(connectionId)
+ }
+
+ changeConnectionId(connectionId)
{
// Abstract
Debug.assert(false);
return null;
- },
- hashCode: function()
+ }
+
+ hashCode()
{
if(this._hashInitialized)
{
return this._hashValue;
}
- var h = 5381;
+ let h = 5381;
h = HashUtil.addNumber(h, this._mode);
h = HashUtil.addBoolean(h, this._secure);
h = HashUtil.addHashable(h, this._identity);
if(this._context !== null && this._context !== undefined)
{
- for(var e = this._context.entries; e !== null; e = e.next)
+ for(let [key, value] of this._context)
{
- h = HashUtil.addString(h, e.key);
- h = HashUtil.addString(h, e.value);
+ h = HashUtil.addString(h, key);
+ h = HashUtil.addString(h, value);
}
}
h = HashUtil.addString(h, this._facet);
- h = HashUtil.addBoolean(h, this._overrideCompress);
- if(this._overrideCompress)
- {
- h = HashUtil.addBoolean(h, this._compress);
- }
h = HashUtil.addHashable(h, this._protocol);
h = HashUtil.addHashable(h, this._encoding);
h = HashUtil.addNumber(h, this._invocationTimeout);
@@ -1169,26 +1179,29 @@ var Reference = Class({
this._hashInitialized = true;
return this._hashValue;
- },
+ }
+
//
// Utility methods
//
- isIndirect: function()
+ isIndirect()
{
// Abstract
Debug.assert(false);
return false;
- },
- isWellKnown: function()
+ }
+
+ isWellKnown()
{
// Abstract
Debug.assert(false);
return false;
- },
+ }
+
//
// Marshal the reference.
//
- streamWrite: function(s)
+ streamWrite(s)
{
//
// Don't write the identity here. Operations calling streamWrite
@@ -1212,18 +1225,19 @@ var Reference = Class({
s.writeBool(this._secure);
- if(!s.getWriteEncoding().equals(Ice.Encoding_1_0))
+ if(!s.getEncoding().equals(Ice.Encoding_1_0))
{
- this._protocol.__write(s);
- this._encoding.__write(s);
+ this._protocol._write(s);
+ this._encoding._write(s);
}
// Derived class writes the remainder of the reference.
- },
+ }
+
//
// Convert the reference to its string form.
//
- toString: function()
+ toString()
{
//
// WARNING: Certain features, such as proxy validation in Glacier2,
@@ -1232,14 +1246,17 @@ var Reference = Class({
// these features. Please review for all features that depend on the
// format of proxyToString() before changing this and related code.
//
- var s = [];
+ const s = [];
+
+ const toStringMode = this._instance.toStringMode();
//
// If the encoded identity string contains characters which
// the reference parser uses as separators, then we enclose
// the identity string in quotes.
//
- var id = this._instance.identityToString(this._identity);
+
+ const id = Ice.identityToString(this._identity, toStringMode);
if(id.search(/[ :@]/) != -1)
{
s.push('"');
@@ -1259,7 +1276,7 @@ var Reference = Class({
// the facet string in quotes.
//
s.push(" -f ");
- var fs = StringUtil.escapeString(this._facet, "");
+ const fs = StringUtil.escapeString(this._facet, "", toStringMode);
if(fs.search(/[ :@]/) != -1)
{
s.push('"');
@@ -1333,27 +1350,31 @@ var Reference = Class({
return s.join("");
// Derived class writes the remainder of the string.
- },
+ }
+
//
// Convert the reference to its property form.
//
- toProperty: function(prefix)
+ toProperty(prefix)
{
// Abstract
Debug.assert(false);
return null;
- },
- getRequestHandler: function(proxy)
+ }
+
+ getRequestHandler(proxy)
{
// Abstract
Debug.assert(false);
- },
- getBatchRequestQueue: function()
+ }
+
+ getBatchRequestQueue()
{
// Abstract
Debug.assert(false);
- },
- equals: function(r)
+ }
+
+ equals(r)
{
//
// Note: if(this === r) and type test are performed by each non-abstract derived class.
@@ -1374,7 +1395,7 @@ var Reference = Class({
return false;
}
- if(!this._context.equals(r._context))
+ if(!MapUtil.equals(this._context, r._context))
{
return false;
}
@@ -1384,15 +1405,6 @@ var Reference = Class({
return false;
}
- if(this._overrideCompress !== r._overrideCompress)
- {
- return false;
- }
- if(this._overrideCompress && this._compress !== r._compress)
- {
- return false;
- }
-
if(!this._protocol.equals(r._protocol))
{
return false;
@@ -1409,139 +1421,161 @@ var Reference = Class({
}
return true;
- },
- clone: function()
+ }
+
+ clone()
{
// Abstract
Debug.assert(false);
return null;
- },
- copyMembers: function(r)
+ }
+
+ copyMembers(r)
{
//
// Copy the members that are not passed to the constructor.
//
r._context = this._context;
- r._overrideCompress = this._overrideCompress;
- r._compress = this._compress;
}
-});
+}
-Reference._emptyContext = new HashMap();
+Reference._emptyContext = new Map();
Reference._emptyEndpoints = [];
Ice.Reference = Reference;
-var FixedReference = Class(Reference, {
- __init__: function(instance, communicator, identity, facet, mode, secure, encoding, connection)
+class FixedReference extends Reference
+{
+ constructor(instance, communicator, identity, facet, mode, secure, encoding, connection)
{
- Reference.call(this, instance, communicator, identity, facet, mode, secure, Ice.Protocol_1_0, encoding);
+ super(instance, communicator, identity, facet, mode, secure, Ice.Protocol_1_0, encoding);
this._fixedConnection = connection;
- },
- getEndpoints: function()
+ }
+
+ getEndpoints()
{
return Reference._emptyEndpoints;
- },
- getAdapterId: function()
+ }
+
+ getAdapterId()
{
return "";
- },
- getRouterInfo: function()
+ }
+
+ getRouterInfo()
{
return null;
- },
- getLocatorInfo: function()
+ }
+
+ getLocatorInfo()
{
return null;
- },
- getCacheConnection: function()
+ }
+
+ getCacheConnection()
{
return true;
- },
- getPreferSecure: function()
+ }
+
+ getPreferSecure()
{
return false;
- },
- getEndpointSelection: function()
+ }
+
+ getEndpointSelection()
{
return EndpointSelectionType.Random;
- },
- getLocatorCacheTimeout: function()
+ }
+
+ getLocatorCacheTimeout()
{
return 0;
- },
- getConnectionId: function()
+ }
+
+ getConnectionId()
{
return "";
- },
- changeAdapterId: function(newAdapterId)
+ }
+
+ changeAdapterId(newAdapterId)
{
throw new Ice.FixedProxyException();
- },
- changeEndpoints: function(newEndpoints)
+ }
+
+ changeEndpoints(newEndpoints)
{
throw new Ice.FixedProxyException();
- },
- changeLocator: function(newLocator)
+ }
+
+ changeLocato(newLocator)
{
throw new Ice.FixedProxyException();
- },
- changeRouter: function(newRouter)
+ }
+
+ changeRouter(newRouter)
{
throw new Ice.FixedProxyException();
- },
- changeCacheConnection: function(newCache)
+ }
+
+ changeCacheConnection(newCache)
{
throw new Ice.FixedProxyException();
- },
- changePreferSecure: function(prefSec)
+ }
+
+ changePreferSecure(prefSec)
{
throw new Ice.FixedProxyException();
- },
- changeEndpointSelection: function(newType)
+ }
+
+ changeEndpointSelection(newType)
{
throw new Ice.FixedProxyException();
- },
- changeLocatorCacheTimeout: function(newTimeout)
+ }
+
+ changeLocatorCacheTimeout(newTimeout)
{
throw new Ice.FixedProxyException();
- },
- changeTimeout: function(newTimeout)
+ }
+
+ changeTimeout(newTimeout)
{
throw new Ice.FixedProxyException();
- },
- changeConnectionId: function(connectionId)
+ }
+
+ changeConnectionId(connectionId)
{
throw new Ice.FixedProxyException();
- },
- isIndirect: function()
+ }
+
+ isIndirect()
{
return false;
- },
- isWellKnown: function()
+ }
+
+ isWellKnown()
{
return false;
- },
- streamWrite: function(s)
- {
- throw new Ice.FixedProxyException();
- },
- toString: function()
+ }
+
+ streamWrite(s)
{
throw new Ice.FixedProxyException();
- },
- toProperty: function(prefix)
+ }
+
+ toProperty(prefix)
{
throw new Ice.FixedProxyException();
- },
- clone: function()
+ }
+
+ clone()
{
- var r = new FixedReference(this.getInstance(), this.getCommunicator(), this.getIdentity(), this.getFacet(),
- this.getMode(), this.getSecure(), this.getEncoding(), this._fixedConnection);
+ const r = new FixedReference(this.getInstance(), this.getCommunicator(), this.getIdentity(), this.getFacet(),
+ this.getMode(), this.getSecure(), this.getEncoding(), this._fixedConnection);
this.copyMembers(r);
return r;
- },
- getRequestHandler: function(proxy)
+ }
+
+ getRequestHandler(proxy)
{
switch(this.getMode())
{
@@ -1571,16 +1605,8 @@ var FixedReference = Class(Reference, {
// If a secure connection is requested or secure overrides is set,
// check if the connection is secure.
//
- var secure;
- var defaultsAndOverrides = this.getInstance().defaultsAndOverrides();
- if(defaultsAndOverrides.overrideSecure)
- {
- secure = defaultsAndOverrides.overrideSecureValue;
- }
- else
- {
- secure = this.getSecure();
- }
+ const defaultsAndOverrides = this.getInstance().defaultsAndOverrides();
+ const secure = defaultsAndOverrides.overrideSecure ? defaultsAndOverrides.overrideSecureValue : this.getSecure();
if(secure && !this._fixedConnection.endpoint().secure())
{
throw new Ice.NoEndpointException("");
@@ -1588,27 +1614,15 @@ var FixedReference = Class(Reference, {
this._fixedConnection.throwException(); // Throw in case our connection is already destroyed.
- var compress;
- if(defaultsAndOverrides.overrideCompress)
- {
- compress = defaultsAndOverrides.overrideCompressValue;
- }
- else if(this._overrideCompress)
- {
- compress = this._compress;
- }
- else
- {
- compress = this._fixedConnection.endpoint().compress();
- }
+ return proxy._setRequestHandler(new ConnectionRequestHandler(this, this._fixedConnection));
+ }
- return proxy.__setRequestHandler(new ConnectionRequestHandler(this, this._fixedConnection, compress));
- },
- getBatchRequestQueue: function()
+ getBatchRequestQueue()
{
return this._fixedConnection.getBatchRequestQueue();
- },
- equals: function(rhs)
+ }
+
+ equals(rhs)
{
if(this === rhs)
{
@@ -1618,23 +1632,23 @@ var FixedReference = Class(Reference, {
{
return false;
}
- if(!Reference.prototype.equals.call(this, rhs))
+ if(!super.equals(rhs))
{
return false;
}
return this._fixedConnection.equals(rhs._fixedConnection);
}
-});
+}
Ice.FixedReference = FixedReference;
-var RoutableReference = Class(Reference, {
- __init__: function(instance, communicator, identity, facet, mode, secure, protocol, encoding, endpoints,
- adapterId, locatorInfo, routerInfo, cacheConnection, preferSecure, endpointSelection,
- locatorCacheTimeout, invocationTimeout)
+class RoutableReference extends Reference
+{
+ constructor(instance, communicator, identity, facet, mode, secure, protocol, encoding, endpoints,
+ adapterId, locatorInfo, routerInfo, cacheConnection, preferSecure, endpointSelection,
+ locatorCacheTimeout, invocationTimeout)
{
- Reference.call(this, instance, communicator, identity, facet, mode, secure, protocol, encoding,
- invocationTimeout);
+ super(instance, communicator, identity, facet, mode, secure, protocol, encoding, invocationTimeout);
this._endpoints = endpoints;
this._adapterId = adapterId;
this._locatorInfo = locatorInfo;
@@ -1656,223 +1670,216 @@ var RoutableReference = Class(Reference, {
}
this._connectionId = "";
Debug.assert(this._adapterId.length === 0 || this._endpoints.length === 0);
- },
- getEndpoints: function()
+ }
+
+ getEndpoints()
{
return this._endpoints;
- },
- getAdapterId: function()
+ }
+
+ getAdapterId()
{
return this._adapterId;
- },
- getRouterInfo: function()
+ }
+
+ getRouterInfo()
{
return this._routerInfo;
- },
- getLocatorInfo: function()
+ }
+
+ getLocatorInfo()
{
return this._locatorInfo;
- },
- getCacheConnection: function()
+ }
+
+ getCacheConnection()
{
return this._cacheConnection;
- },
- getPreferSecure: function()
+ }
+
+ getPreferSecure()
{
return this._preferSecure;
- },
- getEndpointSelection: function()
+ }
+
+ getEndpointSelection()
{
return this._endpointSelection;
- },
- getLocatorCacheTimeout: function()
+ }
+
+ getLocatorCacheTimeout()
{
return this._locatorCacheTimeout;
- },
- getConnectionId: function()
+ }
+
+ getConnectionId()
{
return this._connectionId;
- },
- changeEncoding: function(newEncoding)
+ }
+
+ changeEncoding(newEncoding)
{
- var r = Reference.prototype.changeEncoding.call(this, newEncoding);
+ const r = super.changeEncoding(newEncoding);
if(r !== this)
{
- var locInfo = r._locatorInfo;
- if(locInfo !== null && !locInfo.getLocator().ice_getEncodingVersion().equals(newEncoding))
+ if(r._locatorInfo !== null && !r._locatorInfo.getLocator().ice_getEncodingVersion().equals(newEncoding))
{
r._locatorInfo = this.getInstance().locatorManager().find(
- locInfo.getLocator().ice_encodingVersion(newEncoding));
+ r._locatorInfo.getLocator().ice_encodingVersion(newEncoding));
}
}
return r;
- },
- changeCompress: function(newCompress)
- {
- var r = Reference.prototype.changeCompress.call(this, newCompress);
- if(r !== this && this._endpoints.length > 0) // Also override the compress flag on the endpoints if it was updated.
- {
- var newEndpoints = [];
- for(var i = 0; i < this._endpoints.length; i++)
- {
- newEndpoints[i] = this._endpoints[i].changeCompress(newCompress);
- }
- r._endpoints = newEndpoints;
- }
- return r;
- },
- changeAdapterId: function(newAdapterId)
+ }
+
+ changeAdapterId(newAdapterId)
{
if(this._adapterId === newAdapterId)
{
return this;
}
- var r = this.getInstance().referenceFactory().copy(this);
+ const r = this.getInstance().referenceFactory().copy(this);
r._adapterId = newAdapterId;
r._endpoints = Reference._emptyEndpoints;
return r;
- },
- changeEndpoints: function(newEndpoints)
+ }
+
+ changeEndpoints(newEndpoints)
{
if(ArrayUtil.equals(newEndpoints, this._endpoints, function(e1, e2) { return e1.equals(e2); }))
{
return this;
}
- var r = this.getInstance().referenceFactory().copy(this);
+ const r = this.getInstance().referenceFactory().copy(this);
r._endpoints = newEndpoints;
r._adapterId = "";
r.applyOverrides(r._endpoints);
return r;
- },
- changeLocator: function(newLocator)
+ }
+
+ changeLocator(newLocator)
{
- var newLocatorInfo = this.getInstance().locatorManager().find(newLocator);
+ const newLocatorInfo = this.getInstance().locatorManager().find(newLocator);
if(newLocatorInfo !== null && this._locatorInfo !== null && newLocatorInfo.equals(this._locatorInfo))
{
return this;
}
- var r = this.getInstance().referenceFactory().copy(this);
+ const r = this.getInstance().referenceFactory().copy(this);
r._locatorInfo = newLocatorInfo;
return r;
- },
- changeRouter: function(newRouter)
+ }
+
+ changeRouter(newRouter)
{
- var newRouterInfo = this.getInstance().routerManager().find(newRouter);
+ const newRouterInfo = this.getInstance().routerManager().find(newRouter);
if(newRouterInfo !== null && this._routerInfo !== null && newRouterInfo.equals(this._routerInfo))
{
return this;
}
- var r = this.getInstance().referenceFactory().copy(this);
+ const r = this.getInstance().referenceFactory().copy(this);
r._routerInfo = newRouterInfo;
return r;
- },
- changeCacheConnection: function(newCache)
+ }
+
+ changeCacheConnection(newCache)
{
if(newCache === this._cacheConnection)
{
return this;
}
- var r = this.getInstance().referenceFactory().copy(this);
+ const r = this.getInstance().referenceFactory().copy(this);
r._cacheConnection = newCache;
return r;
- },
- changePreferSecure: function(newPreferSecure)
+ }
+
+ changePreferSecure(newPreferSecure)
{
if(newPreferSecure === this._preferSecure)
{
return this;
}
- var r = this.getInstance().referenceFactory().copy(this);
+ const r = this.getInstance().referenceFactory().copy(this);
r._preferSecure = newPreferSecure;
return r;
- },
- changeEndpointSelection: function(newType)
+ }
+
+ changeEndpointSelection(newType)
{
if(newType === this._endpointSelection)
{
return this;
}
- var r = this.getInstance().referenceFactory().copy(this);
+ const r = this.getInstance().referenceFactory().copy(this);
r._endpointSelection = newType;
return r;
- },
- changeLocatorCacheTimeout: function(newTimeout)
+ }
+
+ changeLocatorCacheTimeout(newTimeout)
{
if(this._locatorCacheTimeout === newTimeout)
{
return this;
}
- var r = this.getInstance().referenceFactory().copy(this);
+ const r = this.getInstance().referenceFactory().copy(this);
r._locatorCacheTimeout = newTimeout;
return r;
- },
- changeTimeout: function(newTimeout)
+ }
+
+ changeTimeout(newTimeout)
{
if(this._overrideTimeout && this._timeout === newTimeout)
{
return this;
}
- var r = this.getInstance().referenceFactory().copy(this);
+ const r = this.getInstance().referenceFactory().copy(this);
r._timeout = newTimeout;
r._overrideTimeout = true;
- if(this._endpoints.length > 0)
- {
- var newEndpoints = [];
- for(var i = 0; i < this._endpoints.length; i++)
- {
- newEndpoints[i] = this._endpoints[i].changeTimeout(newTimeout);
- }
- r._endpoints = newEndpoints;
- }
+ r._endpoints = this._endpoints.map(endpoint => endpoint.changeTimeout(newTimeout));
return r;
- },
- changeConnectionId: function(id)
+ }
+
+ changeConnectionId(id)
{
if(this._connectionId === id)
{
return this;
}
- var r = this.getInstance().referenceFactory().copy(this);
+ const r = this.getInstance().referenceFactory().copy(this);
r._connectionId = id;
- if(this._endpoints.length > 0)
- {
- var newEndpoints = [];
- for(var i = 0; i < this._endpoints.length; i++)
- {
- newEndpoints[i] = this._endpoints[i].changeConnectionId(id);
- }
- r._endpoints = newEndpoints;
- }
+ r._endpoints = this._endpoints.map(endpoint => endpoint.changeConnectionId(id));
return r;
- },
- isIndirect: function()
+ }
+
+ isIndirect()
{
return this._endpoints.length === 0;
- },
- isWellKnown: function()
+ }
+
+ isWellKnown()
{
return this._endpoints.length === 0 && this._adapterId.length === 0;
- },
- streamWrite: function(s)
+ }
+
+ streamWrite(s)
{
- Reference.prototype.streamWrite.call(this, s);
+ super.streamWrite(s);
s.writeSize(this._endpoints.length);
if(this._endpoints.length > 0)
{
Debug.assert(this._adapterId.length === 0);
- for(var i = 0; i < this._endpoints.length; ++i)
- {
- s.writeShort(this._endpoints[i].type());
- this._endpoints[i].streamWrite(s);
- }
+ this._endpoints.forEach(endpoint =>
+ {
+ s.writeShort(endpoint.type());
+ endpoint.streamWrite(s);
+ });
}
else
{
s.writeString(this._adapterId); // Adapter id.
}
- },
- toString: function()
+ }
+
+ toString()
{
//
// WARNING: Certain features, such as proxy validation in Glacier2,
@@ -1881,19 +1888,19 @@ var RoutableReference = Class(Reference, {
// these features. Please review for all features that depend on the
// format of proxyToString() before changing this and related code.
//
- var s = [];
- s.push(Reference.prototype.toString.call(this));
+ const s = [];
+ s.push(super.toString());
if(this._endpoints.length > 0)
{
- for(var i = 0; i < this._endpoints.length; ++i)
- {
- var endp = this._endpoints[i].toString();
- if(endp !== null && endp.length > 0)
+ this._endpoints.forEach(endpoint =>
{
- s.push(':');
- s.push(endp);
- }
- }
+ const endp = endpoint.toString();
+ if(endp !== null && endp.length > 0)
+ {
+ s.push(':');
+ s.push(endp);
+ }
+ });
}
else if(this._adapterId.length > 0)
{
@@ -1904,7 +1911,7 @@ var RoutableReference = Class(Reference, {
// the reference parser uses as separators, then we enclose
// the adapter id string in quotes.
//
- var a = StringUtil.escapeString(this._adapterId, null);
+ const a = StringUtil.escapeString(this._adapterId, null, this._instance.toStringMode());
if(a.search(/[ :@]/) != -1)
{
s.push('"');
@@ -1917,53 +1924,48 @@ var RoutableReference = Class(Reference, {
}
}
return s.join("");
- },
- toProperty: function(prefix)
+ }
+
+ toProperty(prefix)
{
- var properties = new HashMap(), e;
+ const properties = new Map();
properties.set(prefix, this.toString());
properties.set(prefix + ".CollocationOptimized", "0");
properties.set(prefix + ".ConnectionCached", this._cacheConnection ? "1" : "0");
properties.set(prefix + ".PreferSecure", this._preferSecure ? "1" : "0");
properties.set(prefix + ".EndpointSelection",
- this._endpointSelection === EndpointSelectionType.Random ? "Random" : "Ordered");
+ this._endpointSelection === EndpointSelectionType.Random ? "Random" : "Ordered");
properties.set(prefix + ".LocatorCacheTimeout", "" + this._locatorCacheTimeout);
properties.set(prefix + ".InvocationTimeout", "" + this.getInvocationTimeout());
if(this._routerInfo !== null)
{
- var h = this._routerInfo.getRouter();
- var routerProperties = h.__reference().toProperty(prefix + ".Router");
- for(e = routerProperties.entries; e !== null; e = e.next)
- {
- properties.set(e.key, e.value);
- }
+ this._routerInfo.getRouter()._getReference().toProperty(prefix + ".Router").forEach(
+ (value, key) => properties.set(key, value));
}
if(this._locatorInfo !== null)
{
- var p = this._locatorInfo.getLocator();
- var locatorProperties = p.__reference().toProperty(prefix + ".Locator");
- for(e = locatorProperties.entries; e !== null; e = e.next)
- {
- properties.set(e.key, e.value);
- }
+ this._locatorInfo.getLocator()._getReference().toProperty(prefix + ".Locator").forEach(
+ (value, key) => properties.set(key, value));
}
return properties;
- },
- hashCode: function()
+ }
+
+ hashCode()
{
if(!this._hashInitialized)
{
- Reference.prototype.hashCode.call(this); // Initializes _hashValue.
+ super.hashCode(); // Initializes _hashValue.
this._hashValue = HashUtil.addString(this._hashValue, this._adapterId);
}
return this._hashValue;
- },
- equals: function(rhs)
+ }
+
+ equals(rhs)
{
if(this === rhs)
{
@@ -1974,7 +1976,7 @@ var RoutableReference = Class(Reference, {
return false;
}
- if(!Reference.prototype.equals.call(this, rhs))
+ if(!super.equals(rhs))
{
return false;
}
@@ -2024,18 +2026,21 @@ var RoutableReference = Class(Reference, {
return false;
}
return true;
- },
- getRequestHandler: function(proxy)
+ }
+
+ getRequestHandler(proxy)
{
return this._instance.requestHandlerFactory().getRequestHandler(this, proxy);
- },
- getBatchRequestQueue: function()
+ }
+
+ getBatchRequestQueue()
{
return new BatchRequestQueue(this._instance, this._mode === RefMode.ModeBatchDatagram);
- },
- getConnection: function()
+ }
+
+ getConnection()
{
- var promise = new Promise(); // success callback receives (connection, compress)
+ const p = new Ice.Promise(); // success callback receives (connection)
if(this._routerInfo !== null)
{
@@ -2043,117 +2048,90 @@ var RoutableReference = Class(Reference, {
// If we route, we send everything to the router's client
// proxy endpoints.
//
- var self = this;
- this._routerInfo.getClientEndpoints().then(
- function(endpts)
+ this._routerInfo.getClientEndpoints().then(endpts =>
{
if(endpts.length > 0)
{
- self.applyOverrides(endpts);
- self.createConnection(endpts).then(
- function(connection, compress)
- {
- promise.succeed(connection, compress);
- },
- function(ex)
- {
- promise.fail(ex);
- });
+ this.applyOverrides(endpts);
+ this.createConnection(endpts).then(p.resolve, p.reject);
}
else
{
- self.getConnectionNoRouterInfo(promise);
+ this.getConnectionNoRouterInfo(p);
}
- }).exception(
- function(ex)
- {
- promise.fail(ex);
- });
+ }).catch(p.reject);
}
else
{
- this.getConnectionNoRouterInfo(promise);
+ this.getConnectionNoRouterInfo(p);
}
+ return p;
+ }
- return promise;
- },
- getConnectionNoRouterInfo: function(promise)
+ getConnectionNoRouterInfo(p)
{
if(this._endpoints.length > 0)
{
- this.createConnection(this._endpoints).then(
- function(connection, compress)
- {
- promise.succeed(connection, compress);
- }).exception(
- function(ex)
- {
- promise.fail(ex);
- });
+ this.createConnection(this._endpoints).then(p.resolve).catch(p.reject);
return;
}
- var self = this;
if(this._locatorInfo !== null)
{
this._locatorInfo.getEndpoints(this, null, this._locatorCacheTimeout).then(
- function(endpoints, cached)
+ values =>
{
+ const [endpoints, cached] = values;
if(endpoints.length === 0)
{
- promise.fail(new Ice.NoEndpointException(self.toString()));
+ p.reject(new Ice.NoEndpointException(this.toString()));
return;
}
- self.applyOverrides(endpoints);
- self.createConnection(endpoints).then(
- function(connection, compress)
- {
- promise.succeed(connection, compress);
- },
- function(ex)
+ this.applyOverrides(endpoints);
+ this.createConnection(endpoints).then(
+ p.resolve,
+ ex =>
{
if(ex instanceof Ice.NoEndpointException)
{
//
// No need to retry if there's no endpoints.
//
- promise.fail(ex);
+ p.reject(ex);
}
else
{
- Debug.assert(self._locatorInfo !== null);
- self.getLocatorInfo().clearCache(self);
+ Debug.assert(this._locatorInfo !== null);
+ this.getLocatorInfo().clearCache(this);
if(cached)
{
- var traceLevels = self.getInstance().traceLevels();
+ const traceLevels = this.getInstance().traceLevels();
if(traceLevels.retry >= 2)
{
- var s = "connection to cached endpoints failed\n" +
- "removing endpoints from cache and trying one more time\n" +
- ex.toString();
- self.getInstance().initializationData().logger.trace(traceLevels.retryCat, s);
+ this.getInstance().initializationData().logger.trace(
+ traceLevels.retryCat,
+ "connection to cached endpoints failed\n" +
+ "removing endpoints from cache and trying one more time\n" +
+ ex.toString());
}
- self.getConnectionNoRouterInfo(promise); // Retry.
+ this.getConnectionNoRouterInfo(p); // Retry.
return;
}
- promise.fail(ex);
+ p.reject(ex);
}
});
- }).exception(
- function(ex)
- {
- promise.fail(ex);
- });
+ }).catch(p.reject);
}
else
{
- promise.fail(new Ice.NoEndpointException(this.toString()));
+ p.reject(new Ice.NoEndpointException(this.toString()));
}
- },
- clone: function()
+ }
+
+ clone()
{
- var r = new RoutableReference(this.getInstance(),
+ const r = new RoutableReference(this.getInstance(),
this.getCommunicator(),
this.getIdentity(),
this.getFacet(),
@@ -2172,49 +2150,40 @@ var RoutableReference = Class(Reference, {
this._invocationTimeout);
this.copyMembers(r);
return r;
- },
- copyMembers: function(rhs)
+ }
+
+ copyMembers(rhs)
{
//
// Copy the members that are not passed to the constructor.
//
- Reference.prototype.copyMembers.call(this, rhs);
+ super.copyMembers(rhs);
rhs._overrideTimeout = this._overrideTimeout;
rhs._timeout = this._timeout;
rhs._connectionId = this._connectionId;
- },
- applyOverrides: function(endpts)
+ }
+
+ applyOverrides(endpts)
{
//
// Apply the endpoint overrides to each endpoint.
//
- for(var i = 0; i < endpts.length; ++i)
+ for(let i = 0; i < endpts.length; ++i)
{
endpts[i] = endpts[i].changeConnectionId(this._connectionId);
- if(this._overrideCompress)
- {
- endpts[i] = endpts[i].changeCompress(this._compress);
- }
if(this._overrideTimeout)
{
endpts[i] = endpts[i].changeTimeout(this._timeout);
}
}
- },
- filterEndpoints: function(allEndpoints)
- {
- var endpoints = [];
+ }
+ filterEndpoints(allEndpoints)
+ {
//
// Filter out opaque endpoints or endpoints which can't connect.
//
- for(var i = 0; i < allEndpoints.length; ++i)
- {
- if(!(allEndpoints[i] instanceof OpaqueEndpointI) && allEndpoints[i].connectable())
- {
- endpoints.push(allEndpoints[i]);
- }
- }
+ let endpoints = allEndpoints.filter(e => !(e instanceof OpaqueEndpointI) && e.connectable());
//
// Filter out endpoints according to the mode of the reference.
@@ -2228,7 +2197,7 @@ var RoutableReference = Class(Reference, {
//
// Filter out datagram endpoints.
//
- endpoints = ArrayUtil.filter(endpoints, function(e, index, arr) { return !e.datagram(); });
+ endpoints = endpoints.filter(e => !e.datagram());
break;
}
@@ -2238,7 +2207,7 @@ var RoutableReference = Class(Reference, {
//
// Filter out non-datagram endpoints.
//
- endpoints = ArrayUtil.filter(endpoints, function(e, index, arr) { return e.datagram(); });
+ endpoints = endpoints.filter(e => e.datagram());
break;
}
}
@@ -2274,18 +2243,18 @@ var RoutableReference = Class(Reference, {
// make secure endpoints prefered. By default make non-secure
// endpoints preferred over secure endpoints.
//
- var overrides = this.getInstance().defaultsAndOverrides();
+ const overrides = this.getInstance().defaultsAndOverrides();
if(overrides.overrideSecure ? overrides.overrideSecureValue : this.getSecure())
{
- endpoints = ArrayUtil.filter(endpoints, function(e, index, arr) { return e.secure(); });
+ endpoints = endpoints.filter(e => e.secure());
}
else
{
- var preferSecure = this.getPreferSecure();
- var compare = function(e1, e2)
+ const preferSecure = this.getPreferSecure();
+ const compare = (e1, e2) =>
{
- var ls = e1.secure();
- var rs = e2.secure();
+ const ls = e1.secure();
+ const rs = e2.secure();
if((ls && rs) || (!ls && !rs))
{
return 0;
@@ -2302,37 +2271,30 @@ var RoutableReference = Class(Reference, {
endpoints.sort(compare);
}
return endpoints;
- },
- createConnection: function(allEndpoints)
+ }
+
+ createConnection(allEndpoints)
{
- var endpoints = this.filterEndpoints(allEndpoints);
+ const endpoints = this.filterEndpoints(allEndpoints);
if(endpoints.length === 0)
{
- return new Promise().fail(new Ice.NoEndpointException(this.toString()));
+ return Ice.Promise.reject(new Ice.NoEndpointException(this.toString()));
}
//
// Finally, create the connection.
//
- var promise = new Promise();
- var factory = this.getInstance().outgoingConnectionFactory();
- var cb;
+ const promise = new Ice.Promise();
+ const factory = this.getInstance().outgoingConnectionFactory();
if(this.getCacheConnection() || endpoints.length == 1)
{
//
// Get an existing connection or create one if there's no
// existing connection to one of the given endpoints.
//
- cb = new CreateConnectionCallback(this, null, promise);
+ const cb = new CreateConnectionCallback(this, null, promise);
factory.create(endpoints, false, this.getEndpointSelection()).then(
- function(connection, compress)
- {
- cb.setConnection(connection, compress);
- }).exception(
- function(ex)
- {
- cb.setException(ex);
- });
+ connection => cb.setConnection(connection)).catch(ex => cb.setException(ex));
}
else
{
@@ -2343,36 +2305,29 @@ var RoutableReference = Class(Reference, {
// create a new connection even if there's an existing
// connection for one of the endpoints.
//
- var v = [ endpoints[0] ];
- cb = new CreateConnectionCallback(this, endpoints, promise);
- factory.create(v, true, this.getEndpointSelection()).then(
- function(connection, compress)
- {
- cb.setConnection(connection, compress);
- }).exception(
- function(ex)
- {
- cb.setException(ex);
- });
+ const cb = new CreateConnectionCallback(this, endpoints, promise);
+ factory.create([ endpoints[0] ], true, this.getEndpointSelection()).then(
+ connection => cb.setConnection(connection)).catch(ex => cb.setException(ex));
}
-
return promise;
}
-});
+}
Ice.RoutableReference = RoutableReference;
module.exports.Ice = Ice;
-var CreateConnectionCallback = Class({
- __init__: function(r, endpoints, promise)
+class CreateConnectionCallback
+{
+ constructor(r, endpoints, promise)
{
this.ref = r;
this.endpoints = endpoints;
this.promise = promise;
this.i = 0;
this.exception = null;
- },
- setConnection: function(connection, compress)
+ }
+
+ setConnection(connection)
{
//
// If we have a router, set the object adapter for this router
@@ -2383,9 +2338,10 @@ var CreateConnectionCallback = Class({
{
connection.setAdapter(this.ref.getRouterInfo().getAdapter());
}
- this.promise.succeed(connection, compress);
- },
- setException: function(ex)
+ this.promise.resolve(connection);
+ }
+
+ setException(ex)
{
if(this.exception === null)
{
@@ -2394,21 +2350,14 @@ var CreateConnectionCallback = Class({
if(this.endpoints === null || ++this.i === this.endpoints.length)
{
- this.promise.fail(this.exception);
+ this.promise.reject(this.exception);
return;
}
- var more = this.i != this.endpoints.length - 1;
- var arr = [ this.endpoints[this.i] ];
- var self = this;
- this.ref.getInstance().outgoingConnectionFactory().create(arr, more, this.ref.getEndpointSelection()).then(
- function(connection, compress)
- {
- self.setConnection(connection, compress);
- }).exception(
- function(ex)
- {
- self.setException(ex);
- });
+ this.ref.getInstance().outgoingConnectionFactory().create(
+ [ this.endpoints[this.i] ],
+ this.i != this.endpoints.length - 1,
+ this.ref.getEndpointSelection()).then(connection => this.setConnection(connection))
+ .catch(ex => this.setException(ex));
}
-});
+}
diff --git a/js/src/Ice/ReferenceMode.js b/js/src/Ice/ReferenceMode.js
index a57300d4ac9..79d3b439a36 100644
--- a/js/src/Ice/ReferenceMode.js
+++ b/js/src/Ice/ReferenceMode.js
@@ -7,7 +7,7 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
+const Ice = require("../Ice/ModuleRegistry").Ice;
//
// Using a separate module for these constants so that ObjectPrx does
diff --git a/js/src/Ice/RequestHandlerFactory.js b/js/src/Ice/RequestHandlerFactory.js
index b0f9215eb0d..65f5b44d92b 100644
--- a/js/src/Ice/RequestHandlerFactory.js
+++ b/js/src/Ice/RequestHandlerFactory.js
@@ -7,30 +7,31 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/Debug",
"../Ice/HashMap",
"../Ice/Reference",
"../Ice/ConnectRequestHandler"
]);
-var Debug = Ice.Debug;
-var HashMap = Ice.HashMap;
-var ConnectRequestHandler = Ice.ConnectRequestHandler;
+const Debug = Ice.Debug;
+const HashMap = Ice.HashMap;
+const ConnectRequestHandler = Ice.ConnectRequestHandler;
-var RequestHandlerFactory = Ice.Class({
- __init__: function(instance)
+class RequestHandlerFactory
+{
+ constructor(instance)
{
this._instance = instance;
this._handlers = new HashMap(HashMap.compareEquals);
- },
- getRequestHandler: function(ref, proxy)
+ }
+
+ getRequestHandler(ref, proxy)
{
- var connect = false;
- var handler;
+ let connect = false;
+ let handler;
if(ref.getCacheConnection())
{
handler = this._handlers.get(ref);
@@ -49,18 +50,19 @@ var RequestHandlerFactory = Ice.Class({
if(connect)
{
- ref.getConnection().then(function(connection, compress)
+ ref.getConnection().then(connection =>
{
- handler.setConnection(connection, compress);
+ handler.setConnection(connection);
},
- function(ex)
+ ex =>
{
handler.setException(ex);
});
}
- return proxy.__setRequestHandler(handler.connect(proxy));
- },
- removeRequestHandler: function(ref, handler)
+ return proxy._setRequestHandler(handler.connect(proxy));
+ }
+
+ removeRequestHandler(ref, handler)
{
if(ref.getCacheConnection())
{
@@ -70,7 +72,7 @@ var RequestHandlerFactory = Ice.Class({
}
}
}
-});
+}
Ice.RequestHandlerFactory = RequestHandlerFactory;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/RetryException.js b/js/src/Ice/RetryException.js
index 89be13b8b0b..35b76eac103 100644
--- a/js/src/Ice/RetryException.js
+++ b/js/src/Ice/RetryException.js
@@ -7,12 +7,14 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Class", "../Ice/Exception", "../Ice/Debug", "../Ice/LocalException"]);
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module, ["../Ice/Debug", "../Ice/LocalException"]);
-var RetryException = Ice.Class(Error, {
- __init__: function(ex)
+class RetryException extends Error
+{
+ constructor(ex)
{
+ super();
if(ex instanceof Ice.LocalException)
{
this._ex = ex;
@@ -23,13 +25,12 @@ var RetryException = Ice.Class(Error, {
this._ex = ex._ex;
}
}
-});
-
-var prototype = RetryException.prototype;
-
-Object.defineProperty(prototype, "inner", {
- get: function() { return this._ex; }
-});
+
+ get inner()
+ {
+ return this._ex;
+ }
+}
Ice.RetryException = RetryException;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/RetryQueue.js b/js/src/Ice/RetryQueue.js
index d028cd06331..d1ba9ef8d14 100644
--- a/js/src/Ice/RetryQueue.js
+++ b/js/src/Ice/RetryQueue.js
@@ -7,52 +7,93 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Class", "../Ice/LocalException"]);
+const Ice = require("../Ice/LocalException").Ice;
-var Class = Ice.Class;
+class RetryTask
+{
+ constructor(instance, queue, outAsync, interval)
+ {
+ this._instance = instance;
+ this._queue = queue;
+ this._outAsync = outAsync;
+ }
+
+ run()
+ {
+ this._outAsync.retry();
+ this._queue.remove(this);
+ }
-var RetryQueue = Class({
- __init__: function(instance)
+ destroy()
+ {
+ try
+ {
+ this._outAsync.abort(new Ice.CommunicatorDestroyedException());
+ }
+ catch(ex)
+ {
+ // Abort shouldn't throw if there's no callback, ignore.
+ }
+ }
+
+ asyncRequestCanceled(outAsync, ex)
+ {
+ if(this._queue.cancel(this))
+ {
+ if(this._instance.traceLevels().retry >= 1)
+ {
+ this._instance.initializationData().logger.trace(this._instance.traceLevels().retryCat,
+ "operation retry canceled\n" + ex.toString());
+ }
+ this._outAsync.completedEx(ex);
+ }
+ }
+}
+
+class RetryQueue
+{
+ constructor(instance)
{
this._instance = instance;
this._requests = [];
- },
- add: function(outAsync, interval)
+ }
+
+ add(outAsync, interval)
{
if(this._instance === null)
{
throw new Ice.CommunicatorDestroyedException();
}
- var task = new RetryTask(this._instance, this, outAsync);
- outAsync.__cancelable(task); // This will throw if the request is canceled
- task.token = this._instance.timer().schedule(function()
- {
- task.run();
- }, interval);
+ let task = new RetryTask(this._instance, this, outAsync);
+ outAsync.cancelable(task); // This will throw if the request is canceled
+ task.token = this._instance.timer().schedule(() => task.run(), interval);
this._requests.push(task);
- },
- destroy: function()
+ }
+
+ destroy()
{
- for(var i = 0; i < this._requests.length; ++i)
- {
- this._instance.timer().cancel(this._requests[i].token);
- this._requests[i].destroy();
- }
+ this._requests.forEach(request =>
+ {
+ this._instance.timer().cancel(request.token);
+ request.destroy();
+ });
+
this._requests = [];
this._instance = null;
- },
- remove: function(task)
+ }
+
+ remove(task)
{
- var idx = this._requests.indexOf(task);
+ const idx = this._requests.indexOf(task);
if(idx >= 0)
{
this._requests.splice(idx, 1);
}
- },
- cancel: function(task)
+ }
+
+ cancel(task)
{
- var idx = this._requests.indexOf(task);
+ const idx = this._requests.indexOf(task);
if(idx >= 0)
{
this._requests.splice(idx, 1);
@@ -60,43 +101,7 @@ var RetryQueue = Class({
}
return false;
}
-});
+}
Ice.RetryQueue = RetryQueue;
-var RetryTask = Class({
- __init__: function(instance, queue, outAsync, interval)
- {
- this._instance = instance;
- this._queue = queue;
- this._outAsync = outAsync;
- },
- run: function()
- {
- this._outAsync.__retry();
- this._queue.remove(this);
- },
- destroy: function()
- {
- try
- {
- this._outAsync.__abort(new Ice.CommunicatorDestroyedException());
- }
- catch(ex)
- {
- // Abort shouldn't throw if there's no callback, ignore.
- }
- },
- asyncRequestCanceled: function(outAsync, ex)
- {
- if(this._queue.cancel(this))
- {
- if(this._instance.traceLevels().retry >= 1)
- {
- this._instance.initializationData().logger.trace(this._instance.traceLevels().retryCat,
- "operation retry canceled\n" + ex.toString());
- }
- this._outAsync.__completedEx(ex);
- }
- }
-});
module.exports.Ice = Ice;
diff --git a/js/src/Ice/RouterInfo.js b/js/src/Ice/RouterInfo.js
index 35d1af71ae5..178c450344d 100644
--- a/js/src/Ice/RouterInfo.js
+++ b/js/src/Ice/RouterInfo.js
@@ -7,10 +7,9 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/ArrayUtil",
"../Ice/Debug",
"../Ice/HashMap",
@@ -19,13 +18,13 @@ Ice.__M.require(module,
"../Ice/Exception"
]);
-var ArrayUtil = Ice.ArrayUtil;
-var Debug = Ice.Debug;
-var HashMap = Ice.HashMap;
-var Promise = Ice.Promise;
+const ArrayUtil = Ice.ArrayUtil;
+const Debug = Ice.Debug;
+const HashMap = Ice.HashMap;
-var RouterInfo = Ice.Class({
- __init__: function(router)
+class RouterInfo
+{
+ constructor(router)
{
this._router = router;
@@ -36,15 +35,17 @@ var RouterInfo = Ice.Class({
this._adapter = null;
this._identities = new HashMap(HashMap.compareEquals); // Set<Identity> = Map<Identity, 1>
this._evictedIdentities = [];
- },
- destroy: function()
+ }
+
+ destroy()
{
this._clientEndpoints = [];
this._serverEndpoints = [];
this._adapter = null;
this._identities.clear();
- },
- equals: function(rhs)
+ }
+
+ equals(rhs)
{
if(this === rhs)
{
@@ -57,59 +58,51 @@ var RouterInfo = Ice.Class({
}
return false;
- },
- hashCode: function()
+ }
+
+ hashCode()
{
return this._router.hashCode();
- },
- getRouter: function()
+ }
+
+ getRouter()
{
//
// No mutex lock necessary, _router is immutable.
//
return this._router;
- },
- getClientEndpoints: function()
+ }
+
+ getClientEndpoints()
{
- var promise = new Promise();
+ const promise = new Ice.Promise();
if(this._clientEndpoints !== null)
{
- promise.succeed(this._clientEndpoints);
+ promise.resolve(this._clientEndpoints);
}
else
{
- var self = this;
- this._router.getClientProxy().then(
- function(clientProxy)
- {
- self.setClientEndpoints(clientProxy, promise);
- }).exception(
- function(ex)
- {
- promise.fail(ex);
- });
+ this._router.getClientProxy().then(proxy => this.setClientEndpoints(proxy, promise)).catch(promise.reject);
}
return promise;
- },
- getServerEndpoints: function()
+ }
+
+
+ getServerEndpoints()
{
if(this._serverEndpoints !== null) // Lazy initialization.
{
- return new Promise().succeed(this._serverEndpoints);
+ return Ice.Promise.resolve(this._serverEndpoints);
}
else
{
- var self = this;
- return this._router.getServerProxy().then(
- function(proxy)
- {
- return self.setServerEndpoints(proxy);
- });
+ return this._router.getServerProxy().then(proxy => this.setServerEndpoints(proxy));
}
- },
- addProxy: function(proxy)
+ }
+
+ addProxy(proxy)
{
Debug.assert(proxy !== null);
@@ -118,31 +111,34 @@ var RouterInfo = Ice.Class({
//
// Only add the proxy to the router if it's not already in our local map.
//
- return new Promise().succeed();
+ return Ice.Promise.resolve();
}
else
{
- var self = this;
return this._router.addProxies([ proxy ]).then(
- function(evictedProxies)
+ evictedProxies =>
{
- self.addAndEvictProxies(proxy, evictedProxies);
+ this.addAndEvictProxies(proxy, evictedProxies);
});
}
- },
- setAdapter: function(adapter)
+ }
+
+ setAdapter(adapter)
{
this._adapter = adapter;
- },
- getAdapter: function()
+ }
+
+ getAdapter()
{
return this._adapter;
- },
- clearCache: function(ref)
+ }
+
+ clearCache(ref)
{
this._identities.delete(ref.getIdentity());
- },
- setClientEndpoints: function(clientProxy, promise)
+ }
+
+ setClientEndpoints(clientProxy, promise)
{
if(this._clientEndpoints === null)
{
@@ -151,8 +147,8 @@ var RouterInfo = Ice.Class({
//
// If getClientProxy() return nil, use router endpoints.
//
- this._clientEndpoints = this._router.__reference().getEndpoints();
- promise.succeed(this._clientEndpoints);
+ this._clientEndpoints = this._router._getReference().getEndpoints();
+ promise.resolve(this._clientEndpoints);
}
else
{
@@ -163,26 +159,21 @@ var RouterInfo = Ice.Class({
// router, we must use the same timeout as the already
// existing connection.
//
- var self = this;
this._router.ice_getConnection().then(
- function(con)
+ con =>
{
- var proxy = clientProxy.ice_timeout(con.timeout());
- self._clientEndpoints = proxy.__reference().getEndpoints();
- promise.succeed(self._clientEndpoints);
- }).exception(
- function(ex)
- {
- promise.fail(ex);
- });
+ this._clientEndpoints = clientProxy.ice_timeout(con.timeout())._getReference().getEndpoints();
+ promise.resolve(this._clientEndpoints);
+ }).catch(promise.reject);
}
}
else
{
- promise.succeed(this._clientEndpoints);
+ promise.resolve(this._clientEndpoints);
}
- },
- setServerEndpoints: function(serverProxy)
+ }
+
+ setServerEndpoints(serverProxy)
{
if(serverProxy === null)
{
@@ -190,18 +181,18 @@ var RouterInfo = Ice.Class({
}
serverProxy = serverProxy.ice_router(null); // The server proxy cannot be routed.
- this._serverEndpoints = serverProxy.__reference().getEndpoints();
+ this._serverEndpoints = serverProxy._getReference().getEndpoints();
return this._serverEndpoints;
- },
- addAndEvictProxies: function(proxy, evictedProxies)
+ }
+
+ addAndEvictProxies(proxy, evictedProxies)
{
//
// Check if the proxy hasn't already been evicted by a
// concurrent addProxies call. If it's the case, don't
// add it to our local map.
//
- var index = ArrayUtil.indexOf(this._evictedIdentities, proxy.ice_getIdentity(),
- function(i1, i2) { return i1.equals(i2); });
+ const index = this._evictedIdentities.findIndex(e => e.equals(proxy.ice_getIdentity()));
if(index >= 0)
{
this._evictedIdentities.splice(index, 1);
@@ -218,12 +209,12 @@ var RouterInfo = Ice.Class({
//
// We also must remove whatever proxies the router evicted.
//
- for(var i = 0; i < evictedProxies.length; ++i)
- {
- this._identities.delete(evictedProxies[i].ice_getIdentity());
- }
+ evictedProxies.forEach(proxy =>
+ {
+ this._identities.delete(proxy.ice_getIdentity());
+ });
}
-});
+}
Ice.RouterInfo = RouterInfo;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/RouterManager.js b/js/src/Ice/RouterManager.js
index c5540291a86..c40e08d698a 100644
--- a/js/src/Ice/RouterManager.js
+++ b/js/src/Ice/RouterManager.js
@@ -7,31 +7,34 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Class", "../Ice/HashMap", "../Ice/RouterInfo", "../Ice/Router"]);
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module, ["../Ice/HashMap", "../Ice/RouterInfo", "../Ice/Router"]);
-var HashMap = Ice.HashMap;
-var RouterInfo = Ice.RouterInfo;
-var RouterPrx = Ice.RouterPrx;
+const HashMap = Ice.HashMap;
+const RouterInfo = Ice.RouterInfo;
+const RouterPrx = Ice.RouterPrx;
-var RouterManager = Ice.Class({
- __init__: function()
+class RouterManager
+{
+ constructor()
{
this._table = new HashMap(HashMap.compareEquals); // Map<Ice.RouterPrx, RouterInfo>
- },
- destroy: function()
+ }
+
+ destroy()
{
- for(var e = this._table.entries; e !== null; e = e.next)
+ for(let router of this._table.values())
{
- e.value.destroy();
+ router.destroy();
}
this._table.clear();
- },
+ }
+
//
// Returns router info for a given router. Automatically creates
// the router info if it doesn't exist yet.
//
- find: function(rtr)
+ find(rtr)
{
if(rtr === null)
{
@@ -41,9 +44,9 @@ var RouterManager = Ice.Class({
//
// The router cannot be routed.
//
- var router = RouterPrx.uncheckedCast(rtr.ice_router(null));
+ const router = RouterPrx.uncheckedCast(rtr.ice_router(null));
- var info = this._table.get(router);
+ let info = this._table.get(router);
if(info === undefined)
{
info = new RouterInfo(router);
@@ -51,20 +54,21 @@ var RouterManager = Ice.Class({
}
return info;
- },
- erase: function(rtr)
+ }
+
+ erase(rtr)
{
- var info = null;
+ let info = null;
if(rtr !== null)
{
// The router cannot be routed.
- var router = RouterPrx.uncheckedCast(rtr.ice_router(null));
+ let router = RouterPrx.uncheckedCast(rtr.ice_router(null));
info = this._table.get(router);
this._table.delete(router);
}
return info;
}
-});
+}
Ice.RouterManager = RouterManager;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/ServantManager.js b/js/src/Ice/ServantManager.js
index fad025b05f0..ff59dd7e8a8 100644
--- a/js/src/Ice/ServantManager.js
+++ b/js/src/Ice/ServantManager.js
@@ -7,33 +7,35 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/Debug",
- "../Ice/HashMap",
"../Ice/LocalException",
- "../Ice/StringUtil"
+ "../Ice/StringUtil",
+ "../Ice/IdentityUtil",
+ "../Ice/HashMap"
]);
-var Debug = Ice.Debug;
-var HashMap = Ice.HashMap;
-var StringUtil = Ice.StringUtil;
+const Debug = Ice.Debug;
+const StringUtil = Ice.StringUtil;
+const HashMap = Ice.HashMap;
//
// Only for use by Ice.ObjectAdatperI.
//
-var ServantManager = Ice.Class({
- __init__: function(instance, adapterName)
+class ServantManager
+{
+ constructor(instance, adapterName)
{
this._instance = instance;
this._adapterName = adapterName;
- this._servantMapMap = new HashMap(HashMap.compareEquals); // Map<Ice.Identity, Map<String, Ice.Object> >
- this._defaultServantMap = new HashMap(); // Map<String, Ice.Object>
- this._locatorMap = new HashMap(); // Map<String, Ice.ServantLocator>
- },
- addServant: function(servant, ident, facet)
+ this._servantMapMap = new HashMap(HashMap.compareEquals); // Map<Ice.Identity, Map<String, Ice.Object> >
+ this._defaultServantMap = new Map(); // Map<String, Ice.Object>
+ this._locatorMap = new Map(); // Map<String, Ice.ServantLocator>
+ }
+
+ addServant(servant, ident, facet)
{
Debug.assert(this._instance !== null); // Must not be called after destruction.
@@ -42,45 +44,46 @@ var ServantManager = Ice.Class({
facet = "";
}
- var m = this._servantMapMap.get(ident);
+ let m = this._servantMapMap.get(ident);
if(m === undefined)
{
- m = new HashMap();
+ m = new Map();
this._servantMapMap.set(ident, m);
}
else
{
if(m.has(facet))
{
- var ex = new Ice.AlreadyRegisteredException();
- ex.id = this._instance.identityToString(ident);
+ const ex = new Ice.AlreadyRegisteredException();
+ ex.id = Ice.identityToString(ident, this._instance.toStringMode());
ex.kindOfObject = "servant";
if(facet.length > 0)
{
- ex.id += " -f " + StringUtil.escapeString(facet, "");
+ ex.id += " -f " + StringUtil.escapeString(facet, "", this._instance.toStringMode());
}
throw ex;
}
}
m.set(facet, servant);
- },
- addDefaultServant: function(servant, category)
+ }
+
+ addDefaultServant(servant, category)
{
Debug.assert(this._instance !== null); // Must not be called after destruction
- var obj = this._defaultServantMap.get(category);
- if(obj !== undefined)
+ if(this._defaultServantMap.has(category))
{
- var ex = new Ice.AlreadyRegisteredException();
+ const ex = new Ice.AlreadyRegisteredException();
ex.kindOfObject = "default servant";
ex.id = category;
throw ex;
}
this._defaultServantMap.set(category, servant);
- },
- removeServant: function(ident, facet)
+ }
+
+ removeServant(ident, facet)
{
Debug.assert(this._instance !== null); // Must not be called after destruction.
@@ -89,20 +92,20 @@ var ServantManager = Ice.Class({
facet = "";
}
- var m = this._servantMapMap.get(ident);
+ const m = this._servantMapMap.get(ident);
if(m === undefined || !m.has(facet))
{
- var ex = new Ice.NotRegisteredException();
- ex.id = this._instance.identityToString(ident);
+ const ex = new Ice.NotRegisteredException();
+ ex.id = Ice.identityToString(ident, this._instance.toStringMode());
ex.kindOfObject = "servant";
if(facet.length > 0)
{
- ex.id += " -f " + StringUtil.escapeString(facet, "");
+ ex.id += " -f " + StringUtil.escapeString(facet, "", this._instance.toStringMode());
}
throw ex;
}
- var obj = m.get(facet);
+ const obj = m.get(facet);
m.delete(facet);
if(m.size === 0)
@@ -111,15 +114,16 @@ var ServantManager = Ice.Class({
}
return obj;
- },
- removeDefaultServant: function(category)
+ }
+
+ removeDefaultServant(category)
{
Debug.assert(this._instance !== null); // Must not be called after destruction.
- var obj = this._defaultServantMap.get(category);
+ const obj = this._defaultServantMap.get(category);
if(obj === undefined)
{
- var ex = new Ice.NotRegisteredException();
+ const ex = new Ice.NotRegisteredException();
ex.kindOfObject = "default servant";
ex.id = category;
throw ex;
@@ -127,16 +131,17 @@ var ServantManager = Ice.Class({
this._defaultServantMap.delete(category);
return obj;
- },
- removeAllFacets: function(ident)
+ }
+
+ removeAllFacets(ident)
{
Debug.assert(this._instance !== null); // Must not be called after destruction.
- var m = this._servantMapMap.get(ident);
+ const m = this._servantMapMap.get(ident);
if(m === undefined)
{
- var ex = new Ice.NotRegisteredException();
- ex.id = this._instance.identityToString(ident);
+ const ex = new Ice.NotRegisteredException();
+ ex.id = Ice.identityToString(ident, this._instance.toStringMode());
ex.kindOfObject = "servant";
throw ex;
}
@@ -144,8 +149,9 @@ var ServantManager = Ice.Class({
this._servantMapMap.delete(ident);
return m;
- },
- findServant: function(ident, facet)
+ }
+
+ findServant(ident, facet)
{
//
// This assert is not valid if the adapter dispatch incoming
@@ -160,8 +166,8 @@ var ServantManager = Ice.Class({
facet = "";
}
- var m = this._servantMapMap.get(ident);
- var obj = null;
+ const m = this._servantMapMap.get(ident);
+ let obj = null;
if(m === undefined)
{
obj = this._defaultServantMap.get(ident.category);
@@ -176,27 +182,30 @@ var ServantManager = Ice.Class({
}
return obj === undefined ? null : obj;
- },
- findDefaultServant: function(category)
+ }
+
+ findDefaultServant(category)
{
Debug.assert(this._instance !== null); // Must not be called after destruction.
- var ds = this._defaultServantMap.get(category);
+ const ds = this._defaultServantMap.get(category);
return ds === undefined ? null : ds;
- },
- findAllFacets: function(ident)
+ }
+
+ findAllFacets(ident)
{
Debug.assert(this._instance !== null); // Must not be called after destruction.
- var m = this._servantMapMap.get(ident);
+ const m = this._servantMapMap.get(ident);
if(m !== undefined)
{
- return m.clone();
+ return new Map(m);
}
- return new HashMap();
- },
- hasServant: function(ident)
+ return new Map();
+ }
+
+ hasServant(ident)
{
//
// This assert is not valid if the adapter dispatch incoming
@@ -206,7 +215,7 @@ var ServantManager = Ice.Class({
//
//Debug.assert(this._instance !== null); // Must not be called after destruction.
- var m = this._servantMapMap.get(ident);
+ const m = this._servantMapMap.get(ident);
if(m === undefined)
{
return false;
@@ -216,38 +225,40 @@ var ServantManager = Ice.Class({
Debug.assert(m.size > 0);
return true;
}
- },
- addServantLocator: function(locator, category)
+ }
+
+ addServantLocator(locator, category)
{
Debug.assert(this._instance !== null); // Must not be called after destruction.
- var l = this._locatorMap.get(category);
- if(l !== undefined)
+ if(this._locatorMap.has(category))
{
- var ex = new Ice.AlreadyRegisteredException();
- ex.id = StringUtil.escapeString(category, "");
+ const ex = new Ice.AlreadyRegisteredException();
+ ex.id = StringUtil.escapeString(category, "", this._instance.toStringMode());
ex.kindOfObject = "servant locator";
throw ex;
}
this._locatorMap.set(category, locator);
- },
- removeServantLocator: function(category)
+ }
+
+ removeServantLocator(category)
{
Debug.assert(this._instance !== null); // Must not be called after destruction.
- var l = this._locatorMap.get(category);
+ const l = this._locatorMap.get(category);
if(l === undefined)
{
- var ex = new Ice.NotRegisteredException();
- ex.id = StringUtil.escapeString(category, "");
+ const ex = new Ice.NotRegisteredException();
+ ex.id = StringUtil.escapeString(category, "", this._instance.toStringMode());
ex.kindOfObject = "servant locator";
throw ex;
}
this._locatorMap.delete(category);
return l;
- },
- findServantLocator: function(category)
+ }
+
+ findServantLocator(category)
{
//
// This assert is not valid if the adapter dispatch incoming
@@ -257,40 +268,40 @@ var ServantManager = Ice.Class({
//
//Debug.assert(this._instance !== null); // Must not be called after destruction.
- var l = this._locatorMap.get(category);
+ const l = this._locatorMap.get(category);
return l === undefined ? null : l;
- },
+ }
+
//
// Only for use by Ice.ObjectAdapterI.
//
- destroy: function()
+ destroy()
{
Debug.assert(this._instance !== null); // Must not be called after destruction.
- var logger = this._instance.initializationData().logger;
+ const logger = this._instance.initializationData().logger;
this._servantMapMap.clear();
this._defaultServantMap.clear();
- var locatorMap = this._locatorMap.clone();
+ const locatorMap = new Map(this._locatorMap);
this._locatorMap.clear();
this._instance = null;
- for(var e = locatorMap.entries; e !== null; e = e.next)
+ for(let [key, locator] of locatorMap)
{
- var locator = e.value;
try
{
- locator.deactivate(e.key);
+ locator.deactivate(key);
}
catch(ex)
{
- var s = "exception during locator deactivation:\n" + "object adapter: `" + this._adapterName +
- "'\n" + "locator category: `" + e.key + "'\n" + ex.toString();
- logger.error(s);
+ logger.error("exception during locator deactivation:\nobject adapter: `" +
+ this._adapterName + "'\nlocator category: `" + key + "'\n" +
+ ex.toString());
}
}
}
-});
+}
Ice.ServantManager = ServantManager;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/SocketOperation.js b/js/src/Ice/SocketOperation.js
index 546f98906c9..2c4543d2006 100644
--- a/js/src/Ice/SocketOperation.js
+++ b/js/src/Ice/SocketOperation.js
@@ -7,7 +7,7 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
+const Ice = require("../Ice/ModuleRegistry").Ice;
Ice.SocketOperation =
{
None: 0,
diff --git a/js/src/Ice/Stream.js b/js/src/Ice/Stream.js
new file mode 100644
index 00000000000..6dc5c613d7d
--- /dev/null
+++ b/js/src/Ice/Stream.js
@@ -0,0 +1,3515 @@
+// **********************************************************************
+//
+// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
+//
+// This copy of Ice is licensed to you under the terms described in the
+// ICE_LICENSE file included in this distribution.
+//
+// **********************************************************************
+
+const Ice = require("../Ice/ModuleRegistry").Ice;
+const _ModuleRegistry = Ice._ModuleRegistry;
+_ModuleRegistry.require(module,
+ [
+ "../Ice/Debug",
+ "../Ice/ExUtil",
+ "../Ice/FormatType",
+ "../Ice/Object",
+ "../Ice/Value",
+ "../Ice/OptionalFormat",
+ "../Ice/Protocol",
+ "../Ice/TraceUtil",
+ "../Ice/Buffer",
+ "../Ice/Exception",
+ "../Ice/LocalException",
+ "../Ice/Version",
+ "../Ice/CompactIdRegistry",
+ "../Ice/ArrayUtil",
+ "../Ice/UnknownSlicedValue"
+ ]);
+
+const Debug = Ice.Debug;
+const ExUtil = Ice.ExUtil;
+const FormatType = Ice.FormatType;
+const OptionalFormat = Ice.OptionalFormat;
+const Protocol = Ice.Protocol;
+const TraceUtil = Ice.TraceUtil;
+const ArrayUtil = Ice.ArrayUtil;
+const SlicedData = Ice.SlicedData;
+
+const SliceType =
+{
+ NoSlice: 0,
+ ValueSlice: 1,
+ ExceptionSlice: 2
+};
+
+//
+// Number.isNaN polyfill for compatibility with IE
+//
+// see: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
+//
+Number.isNaN = Number.isNaN || function(value)
+{
+ return typeof value === "number" && isNaN(value);
+};
+
+//
+// InputStream
+//
+
+class IndirectPatchEntry
+{
+ constructor(index, cb)
+ {
+ this.index = index;
+ this.cb = cb;
+ }
+}
+
+class EncapsDecoder
+{
+ constructor(stream, encaps, sliceValues, f)
+ {
+ this._stream = stream;
+ this._encaps = encaps;
+ this._sliceValues = sliceValues;
+ this._valueFactoryManager = f;
+ this._patchMap = null; // Lazy initialized, Map<int, Patcher[] >()
+ this._unmarshaledMap = new Map(); // Map<int, Ice.Value>()
+ this._typeIdMap = null; // Lazy initialized, Map<int, String>
+ this._typeIdIndex = 0;
+ this._valueList = null; // Lazy initialized. Ice.Value[]
+ }
+
+ readOptional()
+ {
+ return false;
+ }
+
+ readPendingValues()
+ {
+ }
+
+ readTypeId(isIndex)
+ {
+ if(this._typeIdMap === null) // Lazy initialization
+ {
+ this._typeIdMap = new Map(); // Map<int, String>();
+ }
+
+ let typeId;
+ if(isIndex)
+ {
+ typeId = this._typeIdMap.get(this._stream.readSize());
+ if(typeId === undefined)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+ else
+ {
+ typeId = this._stream.readString();
+ this._typeIdMap.set(++this._typeIdIndex, typeId);
+ }
+ return typeId;
+ }
+
+ newInstance(typeId)
+ {
+ //
+ // Try to find a factory registered for the specific type.
+ //
+ let userFactory = this._valueFactoryManager.find(typeId);
+ let v = null;
+
+ if(userFactory !== undefined)
+ {
+ v = userFactory(typeId);
+ }
+
+ //
+ // If that fails, invoke the default factory if one has been
+ // registered.
+ //
+ if(v === null || v === undefined)
+ {
+ userFactory = this._valueFactoryManager.find("");
+ if(userFactory !== undefined)
+ {
+ v = userFactory(typeId);
+ }
+ }
+
+ //
+ // Last chance: try to instantiate the class dynamically.
+ //
+ if(v === null || v === undefined)
+ {
+ v = this._stream.createInstance(typeId);
+ }
+
+ return v;
+ }
+
+ addPatchEntry(index, cb)
+ {
+ Debug.assert(index > 0);
+
+ //
+ // Check if we have already unmarshaled the instance. If that's the case,
+ // just call the callback and we're done.
+ //
+ const obj = this._unmarshaledMap.get(index);
+ if(obj !== undefined && obj !== null)
+ {
+ cb.call(null, obj);
+ return;
+ }
+
+ if(this._patchMap === null) // Lazy initialization
+ {
+ this._patchMap = new Map(); // Map<Integer, Patcher[] >();
+ }
+
+ //
+ // Add a patch entry if the instance isn't unmarshaled yet,
+ // the callback will be called when the instance is
+ // unmarshaled.
+ //
+ let l = this._patchMap.get(index);
+ if(l === undefined)
+ {
+ //
+ // We have no outstanding instances to be patched for this
+ // index, so make a new entry in the patch map.
+ //
+ l = []; // ReadValueCallback[]
+ this._patchMap.set(index, l);
+ }
+
+ //
+ // Append a patch entry for this instance.
+ //
+ l.push(cb);
+ }
+
+ unmarshal(index, v)
+ {
+ //
+ // Add the instance to the map of unmarshaled instances, this must
+ // be done before reading the instances (for circular references).
+ //
+ this._unmarshaledMap.set(index, v);
+
+ //
+ // Read the instance.
+ //
+ v._iceRead(this._stream);
+
+ if(this._patchMap !== null)
+ {
+ //
+ // Patch all instances now that the instance is unmarshaled.
+ //
+ const l = this._patchMap.get(index);
+ if(l !== undefined)
+ {
+ Debug.assert(l.length > 0);
+
+ //
+ // Patch all pointers that refer to the instance.
+ //
+ for(let i = 0; i < l.length; ++i)
+ {
+ l[i](v);
+ }
+
+ //
+ // Clear out the patch map for that index -- there is nothing left
+ // to patch for that index for the time being.
+ //
+ this._patchMap.delete(index);
+ }
+ }
+
+ if((this._patchMap === null || this._patchMap.size === 0) && this._valueList === null)
+ {
+ try
+ {
+ v.ice_postUnmarshal();
+ }
+ catch(ex)
+ {
+ this._stream.instance.initializationData().logger.warning("exception raised by ice_postUnmarshal:\n" +
+ ex.toString());
+ }
+ }
+ else
+ {
+ if(this._valueList === null) // Lazy initialization
+ {
+ this._valueList = []; // Ice.Value[]
+ }
+ this._valueList.push(v);
+
+ if(this._patchMap === null || this._patchMap.size === 0)
+ {
+ //
+ // Iterate over the instance list and invoke ice_postUnmarshal on
+ // each instance. We must do this after all instances have been
+ // unmarshaled in order to ensure that any instance data members
+ // have been properly patched.
+ //
+ for(let i = 0; i < this._valueList.length; i++)
+ {
+ try
+ {
+ this._valueList[i].ice_postUnmarshal();
+ }
+ catch(ex)
+ {
+ this._stream.instance.initializationData().logger.warning(
+ "exception raised by ice_postUnmarshal:\n" + ex.toString());
+ }
+ }
+ this._valueList = [];
+ }
+ }
+ }
+}
+
+class EncapsDecoder10 extends EncapsDecoder
+{
+ constructor(stream, encaps, sliceValues, f)
+ {
+ super(stream, encaps, sliceValues, f);
+ this._sliceType = SliceType.NoSlice;
+ }
+
+ readValue(cb)
+ {
+ Debug.assert(cb !== null);
+
+ //
+ // Instance references are encoded as a negative integer in 1.0.
+ //
+ let index = this._stream.readInt();
+ if(index > 0)
+ {
+ throw new Ice.MarshalException("invalid object id");
+ }
+ index = -index;
+
+ if(index === 0)
+ {
+ cb.call(null, null);
+ }
+ else
+ {
+ this.addPatchEntry(index, cb);
+ }
+ }
+
+ throwException()
+ {
+ Debug.assert(this._sliceType === SliceType.NoSlice);
+
+ //
+ // User exceptions with the 1.0 encoding start with a boolean flag
+ // that indicates whether or not the exception has classes.
+ //
+ // This allows reading the pending instances even if some part of
+ // the exception was sliced.
+ //
+ const usesClasses = this._stream.readBool();
+
+ this._sliceType = SliceType.ExceptionSlice;
+ this._skipFirstSlice = false;
+
+ //
+ // Read the first slice header.
+ //
+ this.startSlice();
+ const mostDerivedId = this._typeId;
+ while(true)
+ {
+ const userEx = this._stream.createUserException(this._typeId);
+
+ //
+ // We found the exception.
+ //
+ if(userEx !== null)
+ {
+ userEx._read(this._stream);
+ if(usesClasses)
+ {
+ this.readPendingValues();
+ }
+ throw userEx;
+
+ // Never reached.
+ }
+
+ //
+ // Slice off what we don't understand.
+ //
+ this.skipSlice();
+ try
+ {
+ this.startSlice();
+ }
+ catch(ex)
+ {
+ //
+ // An oversight in the 1.0 encoding means there is no marker to indicate
+ // the last slice of an exception. As a result, we just try to read the
+ // next type ID, which raises UnmarshalOutOfBoundsException when the
+ // input buffer underflows.
+ //
+ // Set the reason member to a more helpful message.
+ //
+ if(ex instanceof Ice.UnmarshalOutOfBoundsException)
+ {
+ ex.reason = "unknown exception type `" + mostDerivedId + "'";
+ }
+ throw ex;
+ }
+ }
+ }
+
+ startInstance(sliceType)
+ {
+ Debug.assert(this._sliceType === sliceType);
+ this._skipFirstSlice = true;
+ }
+
+ endInstance(/*preserve*/)
+ {
+ //
+ // Read the Ice::Object slice.
+ //
+ if(this._sliceType === SliceType.ValueSlice)
+ {
+ this.startSlice();
+ let sz = this._stream.readSize(); // For compatibility with the old AFM.
+ if(sz !== 0)
+ {
+ throw new Ice.MarshalException("invalid Object slice");
+ }
+ this.endSlice();
+ }
+
+ this._sliceType = SliceType.NoSlice;
+ return null;
+ }
+
+ startSlice()
+ {
+ //
+ // If first slice, don't read the header, it was already read in
+ // readInstance or throwException to find the factory.
+ //
+ if(this._skipFirstSlice)
+ {
+ this._skipFirstSlice = false;
+ return this._typeId;
+ }
+
+ //
+ // For instances, first read the type ID boolean which indicates
+ // whether or not the type ID is encoded as a string or as an
+ // index. For exceptions, the type ID is always encoded as a
+ // string.
+ //
+ if(this._sliceType === SliceType.ValueSlice) // For exceptions, the type ID is always encoded as a string
+ {
+ let isIndex = this._stream.readBool();
+ this._typeId = this.readTypeId(isIndex);
+ }
+ else
+ {
+ this._typeId = this._stream.readString();
+ }
+
+ this._sliceSize = this._stream.readInt();
+ if(this._sliceSize < 4)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+
+ return this._typeId;
+ }
+
+ endSlice()
+ {
+ }
+
+ skipSlice()
+ {
+ this._stream.traceSkipSlice(this._typeId, this._sliceType);
+ Debug.assert(this._sliceSize >= 4);
+ this._stream.skip(this._sliceSize - 4);
+ }
+
+ readPendingValues()
+ {
+ let num;
+ do
+ {
+ num = this._stream.readSize();
+ for(let k = num; k > 0; --k)
+ {
+ this.readInstance();
+ }
+ }
+ while(num > 0);
+
+ if(this._patchMap !== null && this._patchMap.size !== 0)
+ {
+ //
+ // If any entries remain in the patch map, the sender has sent an index for an instance, but failed
+ // to supply the instance.
+ //
+ throw new Ice.MarshalException("index for class received, but no instance");
+ }
+ }
+
+ readInstance()
+ {
+ let index = this._stream.readInt();
+ let v = null;
+
+ if(index <= 0)
+ {
+ throw new Ice.MarshalException("invalid object id");
+ }
+
+ this._sliceType = SliceType.ValueSlice;
+ this._skipFirstSlice = false;
+
+ //
+ // Read the first slice header.
+ //
+ this.startSlice();
+ const mostDerivedId = this._typeId;
+ while(true)
+ {
+ //
+ // For the 1.0 encoding, the type ID for the base Object class
+ // marks the last slice.
+ //
+ if(this._typeId == Ice.Value.ice_staticId())
+ {
+ throw new Ice.NoValueFactoryException("", mostDerivedId);
+ }
+
+ v = this.newInstance(this._typeId);
+
+ //
+ // We found a factory, we get out of this loop.
+ //
+ if(v)
+ {
+ break;
+ }
+
+ //
+ // If slicing is disabled, stop unmarshaling.
+ //
+ if(!this._sliceValues)
+ {
+ throw new Ice.NoValueFactoryException("no value factory found and slicing is disabled",
+ this._typeId);
+ }
+
+ //
+ // Slice off what we don't understand.
+ //
+ this.skipSlice();
+ this.startSlice(); // Read next Slice header for next iteration.
+ }
+
+ //
+ // Unmarshal the instance and add it to the map of unmarshaled instances.
+ //
+ this.unmarshal(index, v);
+ }
+}
+
+class EncapsDecoder11 extends EncapsDecoder
+{
+ constructor(stream, encaps, sliceValues, f, r)
+ {
+ super(stream, encaps, sliceValues, f);
+ this._compactIdResolver = r;
+ this._current = null;
+ this._valueIdIndex = 1;
+ }
+
+ readValue(cb)
+ {
+ const index = this._stream.readSize();
+ if(index < 0)
+ {
+ throw new Ice.MarshalException("invalid object id");
+ }
+ else if(index === 0)
+ {
+ if(cb !== null)
+ {
+ cb.call(null, null);
+ }
+ }
+ else if(this._current !== null && (this._current.sliceFlags & Protocol.FLAG_HAS_INDIRECTION_TABLE) !== 0)
+ {
+ //
+ // When reading an instance within a slice and there's an
+ // indirect instance table, always read an indirect reference
+ // that points to an instance from the indirect instance table
+ // marshaled at the end of the Slice.
+ //
+ // Maintain a list of indirect references. Note that the
+ // indirect index starts at 1, so we decrement it by one to
+ // derive an index into the indirection table that we'll read
+ // at the end of the slice.
+ //
+ if(cb !== null)
+ {
+ if(this._current.indirectPatchList === null) // Lazy initialization
+ {
+ this._current.indirectPatchList = []; // IndirectPatchEntry[]
+ }
+ this._current.indirectPatchList.push(new IndirectPatchEntry(index - 1, cb));
+ }
+ }
+ else
+ {
+ this.readInstance(index, cb);
+ }
+ }
+
+ throwException()
+ {
+ Debug.assert(this._current === null);
+
+ this.push(SliceType.ExceptionSlice);
+
+ //
+ // Read the first slice header.
+ //
+ this.startSlice();
+ const mostDerivedId = this._current.typeId;
+ while(true)
+ {
+
+ const userEx = this._stream.createUserException(this._current.typeId);
+
+ //
+ // We found the exception.
+ //
+ if(userEx !== null)
+ {
+ userEx._read(this._stream);
+ throw userEx;
+
+ // Never reached.
+ }
+
+ //
+ // Slice off what we don't understand.
+ //
+ this.skipSlice();
+
+ if((this._current.sliceFlags & Protocol.FLAG_IS_LAST_SLICE) !== 0)
+ {
+ if(mostDerivedId.indexOf("::") === 0)
+ {
+ throw new Ice.UnknownUserException(mostDerivedId.substr(2));
+ }
+ throw new Ice.UnknownUserException(mostDerivedId);
+ }
+
+ this.startSlice();
+ }
+ }
+
+ startInstance(sliceType)
+ {
+ Debug.assert(sliceType !== undefined);
+ Debug.assert(this._current.sliceType !== null && this._current.sliceType === sliceType);
+ this._current.skipFirstSlice = true;
+ }
+
+ endInstance(preserve)
+ {
+ let slicedData = null;
+ if(preserve)
+ {
+ slicedData = this.readSlicedData();
+ }
+ if(this._current.slices !== null)
+ {
+ this._current.slices.length = 0; // Clear the array.
+ this._current.indirectionTables.length = 0; // Clear the array.
+ }
+ this._current = this._current.previous;
+ return slicedData;
+ }
+
+ startSlice()
+ {
+ //
+ // If first slice, don't read the header, it was already read in
+ // readInstance or throwException to find the factory.
+ //
+ if(this._current.skipFirstSlice)
+ {
+ this._current.skipFirstSlice = false;
+ return this._current.typeId;
+ }
+
+ this._current.sliceFlags = this._stream.readByte();
+
+ //
+ // Read the type ID, for instance slices the type ID is encoded as a
+ // string or as an index, for exceptions it's always encoded as a
+ // string.
+ //
+ if(this._current.sliceType === SliceType.ValueSlice)
+ {
+ if((this._current.sliceFlags & Protocol.FLAG_HAS_TYPE_ID_COMPACT) ===
+ Protocol.FLAG_HAS_TYPE_ID_COMPACT) // Must be checked 1st!
+ {
+ this._current.typeId = "";
+ this._current.compactId = this._stream.readSize();
+ }
+ else if((this._current.sliceFlags & (Protocol.FLAG_HAS_TYPE_ID_INDEX |
+ Protocol.FLAG_HAS_TYPE_ID_STRING)) !== 0)
+ {
+ this._current.typeId =
+ this.readTypeId((this._current.sliceFlags & Protocol.FLAG_HAS_TYPE_ID_INDEX) !== 0);
+ this._current.compactId = -1;
+ }
+ else
+ {
+ //
+ // Only the most derived slice encodes the type ID for the compact format.
+ //
+ this._current.typeId = "";
+ this._current.compactId = -1;
+ }
+ }
+ else
+ {
+ this._current.typeId = this._stream.readString();
+ this._current.compactId = -1;
+ }
+
+ //
+ // Read the slice size if necessary.
+ //
+ if((this._current.sliceFlags & Protocol.FLAG_HAS_SLICE_SIZE) !== 0)
+ {
+ this._current.sliceSize = this._stream.readInt();
+ if(this._current.sliceSize < 4)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+ else
+ {
+ this._current.sliceSize = 0;
+ }
+
+ return this._current.typeId;
+ }
+
+ endSlice()
+ {
+ if((this._current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) !== 0)
+ {
+ this._stream.skipOptionals();
+ }
+
+ //
+ // Read the indirection table if one is present and transform the
+ // indirect patch list into patch entries with direct references.
+ //
+ if((this._current.sliceFlags & Protocol.FLAG_HAS_INDIRECTION_TABLE) !== 0)
+ {
+ let indirectionTable = [];
+ //
+ // The table is written as a sequence<size> to conserve space.
+ //
+ let length = this._stream.readAndCheckSeqSize(1);
+ for(let i = 0; i < length; ++i)
+ {
+ indirectionTable[i] = this.readInstance(this._stream.readSize(), null);
+ }
+
+ //
+ // Sanity checks. If there are optional members, it's possible
+ // that not all instance references were read if they are from
+ // unknown optional data members.
+ //
+ if(indirectionTable.length === 0)
+ {
+ throw new Ice.MarshalException("empty indirection table");
+ }
+ if((this._current.indirectPatchList === null || this._current.indirectPatchList.length === 0) &&
+ (this._current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) === 0)
+ {
+ throw new Ice.MarshalException("no references to indirection table");
+ }
+
+ //
+ // Convert indirect references into direct references.
+ //
+ if(this._current.indirectPatchList !== null)
+ {
+ this._current.indirectPatchList.forEach(e =>
+ {
+ Debug.assert(e.index >= 0);
+ if(e.index >= indirectionTable.length)
+ {
+ throw new Ice.MarshalException("indirection out of range");
+ }
+ this.addPatchEntry(indirectionTable[e.index], e.cb);
+ });
+ this._current.indirectPatchList.length = 0;
+ }
+ }
+ }
+
+ skipSlice()
+ {
+ this._stream.traceSkipSlice(this._current.typeId, this._current.sliceType);
+
+ const start = this._stream.pos;
+
+ if((this._current.sliceFlags & Protocol.FLAG_HAS_SLICE_SIZE) !== 0)
+ {
+ Debug.assert(this._current.sliceSize >= 4);
+ this._stream.skip(this._current.sliceSize - 4);
+ }
+ else
+ {
+ if(this._current.sliceType === SliceType.ValueSlice)
+ {
+ throw new Ice.NoValueFactoryException("no value factory found and compact format prevents slicing " +
+ "(the sender should use the sliced format instead)",
+ this._current.typeId);
+ }
+ else
+ {
+ if(this._current.typeId.indexOf("::") === 0)
+ {
+ throw new Ice.UnknownUserException(this._current.typeId.substring(2));
+ }
+ else
+ {
+ throw new Ice.UnknownUserException(this._current.typeId);
+ }
+ }
+ }
+
+ //
+ // Preserve this slice.
+ //
+ const info = new Ice.SliceInfo();
+ info.typeId = this._current.typeId;
+ info.compactId = this._current.compactId;
+ info.hasOptionalMembers = (this._current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) !== 0;
+ info.isLastSlice = (this._current.sliceFlags & Protocol.FLAG_IS_LAST_SLICE) !== 0;
+
+ const b = this._stream._buf;
+ const end = b.position;
+ let dataEnd = end;
+ if(info.hasOptionalMembers)
+ {
+ //
+ // Don't include the optional member end marker. It will be re-written by
+ // endSlice when the sliced data is re-written.
+ //
+ --dataEnd;
+ }
+
+ b.position = start;
+ info.bytes = b.getArray(dataEnd - start);
+ b.position = end;
+
+ if(this._current.slices === null) // Lazy initialization
+ {
+ this._current.slices = []; // Ice.SliceInfo[]
+ this._current.indirectionTables = []; // int[]
+ }
+
+ //
+ // Read the indirect instance table. We read the instances or their
+ // IDs if the instance is a reference to an already unmarshaled
+ // instance.
+ //
+
+ if((this._current.sliceFlags & Protocol.FLAG_HAS_INDIRECTION_TABLE) !== 0)
+ {
+ let length = this._stream.readAndCheckSeqSize(1);
+ let indirectionTable = [];
+ for(let i = 0; i < length; ++i)
+ {
+ indirectionTable[i] = this.readInstance(this._stream.readSize(), null);
+ }
+ this._current.indirectionTables.push(indirectionTable);
+ }
+ else
+ {
+ this._current.indirectionTables.push(null);
+ }
+
+ this._current.slices.push(info);
+ }
+
+ readOptional(readTag, expectedFormat)
+ {
+ if(this._current === null)
+ {
+ return this._stream.readOptImpl(readTag, expectedFormat);
+ }
+ else if((this._current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) !== 0)
+ {
+ return this._stream.readOptImpl(readTag, expectedFormat);
+ }
+ return false;
+ }
+
+ readInstance(index, cb)
+ {
+ Debug.assert(index > 0);
+
+ let v = null;
+
+ if(index > 1)
+ {
+ if(cb !== null)
+ {
+ this.addPatchEntry(index, cb);
+ }
+ return index;
+ }
+
+ this.push(SliceType.ValueSlice);
+
+ //
+ // Get the instance ID before we start reading slices. If some
+ // slices are skipped, the indirect instance table is still read and
+ // might read other instances.
+ //
+ index = ++this._valueIdIndex;
+
+ //
+ // Read the first slice header.
+ //
+ this.startSlice();
+ const mostDerivedId = this._current.typeId;
+ while(true)
+ {
+ if(this._current.compactId >= 0)
+ {
+ //
+ // Translate a compact (numeric) type ID into a string type ID.
+ //
+ this._current.typeId = "";
+ if(this._compactIdResolver !== null)
+ {
+ try
+ {
+ this._current.typeId = this._compactIdResolver.call(null, this._current.compactId);
+ }
+ catch(ex)
+ {
+ if(!(ex instanceof Ice.LocalException))
+ {
+ throw new Ice.MarshalException("exception in CompactIdResolver for ID " +
+ this._current.compactId, ex);
+ }
+ throw ex;
+ }
+ }
+
+ if(this._current.typeId.length === 0)
+ {
+ this._current.typeId = this._stream.resolveCompactId(this._current.compactId);
+ }
+ }
+
+ if(this._current.typeId.length > 0)
+ {
+ v = this.newInstance(this._current.typeId);
+ }
+
+ if(v !== null && v !== undefined)
+ {
+ //
+ // We have an instance, we get out of this loop.
+ //
+ break;
+ }
+
+ //
+ // If slicing is disabled, stop unmarshaling.
+ //
+ if(!this._sliceValues)
+ {
+ throw new Ice.NoValueFactoryException("no value factory found and slicing is disabled",
+ this._current.typeId);
+ }
+
+ //
+ // Slice off what we don't understand.
+ //
+ this.skipSlice();
+
+ //
+ // If this is the last slice, keep the instance as an opaque
+ // UnknownSlicedValue object.
+ //
+ if((this._current.sliceFlags & Protocol.FLAG_IS_LAST_SLICE) !== 0)
+ {
+ v = new Ice.UnknownSlicedValue(mostDerivedId);
+ break;
+ }
+
+ this.startSlice(); // Read next Slice header for next iteration.
+ }
+
+ //
+ // Unmarshal the instance.
+ //
+ this.unmarshal(index, v);
+
+ if(this._current === null && this._patchMap !== null && this._patchMap.size !== 0)
+ {
+ //
+ // If any entries remain in the patch map, the sender has sent an index for an instance, but failed
+ // to supply the instance.
+ //
+ throw new Ice.MarshalException("index for class received, but no instance");
+ }
+
+ if(cb !== null)
+ {
+ cb.call(null, v);
+ }
+
+ return index;
+ }
+
+ readSlicedData()
+ {
+ if(this._current.slices === null) // No preserved slices.
+ {
+ return null;
+ }
+
+ //
+ // The _indirectionTables member holds the indirection table for each slice
+ // in _slices.
+ //
+ Debug.assert(this._current.slices.length === this._current.indirectionTables.length);
+ for(let i = 0; i < this._current.slices.length; ++i)
+ {
+ //
+ // We use the "instances" list in SliceInfo to hold references
+ // to the target instances. Note that the instances might not have
+ // been read yet in the case of a circular reference to an
+ // enclosing instance.
+ //
+ const table = this._current.indirectionTables[i];
+ const info = this._current.slices[i];
+ info.instances = [];
+ if(table)
+ {
+ for(let j = 0; j < table.length; ++j)
+ {
+ this.addPatchEntry(table[j], sequencePatcher(info.instances, j, Ice.Value));
+ }
+ }
+ }
+ return new SlicedData(ArrayUtil.clone(this._current.slices));
+ }
+
+ push(sliceType)
+ {
+ if(this._current === null)
+ {
+ this._current = new EncapsDecoder11.InstanceData(null);
+ }
+ else
+ {
+ this._current = !this._current.next ? new EncapsDecoder11.InstanceData(this._current) : this._current.next;
+ }
+ this._current.sliceType = sliceType;
+ this._current.skipFirstSlice = false;
+ }
+}
+
+EncapsDecoder11.InstanceData = class
+{
+ constructor(previous)
+ {
+ if(previous !== null)
+ {
+ previous.next = this;
+ }
+ this.previous = previous;
+ this.next = null;
+
+ // Instance attributes
+ this.sliceType = null;
+ this.skipFirstSlice = false;
+ this.slices = null; // Preserved slices. Ice.SliceInfo[]
+ this.indirectionTables = null; // int[][]
+
+ // Slice attributes
+ this.sliceFlags = 0;
+ this.sliceSize = 0;
+ this.typeId = null;
+ this.compactId = 0;
+ this.indirectPatchList = null; // Lazy initialized, IndirectPatchEntry[]
+ }
+};
+
+const sequencePatcher = function(seq, index, T)
+{
+ return v =>
+ {
+ if(v !== null && !(v instanceof T))
+ {
+ ExUtil.throwUOE(T.ice_staticId(), v);
+ }
+ seq[index] = v;
+ };
+};
+
+class ReadEncaps
+{
+ constructor()
+ {
+ this.start = 0;
+ this.sz = 0;
+ this.encoding = null;
+ this.encoding_1_0 = false;
+ this.decoder = null;
+ this.next = null;
+ }
+
+ reset()
+ {
+ this.decoder = null;
+ }
+
+ setEncoding(encoding)
+ {
+ this.encoding = encoding;
+ this.encoding_1_0 = encoding.equals(Ice.Encoding_1_0);
+ }
+}
+
+class InputStream
+{
+ constructor(arg1, arg2, arg3)
+ {
+ const args =
+ {
+ instance: null,
+ encoding: null,
+ bytes: null,
+ buffer: null
+ };
+ this._checkArgs([arg1, arg2, arg3], args);
+ this._initialize(args);
+ }
+
+ _checkArgs(arr, args)
+ {
+ //
+ // The constructor can accept a variety of argument combinations:
+ //
+ // (<empty>)
+ // (communicator)
+ // (instance)
+ // (encoding)
+ // (array)
+ // (buffer)
+ // (communicator, encoding)
+ // (instance, encoding)
+ // (communicator, array)
+ // (instance, array)
+ // (communicator, buffer)
+ // (instance, buffer)
+ // (communicator, encoding, array)
+ // (instance, encoding, array)
+ // (communicator, encoding, buffer)
+ // (instance, encoding, buffer)
+ // (encoding, array)
+ // (encoding, array)
+ // (encoding, buffer)
+ // (encoding, buffer)
+ //
+ arr.forEach(arg =>
+ {
+ if(arg !== null && arg !== undefined)
+ {
+ if(arg.constructor === Ice.Communicator)
+ {
+ args.instance = arg.instance;
+ }
+ else if(arg.constructor === Ice.Instance)
+ {
+ args.instance = arg;
+ }
+ else if(arg.constructor === Ice.EncodingVersion)
+ {
+ args.encoding = arg;
+ }
+ else if(arg.constructor === Ice.Buffer)
+ {
+ args.buffer = arg;
+ }
+ else if(arg.constructor === Array)
+ {
+ args.bytes = arg;
+ }
+ else
+ {
+ throw new Ice.InitializationException("unknown argument to InputStream constructor");
+ }
+ }
+ });
+ if(args.buffer !== null && args.bytes !== null)
+ {
+ throw new Ice.InitializationException("invalid argument to InputStream constructor");
+ }
+ }
+
+ _initialize(args)
+ {
+ this._instance = args.instance;
+ this._encoding = args.encoding;
+ this._encapsStack = null;
+ this._encapsCache = null;
+ this._closure = null;
+ this._sliceValues = true;
+ this._startSeq = -1;
+ this._sizePos = -1;
+ this._compactIdResolver = null;
+
+ if(this._instance !== null)
+ {
+ if(this._encoding === null)
+ {
+ this._encoding = this._instance.defaultsAndOverrides().defaultEncoding;
+ }
+ this._traceSlicing = this._instance.traceLevels().slicing > 0;
+ this._valueFactoryManager = this._instance.initializationData().valueFactoryManager;
+ this._logger = this._instance.initializationData().logger;
+ }
+ else
+ {
+ if(this._encoding === null)
+ {
+ this._encoding = Protocol.currentEncoding;
+ }
+ this._traceSlicing = false;
+ this._valueFactoryManager = null;
+ this._logger = null;
+ }
+
+ if(args.bytes !== null)
+ {
+ this._buf = new Ice.Buffer(args.bytes);
+ }
+ else if(args.buffer !== null)
+ {
+ this._buf = args.buffer;
+ }
+ else
+ {
+ this._buf = new Ice.Buffer();
+ }
+ }
+
+ //
+ // This function allows this object to be reused, rather than reallocated.
+ //
+ reset()
+ {
+ this._buf.reset();
+ this.clear();
+ }
+
+ clear()
+ {
+ if(this._encapsStack !== null)
+ {
+ Debug.assert(this._encapsStack.next);
+ this._encapsStack.next = this._encapsCache;
+ this._encapsCache = this._encapsStack;
+ this._encapsCache.reset();
+ this._encapsStack = null;
+ }
+
+ this._startSeq = -1;
+ this._sliceValues = true;
+ }
+
+ swap(other)
+ {
+ Debug.assert(this._instance === other._instance);
+
+ [other._buf, this._buf] = [this._buf, other._buf];
+ [other._encoding, this._encoding] = [this._encoding, other._encoding];
+ [other._traceSlicing, this._traceSlicing] = [this._traceSlicing, other._traceSlicing];
+ [other._closure, this._closure] = [this._closure, other.closure];
+ [other._sliceValues, this._sliceValues] = [this._sliceValues, other._sliceValues];
+
+ //
+ // Swap is never called for InputStreams that have encapsulations being read/write. However,
+ // encapsulations might still be set in case marshaling or unmarshaling failed. We just
+ // reset the encapsulations if there are still some set.
+ //
+ this.resetEncapsulation();
+ other.resetEncapsulation();
+
+ [other._startSeq, this._startSeq] = [this._startSeq, other._startSeq];
+ [other._minSeqSize, this._minSeqSize] = [this._minSeqSize, other._minSeqSize];
+ [other._sizePos, this._sizePos] = [this._sizePos, other._sizePos];
+ [other._valueFactoryManager, this._valueFactoryManager] = [this._valueFactoryManager, other._valueFactoryManager];
+ [other._logger, this._logger] = [this._logger, other._logger];
+ [other._compactIdResolver, this._compactIdResolver] = [this._compactIdResolver, other._compactIdResolver];
+ }
+
+ resetEncapsulation()
+ {
+ this._encapsStack = null;
+ }
+
+ resize(sz)
+ {
+ this._buf.resize(sz);
+ this._buf.position = sz;
+ }
+
+ startValue()
+ {
+ Debug.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
+ this._encapsStack.decoder.startInstance(SliceType.ValueSlice);
+ }
+
+ endValue(preserve)
+ {
+ Debug.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
+ return this._encapsStack.decoder.endInstance(preserve);
+ }
+
+ startException()
+ {
+ Debug.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
+ this._encapsStack.decoder.startInstance(SliceType.ExceptionSlice);
+ }
+
+ endException(preserve)
+ {
+ Debug.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
+ return this._encapsStack.decoder.endInstance(preserve);
+ }
+
+ startEncapsulation()
+ {
+ let curr = this._encapsCache;
+ if(curr !== null)
+ {
+ curr.reset();
+ this._encapsCache = this._encapsCache.next;
+ }
+ else
+ {
+ curr = new ReadEncaps();
+ }
+ curr.next = this._encapsStack;
+ this._encapsStack = curr;
+
+ this._encapsStack.start = this._buf.position;
+
+ //
+ // I don't use readSize() for encapsulations, because when creating an encapsulation,
+ // I must know in advance how many bytes the size information will require in the data
+ // stream. If I use an Int, it is always 4 bytes. For readSize(), it could be 1 or 5 bytes.
+ //
+ const sz = this.readInt();
+ if(sz < 6)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ if(sz - 4 > this._buf.remaining)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ this._encapsStack.sz = sz;
+
+ const encoding = new Ice.EncodingVersion();
+ encoding._read(this);
+ Protocol.checkSupportedEncoding(encoding); // Make sure the encoding is supported.
+ this._encapsStack.setEncoding(encoding);
+
+ return encoding;
+ }
+
+ endEncapsulation()
+ {
+ Debug.assert(this._encapsStack !== null);
+
+ if(!this._encapsStack.encoding_1_0)
+ {
+ this.skipOptionals();
+ if(this._buf.position !== this._encapsStack.start + this._encapsStack.sz)
+ {
+ throw new Ice.EncapsulationException();
+ }
+ }
+ else if(this._buf.position !== this._encapsStack.start + this._encapsStack.sz)
+ {
+ if(this._buf.position + 1 !== this._encapsStack.start + this._encapsStack.sz)
+ {
+ throw new Ice.EncapsulationException();
+ }
+
+ //
+ // Ice version < 3.3 had a bug where user exceptions with
+ // class members could be encoded with a trailing byte
+ // when dispatched with AMD. So we tolerate an extra byte
+ // in the encapsulation.
+ //
+
+ try
+ {
+ this._buf.get();
+ }
+ catch(ex)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+
+ const curr = this._encapsStack;
+ this._encapsStack = curr.next;
+ curr.next = this._encapsCache;
+ this._encapsCache = curr;
+ this._encapsCache.reset();
+ }
+
+ skipEmptyEncapsulation()
+ {
+ const sz = this.readInt();
+ if(sz < 6)
+ {
+ throw new Ice.EncapsulationException();
+ }
+ if(sz - 4 > this._buf.remaining)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+
+ const encoding = new Ice.EncodingVersion();
+ encoding._read(this);
+ Protocol.checkSupportedEncoding(encoding); // Make sure the encoding is supported.
+
+ if(encoding.equals(Ice.Encoding_1_0))
+ {
+ if(sz != 6)
+ {
+ throw new Ice.EncapsulationException();
+ }
+ }
+ else
+ {
+ // Skip the optional content of the encapsulation if we are expecting an
+ // empty encapsulation.
+ this._buf.position = this._buf.position + sz - 6;
+ }
+ return encoding;
+ }
+
+ readEncapsulation(encoding)
+ {
+ Debug.assert(encoding !== undefined);
+ const sz = this.readInt();
+ if(sz < 6)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+
+ if(sz - 4 > this._buf.remaining)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+
+ if(encoding !== null)
+ {
+ encoding._read(this);
+ this._buf.position = this._buf.position - 6;
+ }
+ else
+ {
+ this._buf.position = this._buf.position - 4;
+ }
+
+ try
+ {
+ return this._buf.getArray(sz);
+ }
+ catch(ex)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+
+ getEncoding()
+ {
+ return this._encapsStack !== null ? this._encapsStack.encoding : this._encoding;
+ }
+
+ getEncapsulationSize()
+ {
+ Debug.assert(this._encapsStack !== null);
+ return this._encapsStack.sz - 6;
+ }
+
+ skipEncapsulation()
+ {
+ const sz = this.readInt();
+ if(sz < 6)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ const encoding = new Ice.EncodingVersion();
+ encoding._read(this);
+ try
+ {
+ this._buf.position = this._buf.position + sz - 6;
+ }
+ catch(ex)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ return encoding;
+ }
+
+ startSlice() // Returns type ID of next slice
+ {
+ Debug.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
+ return this._encapsStack.decoder.startSlice();
+ }
+
+ endSlice()
+ {
+ Debug.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
+ this._encapsStack.decoder.endSlice();
+ }
+
+ skipSlice()
+ {
+ Debug.assert(this._encapsStack !== null && this._encapsStack.decoder !== null);
+ this._encapsStack.decoder.skipSlice();
+ }
+
+ readPendingValues()
+ {
+ if(this._encapsStack !== null && this._encapsStack.decoder !== null)
+ {
+ this._encapsStack.decoder.readPendingValues();
+ }
+ else if((this._encapsStack !== null && this._encapsStack.encoding_1_0) ||
+ (this._encapsStack === null && this._encoding.equals(Ice.Encoding_1_0)))
+ {
+ //
+ // If using the 1.0 encoding and no instances were read, we
+ // still read an empty sequence of pending instances if
+ // requested (i.e.: if this is called).
+ //
+ // This is required by the 1.0 encoding, even if no instances
+ // are written we do marshal an empty sequence if marshaled
+ // data types use classes.
+ //
+ this.skipSize();
+ }
+ }
+
+ readSize()
+ {
+ try
+ {
+ const b = this._buf.get();
+ if(b === 255)
+ {
+ const v = this._buf.getInt();
+ if(v < 0)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ return v;
+ }
+ return b;
+ }
+ catch(ex)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+
+ readAndCheckSeqSize(minSize)
+ {
+ const sz = this.readSize();
+
+ if(sz === 0)
+ {
+ return sz;
+ }
+
+ //
+ // The _startSeq variable points to the start of the sequence for which
+ // we expect to read at least _minSeqSize bytes from the stream.
+ //
+ // If not initialized or if we already read more data than _minSeqSize,
+ // we reset _startSeq and _minSeqSize for this sequence (possibly a
+ // top-level sequence or enclosed sequence it doesn't really matter).
+ //
+ // Otherwise, we are reading an enclosed sequence and we have to bump
+ // _minSeqSize by the minimum size that this sequence will require on
+ // the stream.
+ //
+ // The goal of this check is to ensure that when we start unmarshaling
+ // a new sequence, we check the minimal size of this new sequence against
+ // the estimated remaining buffer size. This estimatation is based on
+ // the minimum size of the enclosing sequences, it's _minSeqSize.
+ //
+ if(this._startSeq === -1 || this._buf.position > (this._startSeq + this._minSeqSize))
+ {
+ this._startSeq = this._buf.position;
+ this._minSeqSize = sz * minSize;
+ }
+ else
+ {
+ this._minSeqSize += sz * minSize;
+ }
+
+ //
+ // If there isn't enough data to read on the stream for the sequence (and
+ // possibly enclosed sequences), something is wrong with the marshaled
+ // data: it's claiming having more data that what is possible to read.
+ //
+ if(this._startSeq + this._minSeqSize > this._buf.limit)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+
+ return sz;
+ }
+
+ readBlob(sz)
+ {
+ if(this._buf.remaining < sz)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ try
+ {
+ return this._buf.getArray(sz);
+ }
+ catch(ex)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+
+ readOptional(tag, expectedFormat)
+ {
+ Debug.assert(this._encapsStack !== null);
+ if(this._encapsStack.decoder !== null)
+ {
+ return this._encapsStack.decoder.readOptional(tag, expectedFormat);
+ }
+ return this.readOptImpl(tag, expectedFormat);
+ }
+
+ readOptionalHelper(tag, format, read)
+ {
+ if(this.readOptional(tag, format))
+ {
+ return read.call(this);
+ }
+ else
+ {
+ return undefined;
+ }
+ }
+
+ readByte()
+ {
+ try
+ {
+ return this._buf.get();
+ }
+ catch(ex)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+
+ readByteSeq()
+ {
+ return this._buf.getArray(this.readAndCheckSeqSize(1));
+ }
+
+ readBool()
+ {
+ try
+ {
+ return this._buf.get() === 1;
+ }
+ catch(ex)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+
+ readShort()
+ {
+ try
+ {
+ return this._buf.getShort();
+ }
+ catch(ex)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+
+ readInt()
+ {
+ try
+ {
+ return this._buf.getInt();
+ }
+ catch(ex)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+
+ readLong()
+ {
+ try
+ {
+ return this._buf.getLong();
+ }
+ catch(ex)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+
+ readFloat()
+ {
+ try
+ {
+ return this._buf.getFloat();
+ }
+ catch(ex)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+
+ readDouble()
+ {
+ try
+ {
+ return this._buf.getDouble();
+ }
+ catch(ex)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+
+ readString()
+ {
+ const len = this.readSize();
+ if(len === 0)
+ {
+ return "";
+ }
+ //
+ // Check the buffer has enough bytes to read.
+ //
+ if(this._buf.remaining < len)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+
+ try
+ {
+ return this._buf.getString(len);
+ }
+ catch(ex)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ }
+
+ readProxy(type)
+ {
+ return this._instance.proxyFactory().streamToProxy(this, type);
+ }
+
+ readOptionalProxy(tag, type)
+ {
+ if(this.readOptional(tag, OptionalFormat.FSize))
+ {
+ this.skip(4);
+ return this.readProxy(type);
+ }
+ else
+ {
+ return undefined;
+ }
+ }
+
+ readEnum(T)
+ {
+ let v;
+ if(this.getEncoding().equals(Ice.Encoding_1_0))
+ {
+ if(T.maxValue < 127)
+ {
+ v = this.readByte();
+ }
+ else if(T.maxValue < 32767)
+ {
+ v = this.readShort();
+ }
+ else
+ {
+ v = this.readInt();
+ }
+ }
+ else
+ {
+ v = this.readSize();
+ }
+
+ const e = T.valueOf(v);
+ if(e === undefined)
+ {
+ throw new Ice.MarshalException("enumerator value " + v + " is out of range");
+ }
+ return e;
+ }
+
+ readOptionalEnum(tag, T)
+ {
+ if(this.readOptional(tag, OptionalFormat.Size))
+ {
+ return this.readEnum(T);
+ }
+ else
+ {
+ return undefined;
+ }
+ }
+
+ readValue(cb, T)
+ {
+ this.initEncaps();
+ //
+ // BUGFIX:
+ // With Chrome on Linux the invocation of readValue on the decoder sometimes
+ // calls InputStream.readValue with the decoder object as this param.
+ // Use call instead of directly invoking the method to workaround this bug.
+ //
+ this._encapsStack.decoder.readValue.call(
+ this._encapsStack.decoder,
+ obj =>
+ {
+ if(obj !== null && !(obj instanceof T))
+ {
+ ExUtil.throwUOE(T.ice_staticId(), obj);
+ }
+ cb(obj);
+ });
+ }
+
+ readOptionalValue(tag, cb, T)
+ {
+ if(this.readOptional(tag, OptionalFormat.Class))
+ {
+ this.readValue(cb, T);
+ }
+ else
+ {
+ cb(undefined);
+ }
+ }
+
+ throwException()
+ {
+ this.initEncaps();
+ this._encapsStack.decoder.throwException();
+ }
+
+ readOptImpl(readTag, expectedFormat)
+ {
+ if(this.isEncoding_1_0())
+ {
+ return false; // Optional members aren't supported with the 1.0 encoding.
+ }
+
+ while(true)
+ {
+ if(this._buf.position >= this._encapsStack.start + this._encapsStack.sz)
+ {
+ return false; // End of encapsulation also indicates end of optionals.
+ }
+
+ const v = this.readByte();
+
+ if(v === Protocol.OPTIONAL_END_MARKER)
+ {
+ this._buf.position -= 1; // Rewind.
+ return false;
+ }
+
+ const format = OptionalFormat.valueOf(v & 0x07); // First 3 bits.
+ let tag = v >> 3;
+ if(tag === 30)
+ {
+ tag = this.readSize();
+ }
+
+ if(tag > readTag)
+ {
+ const offset = tag < 30 ? 1 : (tag < 255 ? 2 : 6); // Rewind
+ this._buf.position -= offset;
+ return false; // No optional data members with the requested tag.
+ }
+ else if(tag < readTag)
+ {
+ this.skipOptional(format); // Skip optional data members
+ }
+ else
+ {
+ if(format !== expectedFormat)
+ {
+ throw new Ice.MarshalException("invalid optional data member `" + tag + "': unexpected format");
+ }
+ return true;
+ }
+ }
+ }
+
+ skipOptional(format)
+ {
+ switch(format)
+ {
+ case OptionalFormat.F1:
+ this.skip(1);
+ break;
+ case OptionalFormat.F2:
+ this.skip(2);
+ break;
+ case OptionalFormat.F4:
+ this.skip(4);
+ break;
+ case OptionalFormat.F8:
+ this.skip(8);
+ break;
+ case OptionalFormat.Size:
+ this.skipSize();
+ break;
+ case OptionalFormat.VSize:
+ this.skip(this.readSize());
+ break;
+ case OptionalFormat.FSize:
+ this.skip(this.readInt());
+ break;
+ case OptionalFormat.Class:
+ this.readValue(null, Ice.Value);
+ break;
+ }
+ }
+
+ skipOptionals()
+ {
+ //
+ // Skip remaining un-read optional members.
+ //
+ while(true)
+ {
+ if(this._buf.position >= this._encapsStack.start + this._encapsStack.sz)
+ {
+ return; // End of encapsulation also indicates end of optionals.
+ }
+
+ const b = this.readByte();
+ const v = b < 0 ? b + 256 : b;
+ if(v === Protocol.OPTIONAL_END_MARKER)
+ {
+ return;
+ }
+
+ const format = OptionalFormat.valueOf(v & 0x07); // Read first 3 bits.
+ if((v >> 3) === 30)
+ {
+ this.skipSize();
+ }
+ this.skipOptional(format);
+ }
+ }
+
+ skip(size)
+ {
+ if(size > this._buf.remaining)
+ {
+ throw new Ice.UnmarshalOutOfBoundsException();
+ }
+ this._buf.position += size;
+ }
+
+ skipSize()
+ {
+ const b = this.readByte();
+ if(b === 255)
+ {
+ this.skip(4);
+ }
+ }
+
+ isEmpty()
+ {
+ return this._buf.empty();
+ }
+
+ expand(n)
+ {
+ this._buf.expand(n);
+ }
+
+ createInstance(id)
+ {
+ let obj = null;
+ try
+ {
+ const typeId = id.length > 2 ? id.substr(2).replace(/::/g, ".") : "";
+ const Class = _ModuleRegistry.type(typeId);
+ if(Class !== undefined)
+ {
+ obj = new Class();
+ }
+ }
+ catch(ex)
+ {
+ throw new Ice.NoValueFactoryException("no value factory", id, ex);
+ }
+
+ return obj;
+ }
+
+ createUserException(id)
+ {
+ let userEx = null, Class;
+
+ try
+ {
+ const typeId = id.length > 2 ? id.substr(2).replace(/::/g, ".") : "";
+ const Class = _ModuleRegistry.type(typeId);
+ if(Class !== undefined)
+ {
+ userEx = new Class();
+ }
+ }
+ catch(ex)
+ {
+ throw new Ice.MarshalException(ex);
+ }
+ return userEx;
+ }
+
+ resolveCompactId(compactId)
+ {
+ const typeId = Ice.CompactIdRegistry.get(compactId);
+ return typeId === undefined ? "" : typeId;
+ }
+
+ isEncoding_1_0()
+ {
+ return this._encapsStack !== null ? this._encapsStack.encoding_1_0 : this._encoding.equals(Ice.Encoding_1_0);
+ }
+
+ initEncaps()
+ {
+ if(this._encapsStack === null) // Lazy initialization
+ {
+ this._encapsStack = this._encapsCache;
+ if(this._encapsStack !== null)
+ {
+ this._encapsCache = this._encapsCache.next;
+ }
+ else
+ {
+ this._encapsStack = new ReadEncaps();
+ }
+ this._encapsStack.setEncoding(this._encoding);
+ this._encapsStack.sz = this._buf.limit;
+ }
+
+ if(this._encapsStack.decoder === null) // Lazy initialization.
+ {
+ if(this._encapsStack.encoding_1_0)
+ {
+ this._encapsStack.decoder = new EncapsDecoder10(this, this._encapsStack, this._sliceValues,
+ this._valueFactoryManager);
+ }
+ else
+ {
+ this._encapsStack.decoder = new EncapsDecoder11(this, this._encapsStack, this._sliceValues,
+ this._valueFactoryManager, this._compactIdResolver);
+ }
+ }
+ }
+
+ traceSkipSlice(typeId, sliceType)
+ {
+ if(this._traceSlicing && this._logger !== null)
+ {
+ TraceUtil.traceSlicing(sliceType === SliceType.ExceptionSlice ? "exception" : "object", typeId, "Slicing",
+ this._logger);
+ }
+ }
+
+ //
+ // Sets the value factory manager to use when marshaling value instances. If the stream
+ // was initialized with a communicator, the communicator's value factory manager will
+ // be used by default.
+ //
+ get valueFactoryManager()
+ {
+ return this._valueFactoryManager;
+ }
+
+ set valueFactoryManager(value)
+ {
+ this._valueFactoryManager = value !== undefined ? value : null;
+ }
+
+ //
+ // Sets the logger to use when logging trace messages. If the stream
+ // was initialized with a communicator, the communicator's logger will
+ // be used by default.
+ //
+ get logger()
+ {
+ return this._logger;
+ }
+
+ set logger(value)
+ {
+ this._logger = value !== undefined ? value : null;
+ }
+
+ //
+ // Sets the compact ID resolver to use when unmarshaling value and exception
+ // instances. If the stream was initialized with a communicator, the communicator's
+ // resolver will be used by default.
+ //
+ get compactIdResolver()
+ {
+ return this._compactIdResolver;
+ }
+
+ set compactIdResolver(value)
+ {
+ this._compactIdResolver = value !== undefined ? value : null;
+ }
+
+ //
+ // Determines the behavior of the stream when extracting instances of Slice classes.
+ // A instance is "sliced" when a factory cannot be found for a Slice type ID.
+ // The stream's default behavior is to slice instances.
+ //
+ // If slicing is disabled and the stream encounters a Slice type ID
+ // during decoding for which no value factory is installed, it raises
+ // NoValueFactoryException.
+ //
+ get sliceValues()
+ {
+ return this._sliceValues;
+ }
+
+ set sliceValues(value)
+ {
+ this._sliceValues = value;
+ }
+
+ //
+ // Determines whether the stream logs messages about slicing instances of Slice values.
+ //
+ get traceSlicing()
+ {
+ return this._traceSlicing;
+ }
+
+ set traceSlicing(value)
+ {
+ this._traceSlicing = value;
+ }
+
+ get pos()
+ {
+ return this._buf.position;
+ }
+
+ set pos(value)
+ {
+ this._buf.position = value;
+ }
+
+ get size()
+ {
+ return this._buf.limit;
+ }
+
+ get instance()
+ {
+ return this._instance;
+ }
+
+ get closure()
+ {
+ return this._type;
+ }
+
+ set closure(value)
+ {
+ this._type = value;
+ }
+
+ get buffer()
+ {
+ return this._buf;
+ }
+}
+
+//
+// OutputStream
+//
+
+class EncapsEncoder
+{
+ constructor(stream, encaps)
+ {
+ this._stream = stream;
+ this._encaps = encaps;
+ this._marshaledMap = new Map(); // Map<Ice.Value, int>;
+ this._typeIdMap = null; // Lazy initialized. Map<String, int>
+ this._typeIdIndex = 0;
+ }
+
+ writeOptional()
+ {
+ return false;
+ }
+
+ writePendingValues()
+ {
+ return undefined;
+ }
+
+ registerTypeId(typeId)
+ {
+ if(this._typeIdMap === null) // Lazy initialization
+ {
+ this._typeIdMap = new Map(); // Map<String, int>
+ }
+
+ const p = this._typeIdMap.get(typeId);
+ if(p !== undefined)
+ {
+ return p;
+ }
+ else
+ {
+ this._typeIdMap.set(typeId, ++this._typeIdIndex);
+ return -1;
+ }
+ }
+}
+
+class EncapsEncoder10 extends EncapsEncoder
+{
+ constructor(stream, encaps)
+ {
+ super(stream, encaps);
+ this._sliceType = SliceType.NoSlice;
+ this._writeSlice = 0; // Position of the slice data members
+ this._valueIdIndex = 0;
+ this._toBeMarshaledMap = new Map(); // Map<Ice.Value, Integer>();
+ }
+
+ writeValue(v)
+ {
+ Debug.assert(v !== undefined);
+ //
+ // Object references are encoded as a negative integer in 1.0.
+ //
+ if(v !== null)
+ {
+ this._stream.writeInt(-this.registerValue(v));
+ }
+ else
+ {
+ this._stream.writeInt(0);
+ }
+ }
+
+ writeUserException(v)
+ {
+ Debug.assert(v !== null && v !== undefined);
+ //
+ // User exception with the 1.0 encoding start with a boolean
+ // flag that indicates whether or not the exception uses
+ // classes.
+ //
+ // This allows reading the pending instances even if some part of
+ // the exception was sliced.
+ //
+ const usesClasses = v._usesClasses();
+ this._stream.writeBool(usesClasses);
+ v._write(this._stream);
+ if(usesClasses)
+ {
+ this.writePendingValues();
+ }
+ }
+
+ startInstance(sliceType)
+ {
+ this._sliceType = sliceType;
+ }
+
+ endInstance()
+ {
+ if(this._sliceType === SliceType.ValueSlice)
+ {
+ //
+ // Write the Object slice.
+ //
+ this.startSlice(Ice.Value.ice_staticId(), -1, true);
+ this._stream.writeSize(0); // For compatibility with the old AFM.
+ this.endSlice();
+ }
+ this._sliceType = SliceType.NoSlice;
+ }
+
+ startSlice(typeId)
+ {
+ //
+ // For instance slices, encode a boolean to indicate how the type ID
+ // is encoded and the type ID either as a string or index. For
+ // exception slices, always encode the type ID as a string.
+ //
+ if(this._sliceType === SliceType.ValueSlice)
+ {
+ const index = this.registerTypeId(typeId);
+ if(index < 0)
+ {
+ this._stream.writeBool(false);
+ this._stream.writeString(typeId);
+ }
+ else
+ {
+ this._stream.writeBool(true);
+ this._stream.writeSize(index);
+ }
+ }
+ else
+ {
+ this._stream.writeString(typeId);
+ }
+
+ this._stream.writeInt(0); // Placeholder for the slice length.
+
+ this._writeSlice = this._stream.pos;
+ }
+
+ endSlice()
+ {
+ //
+ // Write the slice length.
+ //
+ const sz = this._stream.pos - this._writeSlice + 4;
+ this._stream.rewriteInt(sz, this._writeSlice - 4);
+ }
+
+ writePendingValues()
+ {
+ const writeCB = (value, key) =>
+ {
+ //
+ // Ask the instance to marshal itself. Any new class
+ // instances that are triggered by the classes marshaled
+ // are added to toBeMarshaledMap.
+ //
+ this._stream.writeInt(value);
+ try
+ {
+ key.ice_preMarshal();
+ }
+ catch(ex)
+ {
+ this._stream.instance.initializationData().logger.warning(
+ "exception raised by ice_preMarshal:\n" + ex.toString());
+ }
+ key._iceWrite(this._stream);
+ };
+
+ while(this._toBeMarshaledMap.size > 0)
+ {
+ //
+ // Consider the to be marshalled instances as marshalled now,
+ // this is necessary to avoid adding again the "to be
+ // marshalled instances" into _toBeMarshaledMap while writing
+ // instances.
+ //
+ this._toBeMarshaledMap.forEach((value, key) => this._marshaledMap.set(key, value));
+
+ const savedMap = this._toBeMarshaledMap;
+ this._toBeMarshaledMap = new Map(); // Map<Ice.Value, int>();
+ this._stream.writeSize(savedMap.size);
+ savedMap.forEach(writeCB);
+ }
+ this._stream.writeSize(0); // Zero marker indicates end of sequence of sequences of instances.
+ }
+
+ registerValue(v)
+ {
+ Debug.assert(v !== null);
+
+ //
+ // Look for this instance in the to-be-marshaled map.
+ //
+ let p = this._toBeMarshaledMap.get(v);
+ if(p !== undefined)
+ {
+ return p;
+ }
+
+ //
+ // Didn't find it, try the marshaled map next.
+ //
+ p = this._marshaledMap.get(v);
+ if(p !== undefined)
+ {
+ return p;
+ }
+
+ //
+ // We haven't seen this instance previously, create a new
+ // index, and insert it into the to-be-marshaled map.
+ //
+ this._toBeMarshaledMap.set(v, ++this._valueIdIndex);
+ return this._valueIdIndex;
+ }
+}
+
+class EncapsEncoder11 extends EncapsEncoder
+{
+ constructor(stream, encaps)
+ {
+ super(stream, encaps);
+ this._current = null;
+ this._valueIdIndex = 1;
+ }
+
+ writeValue(v)
+ {
+ Debug.assert(v !== undefined);
+ if(v === null)
+ {
+ this._stream.writeSize(0);
+ }
+ else if(this._current !== null && this._encaps.format === FormatType.SlicedFormat)
+ {
+ if(this._current.indirectionTable === null) // Lazy initialization
+ {
+ this._current.indirectionTable = []; // Ice.Value[]
+ this._current.indirectionMap = new Map(); // Map<Ice.Value, int>
+ }
+
+ //
+ // If writing an instance within a slice and using the sliced
+ // format, write an index from the instance indirection
+ // table. The indirect instance table is encoded at the end of
+ // each slice and is always read (even if the Slice is
+ // unknown).
+ //
+ const index = this._current.indirectionMap.get(v);
+ if(index === undefined)
+ {
+ this._current.indirectionTable.push(v);
+ const idx = this._current.indirectionTable.length; // Position + 1 (0 is reserved for nil)
+ this._current.indirectionMap.set(v, idx);
+ this._stream.writeSize(idx);
+ }
+ else
+ {
+ this._stream.writeSize(index);
+ }
+ }
+ else
+ {
+ this.writeInstance(v); // Write the instance or a reference if already marshaled.
+ }
+ }
+
+ writePendingValues()
+ {
+ return undefined;
+ }
+
+ writeUserException(v)
+ {
+ Debug.assert(v !== null && v !== undefined);
+ v._write(this._stream);
+ }
+
+ startInstance(sliceType, data)
+ {
+ if(this._current === null)
+ {
+ this._current = new EncapsEncoder11.InstanceData(null);
+ }
+ else
+ {
+ this._current =
+ (this._current.next === null) ? new EncapsEncoder11.InstanceData(this._current) : this._current.next;
+ }
+ this._current.sliceType = sliceType;
+ this._current.firstSlice = true;
+
+ if(data !== null && data !== undefined)
+ {
+ this.writeSlicedData(data);
+ }
+ }
+
+ endInstance()
+ {
+ this._current = this._current.previous;
+ }
+
+ startSlice(typeId, compactId, last)
+ {
+ Debug.assert((this._current.indirectionTable === null || this._current.indirectionTable.length === 0) &&
+ (this._current.indirectionMap === null || this._current.indirectionMap.size === 0));
+
+ this._current.sliceFlagsPos = this._stream.pos;
+
+ this._current.sliceFlags = 0;
+ if(this._encaps.format === FormatType.SlicedFormat)
+ {
+ // Encode the slice size if using the sliced format.
+ this._current.sliceFlags |= Protocol.FLAG_HAS_SLICE_SIZE;
+ }
+ if(last)
+ {
+ this._current.sliceFlags |= Protocol.FLAG_IS_LAST_SLICE; // This is the last slice.
+ }
+
+ this._stream.writeByte(0); // Placeholder for the slice flags
+
+ //
+ // For instance slices, encode the flag and the type ID either as a
+ // string or index. For exception slices, always encode the type
+ // ID a string.
+ //
+ if(this._current.sliceType === SliceType.ValueSlice)
+ {
+ //
+ // Encode the type ID (only in the first slice for the compact
+ // encoding).
+ //
+ if(this._encaps.format === FormatType.SlicedFormat || this._current.firstSlice)
+ {
+ if(compactId >= 0)
+ {
+ this._current.sliceFlags |= Protocol.FLAG_HAS_TYPE_ID_COMPACT;
+ this._stream.writeSize(compactId);
+ }
+ else
+ {
+ const index = this.registerTypeId(typeId);
+ if(index < 0)
+ {
+ this._current.sliceFlags |= Protocol.FLAG_HAS_TYPE_ID_STRING;
+ this._stream.writeString(typeId);
+ }
+ else
+ {
+ this._current.sliceFlags |= Protocol.FLAG_HAS_TYPE_ID_INDEX;
+ this._stream.writeSize(index);
+ }
+ }
+ }
+ }
+ else
+ {
+ this._stream.writeString(typeId);
+ }
+
+ if((this._current.sliceFlags & Protocol.FLAG_HAS_SLICE_SIZE) !== 0)
+ {
+ this._stream.writeInt(0); // Placeholder for the slice length.
+ }
+
+ this._current.writeSlice = this._stream.pos;
+ this._current.firstSlice = false;
+ }
+
+ endSlice()
+ {
+ //
+ // Write the optional member end marker if some optional members
+ // were encoded. Note that the optional members are encoded before
+ // the indirection table and are included in the slice size.
+ //
+ if((this._current.sliceFlags & Protocol.FLAG_HAS_OPTIONAL_MEMBERS) !== 0)
+ {
+ this._stream.writeByte(Protocol.OPTIONAL_END_MARKER);
+ }
+
+ //
+ // Write the slice length if necessary.
+ //
+ if((this._current.sliceFlags & Protocol.FLAG_HAS_SLICE_SIZE) !== 0)
+ {
+ const sz = this._stream.pos - this._current.writeSlice + 4;
+ this._stream.rewriteInt(sz, this._current.writeSlice - 4);
+ }
+
+ //
+ // Only write the indirection table if it contains entries.
+ //
+ if(this._current.indirectionTable !== null && this._current.indirectionTable.length !== 0)
+ {
+ Debug.assert(this._encaps.format === FormatType.SlicedFormat);
+ this._current.sliceFlags |= Protocol.FLAG_HAS_INDIRECTION_TABLE;
+
+ //
+ // Write the indirection instance table.
+ //
+ this._stream.writeSize(this._current.indirectionTable.length);
+ this._current.indirectionTable.forEach(o => this.writeInstance(o));
+ this._current.indirectionTable.length = 0; // Faster way to clean array in JavaScript
+ this._current.indirectionMap.clear();
+ }
+
+ //
+ // Finally, update the slice flags.
+ //
+ this._stream.rewriteByte(this._current.sliceFlags, this._current.sliceFlagsPos);
+ }
+
+ writeOptional(tag, format)
+ {
+ if(this._current === null)
+ {
+ return this._stream.writeOptImpl(tag, format);
+ }
+
+ if(this._stream.writeOptImpl(tag, format))
+ {
+ this._current.sliceFlags |= Protocol.FLAG_HAS_OPTIONAL_MEMBERS;
+ return true;
+ }
+
+ return false;
+ }
+
+ writeSlicedData(slicedData)
+ {
+ Debug.assert(slicedData !== null && slicedData !== undefined);
+
+ //
+ // We only remarshal preserved slices if we are using the sliced
+ // format. Otherwise, we ignore the preserved slices, which
+ // essentially "slices" the instance into the most-derived type
+ // known by the sender.
+ //
+ if(this._encaps.format !== FormatType.SlicedFormat)
+ {
+ return;
+ }
+
+ slicedData.slices.forEach(info =>
+ {
+ this.startSlice(info.typeId, info.compactId, info.isLastSlice);
+
+ //
+ // Write the bytes associated with this slice.
+ //
+ this._stream.writeBlob(info.bytes);
+
+ if(info.hasOptionalMembers)
+ {
+ this._current.sliceFlags |= Protocol.FLAG_HAS_OPTIONAL_MEMBERS;
+ }
+
+ //
+ // Make sure to also re-write the instance indirection table.
+ //
+ if(info.instances !== null && info.instances.length > 0)
+ {
+ if(this._current.indirectionTable === null) // Lazy initialization
+ {
+ this._current.indirectionTable = []; // Ice.Value[]
+ this._current.indirectionMap = new Map(); // Map<Ice.Value, int>
+ }
+
+
+ info.instances.forEach(instance => this._current.indirectionTable.push(instance));
+ }
+
+ this.endSlice();
+ });
+ }
+
+ writeInstance(v)
+ {
+ Debug.assert(v !== null && v !== undefined);
+
+ //
+ // If the instance was already marshaled, just write it's ID.
+ //
+ const p = this._marshaledMap.get(v);
+ if(p !== undefined)
+ {
+ this._stream.writeSize(p);
+ return;
+ }
+
+ //
+ // We haven't seen this instance previously, create a new ID,
+ // insert it into the marshaled map, and write the instance.
+ //
+ this._marshaledMap.set(v, ++this._valueIdIndex);
+
+ try
+ {
+ v.ice_preMarshal();
+ }
+ catch(ex)
+ {
+ this._stream.instance.initializationData().logger.warning("exception raised by ice_preMarshal:\n" +
+ ex.toString());
+ }
+
+ this._stream.writeSize(1); // Object instance marker.
+ v._iceWrite(this._stream);
+ }
+}
+
+EncapsEncoder11.InstanceData = class
+{
+ constructor(previous)
+ {
+ Debug.assert(previous !== undefined);
+ if(previous !== null)
+ {
+ previous.next = this;
+ }
+ this.previous = previous;
+ this.next = null;
+
+ // Instance attributes
+ this.sliceType = null;
+ this.firstSlice = false;
+
+ // Slice attributes
+ this.sliceFlags = 0;
+ this.writeSlice = 0; // Position of the slice data members
+ this.sliceFlagsPos = 0; // Position of the slice flags
+ this.indirectionTable = null; // Ice.Value[]
+ this.indirectionMap = null; // Map<Ice.Value, int>
+ }
+};
+
+class WriteEncaps
+{
+ constructor()
+ {
+ this.start = 0;
+ this.format = FormatType.DefaultFormat;
+ this.encoding = null;
+ this.encoding_1_0 = false;
+ this.encoder = null;
+ this.next = null;
+ }
+
+ reset()
+ {
+ this.encoder = null;
+ }
+
+ setEncoding(encoding)
+ {
+ this.encoding = encoding;
+ this.encoding_1_0 = encoding.equals(Ice.Encoding_1_0);
+ }
+}
+
+class OutputStream
+{
+ constructor(arg1, arg2)
+ {
+ this._instance = null;
+ this._encoding = null;
+
+ if(arg1 !== undefined && arg1 !== null)
+ {
+ if(arg1.constructor == Ice.Communicator)
+ {
+ this._instance = arg1.instance;
+ }
+ else if(arg1.constructor == Ice.Instance)
+ {
+ this._instance = arg1;
+ }
+ else if(arg1.constructor == Ice.EncodingVersion)
+ {
+ this._encoding = arg1;
+ }
+ else
+ {
+ throw new Ice.InitializationException("unknown argument to OutputStream constructor");
+ }
+ }
+
+ if(arg2 !== undefined && arg2 !== null)
+ {
+ if(arg2.constructor == Ice.EncodingVersion)
+ {
+ this._encoding = arg2;
+ }
+ else
+ {
+ throw new Ice.InitializationException("unknown argument to OutputStream constructor");
+ }
+ }
+
+ this._buf = new Ice.Buffer();
+
+ this._closure = null;
+
+ this._encapsStack = null;
+ this._encapsCache = null;
+
+ if(this._instance !== null)
+ {
+ if(this._encoding === null)
+ {
+ this._encoding = this._instance.defaultsAndOverrides().defaultEncoding;
+ }
+ this._format = this._instance.defaultsAndOverrides().defaultFormat;
+ }
+ else
+ {
+ if(this._encoding === null)
+ {
+ this._encoding = Protocol.currentEncoding;
+ }
+ this._format = FormatType.CompactFormat;
+ }
+ }
+
+ //
+ // This function allows this object to be reused, rather than reallocated.
+ //
+ reset()
+ {
+ this._buf.reset();
+ this.clear();
+ }
+
+ clear()
+ {
+ if(this._encapsStack !== null)
+ {
+ Debug.assert(this._encapsStack.next);
+ this._encapsStack.next = this._encapsCache;
+ this._encapsCache = this._encapsStack;
+ this._encapsCache.reset();
+ this._encapsStack = null;
+ }
+ }
+
+ finished()
+ {
+ return this.prepareWrite().getArray(this.size);
+ }
+
+ swap(other)
+ {
+ Debug.assert(this._instance === other._instance);
+
+ [other._buf, this._buf] = [this._buf, other._buf];
+ [other._encoding, this._encoding] = [this._encoding, other._encoding];
+ [other._closure, this._closure] = [this._closure, other._closure];
+
+ //
+ // Swap is never called for streams that have encapsulations being written. However,
+ // encapsulations might still be set in case marshaling failed. We just
+ // reset the encapsulations if there are still some set.
+ //
+ this.resetEncapsulation();
+ other.resetEncapsulation();
+ }
+
+ resetEncapsulation()
+ {
+ this._encapsStack = null;
+ }
+
+ resize(sz)
+ {
+ this._buf.resize(sz);
+ this._buf.position = sz;
+ }
+
+ prepareWrite()
+ {
+ this._buf.position = 0;
+ return this._buf;
+ }
+
+ startValue(data)
+ {
+ Debug.assert(this._encapsStack !== null && this._encapsStack.encoder !== null);
+ this._encapsStack.encoder.startInstance(SliceType.ValueSlice, data);
+ }
+
+ endValue()
+ {
+ Debug.assert(this._encapsStack !== null && this._encapsStack.encoder !== null);
+ this._encapsStack.encoder.endInstance();
+ }
+
+ startException(data)
+ {
+ Debug.assert(this._encapsStack !== null && this._encapsStack.encoder !== null);
+ this._encapsStack.encoder.startInstance(SliceType.ExceptionSlice, data);
+ }
+
+ endException()
+ {
+ Debug.assert(this._encapsStack !== null && this._encapsStack.encoder !== null);
+ this._encapsStack.encoder.endInstance();
+ }
+
+ startEncapsulation(encoding, format)
+ {
+ //
+ // If no encoding version is specified, use the current write
+ // encapsulation encoding version if there's a current write
+ // encapsulation, otherwise, use the stream encoding version.
+ //
+
+ if(encoding === undefined)
+ {
+ if(this._encapsStack !== null)
+ {
+ encoding = this._encapsStack.encoding;
+ format = this._encapsStack.format;
+ }
+ else
+ {
+ encoding = this._encoding;
+ format = FormatType.DefaultFormat;
+ }
+ }
+
+ Protocol.checkSupportedEncoding(encoding);
+
+ let curr = this._encapsCache;
+ if(curr !== null)
+ {
+ curr.reset();
+ this._encapsCache = this._encapsCache.next;
+ }
+ else
+ {
+ curr = new WriteEncaps();
+ }
+ curr.next = this._encapsStack;
+ this._encapsStack = curr;
+
+ this._encapsStack.format = format;
+ this._encapsStack.setEncoding(encoding);
+ this._encapsStack.start = this._buf.limit;
+
+ this.writeInt(0); // Placeholder for the encapsulation length.
+ this._encapsStack.encoding._write(this);
+ }
+
+ endEncapsulation()
+ {
+ Debug.assert(this._encapsStack);
+
+ // Size includes size and version.
+ const start = this._encapsStack.start;
+ const sz = this._buf.limit - start;
+ this._buf.putIntAt(start, sz);
+
+ const curr = this._encapsStack;
+ this._encapsStack = curr.next;
+ curr.next = this._encapsCache;
+ this._encapsCache = curr;
+ this._encapsCache.reset();
+ }
+
+ writeEmptyEncapsulation(encoding)
+ {
+ Protocol.checkSupportedEncoding(encoding);
+ this.writeInt(6); // Size
+ encoding._write(this);
+ }
+
+ writeEncapsulation(v)
+ {
+ if(v.length < 6)
+ {
+ throw new Ice.EncapsulationException();
+ }
+ this.expand(v.length);
+ this._buf.putArray(v);
+ }
+
+ getEncoding()
+ {
+ return this._encapsStack !== null ? this._encapsStack.encoding : this._encoding;
+ }
+
+ startSlice(typeId, compactId, last)
+ {
+ Debug.assert(this._encapsStack !== null && this._encapsStack.encoder !== null);
+ this._encapsStack.encoder.startSlice(typeId, compactId, last);
+ }
+
+ endSlice()
+ {
+ Debug.assert(this._encapsStack !== null && this._encapsStack.encoder !== null);
+ this._encapsStack.encoder.endSlice();
+ }
+
+ writePendingValues()
+ {
+ if(this._encapsStack !== null && this._encapsStack.encoder !== null)
+ {
+ this._encapsStack.encoder.writePendingValues();
+ }
+ else if((this._encapsStack !== null && this._encapsStack.encoding_1_0) ||
+ (this._encapsStack === null && this._encoding.equals(Ice.Encoding_1_0)))
+ {
+ //
+ // If using the 1.0 encoding and no instances were written, we
+ // still write an empty sequence for pending instances if
+ // requested (i.e.: if this is called).
+ //
+ // This is required by the 1.0 encoding, even if no instances
+ // are written we do marshal an empty sequence if marshaled
+ // data types use classes.
+ //
+ this.writeSize(0);
+ }
+ }
+
+ writeSize(v)
+ {
+ if(v > 254)
+ {
+ this.expand(5);
+ this._buf.put(255);
+ this._buf.putInt(v);
+ }
+ else
+ {
+ this.expand(1);
+ this._buf.put(v);
+ }
+ }
+
+ startSize()
+ {
+ const pos = this._buf.position;
+ this.writeInt(0); // Placeholder for 32-bit size
+ return pos;
+ }
+
+ endSize(pos)
+ {
+ Debug.assert(pos >= 0);
+ this.rewriteInt(this._buf.position - pos - 4, pos);
+ }
+
+ writeBlob(v)
+ {
+ if(v === null)
+ {
+ return;
+ }
+ this.expand(v.length);
+ this._buf.putArray(v);
+ }
+
+ // Read/write format and tag for optionals
+ writeOptional(tag, format)
+ {
+ Debug.assert(this._encapsStack !== null);
+ if(this._encapsStack.encoder !== null)
+ {
+ return this._encapsStack.encoder.writeOptional(tag, format);
+ }
+ return this.writeOptImpl(tag, format);
+ }
+
+ writeOptionalHelper(tag, format, write, v)
+ {
+ if(v !== undefined)
+ {
+ if(this.writeOptional(tag, format))
+ {
+ write.call(this, v);
+ }
+ }
+ }
+
+ writeByte(v)
+ {
+ this.expand(1);
+ this._buf.put(v);
+ }
+
+ rewriteByte(v, dest)
+ {
+ this._buf.putAt(dest, v);
+ }
+
+ writeByteSeq(v)
+ {
+ if(v === null || v.length === 0)
+ {
+ this.writeSize(0);
+ }
+ else
+ {
+ this.writeSize(v.length);
+ this.expand(v.length);
+ this._buf.putArray(v);
+ }
+ }
+
+ writeBool(v)
+ {
+ this.expand(1);
+ this._buf.put(v ? 1 : 0);
+ }
+
+ rewriteBool(v, dest)
+ {
+ this._buf.putAt(dest, v ? 1 : 0);
+ }
+
+ writeShort(v)
+ {
+ this.expand(2);
+ this._buf.putShort(v);
+ }
+
+ writeInt(v)
+ {
+ this.expand(4);
+ this._buf.putInt(v);
+ }
+
+ rewriteInt(v, dest)
+ {
+ this._buf.putIntAt(dest, v);
+ }
+
+ writeLong(v)
+ {
+ this.expand(8);
+ this._buf.putLong(v);
+ }
+
+ writeFloat(v)
+ {
+ this.expand(4);
+ this._buf.putFloat(v);
+ }
+
+ writeDouble(v)
+ {
+ this.expand(8);
+ this._buf.putDouble(v);
+ }
+
+ writeString(v)
+ {
+ if(v === null || v.length === 0)
+ {
+ this.writeSize(0);
+ }
+ else
+ {
+ this._buf.writeString(this, v);
+ }
+ }
+
+ writeProxy(v)
+ {
+ if(v !== null)
+ {
+ v._write(this);
+ }
+ else
+ {
+ const ident = new Ice.Identity();
+ ident._write(this);
+ }
+ }
+
+ writeOptionalProxy(tag, v)
+ {
+ if(v !== undefined)
+ {
+ if(this.writeOptional(tag, OptionalFormat.FSize))
+ {
+ const pos = this.startSize();
+ this.writeProxy(v);
+ this.endSize(pos);
+ }
+ }
+ }
+
+ writeEnum(v)
+ {
+ if(this.isEncoding_1_0())
+ {
+ if(v.maxValue < 127)
+ {
+ this.writeByte(v.value);
+ }
+ else if(v.maxValue < 32767)
+ {
+ this.writeShort(v.value);
+ }
+ else
+ {
+ this.writeInt(v.value);
+ }
+ }
+ else
+ {
+ this.writeSize(v.value);
+ }
+ }
+
+ writeValue(v)
+ {
+ this.initEncaps();
+ this._encapsStack.encoder.writeValue(v);
+ }
+
+ writeOptionalValue(tag, v)
+ {
+ if(v !== undefined)
+ {
+ if(this.writeOptional(tag, OptionalFormat.Class))
+ {
+ this.writeValue(v);
+ }
+ }
+ }
+
+ writeUserException(e)
+ {
+ this.initEncaps();
+ this._encapsStack.encoder.writeUserException(e);
+ }
+
+ writeOptImpl(tag, format)
+ {
+ if(this.isEncoding_1_0())
+ {
+ return false; // Optional members aren't supported with the 1.0 encoding.
+ }
+
+ let v = format.value;
+ if(tag < 30)
+ {
+ v |= tag << 3;
+ this.writeByte(v);
+ }
+ else
+ {
+ v |= 0x0F0; // tag = 30
+ this.writeByte(v);
+ this.writeSize(tag);
+ }
+ return true;
+ }
+
+ isEmpty()
+ {
+ return this._buf.empty();
+ }
+
+ expand(n)
+ {
+ this._buf.expand(n);
+ }
+
+ isEncoding_1_0()
+ {
+ return this._encapsStack ? this._encapsStack.encoding_1_0 : this._encoding.equals(Ice.Encoding_1_0);
+ }
+
+ initEncaps()
+ {
+ if(!this._encapsStack) // Lazy initialization
+ {
+ this._encapsStack = this._encapsCache;
+ if(this._encapsStack)
+ {
+ this._encapsCache = this._encapsCache.next;
+ }
+ else
+ {
+ this._encapsStack = new WriteEncaps();
+ }
+ this._encapsStack.setEncoding(this._encoding);
+ }
+
+ if(this._encapsStack.format === FormatType.DefaultFormat)
+ {
+ this._encapsStack.format = this._instance.defaultsAndOverrides().defaultFormat;
+ }
+
+ if(!this._encapsStack.encoder) // Lazy initialization.
+ {
+ if(this._encapsStack.encoding_1_0)
+ {
+ this._encapsStack.encoder = new EncapsEncoder10(this, this._encapsStack);
+ }
+ else
+ {
+ this._encapsStack.encoder = new EncapsEncoder11(this, this._encapsStack);
+ }
+ }
+ }
+
+ //
+ // Sets the encoding format for class and exception instances.
+ //
+ get format()
+ {
+ return this._format;
+ }
+
+ set format(value)
+ {
+ this._format = value;
+ }
+
+ get pos()
+ {
+ return this._buf.position;
+ }
+
+ set pos(value)
+ {
+ this._buf.position = value;
+ }
+
+ get size()
+ {
+ return this._buf.limit;
+ }
+
+ get instance()
+ {
+ return this._instance;
+ }
+
+ get closure()
+ {
+ return this._closure;
+ }
+
+ set closure(value)
+ {
+ this._closure = value;
+ }
+
+ get buffer()
+ {
+ return this._buf;
+ }
+}
+
+const defineBuiltinHelper = function(write, read, sz, format, min, max)
+{
+ const helper = class
+ {
+ static write(os, v)
+ {
+ return write.call(os, v);
+ }
+
+ static read(is)
+ {
+ return read.call(is);
+ }
+
+ static writeOptional(os, tag, v)
+ {
+ os.writeOptionalHelper(tag, format, write, v);
+ }
+
+ static readOptional(is, tag)
+ {
+ return is.readOptionalHelper(tag, format, read);
+ }
+
+ static get minWireSize()
+ {
+ return sz;
+ }
+ };
+
+ if(min !== undefined && max !== undefined)
+ {
+ helper.validate = function(v)
+ {
+ return v >= min && v <= max;
+ };
+ }
+
+ return helper;
+};
+
+const istr = InputStream.prototype;
+const ostr = OutputStream.prototype;
+
+//
+// Constants to use in number type range checks.
+//
+const MIN_UINT8_VALUE = 0x0;
+const MAX_UINT8_VALUE = 0xFF;
+
+const MIN_INT16_VALUE = -0x8000;
+const MAX_INT16_VALUE = 0x7FFF;
+
+const MIN_UINT32_VALUE = 0x0;
+const MAX_UINT32_VALUE = 0xFFFFFFFF;
+
+const MIN_INT32_VALUE = -0x80000000;
+const MAX_INT32_VALUE = 0x7FFFFFFF;
+
+const MIN_FLOAT32_VALUE = -3.4028234664e+38;
+const MAX_FLOAT32_VALUE = 3.4028234664e+38;
+
+Ice.ByteHelper = defineBuiltinHelper(ostr.writeByte, istr.readByte, 1, Ice.OptionalFormat.F1,
+ MIN_UINT8_VALUE, MAX_UINT8_VALUE);
+
+Ice.ShortHelper = defineBuiltinHelper(ostr.writeShort, istr.readShort, 2, Ice.OptionalFormat.F2,
+ MIN_INT16_VALUE, MAX_INT16_VALUE);
+
+Ice.IntHelper = defineBuiltinHelper(ostr.writeInt, istr.readInt, 4, Ice.OptionalFormat.F4,
+ MIN_INT32_VALUE, MAX_INT32_VALUE);
+
+Ice.FloatHelper = defineBuiltinHelper(ostr.writeFloat, istr.readFloat, 4, Ice.OptionalFormat.F4,
+ MIN_FLOAT32_VALUE, MAX_FLOAT32_VALUE);
+Ice.FloatHelper.validate = function(v)
+{
+ return Number.isNaN(v) || v == Number.POSITIVE_INFINITY || v == Number.NEGATIVE_INFINITY ||
+ (v >= MIN_FLOAT32_VALUE && v <= MAX_FLOAT32_VALUE);
+};
+
+Ice.DoubleHelper = defineBuiltinHelper(ostr.writeDouble, istr.readDouble, 8, Ice.OptionalFormat.F8,
+ -Number.MAX_VALUE, Number.MAX_VALUE);
+Ice.DoubleHelper.validate = function(v)
+{
+ return Number.isNaN(v) || v == Number.POSITIVE_INFINITY || v == Number.NEGATIVE_INFINITY ||
+ (v >= -Number.MAX_VALUE && v <= Number.MAX_VALUE);
+};
+
+Ice.BoolHelper = defineBuiltinHelper(ostr.writeBool, istr.readBool, 1, Ice.OptionalFormat.F1);
+Ice.LongHelper = defineBuiltinHelper(ostr.writeLong, istr.readLong, 8, Ice.OptionalFormat.F8);
+Ice.LongHelper.validate = function(v)
+{
+ //
+ // For a long to be valid both words must be within the range of UINT32
+ //
+ return v.low >= MIN_UINT32_VALUE && v.low <= MAX_UINT32_VALUE &&
+ v.high >= MIN_UINT32_VALUE && v.high <= MAX_UINT32_VALUE;
+};
+
+Ice.StringHelper = defineBuiltinHelper(ostr.writeString, istr.readString, 1, Ice.OptionalFormat.VSize);
+
+Ice.ObjectHelper = class
+{
+ static write(os, v)
+ {
+ os.writeValue(v);
+ }
+
+ static read(is)
+ {
+ let o;
+ is.readValue(v => o = v, Ice.Value);
+ return o;
+ }
+
+ static writeOptional(os, tag, v)
+ {
+ os.writeOptionalValue(tag, Ice.OptionalFormat.Class, ostr.writeValue, v);
+ }
+
+ static readOptional(is, tag)
+ {
+ let o;
+ is.readOptionalValue(tag, v => o = v, Ice.Value);
+ return o;
+ }
+
+ static get minWireSize()
+ {
+ return 1;
+ }
+};
+
+Ice.InputStream = InputStream;
+Ice.OutputStream = OutputStream;
+module.exports.Ice = Ice;
diff --git a/js/src/Ice/StreamHelpers.js b/js/src/Ice/StreamHelpers.js
index 956dfb6c0e0..0460ade564d 100644
--- a/js/src/Ice/StreamHelpers.js
+++ b/js/src/Ice/StreamHelpers.js
@@ -7,32 +7,29 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Class", "../Ice/HashMap", "../Ice/OptionalFormat"]);
+const Ice = require("../Ice/OptionalFormat").Ice;
-var Class = Ice.Class;
-var defineProperty = Object.defineProperty;
-var HashMap = Ice.HashMap;
-var OptionalFormat = Ice.OptionalFormat;
+const defineProperty = Object.defineProperty;
+const OptionalFormat = Ice.OptionalFormat;
-var StreamHelpers = {};
+const StreamHelpers = {};
StreamHelpers.FSizeOptHelper = function()
{
- this.writeOpt = function(os, tag, v)
+ this.writeOptional = function(os, tag, v)
{
- if(v !== undefined && os.writeOpt(tag, OptionalFormat.FSize))
+ if(v !== undefined && os.writeOptional(tag, OptionalFormat.FSize))
{
- var pos = os.startSize();
+ const pos = os.startSize();
this.write(os, v);
os.endSize(pos);
}
};
- this.readOpt = function(is, tag)
+ this.readOptional = function(is, tag)
{
- var v;
- if(is.readOpt(tag, OptionalFormat.FSize))
+ let v;
+ if(is.readOptional(tag, OptionalFormat.FSize))
{
is.skip(4);
v = this.read(is);
@@ -43,19 +40,19 @@ StreamHelpers.FSizeOptHelper = function()
StreamHelpers.VSizeOptHelper = function()
{
- this.writeOpt = function(os, tag, v)
+ this.writeOptional = function(os, tag, v)
{
- if(v !== undefined && os.writeOpt(tag, OptionalFormat.VSize))
+ if(v !== undefined && os.writeOptional(tag, OptionalFormat.VSize))
{
os.writeSize(this.minWireSize);
this.write(os, v);
}
};
- this.readOpt = function(is, tag)
+ this.readOptional = function(is, tag)
{
- var v;
- if(is.readOpt(tag, OptionalFormat.VSize))
+ let v;
+ if(is.readOptional(tag, OptionalFormat.VSize))
{
is.skipSize();
v = this.read(is);
@@ -66,20 +63,20 @@ StreamHelpers.VSizeOptHelper = function()
StreamHelpers.VSizeContainerOptHelper = function(elementSize)
{
- this.writeOpt = function(os, tag, v)
+ this.writeOptional = function(os, tag, v)
{
- if(v !== undefined && os.writeOpt(tag, OptionalFormat.VSize))
+ if(v !== undefined && os.writeOptional(tag, OptionalFormat.VSize))
{
- var sz = this.size(v);
+ const sz = this.size(v);
os.writeSize(sz > 254 ? sz * elementSize + 5 : sz * elementSize + 1);
this.write(os, v);
}
};
- this.readOpt = function(is, tag)
+ this.readOptional = function(is, tag)
{
- var v;
- if(is.readOpt(tag, OptionalFormat.VSize))
+ let v;
+ if(is.readOptional(tag, OptionalFormat.VSize))
{
is.skipSize();
v = this.read(is);
@@ -90,18 +87,18 @@ StreamHelpers.VSizeContainerOptHelper = function(elementSize)
StreamHelpers.VSizeContainer1OptHelper = function()
{
- this.writeOpt = function(os, tag, v)
+ this.writeOptional = function(os, tag, v)
{
- if(v !== undefined && os.writeOpt(tag, OptionalFormat.VSize))
+ if(v !== undefined && os.writeOptional(tag, OptionalFormat.VSize))
{
this.write(os, v);
}
};
- this.readOpt = function(is, tag)
+ this.readOptional = function(is, tag)
{
- var v;
- if(is.readOpt(tag, OptionalFormat.VSize))
+ let v;
+ if(is.readOptional(tag, OptionalFormat.VSize))
{
v = this.read(is);
}
@@ -112,8 +109,9 @@ StreamHelpers.VSizeContainer1OptHelper = function()
//
// Sequence helper to write sequences
//
-var SequenceHelper = Class({
- write: function(os, v)
+class SequenceHelper
+{
+ write(os, v)
{
if(v === null || v.length === 0)
{
@@ -121,38 +119,43 @@ var SequenceHelper = Class({
}
else
{
- var helper = this.elementHelper;
+ const helper = this.elementHelper;
os.writeSize(v.length);
- for(var i = 0; i < v.length; ++i)
+ for(let i = 0; i < v.length; ++i)
{
helper.write(os, v[i]);
}
}
- },
- read: function(is)
+ }
+
+ read(is)
{
- var helper = this.elementHelper; // Cache the element helper.
- var sz = is.readAndCheckSeqSize(helper.minWireSize);
- var v = [];
+ const helper = this.elementHelper; // Cache the element helper.
+ const sz = is.readAndCheckSeqSize(helper.minWireSize);
+ const v = [];
v.length = sz;
- for(var i = 0; i < sz; ++i)
+ for(let i = 0; i < sz; ++i)
{
v[i] = helper.read(is);
}
return v;
- },
- size: function(v)
+ }
+
+ size(v)
{
return (v === null || v === undefined) ? 0 : v.length;
}
-});
+
+ get minWireSize()
+ {
+ return 1;
+ }
+}
+
-defineProperty(SequenceHelper.prototype, "minWireSize", {
- get: function(){ return 1; }
-});
// Speacialization optimized for ByteSeq
-var byteSeqHelper = new SequenceHelper();
+const byteSeqHelper = new SequenceHelper();
byteSeqHelper.write = function(os, v) { return os.writeByteSeq(v); };
byteSeqHelper.read = function(is) { return is.readByteSeq(); };
defineProperty(byteSeqHelper, "elementHelper", {
@@ -160,21 +163,21 @@ defineProperty(byteSeqHelper, "elementHelper", {
});
StreamHelpers.VSizeContainer1OptHelper.call(byteSeqHelper);
-// Read method for object sequences
-var objectSequenceHelperRead = function(is)
+// Read method for value sequences
+const valueSequenceHelperRead = function(is)
{
- var sz = is.readAndCheckSeqSize(1);
- var v = [];
+ const sz = is.readAndCheckSeqSize(1);
+ const v = [];
v.length = sz;
- var elementType = this.elementType;
- var readObjectAtIndex = function(idx)
+ const elementType = this.elementType;
+ const readValueAtIndex = function(idx)
{
- is.readObject(function(obj) { v[idx] = obj; }, elementType);
+ is.readValue(obj => v[idx] = obj, elementType);
};
- for(var i = 0; i < sz; ++i)
+ for(let i = 0; i < sz; ++i)
{
- readObjectAtIndex(i);
+ readValueAtIndex(i);
}
return v;
};
@@ -186,7 +189,7 @@ StreamHelpers.generateSeqHelper = function(elementHelper, fixed, elementType)
return byteSeqHelper;
}
- var helper = new SequenceHelper();
+ const helper = new SequenceHelper();
if(fixed)
{
if(elementHelper.minWireSize === 1)
@@ -212,7 +215,7 @@ StreamHelpers.generateSeqHelper = function(elementHelper, fixed, elementType)
defineProperty(helper, "elementType", {
get: function(){ return elementType; }
});
- helper.read = objectSequenceHelperRead;
+ helper.read = valueSequenceHelperRead;
}
return helper;
@@ -221,8 +224,9 @@ StreamHelpers.generateSeqHelper = function(elementHelper, fixed, elementType)
//
// Dictionary helper to write dictionaries
//
-var DictionaryHelper = Class({
- write: function(os, v)
+class DictionaryHelper
+{
+ write(os, v)
{
if(v === null || v.size === 0)
{
@@ -230,63 +234,66 @@ var DictionaryHelper = Class({
}
else
{
- var keyHelper = this.keyHelper;
- var valueHelper = this.valueHelper;
+ const keyHelper = this.keyHelper;
+ const valueHelper = this.valueHelper;
os.writeSize(v.size);
- for(var e = v.entries; e !== null; e = e.next)
+ for(let [key, value] of v)
{
- keyHelper.write(os, e.key);
- valueHelper.write(os, e.value);
+ keyHelper.write(os, key);
+ valueHelper.write(os, value);
}
}
- },
- read: function(is)
+ }
+
+ read(is)
{
- var mapType = this.mapType;
- var v = new mapType();
- var sz = is.readSize();
- var keyHelper = this.keyHelper;
- var valueHelper = this.valueHelper;
- for(var i = 0; i < sz; ++i)
+ const mapType = this.mapType;
+ const v = new mapType();
+ const sz = is.readSize();
+ const keyHelper = this.keyHelper;
+ const valueHelper = this.valueHelper;
+ for(let i = 0; i < sz; ++i)
{
v.set(keyHelper.read(is), valueHelper.read(is));
}
return v;
- },
- size: function(v)
+ }
+
+ size(v)
{
return (v === null || v === undefined) ? 0 : v.size;
}
-});
-
-Object.defineProperty(DictionaryHelper.prototype, "minWireSize", {
- get: function(){ return 1; }
-});
+
+ get minWireSize()
+ {
+ return 1;
+ }
+}
-// Read method for dictionaries of objects
-var objectDictionaryHelperRead = function(is)
+// Read method for dictionaries of values
+const valueDictionaryHelperRead = function(is)
{
- var sz = is.readSize();
- var mapType = this.mapType;
- var v = new mapType();
- var valueType = this.valueType;
+ const sz = is.readSize();
+ const mapType = this.mapType;
+ const v = new mapType();
+ const valueType = this.valueType;
- var readObjectForKey = function(key)
+ const readValueForKey = function(key)
{
- is.readObject(function(obj) { v.set(key, obj); }, valueType);
+ is.readValue(function(obj) { v.set(key, obj); }, valueType);
};
- var keyHelper = this.keyHelper;
- for(var i = 0; i < sz; ++i)
+ const keyHelper = this.keyHelper;
+ for(let i = 0; i < sz; ++i)
{
- readObjectForKey(keyHelper.read(is));
+ readValueForKey(keyHelper.read(is));
}
return v;
};
StreamHelpers.generateDictHelper = function(keyHelper, valueHelper, fixed, valueType, mapType)
{
- var helper = new DictionaryHelper();
+ const helper = new DictionaryHelper();
if(fixed)
{
StreamHelpers.VSizeContainerOptHelper.call(helper, keyHelper.minWireSize + valueHelper.minWireSize);
@@ -295,12 +302,15 @@ StreamHelpers.generateDictHelper = function(keyHelper, valueHelper, fixed, value
{
StreamHelpers.FSizeOptHelper.call(helper);
}
+
defineProperty(helper, "mapType", {
get: function(){ return mapType; }
});
+
defineProperty(helper, "keyHelper", {
get: function(){ return keyHelper; }
});
+
defineProperty(helper, "valueHelper", {
get: function(){ return valueHelper; }
});
@@ -310,7 +320,8 @@ StreamHelpers.generateDictHelper = function(keyHelper, valueHelper, fixed, value
defineProperty(helper, "valueType", {
get: function(){ return valueType; }
});
- helper.read = objectDictionaryHelperRead;
+
+ helper.read = valueDictionaryHelperRead;
}
return helper;
diff --git a/js/src/Ice/StringUtil.js b/js/src/Ice/StringUtil.js
index 2ab07467549..0f125dc3e02 100644
--- a/js/src/Ice/StringUtil.js
+++ b/js/src/Ice/StringUtil.js
@@ -7,66 +7,56 @@
//
// **********************************************************************
-var Ice = require("../Ice/Debug").Ice;
-var Debug = Ice.Debug;
+const Ice = require("../Ice/Debug").Ice;
+const Debug = Ice.Debug;
-Ice.StringUtil =
+Ice.StringUtil = class
{
//
// Return the index of the first character in str to
// appear in match, starting from start. Returns -1 if none is
// found.
//
- findFirstOf: function(str, match, start)
+ static findFirstOf(str, match, start)
{
start = start === undefined ? 0 : start;
-
- var len = str.length;
- for(var i = start; i < len; i++)
+ for(let i = start; i < str.length; i++)
{
- var ch = str.charAt(i);
+ const ch = str.charAt(i);
if(match.indexOf(ch) != -1)
{
return i;
}
}
-
return -1;
- },
+ }
//
// Return the index of the first character in str which does
// not appear in match, starting from start. Returns -1 if none is
// found.
//
- findFirstNotOf: function(str, match, start)
+ static findFirstNotOf(str, match, start)
{
start = start === undefined ? 0 : start;
-
- var len = str.length;
- for(var i = start; i < len; i++)
+ for(let i = start; i < str.length; i++)
{
- var ch = str.charAt(i);
+ const ch = str.charAt(i);
if(match.indexOf(ch) == -1)
{
return i;
}
}
-
return -1;
- },
+ }
//
- // Add escape sequences (such as "\n", or "\007") to make a string
- // readable in ASCII. Any characters that appear in special are
- // prefixed with a backlash in the returned string.
+ // Add escape sequences (such as "\n", or "\123") to s
//
- escapeString: function(s, special)
+ static escapeString(s, special, toStringMode)
{
special = special === undefined ? null : special;
-
- var i, length;
if(special !== null)
{
- for(i = 0, length = special.length; i < length; ++i)
+ for(let i = 0; i < special.length; ++i)
{
if(special.charCodeAt(i) < 32 || special.charCodeAt(i) > 126)
{
@@ -75,55 +65,107 @@ Ice.StringUtil =
}
}
- var result = [], c;
- for(i = 0, length = s.length; i < length; ++i)
+ let result = [];
+
+ if(toStringMode === Ice.ToStringMode.Compat)
{
- c = s.charCodeAt(i);
- if(c < 128)
- {
- encodeChar(c, result, special);
- }
- else if(c > 127 && c < 2048)
+ // Encode UTF-8 bytes
+ var bytes = unescape(encodeURIComponent(s));
+ for(let i = 0; i < bytes.length; ++i)
{
- encodeChar((c >> 6) | 192, result, special);
- encodeChar((c & 63) | 128, result, special);
+ const c = bytes.charCodeAt(i);
+ encodeChar(c, result, special, toStringMode);
}
- else
+ }
+ else
+ {
+ for(let i = 0; i < s.length; ++i)
{
- encodeChar((c >> 12) | 224, result, special);
- encodeChar(((c >> 6) & 63) | 128, result, special);
- encodeChar((c & 63) | 128, result, special);
+ const c = s.charCodeAt(i);
+ if(toStringMode === Ice.ToStringMode.Unicode || c < 0xD800 || c > 0xDFFF)
+ {
+ encodeChar(c, result, special, toStringMode);
+ }
+ else
+ {
+ Debug.assert(toStringMode === Ice.ToStringMode.ASCII && c >= 0xD800 && c <= 0xDFFF);
+ if(i + 1 === s.length)
+ {
+ throw new Error("High surrogate without low surrogate");
+ }
+ else
+ {
+ const codePoint = s.codePointAt(i);
+ Debug.assert(codePoint > 0xFFFF);
+ i++;
+
+ // append \Unnnnnnnn
+ result.push("\\U");
+ const hex = codePoint.toString(16);
+ for(let j = hex.length; j < 8; j++)
+ {
+ result.push('0');
+ }
+ result.push(hex);
+ }
+ }
}
}
-
return result.join("");
- },
+ }
//
// Remove escape sequences added by escapeString. Throws Error
// for an invalid input string.
//
- unescapeString: function(s, start, end)
+ static unescapeString(s, start, end, special)
{
start = start === undefined ? 0 : start;
end = end === undefined ? s.length : end;
+ special = special === undefined ? null : special;
Debug.assert(start >= 0 && start <= end && end <= s.length);
- var arr = [];
- decodeString(s, start, end, arr);
+ if(special !== null)
+ {
+ for(let i = 0; i < special.length; ++i)
+ {
+ if(special.charCodeAt(i) < 32 || special.charCodeAt(i) > 126)
+ {
+ throw new Error("special characters must be in ASCII range 32-126");
+ }
+ }
+ }
- return arr.join("");
- },
+ // Optimization for strings without escapes
+ let p = s.indexOf('\\', start);
+ if(p == -1 || p >= end)
+ {
+ p = start;
+ while(p < end)
+ {
+ checkChar(s, p++);
+ }
+ return s.substring(start, end);
+ }
+ else
+ {
+ const arr = [];
+ while(start < end)
+ {
+ start = decodeChar(s, start, end, special, arr);
+ }
+ return arr.join("");
+ }
+ }
//
// Split string helper; returns null for unmatched quotes
//
- splitString: function(str, delim)
+ static splitString(str, delim)
{
- var v = [];
- var s = "";
- var pos = 0;
-
- var quoteChar = null;
+ const v = [];
+ let s = "";
+ let pos = 0;
+ let quoteChar = null;
while(pos < str.length)
{
if(quoteChar === null && (str.charAt(pos) === '"' || str.charAt(pos) === '\''))
@@ -177,24 +219,23 @@ Ice.StringUtil =
}
return v;
- },
+ }
//
// If a single or double quotation mark is found at the start position,
// then the position of the matching closing quote is returned. If no
// quotation mark is found at the start position, then 0 is returned.
// If no matching closing quote is found, then -1 is returned.
//
- checkQuote: function(s, start)
+ static checkQuote(s, start)
{
start = start === undefined ? 0 : start;
- var quoteChar = s.charAt(start);
+ let quoteChar = s.charAt(start);
if(quoteChar == '"' || quoteChar == '\'')
{
start++;
- var len = s.length;
- var pos;
- while(start < len && (pos = s.indexOf(quoteChar, start)) != -1)
+ let pos;
+ while(start < s.length && (pos = s.indexOf(quoteChar, start)) != -1)
{
if(s.charAt(pos - 1) != '\\')
{
@@ -205,22 +246,19 @@ Ice.StringUtil =
return -1; // Unmatched quote
}
return 0; // Not quoted
- },
- hashCode: function(s)
+ }
+ static hashCode(s)
{
- var hash = 0;
- var n = s.length;
-
- for(var i = 0; i < n; i++)
+ let hash = 0;
+ for(let i = 0; i < s.length; i++)
{
hash = 31 * hash + s.charCodeAt(i);
}
-
return hash;
- },
- toInt: function(s)
+ }
+ static toInt(s)
{
- var n = parseInt(s, 10);
+ const n = parseInt(s, 10);
if(isNaN(n))
{
throw new Error("conversion of `" + s + "' to int failed");
@@ -230,15 +268,10 @@ Ice.StringUtil =
};
module.exports.Ice = Ice;
-//
-// Write the byte b as an escape sequence if it isn't a printable ASCII
-// character and append the escape sequence to sb. Additional characters
-// that should be escaped can be passed in special. If b is any of these
-// characters, b is preceded by a backslash in sb.
-//
-function encodeChar(b, sb, special)
+
+function encodeChar(c, sb, special, toStringMode)
{
- switch(b)
+ switch(c)
{
case 92: // '\\'
{
@@ -255,6 +288,19 @@ function encodeChar(b, sb, special)
sb.push("\\\"");
break;
}
+ case 7: // '\a'
+ {
+ if(toStringMode == Ice.ToStringMode.Compat)
+ {
+ // Octal escape for compatibility with 3.6 and earlier
+ sb.push("\\007");
+ }
+ else
+ {
+ sb.push("\\a");
+ }
+ break;
+ }
case 8: // '\b'
{
sb.push("\\b");
@@ -280,48 +326,88 @@ function encodeChar(b, sb, special)
sb.push("\\t");
break;
}
+ case 11: // '\v'
+ {
+ if(toStringMode == Ice.ToStringMode.Compat)
+ {
+ // Octal escape for compatibility with 3.6 and earlier
+ sb.push("\\013");
+ }
+ else
+ {
+ sb.push("\\v");
+ }
+ break;
+ }
default:
{
- if(!(b >= 32 && b <= 126))
+ var s = String.fromCharCode(c);
+
+ if(special !== null && special.indexOf(s) !== -1)
{
sb.push('\\');
- var octal = b.toString(8);
- //
- // Add leading zeroes so that we avoid problems during
- // decoding. For example, consider the encoded string
- // \0013 (i.e., a character with value 1 followed by
- // the character '3'). If the leading zeroes were omitted,
- // the result would be incorrectly interpreted by the
- // decoder as a single character with value 11.
- //
- for(var j = octal.length; j < 3; j++)
- {
- sb.push('0');
- }
- sb.push(octal);
+ sb.push(s);
}
else
{
- var c = String.fromCharCode(b);
- if(special !== null && special.indexOf(c) !== -1)
+ if(c < 32 || c > 126)
{
- sb.push('\\');
- sb.push(c);
+ if(toStringMode === Ice.ToStringMode.Compat)
+ {
+ //
+ // When ToStringMode=Compat, c is a UTF-8 byte
+ //
+ Debug.assert(c < 256);
+ sb.push('\\');
+ const octal = c.toString(8);
+ //
+ // Add leading zeroes so that we avoid problems during
+ // decoding. For example, consider the encoded string
+ // \0013 (i.e., a character with value 1 followed by
+ // the character '3'). If the leading zeroes were omitted,
+ // the result would be incorrectly interpreted by the
+ // decoder as a single character with value 11.
+ //
+ for(let j = octal.length; j < 3; j++)
+ {
+ sb.push('0');
+ }
+ sb.push(octal);
+ }
+ else if(c < 32 || c == 127 || toStringMode === Ice.ToStringMode.ASCII)
+ {
+ // append \\unnnn
+ sb.push("\\u");
+ const hex = c.toString(16);
+ for(let j = hex.length; j < 4; j++)
+ {
+ sb.push('0');
+ }
+ sb.push(hex);
+ }
+ else
+ {
+ // keep as is
+ sb.push(s);
+ }
}
else
{
- sb.push(c);
+ // printable ASCII character
+ sb.push(s);
}
}
+ break;
}
}
}
+
function checkChar(s, pos)
{
- var n = s.charCodeAt(pos);
- if(!(n >= 32 && n <= 126))
+ const c = s.charCodeAt(pos);
+ if(c < 32 || c === 127)
{
- var msg;
+ let msg;
if(pos > 0)
{
msg = "character after `" + s.substring(0, pos) + "'";
@@ -330,76 +416,133 @@ function checkChar(s, pos)
{
msg = "first character";
}
- msg += " is not a printable ASCII character (ordinal " + n + ")";
+ msg += " has invalid ordinal value" + c;
throw new Error(msg);
}
- return n;
+ return s.charAt(pos)
}
-
//
-// Decode the character or escape sequence starting at start and return it.
-// nextStart is set to the index of the first character following the decoded
-// character or escape sequence.
+// Decode the character or escape sequence starting at start and appends it to result;
+// returns the index of the first character following the decoded character
+// or escape sequence.
//
-function decodeChar(s, start, end, nextStart)
+function decodeChar(s, start, end, special, result)
{
Debug.assert(start >= 0);
+ Debug.assert(start < end);
Debug.assert(end <= s.length);
- if(start >= end)
+ if(s.charAt(start) != '\\')
{
- throw new Error("EOF while decoding string");
+ result.push(checkChar(s, start++));
}
-
- var c;
-
- if(s.charAt(start) != '\\')
+ else if(start + 1 === end)
{
- c = checkChar(s, start++);
+ ++start;
+ result.push("\\"); // trailing backslash
}
else
{
- if(start + 1 == end)
- {
- throw new Error("trailing backslash");
- }
- switch(s.charAt(++start))
+ let c = s.charAt(++start);
+
+ switch(c)
{
case '\\':
case '\'':
case '"':
+ case '?':
{
- c = s.charCodeAt(start++);
+ ++start;
+ result.push(c);
+ break;
+ }
+ case 'a':
+ {
+ ++start;
+ result.append("\u0007");
break;
}
case 'b':
{
++start;
- c = "\b".charCodeAt(0);
+ result.push("\b");
break;
}
case 'f':
{
++start;
- c = "\f".charCodeAt(0);
+ result.push("\f");
break;
}
case 'n':
{
++start;
- c = "\n".charCodeAt(0);
+ result.push("\n");
break;
}
case 'r':
{
++start;
- c = "\r".charCodeAt(0);
+ result.push("\r")
break;
}
case 't':
{
++start;
- c = "\t".charCodeAt(0);
+ result.push("\t")
+ break;
+ }
+ case 'v':
+ {
+ ++start;
+ result.push("\v");
+ break;
+ }
+ case 'u':
+ case 'U':
+ {
+ let codePoint = 0;
+ const inBMP = (c === 'u');
+ let size = inBMP ? 4 : 8;
+ ++start;
+ while(size > 0 && start < end)
+ {
+ let charVal = s.charCodeAt(start++);
+ if(charVal >= 0x30 && charVal <= 0x39)
+ {
+ charVal -= 0x30;
+ }
+ else if(charVal >= 0x61 && charVal <= 0x66)
+ {
+ charVal += 10 - 0x61;
+ }
+ else if(charVal >= 0x41 && charVal <= 0x46)
+ {
+ charVal += 10 - 0x41;
+ }
+ else
+ {
+ break; // while
+ }
+ codePoint = codePoint * 16 + charVal;
+ --size;
+ }
+ if(size > 0)
+ {
+ throw new Error("Invalid universal character name: too few hex digits");
+ }
+ if(codePoint >= 0xD800 && codePoint <= 0xDFFF)
+ {
+ throw new Error("A universal character name cannot designate a surrogate");
+ }
+ if(inBMP || codePoint <= 0xFFFF)
+ {
+ result.push(String.fromCharCode(codePoint));
+ }
+ else
+ {
+ result.push(String.fromCodePoint(codePoint));
+ }
break;
}
case '0':
@@ -410,67 +553,95 @@ function decodeChar(s, start, end, nextStart)
case '5':
case '6':
case '7':
+ case 'x':
{
- var octalChars = "01234567";
- var val = 0;
- for(var j = 0; j < 3 && start < end; ++j)
+ // UTF-8 byte sequence encoded with octal or hex escapes
+
+ let arr = [];
+ let more = true;
+ while(more)
{
- var ch = s.charAt(start++);
- if(octalChars.indexOf(ch) == -1)
+ let val = 0;
+ if(c === 'x')
{
- --start;
- break;
+ let size = 2;
+ ++start;
+ while(size > 0 && start < end)
+ {
+ let charVal = s.charCodeAt(start++);
+ if(charVal >= 0x30 && charVal <= 0x39)
+ {
+ charVal -= 0x30;
+ }
+ else if(charVal >= 0x61 && charVal <= 0x66)
+ {
+ charVal += 10 - 0x61;
+ }
+ else if(charVal >= 0x41 && charVal <= 0x46)
+ {
+ charVal += 10 - 0x41;
+ }
+ else
+ {
+ break; // while
+ }
+ val = val * 16 + charVal;
+ --size;
+ }
+ if(size === 2)
+ {
+ throw new Error("Invalid \\x escape sequence: no hex digit");
+ }
+ }
+ else
+ {
+ for(let j = 0; j < 3 && start < end; ++j)
+ {
+ let charVal = s.charCodeAt(start++) - '0'.charCodeAt(0);
+ if(charVal < 0 || charVal > 7)
+ {
+ --start; // move back
+ Debug.assert(j !== 0); // must be at least one digit
+ break; // for
+ }
+ val = val * 8 + charVal;
+ }
+ if(val > 255)
+ {
+ throw new Error("octal value \\" + val.toString(8) + " (" + val + ") is out of range");
+ }
+ }
+
+ arr.push(String.fromCharCode(val));
+
+ more = false;
+ if((start + 1 < end) && s.charAt(start) === '\\')
+ {
+ c = s.charAt(start + 1);
+ let charVal = s.charCodeAt(start + 1);
+ if(c === 'x' || (charVal >= 0x30 && charVal <= 0x39))
+ {
+ start++;
+ more = true;
+ }
}
- val = val * 8 + parseInt(ch);
- }
- if(val > 255)
- {
- var msg = "octal value \\" + val.toString(8) + " (" + val + ") is out of range";
- throw new Error(msg);
}
- c = val;
+
+ // Decode UTF-8 arr into string
+ result.push(decodeURIComponent(escape(arr.join(""))));
break;
}
default:
{
- c = checkChar(s, start++);
+ if(special === null || special.length === 0 || special.indexOf(c) === -1)
+ {
+ result.push("\\"); // not in special, so we keep the backslash
+ }
+ result.push(checkChar(s, start++));
break;
}
}
}
- nextStart.value = start;
- return c;
-}
-
-//
-// Remove escape sequences from s and append the result to sb.
-// Return true if successful, false otherwise.
-//
-function decodeString(s, start, end, arr)
-{
- var nextStart = { 'value': 0 }, c, c2, c3;
- while(start < end)
- {
- c = decodeChar(s, start, end, nextStart);
- start = nextStart.value;
- if(c < 128)
- {
- arr.push(String.fromCharCode(c));
- }
- else if(c > 191 && c < 224)
- {
- c2 = decodeChar(s, start, end, nextStart);
- start = nextStart.value;
- arr.push(String.fromCharCode(((c & 31) << 6) | (c2 & 63)));
- }
- else
- {
- c2 = decodeChar(s, start, end, nextStart);
- start = nextStart.value;
- c3 = decodeChar(s, start, end, nextStart);
- start = nextStart.value;
- arr.push(String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)));
- }
- }
+ return start;
}
diff --git a/js/src/Ice/Struct.js b/js/src/Ice/Struct.js
index caf6a96316e..e18d1889b3f 100644
--- a/js/src/Ice/Struct.js
+++ b/js/src/Ice/Struct.js
@@ -7,22 +7,22 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
"../Ice/HashUtil",
"../Ice/ArrayUtil",
"../Ice/StreamHelpers"
]);
-var ArrayUtil = Ice.ArrayUtil;
+const ArrayUtil = Ice.ArrayUtil;
//
// Use generic equality test from ArrayUtil.
//
-var eq = ArrayUtil.eq;
+const eq = ArrayUtil.eq;
-var equals = function(other)
+function equals(other)
{
if(this === other)
{
@@ -39,11 +39,10 @@ var equals = function(other)
return false;
}
- var e1, e2;
- for(var key in this)
+ for(let key in this)
{
- e1 = this[key];
- e2 = other[key];
+ let e1 = this[key];
+ let e2 = other[key];
if(typeof e1 == "function")
{
continue; // Don't need to compare functions
@@ -54,15 +53,14 @@ var equals = function(other)
}
}
return true;
-};
+}
-var clone = function()
+function clone()
{
- var other = new this.constructor();
- var e;
- for(var key in this)
+ const other = new this.constructor();
+ for(let key in this)
{
- e = this[key];
+ let e = this[key];
if(e === undefined || e === null)
{
other[key] = e;
@@ -85,9 +83,9 @@ var clone = function()
}
}
return other;
-};
+}
-var memberHashCode = function(h, e)
+function memberHashCode(h, e)
{
if(typeof e.hashCode == "function")
{
@@ -99,7 +97,7 @@ var memberHashCode = function(h, e)
}
else
{
- var t = typeof(e);
+ const t = typeof(e);
if(e instanceof String || t == "string")
{
return Ice.HashUtil.addString(h, e);
@@ -113,28 +111,25 @@ var memberHashCode = function(h, e)
return Ice.HashUtil.addBoolean(h, e);
}
}
-};
+}
-var hashCode = function()
+function hashCode()
{
- var __h = 5381;
- var e;
- for(var key in this)
+ let h = 5381;
+ for(let key in this)
{
- e = this[key];
+ let e = this[key];
if(e === undefined || e === null || typeof e == "function")
{
continue;
}
- __h = memberHashCode(__h, e);
+ h = memberHashCode(h, e);
}
- return __h;
-};
+ return h;
+}
-Ice.Slice.defineStruct = function(constructor, legalKeyType, writeImpl, readImpl, minWireSize, fixed)
+Ice.Slice.defineStruct = function(obj, legalKeyType, variableLength)
{
- var obj = constructor;
-
obj.prototype.clone = clone;
obj.prototype.equals = equals;
@@ -147,10 +142,8 @@ Ice.Slice.defineStruct = function(constructor, legalKeyType, writeImpl, readImpl
obj.prototype.hashCode = hashCode;
}
- if(readImpl && writeImpl)
+ if(obj.prototype._write && obj.prototype._read)
{
- obj.prototype.__write = writeImpl;
- obj.prototype.__read = readImpl;
obj.write = function(os, v)
{
if(!v)
@@ -161,27 +154,26 @@ Ice.Slice.defineStruct = function(constructor, legalKeyType, writeImpl, readImpl
}
v = obj.prototype._nullMarshalValue;
}
- v.__write(os);
+ v._write(os);
};
+
obj.read = function(is, v)
{
if(!v || !(v instanceof this))
{
v = new this();
}
- v.__read(is);
+ v._read(is);
return v;
};
- Object.defineProperty(obj, "minWireSize", {
- get: function() { return minWireSize; }
- });
- if(fixed)
+
+ if(variableLength)
{
- Ice.StreamHelpers.VSizeOptHelper.call(obj);
+ Ice.StreamHelpers.FSizeOptHelper.call(obj);
}
else
{
- Ice.StreamHelpers.FSizeOptHelper.call(obj);
+ Ice.StreamHelpers.VSizeOptHelper.call(obj);
}
}
return obj;
diff --git a/js/src/Ice/TcpEndpointFactory.js b/js/src/Ice/TcpEndpointFactory.js
index ecf9a44d6fd..7ef0e6f672c 100644
--- a/js/src/Ice/TcpEndpointFactory.js
+++ b/js/src/Ice/TcpEndpointFactory.js
@@ -7,45 +7,50 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Class", "../Ice/TcpEndpointI"]);
+const Ice = require("../Ice/TcpEndpointI").Ice;
+const TcpEndpointI = Ice.TcpEndpointI;
-var TcpEndpointI = Ice.TcpEndpointI;
-
-var TcpEndpointFactory = Ice.Class({
- __init__: function(instance)
+class TcpEndpointFactory
+{
+ constructor(instance)
{
this._instance = instance;
- },
- type: function()
+ }
+
+ type()
{
return this._instance.type();
- },
- protocol: function()
+ }
+
+ protocol()
{
return this._instance.protocol();
- },
- create: function(args, oaEndpoint)
+ }
+
+ create(args, oaEndpoint)
{
- var e = new TcpEndpointI(this._instance);
+ const e = new TcpEndpointI(this._instance);
e.initWithOptions(args, oaEndpoint);
return e;
- },
- read: function(s)
+ }
+
+ read(s)
{
- var e = new TcpEndpointI(this._instance);
+ const e = new TcpEndpointI(this._instance);
e.initWithStream(s);
return e;
- },
- destroy: function()
+ }
+
+ destroy()
{
this._instance = null;
- },
- clone:function(instance)
+ }
+
+ clone(instance)
{
return new TcpEndpointFactory(instance);
}
-});
+}
Ice.TcpEndpointFactory = TcpEndpointFactory;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/TcpEndpointI.js b/js/src/Ice/TcpEndpointI.js
index 195cc8214a4..9993ca11011 100644
--- a/js/src/Ice/TcpEndpointI.js
+++ b/js/src/Ice/TcpEndpointI.js
@@ -7,10 +7,9 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/Debug",
"../Ice/HashUtil",
"../Ice/StringUtil",
@@ -20,44 +19,47 @@ Ice.__M.require(module,
"../Ice/EndpointInfo"
]);
-var IceSSL = Ice.__M.require(module, ["../Ice/EndpointInfo"]).IceSSL;
+const IceSSL = Ice._ModuleRegistry.require(module, ["../Ice/EndpointInfo"]).IceSSL;
-var Debug = Ice.Debug;
-var HashUtil = Ice.HashUtil;
-var StringUtil = Ice.StringUtil;
-var TcpTransceiver = typeof(Ice.TcpTransceiver) !== "undefined" ? Ice.TcpTransceiver : null;
-var Class = Ice.Class;
+const Debug = Ice.Debug;
+const HashUtil = Ice.HashUtil;
+const StringUtil = Ice.StringUtil;
+const TcpTransceiver = typeof(Ice.TcpTransceiver) !== "undefined" ? Ice.TcpTransceiver : null;
-var TcpEndpointI = Class(Ice.IPEndpointI, {
- __init__: function(instance, ho, po, sif, ti, conId, co)
+class TcpEndpointI extends Ice.IPEndpointI
+{
+ constructor(instance, ho, po, sif, ti, conId, co)
{
- Ice.IPEndpointI.call(this, instance, ho, po, sif, conId);
+ super(instance, ho, po, sif, conId);
this._timeout = ti === undefined ? (instance ? instance.defaultTimeout() : undefined) : ti;
this._compress = co === undefined ? false : co;
- },
+ }
+
//
// Return the endpoint information.
//
- getInfo: function()
+ getInfo()
{
- var info = this.secure() ? new IceSSL.EndpointInfo() : new Ice.TCPEndpointInfo();
+ const info = new Ice.TCPEndpointInfo();
this.fillEndpointInfo(info);
- return info;
- },
+ return this.secure() ? new IceSSL.EndpointInfo(info, info.timeout, info.compress) : info;
+ }
+
//
// Return the timeout for the endpoint in milliseconds. 0 means
// non-blocking, -1 means no timeout.
//
- timeout: function()
+ timeout()
{
return this._timeout;
- },
+ }
+
//
// Return a new endpoint with a different timeout value, provided
// that timeouts are supported by the endpoint. Otherwise the same
// endpoint is returned.
//
- changeTimeout: function(timeout)
+ changeTimeout(timeout)
{
if(timeout === this._timeout)
{
@@ -68,11 +70,12 @@ var TcpEndpointI = Class(Ice.IPEndpointI, {
return new TcpEndpointI(this._instance, this._host, this._port, this._sourceAddr, timeout,
this._connectionId, this._compress);
}
- },
+ }
+
//
// Return a new endpoint with a different connection id.
//
- changeConnectionId: function(connectionId)
+ changeConnectionId(connectionId)
{
if(connectionId === this._connectionId)
{
@@ -83,21 +86,23 @@ var TcpEndpointI = Class(Ice.IPEndpointI, {
return new TcpEndpointI(this._instance, this._host, this._port, this._sourceAddr, this._timeout,
connectionId, this._compress);
}
- },
+ }
+
//
// Return true if the endpoints support bzip2 compress, or false
// otherwise.
//
- compress: function()
+ compress()
{
return this._compress;
- },
+ }
+
//
// Return a new endpoint with a different compression value,
// provided that compression is supported by the
// endpoint. Otherwise the same endpoint is returned.
//
- changeCompress: function(compress)
+ changeCompress(compress)
{
if(compress === this._compress)
{
@@ -108,31 +113,35 @@ var TcpEndpointI = Class(Ice.IPEndpointI, {
return new TcpEndpointI(this._instance, this._host, this._port, this._sourceAddr, this._timeout,
this._connectionId, compress);
}
- },
+ }
+
//
// Return true if the endpoint is datagram-based.
//
- datagram: function()
+ datagram()
{
return false;
- },
- connectable: function()
+ }
+
+ connectable()
{
//
// TCP endpoints are not connectable when running in a browser, SSL
// isn't currently supported.
//
return TcpTransceiver !== null && !this.secure();
- },
- connect: function()
+ }
+
+ connect()
{
Debug.assert(!this.secure());
return TcpTransceiver.createOutgoing(this._instance, this.getAddress(), this._sourceAddr);
- },
+ }
+
//
// Convert the endpoint to its string form
//
- options: function()
+ options()
{
//
// WARNING: Certain features, such as proxy validation in Glacier2,
@@ -141,7 +150,7 @@ var TcpEndpointI = Class(Ice.IPEndpointI, {
// these features. Please review for all features that depend on the
// format of proxyToString() before changing this and related code.
//
- var s = Ice.IPEndpointI.prototype.options.call(this);
+ let s = super.options();
if(this._timeout == -1)
{
s += " -t infinite";
@@ -156,8 +165,9 @@ var TcpEndpointI = Class(Ice.IPEndpointI, {
s += " -z";
}
return s;
- },
- compareTo: function(p)
+ }
+
+ compareTo(p)
{
if(this === p)
{
@@ -192,36 +202,41 @@ var TcpEndpointI = Class(Ice.IPEndpointI, {
return 1;
}
- return Ice.IPEndpointI.prototype.compareTo.call(this, p);
- },
- streamWriteImpl: function(s)
+ return super.compareTo(p);
+ }
+
+ streamWriteImpl(s)
{
- Ice.IPEndpointI.prototype.streamWriteImpl.call(this, s);
+ super.streamWriteImpl(s);
s.writeInt(this._timeout);
s.writeBool(this._compress);
- },
- hashInit: function(h)
+ }
+
+ hashInit(h)
{
- h = Ice.IPEndpointI.prototype.hashInit.call(this, h);
+ h = super.hashInit(h);
h = HashUtil.addNumber(h, this._timeout);
h = HashUtil.addBoolean(h, this._compress);
return h;
- },
- fillEndpointInfo: function(info)
+ }
+
+ fillEndpointInfo(info)
{
- Ice.IPEndpointI.prototype.fillEndpointInfo.call(this, info);
+ super.fillEndpointInfo(info);
info.timeout = this._timeout;
info.compress = this._compress;
- },
- initWithStream: function(s)
+ }
+
+ initWithStream(s)
{
- Ice.IPEndpointI.prototype.initWithStream.call(this, s);
+ super.initWithStream(s);
this._timeout = s.readInt();
this._compress = s.readBool();
- },
- checkOption: function(option, argument, endpoint)
+ }
+
+ checkOption(option, argument, endpoint)
{
- if(Ice.IPEndpointI.prototype.checkOption.call(this, option, argument, endpoint))
+ if(super.checkOption(option, argument, endpoint))
{
return true;
}
@@ -239,7 +254,7 @@ var TcpEndpointI = Class(Ice.IPEndpointI, {
}
else
{
- var invalid = false;
+ let invalid = false;
try
{
this._timeout = StringUtil.toInt(argument);
@@ -270,12 +285,13 @@ var TcpEndpointI = Class(Ice.IPEndpointI, {
return false;
}
return true;
- },
- createEndpoint: function(host, port, conId)
+ }
+
+ createEndpoint(host, port, conId)
{
return new TcpEndpointI(this._instance, host, port, this._sourceAddr, this._timeout, conId, this._compress);
}
-});
+}
Ice.TcpEndpointI = TcpEndpointI;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/TcpTransceiver.js b/js/src/Ice/TcpTransceiver.js
index fd37d439701..ee4517566f3 100644
--- a/js/src/Ice/TcpTransceiver.js
+++ b/js/src/Ice/TcpTransceiver.js
@@ -7,12 +7,11 @@
//
// **********************************************************************
-var net = require("net");
+const net = require("net");
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/Debug",
"../Ice/ExUtil",
"../Ice/SocketOperation",
@@ -22,39 +21,41 @@ Ice.__M.require(module,
"../Ice/Timer"
]);
-var Debug = Ice.Debug;
-var ExUtil = Ice.ExUtil;
-var Network = Ice.Network;
-var SocketOperation = Ice.SocketOperation;
-var LocalException = Ice.LocalException;
-var SocketException = Ice.SocketException;
-var Timer = Ice.Timer;
-
-var StateNeedConnect = 0;
-var StateConnectPending = 1;
-var StateProxyConnectRequest = 2;
-var StateProxyConnectRequestPending = 3;
-var StateConnected = 4;
-var StateClosed = 5;
-
-var TcpTransceiver = Ice.Class({
- __init__: function(instance)
+const Debug = Ice.Debug;
+const ExUtil = Ice.ExUtil;
+const Network = Ice.Network;
+const SocketOperation = Ice.SocketOperation;
+const LocalException = Ice.LocalException;
+const SocketException = Ice.SocketException;
+const Timer = Ice.Timer;
+
+const StateNeedConnect = 0;
+const StateConnectPending = 1;
+const StateProxyConnectRequest = 2;
+const StateProxyConnectRequestPending = 3;
+const StateConnected = 4;
+const StateClosed = 5;
+
+class TcpTransceiver
+{
+ constructor(instance)
{
this._logger = instance.logger();
this._readBuffers = [];
this._readPosition = 0;
this._maxSendPacketSize = instance.properties().getPropertyAsIntWithDefault("Ice.TCP.SndSize", 512 * 1024);
- },
- setCallbacks: function(connectedCallback, bytesAvailableCallback, bytesWrittenCallback)
+ }
+
+ setCallbacks(connectedCallback, bytesAvailableCallback, bytesWrittenCallback)
{
this._connectedCallback = connectedCallback;
this._bytesAvailableCallback = bytesAvailableCallback;
this._bytesWrittenCallback = bytesWrittenCallback;
- },
+ }
//
// Returns SocketOperation.None when initialization is complete.
//
- initialize: function(readBuffer, writeBuffer)
+ initialize(readBuffer, writeBuffer)
{
try
{
@@ -70,9 +71,8 @@ var TcpTransceiver = Ice.Class({
host: this._addr.host,
localAddress: this._sourceAddr});
- var self = this;
- this._fd.on("connect", function() { self.socketConnected(); });
- this._fd.on("data", function(buf) { self.socketBytesAvailable(buf); });
+ this._fd.on("connect", () => this.socketConnected());
+ this._fd.on("data", buf => this.socketBytesAvailable(buf));
//
// The error callback can be triggered from the socket
@@ -81,8 +81,8 @@ var TcpTransceiver = Ice.Class({
// setImmediate. We do the same for close as a
// precaution. See also issue #6226.
//
- this._fd.on("close", function(err) { Timer.setImmediate(function() { self.socketClosed(err); }); });
- this._fd.on("error", function(err) { Timer.setImmediate(function() { self.socketError(err); }); });
+ this._fd.on("close", err => Timer.setImmediate(() => this.socketClosed(err)));
+ this._fd.on("error", err => Timer.setImmediate(() => this.socketError(err)));
return SocketOperation.Connect; // Waiting for connect to complete.
}
@@ -123,8 +123,9 @@ var TcpTransceiver = Ice.Class({
Debug.assert(this._state === StateConnected);
return SocketOperation.None;
- },
- register: function()
+ }
+
+ register()
{
this._registered = true;
this._fd.resume();
@@ -132,8 +133,9 @@ var TcpTransceiver = Ice.Class({
{
this._bytesAvailableCallback();
}
- },
- unregister: function()
+ }
+
+ unregister()
{
if(this._fd === null)
{
@@ -142,8 +144,9 @@ var TcpTransceiver = Ice.Class({
}
this._registered = false;
this._fd.pause();
- },
- close: function()
+ }
+
+ close()
{
if(this._fd === null)
{
@@ -163,19 +166,18 @@ var TcpTransceiver = Ice.Class({
{
this._fd = null;
}
- },
+ }
//
// Returns true if all of the data was flushed to the kernel buffer.
//
- write: function(byteBuffer)
+ write(byteBuffer)
{
if(this._exception)
{
throw this._exception;
}
- var bytesTotal = byteBuffer.remaining;
- var packetSize = bytesTotal;
+ let packetSize = byteBuffer.remaining;
Debug.assert(packetSize > 0);
if(this._maxSendPacketSize > 0 && packetSize > this._maxSendPacketSize)
@@ -185,43 +187,38 @@ var TcpTransceiver = Ice.Class({
while(packetSize > 0)
{
- var slice = byteBuffer.b.slice(byteBuffer.position, byteBuffer.position + packetSize);
+ const slice = byteBuffer.b.slice(byteBuffer.position, byteBuffer.position + packetSize);
- var self = this;
- var sync = true;
+ let sync = true;
/*jshint -W083 */
- sync = this._fd.write(slice, null, function() {
- if(sync)
+ sync = this._fd.write(new Buffer(slice), null, () =>
{
- return;
- }
-
- byteBuffer.position = byteBuffer.position + packetSize;
- self._bytesWrittenCallback(packetSize, bytesTotal);
- });
+ if(!sync)
+ {
+ this._bytesWrittenCallback();
+ }
+ });
/*jshint +W083 */
- if(sync)
+ byteBuffer.position = byteBuffer.position + packetSize;
+ if(!sync)
{
- byteBuffer.position = byteBuffer.position + packetSize;
+ return false; // Wait for callback to be called before sending more data.
+ }
- if(this._maxSendPacketSize > 0 && byteBuffer.remaining > this._maxSendPacketSize)
- {
- packetSize = this._maxSendPacketSize;
- }
- else
- {
- packetSize = byteBuffer.remaining;
- }
+ if(this._maxSendPacketSize > 0 && byteBuffer.remaining > this._maxSendPacketSize)
+ {
+ packetSize = this._maxSendPacketSize;
}
else
{
- return false;
+ packetSize = byteBuffer.remaining;
}
}
return true;
- },
- read: function(byteBuffer, moreData)
+ }
+
+ read(byteBuffer, moreData)
{
if(this._exception)
{
@@ -235,9 +232,8 @@ var TcpTransceiver = Ice.Class({
return false; // No data available.
}
- var avail = this._readBuffers[0].length - this._readPosition;
+ let avail = this._readBuffers[0].length - this._readPosition;
Debug.assert(avail > 0);
- var remaining = byteBuffer.remaining;
while(byteBuffer.remaining > 0)
{
@@ -246,8 +242,8 @@ var TcpTransceiver = Ice.Class({
avail = byteBuffer.remaining;
}
- this._readBuffers[0].copy(byteBuffer.b, byteBuffer.position, this._readPosition,
- this._readPosition + avail);
+ this._readBuffers[0].copy(new Buffer(byteBuffer.b), byteBuffer.position, this._readPosition,
+ this._readPosition + avail);
byteBuffer.position += avail;
this._readPosition += avail;
@@ -271,15 +267,17 @@ var TcpTransceiver = Ice.Class({
moreData.value = this._readBuffers.length > 0;
return byteBuffer.remaining === 0;
- },
- type: function()
+ }
+
+ type()
{
return "tcp";
- },
- getInfo: function()
+ }
+
+ getInfo()
{
Debug.assert(this._fd !== null);
- var info = new Ice.TCPConnectionInfo();
+ const info = new Ice.TCPConnectionInfo();
info.localAddress = this._fd.localAddress;
info.localPort = this._fd.localPort;
info.remoteAddress = this._fd.remoteAddress;
@@ -287,24 +285,29 @@ var TcpTransceiver = Ice.Class({
info.rcvSize = -1;
info.sndSize = this._maxSendPacketSize;
return info;
- },
- checkSendSize: function(stream)
+ }
+
+ checkSendSize(stream)
{
- },
- setBufferSize: function(rcvSize, sndSize)
+ }
+
+ setBufferSize(rcvSize, sndSize)
{
this._maxSendPacketSize = sndSize;
- },
- toString: function()
+ }
+
+ toString()
{
return this._desc;
- },
- socketConnected: function()
+ }
+
+ socketConnected()
{
Debug.assert(this._connectedCallback !== null);
this._connectedCallback();
- },
- socketBytesAvailable: function(buf)
+ }
+
+ socketBytesAvailable(buf)
{
Debug.assert(this._bytesAvailableCallback !== null);
@@ -317,8 +320,9 @@ var TcpTransceiver = Ice.Class({
this._readBuffers.push(buf);
this._bytesAvailableCallback();
}
- },
- socketClosed: function(err)
+ }
+
+ socketClosed(err)
{
//
// Don't call the closed callback if an error occurred; the error callback
@@ -328,8 +332,9 @@ var TcpTransceiver = Ice.Class({
{
this.socketError(null);
}
- },
- socketError: function(err)
+ }
+
+ socketError(err)
{
this._exception = translateError(this._state, err);
if(this._state < StateConnected)
@@ -341,7 +346,37 @@ var TcpTransceiver = Ice.Class({
this._bytesAvailableCallback();
}
}
-});
+
+ static createOutgoing(instance, addr, sourceAddr)
+ {
+ const transceiver = new TcpTransceiver(instance);
+
+ transceiver._fd = null;
+ transceiver._addr = addr;
+ transceiver._sourceAddr = sourceAddr;
+ transceiver._desc = "local address = <not connected>\nremote address = " + addr.host + ":" + addr.port;
+ transceiver._state = StateNeedConnect;
+ transceiver._registered = false;
+ transceiver._exception = null;
+
+ return transceiver;
+ }
+
+ static createIncoming(instance, fd)
+ {
+ const transceiver = new TcpTransceiver(instance);
+
+ transceiver._fd = fd;
+ transceiver._addr = null;
+ transceiver._sourceAddr = null;
+ transceiver._desc = fdToString(fd);
+ transceiver._state = StateConnected;
+ transceiver._registered = false;
+ transceiver._exception = null;
+
+ return transceiver;
+ }
+}
function fdToString(fd, targetAddr)
{
@@ -382,7 +417,7 @@ function addressesToString(localHost, localPort, remoteHost, remotePort, targetA
remoteHost = remoteHost === undefined ? null : remoteHost;
targetAddr = targetAddr === undefined ? null : targetAddr;
- var s = [];
+ const s = [];
s.push("local address = ");
s.push(localHost + ":" + localPort);
@@ -405,46 +440,16 @@ function addressesToString(localHost, localPort, remoteHost, remotePort, targetA
return s.join("");
}
-TcpTransceiver.createOutgoing = function(instance, addr, sourceAddr)
-{
- var transceiver = new TcpTransceiver(instance);
-
- transceiver._fd = null;
- transceiver._addr = addr;
- transceiver._sourceAddr = sourceAddr;
- transceiver._desc = "local address = <not connected>\nremote address = " + addr.host + ":" + addr.port;
- transceiver._state = StateNeedConnect;
- transceiver._registered = false;
- transceiver._exception = null;
-
- return transceiver;
-};
-TcpTransceiver.createIncoming = function(instance, fd)
-{
- var transceiver = new TcpTransceiver(instance);
-
- transceiver._fd = fd;
- transceiver._addr = null;
- transceiver._sourceAddr = null;
- transceiver._desc = fdToString(fd);
- transceiver._state = StateConnected;
- transceiver._registered = false;
- transceiver._exception = null;
-
- return transceiver;
-};
-
-
-var ECONNABORTED = "ECONNABORTED";
-var ECONNREFUSED = "ECONNREFUSED";
-var ECONNRESET = "ECONNRESET";
-var EHOSTUNREACH = "EHOSTUNREACH";
-var ENETUNREACH = "ENETUNREACH";
-var ENOTCONN = "ENOTCONN";
-var EPIPE = "EPIPE";
-var ESHUTDOWN = "ESHUTDOWN";
-var ETIMEDOUT = "ETIMEDOUT";
+const ECONNABORTED = "ECONNABORTED";
+const ECONNREFUSED = "ECONNREFUSED";
+const ECONNRESET = "ECONNRESET";
+const EHOSTUNREACH = "EHOSTUNREACH";
+const ENETUNREACH = "ENETUNREACH";
+const ENOTCONN = "ENOTCONN";
+const EPIPE = "EPIPE";
+const ESHUTDOWN = "ESHUTDOWN";
+const ETIMEDOUT = "ETIMEDOUT";
function connectionRefused(err)
{
diff --git a/js/src/Ice/Timer.js b/js/src/Ice/Timer.js
index 06fd370c813..8a5ffae51a8 100644
--- a/js/src/Ice/Timer.js
+++ b/js/src/Ice/Timer.js
@@ -7,66 +7,60 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/HashMap", "../Ice/LocalException", "../Ice/Class", "../Ice/TimerUtil"]);
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module, ["../Ice/LocalException", "../Ice/TimerUtil"]);
-var HashMap = Ice.HashMap;
-var CommunicatorDestroyedException = Ice.CommunicatorDestroyedException;
+const CommunicatorDestroyedException = Ice.CommunicatorDestroyedException;
-var Timer = Ice.Class({
- __init__: function(logger)
+class Timer
+{
+ constructor(logger)
{
this._logger = logger;
this._destroyed = false;
this._tokenId = 0;
- this._tokens = new HashMap();
- },
- destroy: function()
+ this._tokens = new Map();
+ }
+
+ destroy()
{
- var self = this;
- this._tokens.forEach(function(key, value){
- self.cancel(key);
- });
+ this._tokens.forEach((value, key) => this.cancel(key));
this._destroyed = true;
this._tokens.clear();
- },
- schedule: function(callback, delay)
+ }
+
+ schedule(callback, delay)
{
if(this._destroyed)
{
throw new CommunicatorDestroyedException();
}
-
- var token = this._tokenId++;
- var self = this;
- var id = Timer.setTimeout(function() { self.handleTimeout(token); }, delay);
+ const token = this._tokenId++;
+ const id = Timer.setTimeout(() => this.handleTimeout(token), delay);
this._tokens.set(token, { callback: callback, id: id, isInterval: false });
-
return token;
- },
- scheduleRepeated: function(callback, period)
+ }
+
+ scheduleRepeated(callback, period)
{
if(this._destroyed)
{
throw new CommunicatorDestroyedException();
}
-
- var token = this._tokenId++;
- var self = this;
-
- var id = Timer.setInterval(function() { self.handleInterval(token); }, period);
+ const token = this._tokenId++;
+ const id = Timer.setInterval(() => this.handleInterval(token), period);
this._tokens.set(token, { callback: callback, id: id, isInterval: true });
-
return token;
- },
- cancel: function(id)
+ }
+
+ cancel(id)
{
if(this._destroyed)
{
return false;
}
- var token = this._tokens.get(id);
+ const token = this._tokens.get(id);
if(token === undefined)
{
return false;
@@ -83,15 +77,16 @@ var Timer = Ice.Class({
}
return true;
- },
- handleTimeout: function(id)
+ }
+
+ handleTimeout(id)
{
if(this._destroyed)
{
return;
}
- var token = this._tokens.get(id);
+ const token = this._tokens.get(id);
if(token !== undefined)
{
this._tokens.delete(id);
@@ -104,15 +99,16 @@ var Timer = Ice.Class({
this._logger.warning("uncaught exception while executing timer:\n" + ex);
}
}
- },
- handleInterval: function(id)
+ }
+
+ handleInterval(id)
{
if(this._destroyed)
{
return;
}
- var token = this._tokens.get(id);
+ const token = this._tokens.get(id);
if(token !== undefined)
{
try
@@ -125,7 +121,7 @@ var Timer = Ice.Class({
}
}
}
-});
+}
Timer.setTimeout = Ice.Timer.setTimeout;
Timer.clearTimeout = Ice.Timer.clearTimeout;
diff --git a/js/src/Ice/TimerUtil.js b/js/src/Ice/TimerUtil.js
index 72ca50bece5..e0e26dca2eb 100644
--- a/js/src/Ice/TimerUtil.js
+++ b/js/src/Ice/TimerUtil.js
@@ -7,9 +7,11 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
+const Ice = require("../Ice/ModuleRegistry").Ice;
-var Timer = {};
+class Timer
+{
+}
Timer.setTimeout = setTimeout;
Timer.clearTimeout = clearTimeout;
@@ -18,4 +20,4 @@ Timer.clearInterval = clearInterval;
Timer.setImmediate = setImmediate;
Ice.Timer = Timer;
-module.exports.Ice = Ice; \ No newline at end of file
+module.exports.Ice = Ice;
diff --git a/js/src/Ice/DispatchStatus.js b/js/src/Ice/ToStringMode.js
index 38b31410e46..ed2112858dd 100644
--- a/js/src/Ice/DispatchStatus.js
+++ b/js/src/Ice/ToStringMode.js
@@ -1,12 +1,12 @@
// **********************************************************************
//
-// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
+// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.DispatchStatus = {DispatchOK: 0, DispatchUserException: 1, DispatchAsync: 2};
+const Ice = require("../Ice/EnumBase").Ice;
+Ice.ToStringMode = Ice.Slice.defineEnum([['Unicode', 0], ['ASCII',1], ['Compat',2]]);
module.exports.Ice = Ice;
diff --git a/js/src/Ice/TraceLevels.js b/js/src/Ice/TraceLevels.js
index 42fc9ae2307..eba2c695e89 100644
--- a/js/src/Ice/TraceLevels.js
+++ b/js/src/Ice/TraceLevels.js
@@ -7,56 +7,77 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
+const Ice = require("../Ice/ModuleRegistry").Ice;
Ice.TraceLevels = function(properties)
{
- var networkCat = "Network";
- var protocolCat = "Protocol";
- var retryCat = "Retry";
- var locationCat = "Locator";
- var slicingCat = "Slicing";
-
- var keyBase = "Ice.Trace.";
-
- var network = properties.getPropertyAsInt(keyBase + networkCat);
- var protocol = properties.getPropertyAsInt(keyBase + protocolCat);
- var retry = properties.getPropertyAsInt(keyBase + retryCat);
- var location = properties.getPropertyAsInt(keyBase + locationCat);
- var slicing = properties.getPropertyAsInt(keyBase + slicingCat);
+ const networkCat = "Network";
+ const protocolCat = "Protocol";
+ const retryCat = "Retry";
+ const locationCat = "Locator";
+ const slicingCat = "Slicing";
+
+ const keyBase = "Ice.Trace.";
+
+ const network = properties.getPropertyAsInt(keyBase + networkCat);
+ const protocol = properties.getPropertyAsInt(keyBase + protocolCat);
+ const retry = properties.getPropertyAsInt(keyBase + retryCat);
+ const location = properties.getPropertyAsInt(keyBase + locationCat);
+ const slicing = properties.getPropertyAsInt(keyBase + slicingCat);
+
properties.getPropertyAsInt(keyBase + "ThreadPool"); // Avoid an "unused property" warning.
- return Object.create(null, {
- 'network': {
- get: function() { return network; }
- },
- 'networkCat': {
- get: function() { return networkCat; }
- },
- 'protocol': {
- get: function() { return protocol; }
- },
- 'protocolCat': {
- get: function() { return protocolCat; }
- },
- 'retry': {
- get: function() { return retry; }
- },
- 'retryCat': {
- get: function() { return retryCat; }
- },
- 'location': {
- get: function() { return location; }
- },
- 'locationCat': {
- get: function() { return locationCat; }
- },
- 'slicing': {
- get: function() { return slicing; }
- },
- 'slicingCat': {
- get: function() { return slicingCat; }
- }
- });
+ return class
+ {
+ static get network()
+ {
+ return network;
+ }
+
+ static get networkCat()
+ {
+ return networkCat;
+ }
+
+ static get protocol()
+ {
+ return protocol;
+ }
+
+ static get protocolCat()
+ {
+ return protocolCat;
+ }
+
+ static get retry()
+ {
+ return retry;
+ }
+
+ static get retryCat()
+ {
+ return retryCat;
+ }
+
+ static get location()
+ {
+ return location;
+ }
+
+ static get locationCat()
+ {
+ return locationCat;
+ }
+
+ static get slicing()
+ {
+ return slicing;
+ }
+
+ static get slicingCat()
+ {
+ return slicingCat;
+ }
+ };
};
module.exports.Ice = Ice;
diff --git a/js/src/Ice/TraceUtil.js b/js/src/Ice/TraceUtil.js
index ac198b1ea54..eee9a10d7b1 100644
--- a/js/src/Ice/TraceUtil.js
+++ b/js/src/Ice/TraceUtil.js
@@ -7,11 +7,10 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
"../Ice/Debug",
- "../Ice/HashMap",
"../Ice/Protocol",
"../Ice/StringUtil",
"../Ice/Current",
@@ -21,167 +20,49 @@ Ice.__M.require(module,
//
// Local aliases.
//
-var Debug = Ice.Debug;
-var HashMap = Ice.HashMap;
-var Protocol = Ice.Protocol;
-var StringUtil = Ice.StringUtil;
-var OperationMode = Ice.OperationMode;
-var Identity = Ice.Identity;
+const Debug = Ice.Debug;
+const Protocol = Ice.Protocol;
+const StringUtil = Ice.StringUtil;
+const OperationMode = Ice.OperationMode;
+const Identity = Ice.Identity;
-var TraceUtil = {};
-
-TraceUtil.traceSend = function(stream, logger, traceLevels)
-{
- if(traceLevels.protocol >= 1)
- {
- var p = stream.pos;
- stream.pos = 0;
-
- var s = [];
- var type = printMessage(s, stream);
-
- logger.trace(traceLevels.protocolCat, "sending " + getMessageTypeAsString(type) + " " + s.join(""));
-
- stream.pos = p;
- }
-};
-
-TraceUtil.traceRecv = function(stream, logger, traceLevels)
-{
- if(traceLevels.protocol >= 1)
- {
- var p = stream.pos;
- stream.pos = 0;
-
- var s = [];
- var type = printMessage(s, stream);
-
- logger.trace(traceLevels.protocolCat, "received " + getMessageTypeAsString(type) + " " + s.join(""));
-
- stream.pos = p;
- }
-};
-
-TraceUtil.trace = function(heading, stream, logger, traceLevels)
-{
- if(traceLevels.protocol >= 1)
- {
- var p = stream.pos;
- stream.pos = 0;
-
- var s = [];
- s.push(heading);
- printMessage(s, stream);
-
- logger.trace(traceLevels.protocolCat, s.join(""));
- stream.pos = p;
- }
-};
-
-var slicingIds = new HashMap();
+const slicingIds = new Map();
function traceSlicing(kind, typeId, slicingCat, logger)
{
if(!slicingIds.has(typeId))
{
- var s = "unknown " + kind + " type `" + typeId + "'";
- logger.trace(slicingCat, s);
+ logger.trace(slicingCat, `unknown ${kind} type \`${typeId}'`);
slicingIds.set(typeId, 1);
}
}
-TraceUtil.dumpStream = function(stream)
-{
- var pos = stream.pos;
- stream.pos = 0;
-
- var data = stream.readBlob(stream.size());
- TraceUtil.dumpOctets(data);
-
- stream.pos = pos;
-};
-
-TraceUtil.dumpOctets = function(data)
+function printIdentityFacetOperation(s, stream)
{
- var inc = 8;
- var buf = [];
-
- for(var i = 0; i < data.length; i += inc)
+ let toStringMode = Ice.ToStringMode.Unicode;
+ if(stream.instance !== null)
{
- var j;
- for(j = i; j - i < inc; j++)
- {
- if(j < data.length)
- {
- var n = data[j];
- if(n < 0)
- {
- n += 256;
- }
- var s;
- if(n < 10)
- {
- s = " " + n;
- }
- else if(n < 100)
- {
- s = " " + n;
- }
- else
- {
- s = "" + n;
- }
- buf.push(s + " ");
- }
- else
- {
- buf.push(" ");
- }
- }
-
- buf.push('"');
-
- for(j = i; j < data.length && j - i < inc; j++)
- {
- if(data[j] >= 32 && data[j] < 127)
- {
- buf.push(String.fromCharCode(data[j]));
- }
- else
- {
- buf.push('.');
- }
- }
-
- buf.push("\"\n");
+ toStringMode = stream.instance.toStringMode();
}
- console.log(buf.join(""));
-};
+ const identity = new Identity();
+ identity._read(stream);
+ s.push("\nidentity = " + Ice.identityToString(identity, toStringMode));
-Ice.TraceUtil = TraceUtil;
-module.exports.Ice = Ice;
-
-function printIdentityFacetOperation(s, stream)
-{
- var identity = new Identity();
- identity.__read(stream);
- s.push("\nidentity = " + stream.instance.identityToString(identity));
-
- var facet = Ice.StringSeqHelper.read(stream);
+ const facet = Ice.StringSeqHelper.read(stream);
s.push("\nfacet = ");
if(facet.length > 0)
{
- s.push(StringUtil.escapeString(facet[0], ""));
+ s.push(StringUtil.escapeString(facet[0], "", toStringMode));
}
- var operation = stream.readString();
+ const operation = stream.readString();
s.push("\noperation = " + operation);
}
function printRequest(s, stream)
{
- var requestId = stream.readInt();
+ const requestId = stream.readInt();
s.push("\nrequest id = " + requestId);
if(requestId === 0)
{
@@ -193,10 +74,10 @@ function printRequest(s, stream)
function printBatchRequest(s, stream)
{
- var batchRequestNum = stream.readInt();
+ const batchRequestNum = stream.readInt();
s.push("\nnumber of requests = " + batchRequestNum);
- for(var i = 0; i < batchRequestNum; ++i)
+ for(let i = 0; i < batchRequestNum; ++i)
{
s.push("\nrequest #" + i + ':');
printRequestHeader(s, stream);
@@ -205,10 +86,10 @@ function printBatchRequest(s, stream)
function printReply(s, stream)
{
- var requestId = stream.readInt();
+ const requestId = stream.readInt();
s.push("\nrequest id = " + requestId);
- var replyStatus = stream.readByte();
+ const replyStatus = stream.readByte();
s.push("\nreply status = " + replyStatus + ' ');
switch(replyStatus)
@@ -291,7 +172,7 @@ function printReply(s, stream)
}
}
- var unknown = stream.readString();
+ const unknown = stream.readString();
s.push("\nunknown = " + unknown);
break;
}
@@ -305,7 +186,7 @@ function printReply(s, stream)
if(replyStatus === Protocol.replyOK || replyStatus === Protocol.replyUserException)
{
- var ver = stream.skipEncaps();
+ const ver = stream.skipEncapsulation();
if(!ver.equals(Ice.Encoding_1_0))
{
s.push("\nencoding = ");
@@ -318,7 +199,7 @@ function printRequestHeader(s, stream)
{
printIdentityFacetOperation(s, stream);
- var mode = stream.readByte();
+ const mode = stream.readByte();
s.push("\nmode = " + mode + ' ');
switch(OperationMode.valueOf(mode))
{
@@ -347,12 +228,12 @@ function printRequestHeader(s, stream)
}
}
- var sz = stream.readSize();
+ let sz = stream.readSize();
s.push("\ncontext = ");
while(sz-- > 0)
{
- var key = stream.readString();
- var value = stream.readString();
+ const key = stream.readString();
+ const value = stream.readString();
s.push(key + '/'+ value);
if(sz > 0)
{
@@ -360,7 +241,7 @@ function printRequestHeader(s, stream)
}
}
- var ver = stream.skipEncaps();
+ const ver = stream.skipEncapsulation();
if(!ver.equals(Ice.Encoding_1_0))
{
s.push("\nencoding = ");
@@ -375,22 +256,22 @@ function printHeader(s, stream)
stream.readByte();
stream.readByte();
-// var pMajor = stream.readByte();
-// var pMinor = stream.readByte();
+// const pMajor = stream.readByte();
+// const pMinor = stream.readByte();
// s.push("\nprotocol version = " + pMajor + "." + pMinor);
stream.readByte(); // major
stream.readByte(); // minor
-// var eMajor = stream.readByte();
-// var eMinor = stream.readByte();
+// const eMajor = stream.readByte();
+// const eMinor = stream.readByte();
// s.push("\nencoding version = " + eMajor + "." + eMinor);
stream.readByte(); // major
stream.readByte(); // minor
- var type = stream.readByte();
+ const type = stream.readByte();
s.push("\nmessage type = " + type + " (" + getMessageTypeAsString(type) + ')');
- var compress = stream.readByte();
+ const compress = stream.readByte();
s.push("\ncompression status = " + compress + ' ');
switch(compress)
{
@@ -419,14 +300,14 @@ function printHeader(s, stream)
}
}
- var size = stream.readInt();
+ const size = stream.readInt();
s.push("\nmessage size = " + size);
return type;
}
function printMessage(s, stream)
{
- var type = printHeader(s, stream);
+ const type = printHeader(s, stream);
switch(type)
{
@@ -482,3 +363,143 @@ function getMessageTypeAsString(type)
return "unknown";
}
}
+
+class TraceUtil
+{
+ static traceSend(stream, logger, traceLevels)
+ {
+ if(traceLevels.protocol >= 1)
+ {
+ const p = stream.pos;
+ const is = new Ice.InputStream(stream.instance, stream.getEncoding(), stream.buffer);
+ is.pos = 0;
+
+ const s = [];
+ const type = printMessage(s, is);
+
+ logger.trace(traceLevels.protocolCat, "sending " + getMessageTypeAsString(type) + " " + s.join(""));
+
+ stream.pos = p;
+ }
+ }
+
+ static traceRecv(stream, logger, traceLevels)
+ {
+ if(traceLevels.protocol >= 1)
+ {
+ const p = stream.pos;
+ stream.pos = 0;
+
+ const s = [];
+ const type = printMessage(s, stream);
+
+ logger.trace(traceLevels.protocolCat, "received " + getMessageTypeAsString(type) + " " + s.join(""));
+
+ stream.pos = p;
+ }
+ }
+
+ static traceOut(heading, stream, logger, traceLevels)
+ {
+ if(traceLevels.protocol >= 1)
+ {
+ const p = stream.pos;
+ const is = new Ice.InputStream(stream.instance, stream.getEncoding(), stream.buffer);
+ is.pos = 0;
+
+ const s = [];
+ s.push(heading);
+ printMessage(s, is);
+
+ logger.trace(traceLevels.protocolCat, s.join(""));
+ stream.pos = p;
+ }
+ }
+
+ static traceIn(heading, stream, logger, traceLevels)
+ {
+ if(traceLevels.protocol >= 1)
+ {
+ const p = stream.pos;
+ stream.pos = 0;
+
+ const s = [];
+ s.push(heading);
+ printMessage(s, stream);
+
+ logger.trace(traceLevels.protocolCat, s.join(""));
+ stream.pos = p;
+ }
+ }
+
+ static dumpStream(stream)
+ {
+ const pos = stream.pos;
+ stream.pos = 0;
+
+ const data = stream.readBlob(stream.size());
+ TraceUtil.dumpOctets(data);
+
+ stream.pos = pos;
+ }
+
+ static dumpOctets(data)
+ {
+ const inc = 8;
+ const buf = [];
+
+ for(let i = 0; i < data.length; i += inc)
+ {
+ for(let j = i; j - i < inc; j++)
+ {
+ if(j < data.length)
+ {
+ let n = data[j];
+ if(n < 0)
+ {
+ n += 256;
+ }
+ let s;
+ if(n < 10)
+ {
+ s = " " + n;
+ }
+ else if(n < 100)
+ {
+ s = " " + n;
+ }
+ else
+ {
+ s = "" + n;
+ }
+ buf.push(s + " ");
+ }
+ else
+ {
+ buf.push(" ");
+ }
+ }
+
+ buf.push('"');
+
+ for(let j = i; j < data.length && j - i < inc; j++)
+ {
+ if(data[j] >= 32 && data[j] < 127)
+ {
+ buf.push(String.fromCharCode(data[j]));
+ }
+ else
+ {
+ buf.push('.');
+ }
+ }
+
+ buf.push("\"\n");
+ }
+
+ console.log(buf.join(""));
+ }
+}
+
+Ice.TraceUtil = TraceUtil;
+module.exports.Ice = Ice;
diff --git a/js/src/Ice/UUID.js b/js/src/Ice/UUID.js
index d0e1d62bf67..9a63041768c 100644
--- a/js/src/Ice/UUID.js
+++ b/js/src/Ice/UUID.js
@@ -9,15 +9,15 @@
function generateUUID()
{
- var d = new Date().getTime();
- var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
- var r = (d + Math.random() * 16) % 16 | 0;
+ let d = new Date().getTime();
+ let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
+ let r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
});
return uuid;
}
-var Ice = require("../Ice/ModuleRegistry").Ice;
+const Ice = require("../Ice/ModuleRegistry").Ice;
Ice.generateUUID = generateUUID;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/UnknownSlicedObject.js b/js/src/Ice/UnknownSlicedObject.js
deleted file mode 100644
index 17cfb3bfba4..00000000000
--- a/js/src/Ice/UnknownSlicedObject.js
+++ /dev/null
@@ -1,76 +0,0 @@
-// **********************************************************************
-//
-// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
-//
-// This copy of Ice is licensed to you under the terms described in the
-// ICE_LICENSE file included in this distribution.
-//
-// **********************************************************************
-
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Object", "../Ice/Class"]);
-
-var SliceInfo = function()
-{
- /**
- * The Slice type ID for this slice.
- **/
- this.typeId = "";
-
- /**
- * The Slice compact type ID for this slice.
- **/
- this.compactId = -1;
-
- /**
- * The encoded bytes for this slice, including the leading size integer.
- **/
- this.bytes = [];
-
- /**
- * The Ice objects referenced by this slice.
- **/
- this.objects = [];
-
- /**
- * Whether or not the slice contains optional members.
- **/
- this.hasOptionalMembers = false;
-
- /**
- * Whether or not this is the last slice.
- **/
- this.isLastSlice = false;
-};
-Ice.SliceInfo = SliceInfo;
-
-var SlicedData = function(slices)
-{
- this.slices = slices;
-};
-Ice.SlicedData = SlicedData;
-
-var UnknownSlicedObject = Ice.Class(Ice.Object,
- {
- __init__: function(unknownTypeId)
- {
- this._unknownTypeId = unknownTypeId;
- },
- getUnknownTypeId: function()
- {
- return this._unknownTypeId;
- },
- __write: function(os)
- {
- os.startWriteObject(this._slicedData);
- os.endWriteObject();
- },
- __read: function(is)
- {
- is.startReadObject();
- this._slicedData = is.endReadObject(true);
- }
- });
-Ice.UnknownSlicedObject = UnknownSlicedObject;
-
-module.exports.Ice = Ice;
diff --git a/js/src/Ice/UnknownSlicedValue.js b/js/src/Ice/UnknownSlicedValue.js
new file mode 100644
index 00000000000..3348ef2e164
--- /dev/null
+++ b/js/src/Ice/UnknownSlicedValue.js
@@ -0,0 +1,85 @@
+// **********************************************************************
+//
+// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
+//
+// This copy of Ice is licensed to you under the terms described in the
+// ICE_LICENSE file included in this distribution.
+//
+// **********************************************************************
+
+const Ice = require("../Ice/Value").Ice;
+
+class SliceInfo
+{
+ constructor()
+ {
+ /**
+ * The Slice type ID for this slice.
+ **/
+ this.typeId = "";
+
+ /**
+ * The Slice compact type ID for this slice.
+ **/
+ this.compactId = -1;
+
+ /**
+ * The encoded bytes for this slice, including the leading size integer.
+ **/
+ this.bytes = [];
+
+ /**
+ * The class instances referenced by this slice.
+ **/
+ this.instances = [];
+
+ /**
+ * Whether or not the slice contains optional members.
+ **/
+ this.hasOptionalMembers = false;
+
+ /**
+ * Whether or not this is the last slice.
+ **/
+ this.isLastSlice = false;
+ }
+}
+Ice.SliceInfo = SliceInfo;
+
+class SlicedData
+{
+ constructor(slices)
+ {
+ this.slices = slices;
+ }
+}
+Ice.SlicedData = SlicedData;
+
+class UnknownSlicedValue extends Ice.Value
+{
+ constructor(unknownTypeId)
+ {
+ super();
+ this._unknownTypeId = unknownTypeId;
+ }
+
+ getUnknownTypeId()
+ {
+ return this._unknownTypeId;
+ }
+
+ _iceWrite(os)
+ {
+ os.startValue(this._slicedData);
+ os.endValue();
+ }
+
+ _iceRead(is)
+ {
+ is.startValue();
+ this._slicedData = is.endValue(true);
+ }
+}
+Ice.UnknownSlicedValue = UnknownSlicedValue;
+
+module.exports.Ice = Ice;
diff --git a/js/src/Ice/Value.js b/js/src/Ice/Value.js
new file mode 100644
index 00000000000..39f5b636778
--- /dev/null
+++ b/js/src/Ice/Value.js
@@ -0,0 +1,216 @@
+// **********************************************************************
+//
+// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
+//
+// This copy of Ice is licensed to you under the terms described in the
+// ICE_LICENSE file included in this distribution.
+//
+// **********************************************************************
+
+//
+// Ice.Value
+//
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
+ [
+ "../Ice/Exception",
+ "../Ice/FormatType",
+ "../Ice/StreamHelpers",
+ "../Ice/OptionalFormat"
+ ]);
+
+const ids = ["::Ice::Object"];
+
+Ice.Value = class
+{
+ ice_preMarshal()
+ {
+ }
+
+ ice_postUnmarshal()
+ {
+ }
+
+ _iceWrite(os)
+ {
+ os.startValue(null);
+ writeImpl(this, os, this._iceMostDerivedType());
+ os.endValue();
+ }
+
+ _iceRead(is)
+ {
+ is.startValue();
+ readImpl(this, is, this._iceMostDerivedType());
+ is.endValue(false);
+ }
+
+ //
+ // These methods are used for object parameters.
+ //
+ static write(os, v)
+ {
+ os.writeValue(v);
+ }
+
+ static writeOptional(os, tag, v)
+ {
+ os.writeOptionalValue(tag, v);
+ }
+
+ static read(is)
+ {
+ const v = { value: null };
+ is.readValue(o => v.value = o, this);
+ return v;
+ }
+
+ static readOptional(is, tag)
+ {
+ const v = { value: undefined };
+ is.readOptionalValue(tag, o => v.value = o, this);
+ return v;
+ }
+};
+
+Ice.InterfaceByValue = class extends Ice.Value
+{
+ constructor(id)
+ {
+ super();
+ this._id = id;
+ }
+
+ ice_id()
+ {
+ return this._id;
+ }
+
+ _iceWrite(os)
+ {
+ os.startValue(null);
+ os.startSlice(this.ice_id(), -1, true);
+ os.endSlice();
+ os.endValue();
+ }
+
+ _iceRead(is)
+ {
+ is.startValue();
+ is.startSlice();
+ is.endSlice();
+ is.endValue(false);
+ }
+};
+
+//
+// Private methods
+//
+const writeImpl = function(obj, os, type)
+{
+ //
+ // The writeImpl method is a recursive method that goes down the
+ // class hierarchy to marshal each slice of the class using the
+ // generated _iceWriteMemberImpl method.
+ //
+
+ if(type === undefined || type === Ice.Value)
+ {
+ return; // Don't marshal anything for Ice.Value
+ }
+
+ os.startSlice(type.ice_staticId(),
+ Object.prototype.hasOwnProperty.call(type, '_iceCompactId') ? type._iceCompactId : -1 ,
+ Object.getPrototypeOf(type) === Ice.Value);
+ if(type.prototype._iceWriteMemberImpl)
+ {
+ type.prototype._iceWriteMemberImpl.call(obj, os);
+ }
+ os.endSlice();
+ writeImpl(obj, os, Object.getPrototypeOf(type));
+};
+
+const readImpl = function(obj, is, type)
+{
+ //
+ // The readImpl method is a recursive method that goes down the
+ // class hierarchy to unmarshal each slice of the class using the
+ // generated _iceReadMemberImpl method.
+ //
+
+ if(type === undefined || type === Ice.Value)
+ {
+ return; // Don't unmarshal anything for Ice.Value
+ }
+
+ is.startSlice();
+ if(type.prototype._iceReadMemberImpl)
+ {
+ type.prototype._iceReadMemberImpl.call(obj, is);
+ }
+ is.endSlice();
+ readImpl(obj, is, Object.getPrototypeOf(type));
+};
+
+function writePreserved(os)
+{
+ //
+ // For Slice classes which are marked "preserved", the implementation of this method
+ // replaces the Ice.Value.prototype._iceWrite method.
+ //
+ os.startValue(this._iceSlicedData);
+ writeImpl(this, os, this._iceMostDerivedType());
+ os.endValue();
+}
+
+function readPreserved(is)
+{
+ //
+ // For Slice classes which are marked "preserved", the implementation of this method
+ // replaces the Ice.Value.prototype._iceRead method.
+ //
+ is.startValue();
+ readImpl(this, is, this._iceMostDerivedType());
+ this._iceSlicedData = is.endValue(true);
+};
+
+
+const Slice = Ice.Slice;
+
+Slice.PreservedObject = function(obj)
+{
+ obj.prototype._iceWrite = writePreserved;
+ obj.prototype._iceRead = readPreserved;
+};
+
+Slice.defineValue = function(valueType, id, preserved, compactId = 0)
+{
+ valueType.prototype.ice_id = function()
+ {
+ return id;
+ }
+
+ valueType.prototype._iceMostDerivedType = function()
+ {
+ return valueType;
+ }
+
+ valueType.ice_staticId = function()
+ {
+ return id;
+ }
+
+ if(preserved)
+ {
+ valueType.prototype._iceWrite = writePreserved;
+ valueType.prototype._iceRead = readPreserved;
+ }
+
+ if(compactId > 0)
+ {
+ Ice.CompactIdRegistry.set(compactId, id);
+ }
+}
+Slice.defineValue(Ice.Value, "::Ice::Object");
+
+module.exports.Ice = Ice; \ No newline at end of file
diff --git a/js/src/Ice/ValueFactoryManagerI.js b/js/src/Ice/ValueFactoryManagerI.js
new file mode 100644
index 00000000000..03f9436a439
--- /dev/null
+++ b/js/src/Ice/ValueFactoryManagerI.js
@@ -0,0 +1,46 @@
+// **********************************************************************
+//
+// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
+//
+// This copy of Ice is licensed to you under the terms described in the
+// ICE_LICENSE file included in this distribution.
+//
+// **********************************************************************
+
+const Ice = require("../Ice/LocalException").Ice;
+
+const AlreadyRegisteredException = Ice.AlreadyRegisteredException;
+const NotRegisteredException = Ice.NotRegisteredException;
+
+//
+// Only for use by Instance
+//
+class ValueFactoryManagerI
+{
+ constructor()
+ {
+ this._factoryMap = new Map(); // Map<String, ValueFactory>
+ }
+
+ add(factory, id)
+ {
+ if(this._factoryMap.has(id))
+ {
+ throw new AlreadyRegisteredException("value factory", id);
+ }
+ this._factoryMap.set(id, factory);
+ }
+
+ find(id)
+ {
+ return this._factoryMap.get(id);
+ }
+
+ destroy()
+ {
+ this._factoryMap = new Map(); // Map<String, ValueFactory>
+ }
+}
+
+Ice.ValueFactoryManagerI = ValueFactoryManagerI;
+module.exports.Ice = Ice;
diff --git a/js/src/Ice/WSEndpoint.js b/js/src/Ice/WSEndpoint.js
index d78ed3403b8..7cd2f52bea8 100644
--- a/js/src/Ice/WSEndpoint.js
+++ b/js/src/Ice/WSEndpoint.js
@@ -7,11 +7,10 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
+const Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/HashUtil",
"../Ice/StringUtil",
"../Ice/EndpointI",
@@ -19,47 +18,55 @@ Ice.__M.require(module,
"../Ice/WSTransceiver",
"../Ice/EndpointInfo"
]);
-var IceSSL = Ice.__M.module("IceSSL");
-var HashUtil = Ice.HashUtil;
-var StringUtil = Ice.StringUtil;
-var EndpointI = Ice.EndpointI;
-var Class = Ice.Class;
+const HashUtil = Ice.HashUtil;
+const StringUtil = Ice.StringUtil;
+const EndpointI = Ice.EndpointI;
-var WSEndpoint = Class(EndpointI, {
- __init__: function(instance, del, re)
+class WSEndpoint extends EndpointI
+{
+ constructor(instance, del, re)
{
+ super();
this._instance = instance;
this._delegate = del;
this._resource = re || "/";
- },
- getInfo: function()
+ }
+
+ getInfo()
{
- var info = this._delegate.secure() ? new IceSSL.WSSEndpointInfo() : new Ice.WSEndpointInfo();
+ let info = new Ice.WSEndpointInfo();
info.resource = this._resource;
- this._delegate.fillEndpointInfo(info);
+ info.underlying = this._delegate.getInfo();
+ info.timeout = info.underlying.timeout;
+ info.compress = info.underlying.compress;
return info;
- },
- type: function()
+ }
+
+ type()
{
return this._delegate.type();
- },
- protocol: function()
+ }
+
+ protocol()
{
return this._delegate.protocol();
- },
- streamWrite: function(s)
+ }
+
+ streamWrite(s)
{
- s.startWriteEncaps();
+ s.startEncapsulation();
this._delegate.streamWriteImpl(s);
s.writeString(this._resource);
- s.endWriteEncaps();
- },
- timeout: function()
+ s.endEncapsulation();
+ }
+
+ timeout()
{
return this._delegate.timeout();
- },
- changeTimeout: function(timeout)
+ }
+
+ changeTimeout(timeout)
{
if(timeout === this._delegate.timeout())
{
@@ -69,8 +76,9 @@ var WSEndpoint = Class(EndpointI, {
{
return new WSEndpoint(this._instance, this._delegate.changeTimeout(timeout), this._resource);
}
- },
- changeConnectionId: function(connectionId)
+ }
+
+ changeConnectionId(connectionId)
{
if(connectionId === this._delegate.connectionId())
{
@@ -80,12 +88,14 @@ var WSEndpoint = Class(EndpointI, {
{
return new WSEndpoint(this._instance, this._delegate.changeConnectionId(connectionId), this._resource);
}
- },
- compress: function()
+ }
+
+ compress()
{
return this._delegate.compress();
- },
- changeCompress: function(compress)
+ }
+
+ changeCompress(compress)
{
if(compress === this._delegate.compress())
{
@@ -95,23 +105,27 @@ var WSEndpoint = Class(EndpointI, {
{
return new WSEndpoint(this._instance, this._delegate.changeCompress(compress), this._resource);
}
- },
- datagram: function()
+ }
+
+ datagram()
{
return this._delegate.datagram();
- },
- secure: function()
+ }
+
+ secure()
{
return this._delegate.secure();
- },
- connect: function()
+ }
+
+ connect()
{
return Ice.WSTransceiver.createOutgoing(this._instance,
this._delegate.secure(),
this._delegate.getAddress(),
this._resource);
- },
- hashCode: function()
+ }
+
+ hashCode()
{
if(this._hashCode === undefined)
{
@@ -119,8 +133,9 @@ var WSEndpoint = Class(EndpointI, {
this._hashCode = HashUtil.addString(this._hashCode, this._resource);
}
return this._hashCode;
- },
- compareTo: function(p)
+ }
+
+ compareTo(p)
{
if(this === p)
{
@@ -137,7 +152,7 @@ var WSEndpoint = Class(EndpointI, {
return this.type() < p.type() ? -1 : 1;
}
- var r = this._delegate.compareTo(p._delegate);
+ let r = this._delegate.compareTo(p._delegate);
if(r !== 0)
{
return r;
@@ -149,8 +164,9 @@ var WSEndpoint = Class(EndpointI, {
}
return 0;
- },
- options: function()
+ }
+
+ options()
{
//
// WARNING: Certain features, such as proxy validation in Glacier2,
@@ -159,7 +175,7 @@ var WSEndpoint = Class(EndpointI, {
// these features. Please review for all features that depend on the
// format of proxyToString() before changing this and related code.
//
- var s = this._delegate.options();
+ let s = this._delegate.options();
if(this._resource !== null && this._resource.length > 0)
{
@@ -168,16 +184,19 @@ var WSEndpoint = Class(EndpointI, {
}
return s;
- },
- toConnectorString: function()
+ }
+
+ toConnectorString()
{
return this._delegate.toConnectorString();
- },
- initWithStream: function(s)
+ }
+
+ initWithStream(s)
{
this._resource = s.readString();
- },
- checkOption: function(option, argument, endpoint)
+ }
+
+ checkOption(option, argument, endpoint)
{
if(option === "-r")
{
@@ -192,8 +211,8 @@ var WSEndpoint = Class(EndpointI, {
return false;
}
return true;
- },
-});
+ }
+}
if(typeof(Ice.WSTransceiver) !== "undefined")
{
diff --git a/js/src/Ice/WSEndpointFactory.js b/js/src/Ice/WSEndpointFactory.js
index 183ae653b74..78728436973 100644
--- a/js/src/Ice/WSEndpointFactory.js
+++ b/js/src/Ice/WSEndpointFactory.js
@@ -7,42 +7,48 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Class", "../Ice/WSEndpoint"]);
+const Ice = require("../Ice/WSEndpoint").Ice;
+const WSEndpoint = Ice.WSEndpoint;
-var WSEndpoint = Ice.WSEndpoint;
-
-var WSEndpointFactory = Ice.Class({
- __init__:function(instance, delegate)
+class WSEndpointFactory extends WSEndpoint
+{
+ constructor(instance, delegate)
{
+ super();
this._instance = instance;
this._delegate = delegate;
- },
- type: function()
+ }
+
+ type()
{
return this._instance.type();
- },
- protocol: function()
+ }
+
+ protocol()
{
return this._instance.protocol();
- },
- create: function(args, oaEndpoint)
+ }
+
+ create(args, oaEndpoint)
{
- var e = new WSEndpoint(this._instance, this._delegate.create(args, oaEndpoint));
+ let e = new WSEndpoint(this._instance, this._delegate.create(args, oaEndpoint));
e.initWithOptions(args);
return e;
- },
- read: function(s)
+ }
+
+ read(s)
{
- var e = new WSEndpoint(this._instance, this._delegate.read(s));
+ let e = new WSEndpoint(this._instance, this._delegate.read(s));
e.initWithStream(s);
return e;
- },
- destroy: function()
+ }
+
+ destroy()
{
this._delegate.destroy();
this._instance = null;
}
-});
+}
+
Ice.WSEndpointFactory = WSEndpointFactory;
-exports.Ice = Ice; \ No newline at end of file
+exports.Ice = Ice;
diff --git a/js/src/Ice/browser/Buffer.js b/js/src/Ice/browser/Buffer.js
deleted file mode 100644
index 58924541169..00000000000
--- a/js/src/Ice/browser/Buffer.js
+++ /dev/null
@@ -1,419 +0,0 @@
-// **********************************************************************
-//
-// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
-//
-// This copy of Ice is licensed to you under the terms described in the
-// ICE_LICENSE file included in this distribution.
-//
-// **********************************************************************
-
-var Ice = require("../Ice/ModuleRegistry").Ice;
-
-Ice.__M.require(module, ["../Ice/Class", "../Ice/Long"]);
-
-var Long = Ice.Long;
-
-//
-// IE 10 doesn't implement ArrayBuffer.slice
-//
-
-if(!ArrayBuffer.prototype.slice)
-{
- ArrayBuffer.prototype.slice = function (start, end)
- {
- var b = new Uint8Array(this);
- end = end === undefined ? b.length : end;
- var result = new Uint8Array(new ArrayBuffer(end - start));
- for(var i = 0, length = result.length; i < length; i++)
- {
- result[i] = b[i + start];
- }
- return result.buffer;
- };
-}
-
-var __BufferOverflowException__ = "BufferOverflowException";
-var __BufferUnderflowException__ = "BufferUnderflowException";
-var __IndexOutOfBoundsException__ = "IndexOutOfBoundsException";
-
-//
-// Buffer implementation to be used by web browsers, it uses ArrayBuffer as
-// the store.
-//
-var Buffer = Ice.Class({
- __init__: function(buffer)
- {
- if(buffer !== undefined)
- {
- this.b = buffer;
- this.v = new DataView(this.b);
- }
- else
- {
- this.b = null; // ArrayBuffer
- this.v = null; // DataView
- }
- this._position = 0;
- this._limit = 0;
- this._shrinkCounter = 0;
- },
- empty: function()
- {
- return this._limit === 0;
- },
- resize: function(n)
- {
- if(n === 0)
- {
- this.clear();
- }
- else if(n > this.capacity)
- {
- this.reserve(n);
- }
- this._limit = n;
- },
- clear: function()
- {
- this.b = null;
- this.v = null;
- this._position = 0;
- this._limit = 0;
- },
- //
- // Call expand(n) to add room for n additional bytes. Note that expand()
- // examines the current position of the buffer first; we don't want to
- // expand the buffer if the caller is writing to a location that is
- // already in the buffer.
- //
- expand: function(n)
- {
- var sz = this.capacity === 0 ? n : this._position + n;
- if(sz > this._limit)
- {
- this.resize(sz);
- }
- },
- reset: function()
- {
- if(this._limit > 0 && this._limit * 2 < this.capacity)
- {
- //
- // If the current buffer size is smaller than the
- // buffer capacity, we shrink the buffer memory to the
- // current size. This is to avoid holding on to too much
- // memory if it's not needed anymore.
- //
- if(++this._shrinkCounter > 2)
- {
- this.reserve(this._limit);
- this._shrinkCounter = 0;
- }
- }
- else
- {
- this._shrinkCounter = 0;
- }
- this._limit = 0;
- this._position = 0;
- },
- reserve: function(n)
- {
- if(n > this.capacity)
- {
- var capacity = Math.max(n, 2 * this.capacity);
- capacity = Math.max(1024, capacity);
- if(!this.b)
- {
- this.b = new ArrayBuffer(capacity);
- }
- else
- {
- var b = new Uint8Array(capacity);
- b.set(new Uint8Array(this.b));
- this.b = b.buffer;
- }
- this.v = new DataView(this.b);
- }
- else if(n < this.capacity)
- {
- this.b = this.b.slice(0, this.capacity);
- this.v = new DataView(this.b);
- }
- else
- {
- return;
- }
- },
- put: function(v)
- {
- if(this._position === this._limit)
- {
- throw new Error(__BufferOverflowException__);
- }
- this.v.setUint8(this._position, v);
- this._position++;
- },
- putAt: function(i, v)
- {
- if(i >= this._limit)
- {
- throw new Error(__IndexOutOfBoundsException__);
- }
- this.v.setUint8(i, v);
- },
- putArray: function(v)
- {
- //Expects an Uint8Array
- if(!(v instanceof Uint8Array))
- {
- throw new TypeError('argument is not a Uint8Array');
- }
- if(v.byteLength > 0)
- {
- if(this._position + v.length > this._limit)
- {
- throw new Error(__BufferOverflowException__);
- }
- new Uint8Array(this.b, 0, this.b.byteLength).set(v, this._position);
- this._position += v.byteLength;
- }
- },
- putShort: function(v)
- {
- if(this._position + 2 > this._limit)
- {
- throw new Error(__BufferOverflowException__);
- }
- this.v.setInt16(this._position, v, true);
- this._position += 2;
- },
- putInt: function(v)
- {
- if(this._position + 4 > this._limit)
- {
- throw new Error(__BufferOverflowException__);
- }
- this.v.setInt32(this._position, v, true);
- this._position += 4;
- },
- putIntAt: function(i, v)
- {
- if(i + 4 > this._limit || i < 0)
- {
- throw new Error(__IndexOutOfBoundsException__);
- }
- this.v.setInt32(i, v, true);
- },
- putFloat: function(v)
- {
- if(this._position + 4 > this._limit)
- {
- throw new Error(__BufferOverflowException__);
- }
- this.v.setFloat32(this._position, v, true);
- this._position += 4;
- },
- putDouble: function(v)
- {
- if(this._position + 8 > this._limit)
- {
- throw new Error(__BufferOverflowException__);
- }
- this.v.setFloat64(this._position, v, true);
- this._position += 8;
- },
- putLong: function(v)
- {
- if(this._position + 8 > this._limit)
- {
- throw new Error(__BufferOverflowException__);
- }
- this.v.setInt32(this._position, v.low, true);
- this._position += 4;
- this.v.setInt32(this._position, v.high, true);
- this._position += 4;
- },
- writeString: function(stream, v)
- {
- //
- // Encode the string as utf8
- //
- var encoded = unescape(encodeURIComponent(v));
-
- stream.writeSize(encoded.length);
- stream.expand(encoded.length);
- this.putString(encoded, encoded.length);
- },
- putString: function(v, sz)
- {
- if(this._position + sz > this._limit)
- {
- throw new Error(__BufferOverflowException__);
- }
- for(var i = 0; i < sz; ++i)
- {
- this.v.setUint8(this._position, v.charCodeAt(i));
- this._position++;
- }
- },
- get: function()
- {
- if(this._position >= this._limit)
- {
- throw new Error(__BufferUnderflowException__);
- }
- var v = this.v.getUint8(this._position);
- this._position++;
- return v;
- },
- getAt: function(i)
- {
- if(i < 0 || i >= this._limit)
- {
- throw new Error(__IndexOutOfBoundsException__);
- }
- return this.v.getUint8(i);
- },
- getArray: function(length)
- {
- if(this._position + length > this._limit)
- {
- throw new Error(__BufferUnderflowException__);
- }
- var buffer = this.b.slice(this._position, this._position + length);
- this._position += length;
- return new Uint8Array(buffer);
- },
- getArrayAt: function(position, length)
- {
- if(position + length > this._limit)
- {
- throw new Error(__BufferUnderflowException__);
- }
- length = length === undefined ? (this.b.byteLength - position) : length;
- return new Uint8Array(this.b.slice(position, position + length));
- },
- getShort: function()
- {
- if(this._limit - this._position < 2)
- {
- throw new Error(__BufferUnderflowException__);
- }
- var v = this.v.getInt16(this._position, true);
- this._position += 2;
- return v;
- },
- getInt: function()
- {
- if(this._limit - this._position < 4)
- {
- throw new Error(__BufferUnderflowException__);
- }
- var v = this.v.getInt32(this._position, true);
- this._position += 4;
- return v;
- },
- getFloat: function()
- {
- if(this._limit - this._position < 4)
- {
- throw new Error(__BufferUnderflowException__);
- }
- var v = this.v.getFloat32(this._position, true);
- this._position += 4;
- return v;
- },
- getDouble: function()
- {
- if(this._limit - this._position < 8)
- {
- throw new Error(__BufferUnderflowException__);
- }
- var v = this.v.getFloat64(this._position, true);
- this._position += 8;
- return v;
- },
- getLong: function()
- {
- if(this._limit - this._position < 8)
- {
- throw new Error(__BufferUnderflowException__);
- }
- var v = new Long();
- v.low = this.v.getUint32(this._position, true);
- this._position += 4;
- v.high = this.v.getUint32(this._position, true);
- this._position += 4;
- return v;
- },
- getString: function(length)
- {
- if(this._position + length > this._limit)
- {
- throw new Error(__BufferUnderflowException__);
- }
-
- var data = new DataView(this.b, this._position, length);
- var s = "";
-
- for(var i = 0; i < length; ++i)
- {
- s += String.fromCharCode(data.getUint8(i));
- }
- this._position += length;
- s = decodeURIComponent(escape(s));
- return s;
- }
-});
-
-var prototype = Buffer.prototype;
-
-Object.defineProperty(prototype, "position", {
- get: function() { return this._position; },
- set: function(position){
- if(position >= 0 && position <= this._limit)
- {
- this._position = position;
- }
- }
-});
-
-Object.defineProperty(prototype, "limit", {
- get: function() { return this._limit; },
- set: function(limit){
- if(limit <= this.capacity)
- {
- this._limit = limit;
- if(this._position > limit)
- {
- this._position = limit;
- }
- }
- }
-});
-
-Object.defineProperty(prototype, "capacity", {
- get: function() { return this.b === null ? 0 : this.b.byteLength; }
-});
-
-Object.defineProperty(prototype, "remaining", {
- get: function() { return this._limit - this._position; }
-});
-
-//
-// Create a native buffer from an array of bytes.
-//
-Buffer.createNative = function(data)
-{
- if(data === undefined)
- {
- return new Uint8Array(0);
- }
- else
- {
- return new Uint8Array(data);
- }
-};
-
-Ice.Buffer = Buffer;
diff --git a/js/src/Ice/browser/Debug.js b/js/src/Ice/browser/Debug.js
index ae3c81dd174..e81e4800972 100644
--- a/js/src/Ice/browser/Debug.js
+++ b/js/src/Ice/browser/Debug.js
@@ -7,22 +7,23 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module, ["../Ice/Class", "../Ice/Exception"]);
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module, ["../Ice/Class", "../Ice/Exception"]);
-Ice.AssertionFailedException = Ice.Class(Error,
+class AssertionFailedException extends Error
+{
+ constructor(message)
{
- __init__: function(message)
- {
- Error.call(this);
- Ice.Exception.captureStackTrace(this);
- this.message = message;
- }
- });
+ super();
+ Ice.Exception.captureStackTrace(this);
+ this.message = message;
+ }
+}
+Ice.AssertionFailedException = AssertionFailedException;
-Ice.Debug =
+class Debug
{
- assert: function(b, msg)
+ static assert(b, msg)
{
if(!b)
{
@@ -31,5 +32,7 @@ Ice.Debug =
throw new Ice.AssertionFailedException(msg === undefined ? "assertion failed" : msg);
}
}
-};
+}
+
+Ice.Debug = Debug;
module.exports.Ice = Ice;
diff --git a/js/src/Ice/browser/ModuleRegistry.js b/js/src/Ice/browser/ModuleRegistry.js
index a4c0e9d1082..006b28a937f 100644
--- a/js/src/Ice/browser/ModuleRegistry.js
+++ b/js/src/Ice/browser/ModuleRegistry.js
@@ -8,33 +8,35 @@
// **********************************************************************
/* globals self */
-var __root = typeof(window) !== "undefined" ? window : self;
+const root = typeof(window) !== "undefined" ? window : typeof(global) !== "undefined" ? global : typeof(self) !== "undefined" ? self : {};
/* globals -self */
-var __M =
+class _ModuleRegistry
{
- module: function(name)
+ static module(name)
{
- var m = __root[name];
+ var m = root[name];
if(m === undefined)
{
m = {};
- __root[name] = m;
+ root[name] = m;
}
return m;
- },
- require: function(name)
+ }
+
+ static require(name)
{
- return __root;
- },
- type: function(scoped)
+ return root;
+ }
+
+ static type(scoped)
{
if(scoped === undefined)
{
return undefined;
}
var components = scoped.split(".");
- var T = __root;
+ var T = root;
for(var i = 0, length = components.length; i < length; ++i)
{
@@ -46,14 +48,14 @@ var __M =
}
return T;
}
-};
+}
-var Ice = __M.module("Ice");
+const Ice = _ModuleRegistry.module("Ice");
-Ice.__require = function()
+Ice._require = function()
{
- return __root;
+ return root;
};
Ice.Slice = Ice.Slice || {};
-Ice.__M = __M;
+Ice._ModuleRegistry = _ModuleRegistry;
diff --git a/js/src/Ice/browser/TimerUtil.js b/js/src/Ice/browser/TimerUtil.js
index 9202d7f0d7d..3acbb4606ac 100644
--- a/js/src/Ice/browser/TimerUtil.js
+++ b/js/src/Ice/browser/TimerUtil.js
@@ -14,7 +14,7 @@
/* global WorkerGlobalScope */
-var Ice = require("../Ice/ModuleRegistry").Ice;
+const Ice = require("../Ice/ModuleRegistry").Ice;
//
// Create a timer object that uses the default browser methods. Note that we also
@@ -24,36 +24,57 @@ var Ice = require("../Ice/ModuleRegistry").Ice;
//
function createTimerObject()
{
- var Timer = {};
- Timer.setTimeout = function () { setTimeout.apply(null, arguments); };
- Timer.clearTimeout = function () { clearTimeout.apply(null, arguments); };
- Timer.setInterval = function () { setInterval.apply(null, arguments); };
- Timer.clearInterval = function () { clearInterval.apply(null, arguments); };
- Timer.setImmediate = typeof(setImmediate) == "function" ?
- function () { setImmediate.apply(null, arguments); } :
- function () { setTimeout.apply(null, arguments); };
- return Timer;
-}
+ let Timer = class
+ {
+ static setTimeout()
+ {
+ setTimeout.apply(null, arguments);
+ }
+
+ static clearTimeout()
+ {
+ clearTimeout.apply(null, arguments);
+ }
+ static setInterval()
+ {
+ setInterval.apply(null, arguments);
+ }
+
+ static clearInterval()
+ {
+ clearInterval.apply(null, arguments);
+ }
+ };
-Ice.__M.require(module,
- [
- "../Ice/HashMap",
- ]);
+ if(typeof(setImmediate) == "function")
+ {
+ Timer.setImmediate = function()
+ {
+ setImmediate.apply(null, arguments);
+ };
+ }
+ else
+ {
+ Timer.setImmediate = function()
+ {
+ setTimeout.apply(null, arguments);
+ };
+ }
-var HashMap = Ice.HashMap;
+ return Timer;
+}
-var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
+const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
-var _timers = new HashMap();
+const _timers = new Map();
-var _SetTimeoutType = 0,
- _SetIntervalType = 1,
- _SetImmediateType = 2,
- _ClearTimeoutType = 3,
- _ClearIntervalType = 4;
+const _SetTimeoutType = 0,
+ _SetIntervalType = 1,
+ _SetImmediateType = 2,
+ _ClearTimeoutType = 3,
+ _ClearIntervalType = 4;
-var Timer = {};
var worker;
var _nextId = 0;
@@ -67,59 +88,62 @@ var nextId = function()
return _nextId++;
};
-Timer.setTimeout = function(cb, ms)
-{
- var id = nextId();
- _timers.set(id, cb);
- worker.postMessage({type: _SetTimeoutType, id: id, ms: ms});
- return id;
-};
-
-Timer.clearTimeout = function(id)
-{
- _timers.delete(id);
- worker.postMessage({type: _ClearTimeoutType, id: id});
-};
-
-Timer.setInterval = function(cb, ms)
+class Timer
{
- var id = nextId();
- _timers.set(id, cb);
- worker.postMessage({type: _SetIntervalType, id: id, ms: ms});
- return id;
-};
+ static setTimeout(cb, ms)
+ {
+ var id = nextId();
+ _timers.set(id, cb);
+ worker.postMessage({type: _SetTimeoutType, id: id, ms: ms});
+ return id;
+ }
-Timer.clearInterval = function(id)
-{
- _timers.delete(id);
- worker.postMessage({type: _ClearIntervalType, id: id});
-};
+ static clearTimeout(id)
+ {
+ _timers.delete(id);
+ worker.postMessage({type: _ClearTimeoutType, id: id});
+ }
-Timer.setImmediate = function(cb)
-{
- var id = nextId();
- _timers.set(id, cb);
- worker.postMessage({type: _SetImmediateType, id: id});
- return id;
-};
+ static setInterval(cb, ms)
+ {
+ var id = nextId();
+ _timers.set(id, cb);
+ worker.postMessage({type: _SetIntervalType, id: id, ms: ms});
+ return id;
+ }
-Timer.onmessage = function(e)
-{
- var cb;
- if(e.data.type === _SetIntervalType)
+ static clearInterval(id)
{
- cb = _timers.get(e.data.id);
+ _timers.delete(id);
+ worker.postMessage({type: _ClearIntervalType, id: id});
}
- else
+
+ static setImmediate(cb)
{
- cb = _timers.delete(e.data.id);
+ var id = nextId();
+ _timers.set(id, cb);
+ worker.postMessage({type: _SetImmediateType, id: id});
+ return id;
}
- if(cb !== undefined)
+ static onmessage(e)
{
- cb.call();
+ var cb;
+ if(e.data.type === _SetIntervalType)
+ {
+ cb = _timers.get(e.data.id);
+ }
+ else
+ {
+ cb = _timers.delete(e.data.id);
+ }
+
+ if(cb !== undefined)
+ {
+ cb.call();
+ }
}
-};
+}
var workerCode = function()
{
@@ -137,23 +161,15 @@ var workerCode = function()
var timers = {};
- self.onmessage = function(e)
+ self.onmessage = e =>
{
if(e.data.type == _wSetTimeoutType)
{
- timers[e.data.id] = setTimeout(function()
- {
- self.postMessage(e.data);
- },
- e.data.ms);
+ timers[e.data.id] = setTimeout(() => self.postMessage(e.data), e.data.ms);
}
else if(e.data.type == _wSetIntervalType)
{
- timers[e.data.id] = setInterval(function()
- {
- self.postMessage(e.data);
- },
- e.data.ms);
+ timers[e.data.id] = setInterval(() => self.postMessage(e.data), e.data.ms);
}
else if(e.data.type == _wSetImmediateType)
{
@@ -177,7 +193,14 @@ var workerCode = function()
}.toString() + "());";
};
-if(worker === undefined)
+if(self == this)
+{
+ //
+ // If we are running in a worker don't spawn a separate worker for the timer
+ //
+ Ice.Timer = createTimerObject();
+}
+else if(worker === undefined)
{
var url;
try
diff --git a/js/src/Ice/browser/WSTransceiver.js b/js/src/Ice/browser/WSTransceiver.js
index ca07a96f2b4..a4870d49b1f 100644
--- a/js/src/Ice/browser/WSTransceiver.js
+++ b/js/src/Ice/browser/WSTransceiver.js
@@ -7,10 +7,9 @@
//
// **********************************************************************
-var Ice = require("../Ice/ModuleRegistry").Ice;
-Ice.__M.require(module,
+const Ice = require("../Ice/ModuleRegistry").Ice;
+Ice._ModuleRegistry.require(module,
[
- "../Ice/Class",
"../Ice/Debug",
"../Ice/ExUtil",
"../Ice/Network",
@@ -21,7 +20,7 @@ Ice.__M.require(module,
"../Ice/Timer",
"../Ice/ConnectionInfo"
]);
-var IceSSL = Ice.__M.module("IceSSL");
+const IceSSL = Ice._ModuleRegistry.module("IceSSL");
//
// With Chrome we don't want to close the socket while connection is in progress,
@@ -29,49 +28,51 @@ var IceSSL = Ice.__M.module("IceSSL");
//
// We need to check for Edge browser as it might include Chrome in its user agent.
//
-var IsChrome = navigator.userAgent.indexOf("Edge/") === -1 &&
- navigator.userAgent.indexOf("Chrome/") !== -1;
-
-var Debug = Ice.Debug;
-var ExUtil = Ice.ExUtil;
-var Network = Ice.Network;
-var SocketOperation = Ice.SocketOperation;
-var Conn = Ice.Connection;
-var LocalException = Ice.LocalException;
-var SocketException = Ice.SocketException;
-var Timer = Ice.Timer;
-
-var StateNeedConnect = 0;
-var StateConnectPending = 1;
-var StateConnected = 2;
-var StateClosePending = 3;
-var StateClosed = 4;
-
-var WSTransceiver = Ice.Class({
- __init__: function(instance)
+const IsChrome = navigator.userAgent.indexOf("Edge/") === -1 &&
+ navigator.userAgent.indexOf("Chrome/") !== -1;
+
+const Debug = Ice.Debug;
+const ExUtil = Ice.ExUtil;
+const Network = Ice.Network;
+const SocketOperation = Ice.SocketOperation;
+const Conn = Ice.Connection;
+const LocalException = Ice.LocalException;
+const SocketException = Ice.SocketException;
+const Timer = Ice.Timer;
+
+const StateNeedConnect = 0;
+const StateConnectPending = 1;
+const StateConnected = 2;
+const StateClosePending = 3;
+const StateClosed = 4;
+
+class WSTransceiver
+{
+ constructor(instance)
{
- this._logger = instance.logger();
this._readBuffers = [];
this._readPosition = 0;
this._maxSendPacketSize = instance.properties().getPropertyAsIntWithDefault("Ice.TCP.SndSize", 512 * 1024);
this._writeReadyTimeout = 0;
- },
- writeReadyTimeout: function()
+ }
+
+ writeReadyTimeout()
{
var t = Math.round(this._writeReadyTimeout);
this._writeReadyTimeout += (this._writeReadyTimeout >= 5 ? 5 : 0.2);
return Math.min(t, 25);
- },
- setCallbacks: function(connectedCallback, bytesAvailableCallback, bytesWrittenCallback)
+ }
+
+ setCallbacks(connectedCallback, bytesAvailableCallback, bytesWrittenCallback)
{
this._connectedCallback = connectedCallback;
this._bytesAvailableCallback = bytesAvailableCallback;
this._bytesWrittenCallback = bytesWrittenCallback;
- },
+ }
//
// Returns SocketOperation.None when initialization is complete.
//
- initialize: function(readBuffer, writeBuffer)
+ initialize(readBuffer, writeBuffer)
{
try
{
@@ -85,10 +86,9 @@ var WSTransceiver = Ice.Class({
this._state = StateConnectPending;
this._fd = new WebSocket(this._url, "ice.zeroc.com");
this._fd.binaryType = "arraybuffer";
- var self = this;
- this._fd.onopen = function(e) { self.socketConnected(e); };
- this._fd.onmessage = function(e) { self.socketBytesAvailable(e.data); };
- this._fd.onclose = function(e) { self.socketClosed(e); };
+ this._fd.onopen = e => this.socketConnected(e);
+ this._fd.onmessage = e => this.socketBytesAvailable(e.data);
+ this._fd.onclose = e => this.socketClosed(e);
return SocketOperation.Connect; // Waiting for connect to complete.
}
else if(this._state === StateConnectPending)
@@ -111,8 +111,9 @@ var WSTransceiver = Ice.Class({
Debug.assert(this._state === StateConnected);
return SocketOperation.None;
- },
- register: function()
+ }
+
+ register()
{
//
// Register the socket data listener.
@@ -123,15 +124,17 @@ var WSTransceiver = Ice.Class({
this._bytesAvailableCallback();
this._hasBytesAvailable = false;
}
- },
- unregister: function()
+ }
+
+ unregister()
{
//
// Unregister the socket data listener.
//
this._registered = false;
- },
- close: function()
+ }
+
+ close()
{
if(this._fd === null)
{
@@ -167,11 +170,12 @@ var WSTransceiver = Ice.Class({
{
this._fd = null;
}
- },
+ }
+
//
// Returns true if all of the data was flushed to the kernel buffer.
//
- write: function(byteBuffer)
+ write(byteBuffer)
{
if(this._exception)
{
@@ -220,8 +224,9 @@ var WSTransceiver = Ice.Class({
byteBuffer.position = byteBuffer.position + packetSize;
}
return true;
- },
- read: function(byteBuffer, moreData)
+ }
+
+ read(byteBuffer, moreData)
{
if(this._exception)
{
@@ -272,40 +277,44 @@ var WSTransceiver = Ice.Class({
moreData.value = this._readBuffers.byteLength > 0;
return byteBuffer.remaining === 0;
- },
- type: function()
+ }
+
+ type()
{
return this._secure ? "wss" : "ws";
- },
- getInfo: function()
+ }
+
+ getInfo()
{
Debug.assert(this._fd !== null);
- var info = this._secure ? new IceSSL.WSSConnectionInfo() : new Ice.WSConnectionInfo();
-
- //
- // The WebSocket API doens't provide this info
- //
- info.localAddress = "";
- info.localPort = -1;
- info.remoteAddress = this._addr.host;
- info.remotePort = this._addr.port;
+ var info = new Ice.WSConnectionInfo();
+ var tcpinfo = new Ice.TCPConnectionInfo();
+ tcpinfo.localAddress = "";
+ tcpinfo.localPort = -1;
+ tcpinfo.remoteAddress = this._addr.host;
+ tcpinfo.remotePort = this._addr.port;
+ info.underlying = this._secure ? new IceSSL.ConnectionInfo(tcpinfo, tcpinfo.timeout, tcpinfo.compress) : tcpinfo;
info.rcvSize = -1;
info.sndSize = this._maxSendPacketSize;
info.headers = {};
return info;
- },
- checkSendSize: function(stream)
+ }
+
+ checkSendSize(stream)
{
- },
- setBufferSize: function(rcvSize, sndSize)
+ }
+
+ setBufferSize(rcvSize, sndSize)
{
this._maxSendPacketSize = sndSize;
- },
- toString: function()
+ }
+
+ toString()
{
return this._desc;
- },
- socketConnected: function(e)
+ }
+
+ socketConnected(e)
{
if(this._state == StateClosePending)
{
@@ -315,8 +324,9 @@ var WSTransceiver = Ice.Class({
Debug.assert(this._connectedCallback !== null);
this._connectedCallback();
- },
- socketBytesAvailable: function(buf)
+ }
+
+ socketBytesAvailable(buf)
{
Debug.assert(this._bytesAvailableCallback !== null);
if(buf.byteLength > 0)
@@ -331,8 +341,9 @@ var WSTransceiver = Ice.Class({
this._hasBytesAvailable = true;
}
}
- },
- socketClosed: function(err)
+ }
+
+ socketClosed(err)
{
if(this._state == StateClosePending)
{
@@ -349,8 +360,30 @@ var WSTransceiver = Ice.Class({
{
this._bytesAvailableCallback();
}
- },
-});
+ }
+
+ static createOutgoing(instance, secure, addr, resource)
+ {
+ var transceiver = new WSTransceiver(instance);
+
+ var url = secure ? "wss" : "ws";
+ url += "://" + addr.host;
+ if(addr.port !== 80)
+ {
+ url += ":" + addr.port;
+ }
+ url += resource ? resource : "/";
+ transceiver._url = url;
+ transceiver._fd = null;
+ transceiver._addr = addr;
+ transceiver._desc = "local address = <not available>\nremote address = " + addr.host + ":" + addr.port;
+ transceiver._state = StateNeedConnect;
+ transceiver._secure = secure;
+ transceiver._exception = null;
+
+ return transceiver;
+ }
+}
function fdToString(address)
{
@@ -373,26 +406,4 @@ function translateError(state, err)
}
}
-WSTransceiver.createOutgoing = function(instance, secure, addr, resource)
-{
- var transceiver = new WSTransceiver(instance);
-
- var url = secure ? "wss" : "ws";
- url += "://" + addr.host;
- if(addr.port !== 80)
- {
- url += ":" + addr.port;
- }
- url += resource ? resource : "/";
- transceiver._url = url;
- transceiver._fd = null;
- transceiver._addr = addr;
- transceiver._desc = "local address = <not available>\nremote address = " + addr.host + ":" + addr.port;
- transceiver._state = StateNeedConnect;
- transceiver._secure = secure;
- transceiver._exception = null;
-
- return transceiver;
-};
-
Ice.WSTransceiver = WSTransceiver;
diff --git a/js/src/Ice/sources.json b/js/src/Ice/sources.json
index 99cf32a9021..e44c94ad942 100644
--- a/js/src/Ice/sources.json
+++ b/js/src/Ice/sources.json
@@ -32,16 +32,14 @@
"AsyncResultBase.js",
"AsyncStatus.js",
"Base64.js",
- "BasicStream.js",
"BatchRequestQueue.js",
- "Class.js",
+ "Buffer.js",
"Communicator.js",
"CompactIdRegistry.js",
"ConnectionI.js",
"ConnectionRequestHandler.js",
"ConnectRequestHandler.js",
"DefaultsAndOverrides.js",
- "DispatchStatus.js",
"EndpointI.js",
"EndpointFactoryManager.js",
"EnumBase.js",
@@ -61,11 +59,10 @@
"LocatorTable.js",
"Logger.js",
"Long.js",
+ "MapUtil.js",
"Object.js",
"ObjectAdapterFactory.js",
"ObjectAdapterI.js",
- "ObjectFactory.js",
- "ObjectFactoryManager.js",
"ObjectPrx.js",
"OpaqueEndpointI.js",
"Operation.js",
@@ -89,21 +86,24 @@
"RouterManager.js",
"ServantManager.js",
"SocketOperation.js",
+ "Stream.js",
"StreamHelpers.js",
"StringUtil.js",
"Struct.js",
"TcpEndpointFactory.js",
"TcpEndpointI.js",
"Timer.js",
+ "ToStringMode.js",
"TraceLevels.js",
"TraceUtil.js",
- "UnknownSlicedObject.js",
+ "UnknownSlicedValue.js",
"UUID.js",
+ "Value.js",
+ "ValueFactoryManagerI.js",
"WSEndpoint.js",
"WSEndpointFactory.js"],
"node":[
- "Buffer.js",
"Debug.js",
"Ice.js",
"ModuleRegistry.js",
@@ -111,7 +111,6 @@
"TimerUtil.js"],
"browser":[
- "browser/Buffer.js",
"browser/Debug.js",
"browser/ModuleRegistry.js",
"browser/TimerUtil.js",
diff --git a/js/src/IceGrid/IceGrid.js b/js/src/IceGrid/IceGrid.js
index acdef4afd9a..a8fa5f986f3 100644
--- a/js/src/IceGrid/IceGrid.js
+++ b/js/src/IceGrid/IceGrid.js
@@ -7,17 +7,14 @@
//
// **********************************************************************
-var __M = require("../Ice/ModuleRegistry").Ice.__M;
+var _ModuleRegistry = require("../Ice/ModuleRegistry").Ice._ModuleRegistry;
-module.exports.IceGrid = __M.require(module,
+module.exports.IceGrid = _ModuleRegistry.require(module,
[
"../IceGrid/Admin",
"../IceGrid/Descriptor",
"../IceGrid/Exception",
"../IceGrid/FileParser",
- "../IceGrid/Locator",
- "../IceGrid/Observer",
- "../IceGrid/Query",
"../IceGrid/Registry",
"../IceGrid/Session",
"../IceGrid/UserAccountMapper"
diff --git a/js/src/IceGrid/sources.json b/js/src/IceGrid/sources.json
index 3ccaca61e66..a6b8622dea2 100644
--- a/js/src/IceGrid/sources.json
+++ b/js/src/IceGrid/sources.json
@@ -7,9 +7,6 @@
"IceGrid/Descriptor.ice",
"IceGrid/Exception.ice",
"IceGrid/FileParser.ice",
- "IceGrid/Locator.ice",
- "IceGrid/Observer.ice",
- "IceGrid/Query.ice",
"IceGrid/Registry.ice",
"IceGrid/Session.ice",
"IceGrid/UserAccountMapper.ice"],
diff --git a/js/src/es5/index.js b/js/src/es5/index.js
new file mode 100644
index 00000000000..92ef3101dad
--- /dev/null
+++ b/js/src/es5/index.js
@@ -0,0 +1,16 @@
+// **********************************************************************
+//
+// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
+//
+// This copy of Ice is licensed to you under the terms described in the
+// ICE_LICENSE file included in this distribution.
+//
+// **********************************************************************
+
+require("babel-polyfill")
+module.exports.Ice = require("./Ice/Ice").Ice;
+module.exports.IceMX = require("./Ice/Ice").IceMX;
+module.exports.IceSSL = require("./Ice/Ice").IceSSL;
+module.exports.Glacier2 = require("./Glacier2/Glacier2").Glacier2;
+module.exports.IceGrid = require("./IceGrid/IceGrid").IceGrid;
+module.exports.IceStorm = require("./IceStorm/IceStorm").IceStorm;
diff --git a/js/src/ice.js b/js/src/index.js
index db87f9351c0..db87f9351c0 100644
--- a/js/src/ice.js
+++ b/js/src/index.js