diff options
author | Benoit Foucher <benoit@zeroc.com> | 2009-03-24 11:45:18 +0100 |
---|---|---|
committer | Benoit Foucher <benoit@zeroc.com> | 2009-03-24 11:45:18 +0100 |
commit | 06a08ecf28e205277336a97a6173db7ccbed1adc (patch) | |
tree | a369a5044a63f8cdba9e7c0a461e24ae344486b4 /java/src | |
parent | Merge branch 'R3_3_branch' (diff) | |
parent | Bug 3924: slice2py missing from VC60 installer (diff) | |
download | ice-06a08ecf28e205277336a97a6173db7ccbed1adc.tar.bz2 ice-06a08ecf28e205277336a97a6173db7ccbed1adc.tar.xz ice-06a08ecf28e205277336a97a6173db7ccbed1adc.zip |
Merge commit 'origin/R3_3_branch'
Conflicts:
CHANGES
cpp/demo/Freeze/backup/.depend
cpp/demo/Freeze/bench/.depend
cpp/demo/Freeze/casino/.depend
cpp/demo/Freeze/customEvictor/.depend
cpp/demo/Freeze/library/.depend
cpp/demo/Freeze/phonebook/.depend
cpp/demo/Freeze/transform/.depend
cpp/demo/Glacier2/callback/.depend
cpp/demo/Glacier2/chat/.depend
cpp/demo/Ice/async/.depend
cpp/demo/Ice/bidir/.depend
cpp/demo/Ice/callback/.depend
cpp/demo/Ice/converter/.depend
cpp/demo/Ice/hello/.depend
cpp/demo/Ice/invoke/.depend
cpp/demo/Ice/latency/.depend
cpp/demo/Ice/minimal/.depend
cpp/demo/Ice/multicast/.depend
cpp/demo/Ice/nested/.depend
cpp/demo/Ice/nrvo/.depend
cpp/demo/Ice/session/.depend
cpp/demo/Ice/throughput/.depend
cpp/demo/Ice/value/.depend
cpp/demo/IceBox/hello/.depend
cpp/demo/IceGrid/allocate/.depend
cpp/demo/IceGrid/icebox/.depend
cpp/demo/IceGrid/replication/.depend
cpp/demo/IceGrid/sessionActivation/.depend
cpp/demo/IceGrid/simple/.depend
cpp/demo/IceStorm/clock/.depend
cpp/demo/IceStorm/counter/.depend
cpp/demo/IceStorm/replicated/.depend
cpp/demo/IceStorm/replicated2/.depend
cpp/demo/book/freeze_filesystem/.depend
cpp/demo/book/lifecycle/.depend
cpp/demo/book/printer/.depend
cpp/demo/book/simple_filesystem/.depend
cpp/src/Freeze/.depend
cpp/src/FreezeScript/.depend
cpp/src/Ice/.depend
cpp/src/Ice/UdpTransceiver.cpp
cpp/src/Ice/UdpTransceiver.h
cpp/src/IceBox/.depend
cpp/src/IceGrid/.depend
cpp/src/IceGridLib/.depend
cpp/src/IcePatch2/.depend
cpp/src/IceStorm/.depend
cpp/src/slice2freeze/.depend
cpp/test/Freeze/complex/.depend
cpp/test/Freeze/dbmap/.depend
cpp/test/Freeze/evictor/.depend
cpp/test/Freeze/oldevictor/.depend
cpp/test/FreezeScript/dbmap/.depend
cpp/test/FreezeScript/evictor/.depend
cpp/test/Glacier2/attack/.depend
cpp/test/Glacier2/dynamicFiltering/.depend
cpp/test/Glacier2/router/.depend
cpp/test/Glacier2/sessionControl/.depend
cpp/test/Glacier2/ssl/.depend
cpp/test/Glacier2/staticFiltering/.depend
cpp/test/Ice/adapterDeactivation/.depend
cpp/test/Ice/background/.depend
cpp/test/Ice/binding/.depend
cpp/test/Ice/checksum/.depend
cpp/test/Ice/checksum/server/.depend
cpp/test/Ice/custom/.depend
cpp/test/Ice/exceptions/.depend
cpp/test/Ice/facets/.depend
cpp/test/Ice/faultTolerance/.depend
cpp/test/Ice/gc/.depend
cpp/test/Ice/hold/.depend
cpp/test/Ice/inheritance/.depend
cpp/test/Ice/interceptor/.depend
cpp/test/Ice/location/.depend
cpp/test/Ice/objects/.depend
cpp/test/Ice/operations/.depend
cpp/test/Ice/proxy/.depend
cpp/test/Ice/retry/.depend
cpp/test/Ice/servantLocator/.depend
cpp/test/Ice/slicing/exceptions/.depend
cpp/test/Ice/slicing/objects/.depend
cpp/test/Ice/stream/.depend
cpp/test/Ice/stringConverter/.depend
cpp/test/Ice/timeout/.depend
cpp/test/Ice/udp/.depend
cpp/test/IceBox/configuration/.depend
cpp/test/IceGrid/activation/.depend
cpp/test/IceGrid/allocation/.depend
cpp/test/IceGrid/deployer/.depend
cpp/test/IceGrid/distribution/.depend
cpp/test/IceGrid/replicaGroup/.depend
cpp/test/IceGrid/replication/.depend
cpp/test/IceGrid/session/.depend
cpp/test/IceGrid/simple/.depend
cpp/test/IceGrid/update/.depend
cpp/test/IceSSL/configuration/.depend
cpp/test/IceStorm/federation/.depend
cpp/test/IceStorm/federation2/.depend
cpp/test/IceStorm/rep1/.depend
cpp/test/IceStorm/repgrid/.depend
cpp/test/IceStorm/repstress/.depend
cpp/test/IceStorm/single/.depend
cpp/test/IceStorm/stress/.depend
cpp/test/Slice/keyword/.depend
cs/src/Ice/Instance.cs
cs/src/IceSSL/ConnectorI.cs
java/demo/book/simple_filesystem/Filesystem/DirectoryI.java
java/demo/book/simple_filesystem/Filesystem/FileI.java
java/src/IceInternal/TcpConnector.java
java/src/IceSSL/ConnectorI.java
py/modules/IcePy/.depend
rb/src/IceRuby/.depend
Diffstat (limited to 'java/src')
56 files changed, 1544 insertions, 1032 deletions
diff --git a/java/src/Ice/ConnectionI.java b/java/src/Ice/ConnectionI.java index b450c2ef715..840c3b7824a 100644 --- a/java/src/Ice/ConnectionI.java +++ b/java/src/Ice/ConnectionI.java @@ -305,7 +305,7 @@ public final class ConnectionI extends IceInternal.EventHandler implements Conne } synchronized public void - monitor() + monitor(long now) { if(_state != StateActive) { @@ -323,7 +323,7 @@ public final class ConnectionI extends IceInternal.EventHandler implements Conne return; } - if(IceInternal.Time.currentMonotonicTimeMillis() >= _acmAbsoluteTimeoutMillis) + if(now >= _acmAbsoluteTimeoutMillis) { setState(StateClosing, new ConnectionTimeoutException()); } @@ -837,12 +837,7 @@ public final class ConnectionI extends IceInternal.EventHandler implements Conne public synchronized void setAdapter(ObjectAdapter adapter) { - if(_state == StateClosing || _state == StateClosed) - { - assert(_exception != null); - throw _exception; - } - else if(_state <= StateNotValidated) + if(_state <= StateNotValidated || _state >= StateClosing) { return; } @@ -1630,7 +1625,7 @@ public final class ConnectionI extends IceInternal.EventHandler implements Conne { throw new ConnectionNotValidatedException(); } - byte compress = is.readByte(); // Ignore compression status for validate connection. + is.readByte(); // Ignore compression status for validate connection. int size = is.readInt(); if(size != IceInternal.Protocol.headerSize) { @@ -1963,6 +1958,7 @@ public final class ConnectionI extends IceInternal.EventHandler implements Conne throw new UnknownRequestIdException(); } } + notifyAll(); // Notify threads blocked in close(false) break; } @@ -1984,10 +1980,6 @@ public final class ConnectionI extends IceInternal.EventHandler implements Conne } } } - catch(SocketException ex) - { - setState(StateClosed, ex); - } catch(LocalException ex) { if(_endpoint.datagram()) @@ -2071,6 +2063,17 @@ public final class ConnectionI extends IceInternal.EventHandler implements Conne _logger.error(uex.unknown); invokeException(uex, invokeNum); } + catch(java.lang.OutOfMemoryError ex) + { + UnknownException uex = new UnknownException(); + java.io.StringWriter sw = new java.io.StringWriter(); + java.io.PrintWriter pw = new java.io.PrintWriter(sw); + ex.printStackTrace(pw); + pw.flush(); + uex.unknown = sw.toString(); + _logger.error(uex.unknown); + invokeException(uex, invokeNum); + } finally { if(in != null) @@ -2091,17 +2094,6 @@ public final class ConnectionI extends IceInternal.EventHandler implements Conne _logger.warning(s); } - private void - error(String msg, Exception ex) - { - java.io.StringWriter sw = new java.io.StringWriter(); - java.io.PrintWriter pw = new java.io.PrintWriter(sw); - ex.printStackTrace(pw); - pw.flush(); - String s = msg + ":\n" + _desc + "\n" + sw.toString(); - _logger.error(s); - } - private IceInternal.Incoming getIncoming(ObjectAdapter adapter, boolean response, byte compress, int requestId) { diff --git a/java/src/Ice/InputStream.java b/java/src/Ice/InputStream.java index da108992b7b..9028cad551d 100644 --- a/java/src/Ice/InputStream.java +++ b/java/src/Ice/InputStream.java @@ -21,6 +21,8 @@ public interface InputStream byte readByte(); byte[] readByteSeq(); + java.io.Serializable readSerializable(); + short readShort(); short[] readShortSeq(); diff --git a/java/src/Ice/InputStreamI.java b/java/src/Ice/InputStreamI.java index a5f970e54d4..cbed1636c37 100644 --- a/java/src/Ice/InputStreamI.java +++ b/java/src/Ice/InputStreamI.java @@ -61,6 +61,12 @@ public class InputStreamI implements InputStream return _is.readByteSeq(); } + public java.io.Serializable + readSerializable() + { + return _is.readSerializable(); + } + public short readShort() { @@ -219,7 +225,7 @@ public class InputStreamI implements InputStream public void endEncapsulation() { - _is.endReadEncaps(); + _is.endReadEncapsChecked(); } public void diff --git a/java/src/Ice/LoggerI.java b/java/src/Ice/LoggerI.java index a3ab0ac071c..0966b981a3a 100644 --- a/java/src/Ice/LoggerI.java +++ b/java/src/Ice/LoggerI.java @@ -33,7 +33,8 @@ public class LoggerI implements Logger public void trace(String category, String message) { - StringBuffer s = new StringBuffer("[ "); + StringBuilder s = new StringBuilder(256); + s.append("[ "); s.append(_date.format(new java.util.Date())); s.append(_time.format(new java.util.Date())); s.append(' '); @@ -48,35 +49,40 @@ public class LoggerI implements Logger s.insert(idx + 1, " "); ++idx; } - System.err.print(s.toString() + _lineSeparator); + s.append(_lineSeparator); + System.err.print(s.toString()); } public void warning(String message) { - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(256); s.append(_date.format(new java.util.Date())); s.append(_time.format(new java.util.Date())); s.append(' '); s.append(_prefix); s.append("warning: "); - s.append(Thread.currentThread().getName() + ": "); + s.append(Thread.currentThread().getName()); + s.append(": "); s.append(message); - System.err.print(s.toString() + _lineSeparator); + s.append(_lineSeparator); + System.err.print(s.toString()); } public void error(String message) { - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(256); s.append(_date.format(new java.util.Date())); s.append(_time.format(new java.util.Date())); s.append(' '); s.append(_prefix); s.append("error: "); - s.append(Thread.currentThread().getName() + ": "); + s.append(Thread.currentThread().getName()); + s.append(": "); s.append(message); - System.err.print(s.toString() + _lineSeparator); + s.append(_lineSeparator); + System.err.print(s.toString()); } String _prefix = ""; diff --git a/java/src/Ice/ObjectAdapterI.java b/java/src/Ice/ObjectAdapterI.java index 586a6f4a54d..49f78794cc7 100644 --- a/java/src/Ice/ObjectAdapterI.java +++ b/java/src/Ice/ObjectAdapterI.java @@ -1219,8 +1219,10 @@ public final class ObjectAdapterI implements ObjectAdapter { if(_instance.traceLevels().location >= 1) { - StringBuffer s = new StringBuffer(); - s.append("couldn't update object adapter `" + _id + "' endpoints with the locator registry:\n"); + StringBuilder s = new StringBuilder(128); + s.append("couldn't update object adapter `"); + s.append(_id); + s.append("' endpoints with the locator registry:\n"); s.append("the object adapter is not known to the locator registry"); _instance.initializationData().logger.trace(_instance.traceLevels().locationCat, s.toString()); } @@ -1234,9 +1236,13 @@ public final class ObjectAdapterI implements ObjectAdapter { if(_instance.traceLevels().location >= 1) { - StringBuffer s = new StringBuffer(); - s.append("couldn't update object adapter `" + _id + "' endpoints with the locator registry:\n"); - s.append("the replica group `" + _replicaGroupId + "' is not known to the locator registry"); + StringBuilder s = new StringBuilder(128); + s.append("couldn't update object adapter `"); + s.append(_id); + s.append("' endpoints with the locator registry:\n"); + s.append("the replica group `"); + s.append(_replicaGroupId); + s.append("' is not known to the locator registry"); _instance.initializationData().logger.trace(_instance.traceLevels().locationCat, s.toString()); } @@ -1249,8 +1255,10 @@ public final class ObjectAdapterI implements ObjectAdapter { if(_instance.traceLevels().location >= 1) { - StringBuffer s = new StringBuffer(); - s.append("couldn't update object adapter `" + _id + "' endpoints with the locator registry:\n"); + StringBuilder s = new StringBuilder(128); + s.append("couldn't update object adapter `"); + s.append(_id); + s.append("' endpoints with the locator registry:\n"); s.append("the object adapter endpoints are already set"); _instance.initializationData().logger.trace(_instance.traceLevels().locationCat, s.toString()); } @@ -1263,8 +1271,11 @@ public final class ObjectAdapterI implements ObjectAdapter { if(_instance.traceLevels().location >= 1) { - StringBuffer s = new StringBuffer(); - s.append("couldn't update object adapter `" + _id + "' endpoints with the locator registry:\n" + e); + StringBuilder s = new StringBuilder(128); + s.append("couldn't update object adapter `"); + s.append(_id); + s.append("' endpoints with the locator registry:\n"); + s.append(e.toString()); _instance.initializationData().logger.trace(_instance.traceLevels().locationCat, s.toString()); } throw e; // TODO: Shall we raise a special exception instead of a non obvious local exception? @@ -1272,8 +1283,10 @@ public final class ObjectAdapterI implements ObjectAdapter if(_instance.traceLevels().location >= 1) { - StringBuffer s = new StringBuffer(); - s.append("updated object adapter `" + _id + "' endpoints with the locator registry\n"); + StringBuilder s = new StringBuilder(128); + s.append("updated object adapter `"); + s.append(_id); + s.append("' endpoints with the locator registry\n"); s.append("endpoints = "); if(proxy != null) { @@ -1311,8 +1324,10 @@ public final class ObjectAdapterI implements ObjectAdapter { if(_instance.traceLevels().location >= 1) { - StringBuffer s = new StringBuffer(); - s.append("couldn't register server `" + serverId + "' with the locator registry:\n"); + StringBuilder s = new StringBuilder(128); + s.append("couldn't register server `"); + s.append(serverId); + s.append("' with the locator registry:\n"); s.append("the server is not known to the locator registry"); _instance.initializationData().logger.trace(_instance.traceLevels().locationCat, s.toString()); } @@ -1326,17 +1341,22 @@ public final class ObjectAdapterI implements ObjectAdapter { if(_instance.traceLevels().location >= 1) { - StringBuffer s = new StringBuffer(); - s.append("couldn't register server `" + serverId + "' with the locator registry:\n" + ex); + StringBuilder s = new StringBuilder(128); + s.append("couldn't register server `"); + s.append(serverId); + s.append("' with the locator registry:\n"); + s.append(ex.toString()); _instance.initializationData().logger.trace(_instance.traceLevels().locationCat, s.toString()); } - throw ex; // TODO: Shall we raise a special exception instead of a non obvious local exception? + throw ex; // TODO: Shall we raise a special exception instead of a non-obvious local exception? } if(_instance.traceLevels().location >= 1) { - StringBuffer s = new StringBuffer(); - s.append("registered server `" + serverId + "' with the locator registry"); + StringBuilder s = new StringBuilder(128); + s.append("registered server `"); + s.append(serverId); + s.append("' with the locator registry"); _instance.initializationData().logger.trace(_instance.traceLevels().locationCat, s.toString()); } } diff --git a/java/src/Ice/ObjectImpl.java b/java/src/Ice/ObjectImpl.java index 4f3b2b12f0e..397ace706ba 100644 --- a/java/src/Ice/ObjectImpl.java +++ b/java/src/Ice/ObjectImpl.java @@ -9,7 +9,7 @@ package Ice; -public abstract class ObjectImpl implements Object, java.lang.Cloneable +public abstract class ObjectImpl implements Object, java.lang.Cloneable, java.io.Serializable { public ObjectImpl() @@ -243,7 +243,7 @@ public abstract class ObjectImpl implements Object, java.lang.Cloneable { if(__rid) { - String myId = __is.readTypeId(); + __is.readTypeId(); } __is.startReadSlice(); @@ -272,7 +272,7 @@ public abstract class ObjectImpl implements Object, java.lang.Cloneable { if(__rid) { - String myId = __inS.readTypeId(); + __inS.readTypeId(); } __inS.startSlice(); diff --git a/java/src/Ice/ObjectInputStream.java b/java/src/Ice/ObjectInputStream.java new file mode 100644 index 00000000000..f8e5ce11762 --- /dev/null +++ b/java/src/Ice/ObjectInputStream.java @@ -0,0 +1,34 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2009 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. +// +// ********************************************************************** + +package Ice; + +// +// If you are attempting to deserialize a Slice type that includes a +// proxy, you must instantiate (or subclass) Ice.ObjectInputStream and +// supply a communicator for use in reconstructing the proxy. +// +public class ObjectInputStream extends java.io.ObjectInputStream +{ + public + ObjectInputStream(Communicator communicator, java.io.InputStream stream) + throws java.io.IOException + { + super(stream); + _communicator = communicator; + } + + public Communicator + getCommunicator() + { + return _communicator; + } + + private Communicator _communicator; +} diff --git a/java/src/Ice/ObjectPrxHelperBase.java b/java/src/Ice/ObjectPrxHelperBase.java index f44b22ad66e..302ec582abd 100644 --- a/java/src/Ice/ObjectPrxHelperBase.java +++ b/java/src/Ice/ObjectPrxHelperBase.java @@ -9,7 +9,7 @@ package Ice; -public class ObjectPrxHelperBase implements ObjectPrx +public class ObjectPrxHelperBase implements ObjectPrx, java.io.Serializable { public final int hashCode() @@ -716,7 +716,7 @@ public class ObjectPrxHelperBase implements ObjectPrx // Don't wait for the connection to be established. return __del.__getRequestHandler().getConnection(false); } - catch(CollocationOptimizationException ex) + catch(LocalException ex) { } } @@ -1052,6 +1052,41 @@ public class ObjectPrxHelperBase implements ObjectPrx } } + private void + writeObject(java.io.ObjectOutputStream out) + throws java.io.IOException + { + out.writeUTF(toString()); + } + + private void + readObject(java.io.ObjectInputStream in) + throws java.io.IOException, ClassNotFoundException + { + String s = in.readUTF(); + try + { + Communicator communicator = ((Ice.ObjectInputStream)in).getCommunicator(); + if(communicator == null) + { + throw new java.io.IOException("Cannot deserialize proxy: no communicator provided"); + } + ObjectPrxHelperBase proxy = (ObjectPrxHelperBase)communicator.stringToProxy(s); + _reference = proxy._reference; + assert(proxy._delegate == null); + } + catch(ClassCastException ex) + { + throw new java.io.IOException("Cannot deserialize proxy: Ice.ObjectInputStream not found"); + } + catch(LocalException ex) + { + java.io.IOException e = new java.io.IOException("Failure occurred while deserializing proxy"); + e.initCause(ex); + throw e; + } + } + protected static final java.util.Map<String, String> _emptyContext = new java.util.HashMap<String, String>(); private IceInternal.Reference _reference; diff --git a/java/src/Ice/OutputStream.java b/java/src/Ice/OutputStream.java index d481187c89d..4105fbc94b6 100644 --- a/java/src/Ice/OutputStream.java +++ b/java/src/Ice/OutputStream.java @@ -19,6 +19,8 @@ public interface OutputStream void writeByte(byte v); void writeByteSeq(byte[] v); + void writeSerializable(java.io.Serializable o); + void writeShort(short v); void writeShortSeq(short[] v); diff --git a/java/src/Ice/OutputStreamI.java b/java/src/Ice/OutputStreamI.java index 39130ee350a..7cd54936769 100644 --- a/java/src/Ice/OutputStreamI.java +++ b/java/src/Ice/OutputStreamI.java @@ -56,6 +56,12 @@ public class OutputStreamI implements OutputStream } public void + writeSerializable(java.io.Serializable v) + { + _os.writeSerializable(v); + } + + public void writeShort(short v) { _os.writeShort(v); @@ -130,6 +136,11 @@ public class OutputStreamI implements OutputStream public void writeSize(int sz) { + if(sz < 0) + { + throw new NegativeSizeException(); + } + _os.writeSize(sz); } @@ -178,7 +189,7 @@ public class OutputStreamI implements OutputStream public void endEncapsulation() { - _os.endWriteEncaps(); + _os.endWriteEncapsChecked(); } public void diff --git a/java/src/Ice/PluginManagerI.java b/java/src/Ice/PluginManagerI.java index 2c5e33bfb63..89f856be484 100644 --- a/java/src/Ice/PluginManagerI.java +++ b/java/src/Ice/PluginManagerI.java @@ -118,8 +118,8 @@ public final class PluginManagerI implements PluginManager } catch(RuntimeException ex) { - Ice.Util.getProcessLogger().warning("unexpected exception raised by plug-in '" + entry.getKey() + "' destruction.\n"); - Ice.Util.getProcessLogger().warning("exception: " + ex.toString()); + Ice.Util.getProcessLogger().warning("unexpected exception raised by plug-in `" + + entry.getKey() + "' destruction:\n" + ex.toString()); } } } @@ -306,7 +306,7 @@ public final class PluginManagerI implements PluginManager PluginFactory pluginFactory = null; try { - Class c = Class.forName(className); + Class<?> c = Class.forName(className); java.lang.Object obj = c.newInstance(); try { diff --git a/java/src/Ice/SysLoggerI.java b/java/src/Ice/SysLoggerI.java index 07c23f5e96a..69281db127d 100644 --- a/java/src/Ice/SysLoggerI.java +++ b/java/src/Ice/SysLoggerI.java @@ -31,7 +31,7 @@ public final class SysLoggerI implements Logger _socket = new DatagramSocket(); _socket.connect(_host, _port); } - catch(java.io.IOException ex) + catch(IOException ex) { Ice.SocketException se = new Ice.SocketException(); se.initCause(ex); @@ -84,7 +84,7 @@ public final class SysLoggerI implements Logger DatagramPacket p = new DatagramPacket(buf, buf.length, _host, _port); _socket.send(p); } - catch(java.io.IOException ex) + catch(IOException ex) { Ice.SocketException se = new Ice.SocketException(); se.initCause(ex); diff --git a/java/src/Ice/Util.java b/java/src/Ice/Util.java index 6e516d1e5a1..99ae9a1a691 100644 --- a/java/src/Ice/Util.java +++ b/java/src/Ice/Util.java @@ -191,7 +191,7 @@ public final class Util public static String identityToString(Identity ident) { - if(ident.category.length() == 0) + if(ident.category == null || ident.category.length() == 0) { return IceUtilInternal.StringUtil.escapeString(ident.name, "/"); } diff --git a/java/src/IceBox/Server.java b/java/src/IceBox/Server.java index 997a7251e4b..6438692c86b 100644 --- a/java/src/IceBox/Server.java +++ b/java/src/IceBox/Server.java @@ -50,7 +50,7 @@ public final class Server extends Ice.Application } } - ServiceManagerI serviceManagerImpl = new ServiceManagerI(this, args); + ServiceManagerI serviceManagerImpl = new ServiceManagerI(communicator(), args); return serviceManagerImpl.run(); } } diff --git a/java/src/IceBox/ServiceManagerI.java b/java/src/IceBox/ServiceManagerI.java index 87fb274fac1..95cfac6fb1a 100644 --- a/java/src/IceBox/ServiceManagerI.java +++ b/java/src/IceBox/ServiceManagerI.java @@ -16,13 +16,12 @@ package IceBox; public class ServiceManagerI extends _ServiceManagerDisp { public - ServiceManagerI(Ice.Application server, String[] args) + ServiceManagerI(Ice.Communicator communicator, String[] args) { - _server = server; - _logger = _server.communicator().getLogger(); + _communicator = communicator; + _logger = _communicator.getLogger(); _argv = args; - _traceServiceObserver = - _server.communicator().getProperties().getPropertyAsInt("IceBox.Trace.ServiceObserver"); + _traceServiceObserver = _communicator.getProperties().getPropertyAsInt("IceBox.Trace.ServiceObserver"); } public java.util.Map @@ -67,8 +66,7 @@ public class ServiceManagerI extends _ServiceManagerDisp boolean started = false; try { - info.service.start(name, info.communicator == null ? _server.communicator() : info.communicator, - info.args); + info.service.start(name, info.communicator == null ? _sharedCommunicator : info.communicator, info.args); started = true; } catch(java.lang.Exception e) @@ -81,7 +79,6 @@ public class ServiceManagerI extends _ServiceManagerDisp sw.toString()); } - java.util.Set<ServiceObserverPrx> observers = null; synchronized(this) { java.util.Iterator<ServiceInfo> p = _services.iterator(); @@ -203,7 +200,7 @@ public class ServiceManagerI extends _ServiceManagerDisp if(_traceServiceObserver >= 1) { _logger.trace("IceBox.ServiceObserver", - "Added service observer " + _server.communicator().proxyToString(observer)); + "Added service observer " + _communicator.proxyToString(observer)); } @@ -244,7 +241,7 @@ public class ServiceManagerI extends _ServiceManagerDisp public void shutdown(Ice.Current current) { - _server.communicator().shutdown(); + _communicator.shutdown(); } public int @@ -252,7 +249,7 @@ public class ServiceManagerI extends _ServiceManagerDisp { try { - Ice.Properties properties = _server.communicator().getProperties(); + Ice.Properties properties = _communicator.getProperties(); // // Create an object adapter. Services probably should NOT share @@ -262,7 +259,7 @@ public class ServiceManagerI extends _ServiceManagerDisp Ice.ObjectAdapter adapter = null; if(!properties.getProperty("IceBox.ServiceManager.Endpoints").equals("")) { - adapter = _server.communicator().createObjectAdapter("IceBox.ServiceManager"); + adapter = _communicator.createObjectAdapter("IceBox.ServiceManager"); Ice.Identity identity = new Ice.Identity(); identity.category = properties.getPropertyWithDefault("IceBox.InstanceName", "IceBox"); @@ -271,18 +268,18 @@ public class ServiceManagerI extends _ServiceManagerDisp } // - // Load and start the services defined in the property set - // with the prefix "IceBox.Service.". These properties should - // have the following format: + // Parse the property set with the prefix "IceBox.Service.". These + // properties should have the following format: // // IceBox.Service.Foo=Package.Foo [args] // - // We load the services specified in IceBox.LoadOrder first, - // then load any remaining services. + // We parse the service properties specified in IceBox.LoadOrder + // first, then the ones from remaining services. // final String prefix = "IceBox.Service."; java.util.Map<String, String> services = properties.getPropertiesForPrefix(prefix); String[] loadOrder = properties.getPropertyAsList("IceBox.LoadOrder"); + java.util.List<StartServiceInfo> servicesInfo = new java.util.ArrayList<StartServiceInfo>(); for(int i = 0; i < loadOrder.length; ++i) { if(loadOrder[i].length() > 0) @@ -295,7 +292,7 @@ public class ServiceManagerI extends _ServiceManagerDisp ex.reason = "ServiceManager: no service definition for `" + loadOrder[i] + "'"; throw ex; } - load(loadOrder[i], value); + servicesInfo.add(new StartServiceInfo(loadOrder[i], value, _argv)); services.remove(key); } } @@ -305,7 +302,73 @@ public class ServiceManagerI extends _ServiceManagerDisp java.util.Map.Entry<String, String> entry = p.next(); String name = entry.getKey().substring(prefix.length()); String value = entry.getValue(); - load(name, value); + servicesInfo.add(new StartServiceInfo(name, value, _argv)); + } + + // + // Check if some services are using the shared communicator in which + // case we create the shared communicator now with a property set which + // is the union of all the service properties (services which are using + // the shared communicator). + // + if(properties.getPropertiesForPrefix("IceBox.UseSharedCommunicator.").size() > 0) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = createServiceProperties("SharedCommunicator"); + for(StartServiceInfo service : servicesInfo) + { + if(properties.getPropertyAsInt("IceBox.UseSharedCommunicator." + service.name) <= 0) + { + continue; + } + + // + // Load the service properties using the shared communicator properties as + // the default properties. + // + Ice.StringSeqHolder serviceArgs = new Ice.StringSeqHolder(service.args); + Ice.Properties svcProperties = Ice.Util.createProperties(serviceArgs, initData.properties); + service.args = serviceArgs.value; + + // + // Erase properties from the shared communicator which don't exist in the + // service properties (which include the shared communicator properties + // overriden by the service properties). + // + java.util.Map<String, String> allProps = initData.properties.getPropertiesForPrefix(""); + java.util.Iterator<String> q = allProps.keySet().iterator(); + while(q.hasNext()) + { + String key = q.next(); + if(svcProperties.getProperty(key).length() == 0) + { + initData.properties.setProperty(key, ""); + } + } + + // + // Add the service properties to the shared communicator properties. + // + java.util.Iterator<java.util.Map.Entry<String, String> > r = + svcProperties.getPropertiesForPrefix("").entrySet().iterator(); + while(r.hasNext()) + { + java.util.Map.Entry<String, String> entry = r.next(); + initData.properties.setProperty(entry.getKey(), entry.getValue()); + } + + // + // Parse <service>.* command line options (the Ice command line options + // were parsed by the createProperties above) + // + service.args = initData.properties.parseCommandLineOptions(service.name, service.args); + } + _sharedCommunicator = Ice.Util.initialize(initData); + } + + for(StartServiceInfo s : servicesInfo) + { + start(s.name, s.className, s.args); } // @@ -332,8 +395,7 @@ public class ServiceManagerI extends _ServiceManagerDisp // reachable before sending a signal to shutdown the // IceBox. // - _server.shutdownOnInterrupt(); - + Ice.Application.shutdownOnInterrupt(); // // Register "this" as a facet to the Admin object and @@ -341,7 +403,7 @@ public class ServiceManagerI extends _ServiceManagerDisp // try { - _server.communicator().addAdminFacet(this, "IceBox.ServiceManager"); + _communicator.addAdminFacet(this, "IceBox.ServiceManager"); // // Add a Properties facet for each service @@ -349,11 +411,11 @@ public class ServiceManagerI extends _ServiceManagerDisp for(ServiceInfo info: _services) { Ice.Communicator communicator = info.communicator != null ? info.communicator : _sharedCommunicator; - _server.communicator().addAdminFacet(new PropertiesAdminI(communicator.getProperties()), + _communicator.addAdminFacet(new PropertiesAdminI(communicator.getProperties()), "IceBox.Service." + info.name + ".Properties"); } - _server.communicator().getAdmin(); + _communicator.getAdmin(); } catch(Ice.ObjectAdapterDeactivatedException ex) { @@ -379,8 +441,8 @@ public class ServiceManagerI extends _ServiceManagerDisp } } - _server.communicator().waitForShutdown(); - _server.defaultInterrupt(); + _communicator.waitForShutdown(); + Ice.Application.defaultInterrupt(); // // Invoke stop() on the services. @@ -422,76 +484,20 @@ public class ServiceManagerI extends _ServiceManagerDisp return 0; } - - private void - load(String name, String value) - throws FailureException - { - // - // Separate the entry point from the arguments. - // - String className; - String[] args; - int pos = IceUtilInternal.StringUtil.findFirstOf(value, " \t\n"); - if(pos == -1) - { - className = value; - args = new String[0]; - } - else - { - className = value.substring(0, pos); - try - { - args = IceUtilInternal.Options.split(value.substring(pos)); - } - catch(IceUtilInternal.Options.BadQuote ex) - { - FailureException e = new FailureException(); - e.reason = "ServiceManager: invalid arguments for service `" + name + "':\n" + ex.toString(); - throw e; - } - } - - start(name, className, args); - } - synchronized private void start(String service, String className, String[] args) throws FailureException { // - // Create the service property set from the service arguments - // and the server arguments. The service property set will be - // used to create a new communicator, or will be added to the - // shared communicator, depending on the value of the - // IceBox.UseSharedCommunicator property. - // - java.util.List<String> l = new java.util.ArrayList<String>(); - for(int j = 0; j < args.length; j++) - { - l.add(args[j]); - } - for(int j = 0; j < _argv.length; j++) - { - if(_argv[j].startsWith("--" + service + ".")) - { - l.add(_argv[j]); - } - } - - Ice.StringSeqHolder serviceArgs = new Ice.StringSeqHolder(); - serviceArgs.value = (String[])l.toArray(new String[0]); - - // // Instantiate the class. // ServiceInfo info = new ServiceInfo(); info.name = service; info.status = StatusStopped; + info.args = args; try { - Class c = Class.forName(className); + Class<?> c = Class.forName(className); java.lang.Object obj = c.newInstance(); try { @@ -539,57 +545,46 @@ public class ServiceManagerI extends _ServiceManagerDisp // commnunicator property set. // Ice.Communicator communicator; - if(_server.communicator().getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0) + if(_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0) { - if(_sharedCommunicator == null) - { - _sharedCommunicator = createCommunicator("", new Ice.StringSeqHolder()); - } + assert(_sharedCommunicator != null); communicator = _sharedCommunicator; - - Ice.Properties properties = _sharedCommunicator.getProperties(); - Ice.Properties svcProperties = Ice.Util.createProperties(serviceArgs, properties); - + } + else + { // - // Erase properties in 'properties' + // Create the service properties. We use the communicator properties as the default + // properties if IceBox.InheritProperties is set. // - java.util.Map<String, String> allProps = properties.getPropertiesForPrefix(""); - java.util.Iterator<String> p = allProps.keySet().iterator(); - while(p.hasNext()) + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = createServiceProperties(service); + Ice.StringSeqHolder serviceArgs = new Ice.StringSeqHolder(info.args); + if(serviceArgs.value.length > 0) { - String key = p.next(); - if(svcProperties.getProperty(key).length() == 0) - { - properties.setProperty(key, ""); - } - } + // + // Create the service properties with the given service arguments. This should + // read the service config file if it's specified with --Ice.Config. + // + initData.properties = Ice.Util.createProperties(serviceArgs, initData.properties); - // - // Add the service properties to the shared communicator properties. - // - java.util.Iterator<java.util.Map.Entry<String, String> > q = - svcProperties.getPropertiesForPrefix("").entrySet().iterator(); - while(q.hasNext()) - { - java.util.Map.Entry<String, String> entry = q.next(); - properties.setProperty(entry.getKey(), entry.getValue()); + // + // Next, parse the service "<service>.*" command line options (the Ice command + // line options were parsed by the createProperties above) + // + serviceArgs.value = initData.properties.parseCommandLineOptions(service, serviceArgs.value); } - + // - // Parse <service>.* command line options - // (the Ice command line options were parse by the createProperties above) + // Remaining command line options are passed to the communicator. This is + // necessary for Ice plug-in properties (e.g.: IceSSL). // - serviceArgs.value = properties.parseCommandLineOptions(service, serviceArgs.value); - } - else - { - info.communicator = createCommunicator(service, serviceArgs); + info.communicator = Ice.Util.initialize(serviceArgs, initData); + info.args = serviceArgs.value; communicator = info.communicator; } try { - info.args = serviceArgs.value; info.service.start(service, communicator, info.args); info.status = StatusStarted; @@ -705,7 +700,7 @@ public class ServiceManagerI extends _ServiceManagerDisp try { - _server.communicator().removeAdminFacet("IceBox.Service." + info.name + ".Properties"); + _communicator.removeAdminFacet("IceBox.Service." + info.name + ".Properties"); } catch(Ice.LocalException e) { @@ -857,7 +852,7 @@ public class ServiceManagerI extends _ServiceManagerDisp if(!(ex instanceof Ice.CommunicatorDestroyedException)) { _logger.trace("IceBox.ServiceObserver", - "Removed service observer " + _server.communicator().proxyToString(observer) + "Removed service observer " + _communicator.proxyToString(observer) + "\nafter catching " + ex.toString()); } } @@ -912,90 +907,83 @@ public class ServiceManagerI extends _ServiceManagerDisp private final Ice.Properties _properties; } - private Ice.Communicator - createCommunicator(String service, Ice.StringSeqHolder args) + static class StartServiceInfo { - Ice.Properties communicatorProperties = _server.communicator().getProperties(); - - // - // Create the service properties. We use the communicator properties as the default - // properties if IceBox.InheritProperties is set. - // - Ice.Properties properties; - if(communicatorProperties.getPropertyAsInt("IceBox.InheritProperties") > 0) + StartServiceInfo(String service, String value, String[] serverArgs) { - properties = communicatorProperties._clone(); - properties.setProperty("Ice.Admin.Endpoints", ""); // Inherit all except Ice.Admin.Endpoints! - } - else - { - properties = Ice.Util.createProperties(); - } + name = service; - // - // Set the default program name for the service properties. By default it's - // the IceBox program name + "-" + the service name, or just the IceBox - // program name if we're creating the shared communicator (service == ""). - // - String programName = communicatorProperties.getProperty("Ice.ProgramName"); - if(service.length() == 0) - { - if(programName.length() == 0) + // + // Separate the entry point from the arguments. + // + int pos = IceUtilInternal.StringUtil.findFirstOf(value, " \t\n"); + if(pos == -1) { - properties.setProperty("Ice.ProgramName", "SharedCommunicator"); + className = value; + args = new String[0]; } else { - properties.setProperty("Ice.ProgramName", programName + "-SharedCommunicator"); - } - } - else - { - if(programName.length() == 0) - { - properties.setProperty("Ice.ProgramName", service); + className = value.substring(0, pos); + try + { + args = IceUtilInternal.Options.split(value.substring(pos)); + } + catch(IceUtilInternal.Options.BadQuote ex) + { + FailureException e = new FailureException(); + e.reason = "ServiceManager: invalid arguments for service `" + name + "':\n" + ex.toString(); + throw e; + } } - else + + if(serverArgs.length > 0) { - properties.setProperty("Ice.ProgramName", programName + "-" + service); + java.util.List<String> l = new java.util.ArrayList<String>(java.util.Arrays.asList(args)); + for(int j = 0; j < serverArgs.length; j++) + { + if(serverArgs[j].startsWith("--" + service + ".")) + { + l.add(serverArgs[j]); + } + } + args = l.toArray(args); } } - if(args.value != null && args.value.length > 0) - { - // - // Create the service properties with the given service arguments. This should - // read the service config file if it's specified with --Ice.Config. - // - properties = Ice.Util.createProperties(args, properties); + String name; + String[] args; + String className; + } - if(service.length() > 0) - { - // - // Next, parse the service "<service>.*" command line options (the Ice command - // line options were parsed by the createProperties above) - // - args.value = properties.parseCommandLineOptions(service, args.value); - } + private Ice.Properties + createServiceProperties(String service) + { + Ice.Properties properties; + Ice.Properties communicatorProperties = _communicator.getProperties(); + if(communicatorProperties.getPropertyAsInt("IceBox.InheritProperties") > 0) + { + properties = communicatorProperties._clone(); + properties.setProperty("Ice.Admin.Endpoints", ""); // Inherit all except Ice.Admin.Endpoints! + } + else + { + properties = Ice.Util.createProperties(); } - // - // Remaining command line options are passed to the communicator. This is - // necessary for Ice plug-in properties (e.g.: IceSSL). - // - Ice.InitializationData initData = new Ice.InitializationData(); - initData.properties = properties; - if(args.value != null) + String programName = communicatorProperties.getProperty("Ice.ProgramName"); + if(programName.length() == 0) { - return Ice.Util.initialize(args, initData); + properties.setProperty("Ice.ProgramName", service); } else { - return Ice.Util.initialize(initData); + properties.setProperty("Ice.ProgramName", programName + "-" + service); } + return properties; } - private Ice.Application _server; + private Ice.Communicator _communicator; private Ice.Communicator _sharedCommunicator; private Ice.Logger _logger; private String[] _argv; // Filtered server argument vector diff --git a/java/src/IceGridGUI/LiveDeploymentPane.java b/java/src/IceGridGUI/LiveDeploymentPane.java index e978c7b5787..3267f0b9bb2 100644 --- a/java/src/IceGridGUI/LiveDeploymentPane.java +++ b/java/src/IceGridGUI/LiveDeploymentPane.java @@ -26,9 +26,6 @@ import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeSelectionModel; import javax.swing.tree.TreePath; -import com.jgoodies.looks.Options; -import com.jgoodies.looks.plastic.PlasticLookAndFeel; -import com.jgoodies.looks.windows.WindowsLookAndFeel; import com.jgoodies.forms.factories.Borders; import IceGrid.*; diff --git a/java/src/IceInternal/BasicStream.java b/java/src/IceInternal/BasicStream.java index ae39f1055bb..9be9e9e533c 100644 --- a/java/src/IceInternal/BasicStream.java +++ b/java/src/IceInternal/BasicStream.java @@ -367,6 +367,17 @@ public class BasicStream } public void + endWriteEncapsChecked() // Used by public stream API. + { + if(_writeEncapsStack == null) + { + throw new Ice.EncapsulationException("not in an encapsulation"); + } + + endWriteEncaps(); + } + + public void startReadEncaps() { { @@ -478,6 +489,17 @@ public class BasicStream } } + public void + endReadEncapsChecked() // Used by public stream API. + { + if(_readEncapsStack == null) + { + throw new Ice.EncapsulationException("not in an encapsulation"); + } + + endReadEncaps(); + } + public int getReadEncapsSize() { @@ -592,6 +614,14 @@ public class BasicStream public void writeTypeId(String id) { + if(_writeEncapsStack == null || _writeEncapsStack.typeIdMap == null) + { + // + // writeObject() must be called first. + // + throw new Ice.MarshalException("type ids require an encapsulation"); + } + Integer index = _writeEncapsStack.typeIdMap.get(id); if(index != null) { @@ -610,6 +640,14 @@ public class BasicStream public String readTypeId() { + if(_readEncapsStack == null || _readEncapsStack.typeIdMap == null) + { + // + // readObject() must be called first. + // + throw new Ice.MarshalException("type ids require an encapsulation"); + } + String id; Integer index; final boolean isIndex = readBool(); @@ -692,6 +730,28 @@ public class BasicStream } } + public void + writeSerializable(java.io.Serializable o) + { + if(o == null) + { + writeSize(0); + return; + } + try + { + OutputStreamWrapper w = new OutputStreamWrapper(this); + java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(w); + out.writeObject(o); + out.close(); + w.close(); + } + catch(java.lang.Exception ex) + { + throw new Ice.MarshalException("cannot serialize object: " + ex); + } + } + public byte readByte() { @@ -733,6 +793,27 @@ public class BasicStream } } + public java.io.Serializable + readSerializable() + { + int sz = readSize(); + if (sz == 0) + { + return null; + } + checkFixedSeq(sz, 1); + try + { + InputStreamWrapper w = new InputStreamWrapper(sz, this); + java.io.ObjectInputStream in = new java.io.ObjectInputStream(w); + return (java.io.Serializable)in.readObject(); + } + catch(java.lang.Exception ex) + { + throw new Ice.MarshalException("cannot deserialize object: " + ex); + } + } + public void writeBool(boolean v) { @@ -1377,33 +1458,40 @@ public class BasicStream int index = readInt(); - if(index == 0) + if(patcher != null) { - patcher.patch(null); - return; - } + if(index == 0) + { + patcher.patch(null); + return; + } - if(index < 0 && patcher != null) - { - Integer i = new Integer(-index); - java.util.LinkedList<Patcher> patchlist = _readEncapsStack.patchMap.get(i); - if(patchlist == null) + if(index < 0) { + Integer i = new Integer(-index); + java.util.LinkedList<Patcher> patchlist = _readEncapsStack.patchMap.get(i); + if(patchlist == null) + { + // + // We have no outstanding instances to be patched for + // this index, so make a new entry in the patch map. + // + patchlist = new java.util.LinkedList<Patcher>(); + _readEncapsStack.patchMap.put(i, patchlist); + } // - // We have no outstanding instances to be patched for - // this index, so make a new entry in the patch map. + // Append a patcher for this instance and see if we can + // patch the instance. (The instance may have been + // unmarshaled previously.) // - patchlist = new java.util.LinkedList<Patcher>(); - _readEncapsStack.patchMap.put(i, patchlist); + patchlist.add(patcher); + patchReferences(null, i); + return; } - // - // Append a patcher for this instance and see if we can - // patch the instance. (The instance may have been - // unmarshaled previously.) - // - patchlist.add(patcher); - patchReferences(null, i); - return; + } + if(index < 0) + { + throw new Ice.MarshalException("Invalid class instance index"); } String mostDerivedId = readTypeId(); @@ -1523,6 +1611,7 @@ public class BasicStream boolean usesClasses = readBool(); String id = readString(); + final String origId = id; for(;;) { @@ -1567,8 +1656,24 @@ public class BasicStream { TraceUtil.traceSlicing("exception", id, _slicingCat, _instance.initializationData().logger); } + skipSlice(); // Slice off what we don't understand. - id = readString(); // Read type id for next slice. + + try + { + id = readString(); // Read type id for next slice. + } + catch(Ice.UnmarshalOutOfBoundsException ex) + { + // + // When readString raises this exception it means we've seen the last slice, + // so we set the reason member to a more helpful message. + // + Ice.UnmarshalOutOfBoundsException e = new Ice.UnmarshalOutOfBoundsException(); + e.reason = "unknown exception type `" + origId + "'"; + e.initCause(ex); + throw e; + } } } @@ -1636,6 +1741,15 @@ public class BasicStream } while(num > 0); + if(_readEncapsStack != null && _readEncapsStack.patchMap != null && _readEncapsStack.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"); + } + // // Iterate over unmarshaledMap and invoke ice_postUnmarshal on // each object. We must do this after all objects in this @@ -2023,7 +2137,7 @@ public class BasicStream return ucStream; } - private void + public void expand(int n) { if(!_unlimited && _buf.b != null && _buf.b.position() + n > _messageSizeMax) @@ -2035,7 +2149,7 @@ public class BasicStream private static final class DynamicObjectFactory implements Ice.ObjectFactory { - DynamicObjectFactory(Class c) + DynamicObjectFactory(Class<?> c) { _class = c; } @@ -2060,7 +2174,7 @@ public class BasicStream { } - private Class _class; + private Class<?> _class; } private Ice.ObjectFactory @@ -2070,7 +2184,7 @@ public class BasicStream try { - Class c = findClass(id); + Class<?> c = findClass(id); if(c != null) { Ice.ObjectFactory dynamicFactory = new DynamicObjectFactory(c); @@ -2115,7 +2229,7 @@ public class BasicStream private static final class DynamicUserExceptionFactory implements UserExceptionFactory { - DynamicUserExceptionFactory(Class c) + DynamicUserExceptionFactory(Class<?> c) { _class = c; } @@ -2145,7 +2259,7 @@ public class BasicStream { } - private Class _class; + private Class<?> _class; } private UserExceptionFactory @@ -2162,7 +2276,7 @@ public class BasicStream { try { - Class c = findClass(id); + Class<?> c = findClass(id); if(c != null) { factory = new DynamicUserExceptionFactory(c); @@ -2187,11 +2301,11 @@ public class BasicStream return factory; } - private Class + private Class<?> findClass(String id) throws LinkageError { - Class c = null; + Class<?> c = null; // // To convert a Slice type id into a Java class, we do the following: @@ -2231,13 +2345,13 @@ public class BasicStream return c; } - private Class + private Class<?> getConcreteClass(String className) throws LinkageError { try { - Class c = Class.forName(className); + Class<?> c = Class.forName(className); // // Ensure the class is instantiable. The constants are // defined in the JVM specification (0x200 = interface, @@ -2289,7 +2403,7 @@ public class BasicStream throw new Ice.MarshalException(); } - StringBuffer buf = new StringBuffer(id.length()); + StringBuilder buf = new StringBuilder(id.length()); int start = 2; boolean done = false; @@ -2417,8 +2531,8 @@ public class BasicStream return _bzInputStreamCtor != null && _bzOutputStreamCtor != null; } - private static java.lang.reflect.Constructor _bzInputStreamCtor; - private static java.lang.reflect.Constructor _bzOutputStreamCtor; + private static java.lang.reflect.Constructor<?> _bzInputStreamCtor; + private static java.lang.reflect.Constructor<?> _bzOutputStreamCtor; static { try diff --git a/java/src/IceInternal/ConnectionMonitor.java b/java/src/IceInternal/ConnectionMonitor.java index 2ef72a8cbe1..1d66123c06e 100644 --- a/java/src/IceInternal/ConnectionMonitor.java +++ b/java/src/IceInternal/ConnectionMonitor.java @@ -79,6 +79,7 @@ public final class ConnectionMonitor implements IceInternal.TimerTask // so that connections can be added or removed during // monitoring. // + long now = IceInternal.Time.currentMonotonicTimeMillis(); java.util.Iterator<Ice.ConnectionI> iter = connections.iterator(); while(iter.hasNext()) { @@ -86,7 +87,7 @@ public final class ConnectionMonitor implements IceInternal.TimerTask try { - connection.monitor(); + connection.monitor(now); } catch(Ice.LocalException ex) { diff --git a/java/src/IceInternal/Connector.java b/java/src/IceInternal/Connector.java index 326c264d498..d8e94ecd803 100644 --- a/java/src/IceInternal/Connector.java +++ b/java/src/IceInternal/Connector.java @@ -20,5 +20,4 @@ public interface Connector // Compare connectors for sorting process. // boolean equals(java.lang.Object obj); - int compareTo(java.lang.Object obj); // From java.lang.Comparable. } diff --git a/java/src/IceInternal/Direct.java b/java/src/IceInternal/Direct.java index 5d6f83e1966..5317fc28300 100644 --- a/java/src/IceInternal/Direct.java +++ b/java/src/IceInternal/Direct.java @@ -44,63 +44,52 @@ public abstract class Direct implements Ice.Request ServantManager servantManager = adapter.getServantManager(); assert(servantManager != null); - try + _servant = servantManager.findServant(_current.id, _current.facet); + if(_servant == null) { - _servant = servantManager.findServant(_current.id, _current.facet); - if(_servant == null) + _locator = servantManager.findServantLocator(_current.id.category); + if(_locator == null && _current.id.category.length() > 0) { - _locator = servantManager.findServantLocator(_current.id.category); - if(_locator == null && _current.id.category.length() > 0) - { - _locator = servantManager.findServantLocator(""); - } - if(_locator != null) - { - _cookie = new Ice.LocalObjectHolder(); // Lazy creation. - try - { - _servant = _locator.locate(_current, _cookie); - } - catch(Ice.UserException ex) - { - adapter.decDirectCount(); - throw ex; - } - } + _locator = servantManager.findServantLocator(""); } - if(_servant == null) + if(_locator != null) { - if(servantManager != null && servantManager.hasServant(_current.id)) + _cookie = new Ice.LocalObjectHolder(); // Lazy creation. + try + { + _servant = _locator.locate(_current, _cookie); + } + catch(Ice.UserException ex) { - Ice.FacetNotExistException ex = new Ice.FacetNotExistException(); - ex.id = _current.id; - ex.facet = _current.facet; - ex.operation = _current.operation; + adapter.decDirectCount(); throw ex; } - else + catch(java.lang.RuntimeException ex) { - Ice.ObjectNotExistException ex = new Ice.ObjectNotExistException(); - ex.id = _current.id; - ex.facet = _current.facet; - ex.operation = _current.operation; + adapter.decDirectCount(); throw ex; } } } - catch(RuntimeException ex) + + if(_servant == null) { - try + adapter.decDirectCount(); + if(servantManager != null && servantManager.hasServant(_current.id)) { - if(_locator != null && _servant != null) - { - _locator.finished(_current, _servant, _cookie.value); - } + Ice.FacetNotExistException ex = new Ice.FacetNotExistException(); + ex.id = _current.id; + ex.facet = _current.facet; + ex.operation = _current.operation; throw ex; } - finally + else { - adapter.decDirectCount(); + Ice.ObjectNotExistException ex = new Ice.ObjectNotExistException(); + ex.id = _current.id; + ex.facet = _current.facet; + ex.operation = _current.operation; + throw ex; } } } diff --git a/java/src/IceInternal/EndpointFactoryManager.java b/java/src/IceInternal/EndpointFactoryManager.java index 98a4c393bec..4e7c302b248 100644 --- a/java/src/IceInternal/EndpointFactoryManager.java +++ b/java/src/IceInternal/EndpointFactoryManager.java @@ -112,7 +112,7 @@ public final class EndpointFactoryManager ue.streamWrite(bs); Buffer buf = bs.getBuffer(); buf.b.position(0); - short type = bs.readShort(); + bs.readShort(); // type return f.read(bs); } } @@ -125,7 +125,6 @@ public final class EndpointFactoryManager public synchronized EndpointI read(BasicStream s) { - EndpointI v; short type = s.readShort(); for(int i = 0; i < _factories.size(); i++) diff --git a/java/src/IceInternal/Incoming.java b/java/src/IceInternal/Incoming.java index a72e45b74ef..28dd812dbbd 100644 --- a/java/src/IceInternal/Incoming.java +++ b/java/src/IceInternal/Incoming.java @@ -120,83 +120,76 @@ final public class Incoming extends IncomingBase implements Ice.Request // the caller of this operation. // - try + if(servantManager != null) { - try + _servant = servantManager.findServant(_current.id, _current.facet); + if(_servant == null) { - if(servantManager != null) + _locator = servantManager.findServantLocator(_current.id.category); + if(_locator == null && _current.id.category.length() > 0) { - _servant = servantManager.findServant(_current.id, _current.facet); - if(_servant == null) - { - _locator = servantManager.findServantLocator(_current.id.category); - if(_locator == null && _current.id.category.length() > 0) - { - _locator = servantManager.findServantLocator(""); - } - if(_locator != null) - { - try - { - _servant = _locator.locate(_current, _cookie); - } - catch(Ice.UserException ex) - { - _os.writeUserException(ex); - replyStatus = ReplyStatus.replyUserException; - } - } - } + _locator = servantManager.findServantLocator(""); } - if(replyStatus == ReplyStatus.replyOK) + + if(_locator != null) { - if(_servant == null) + try { - if(servantManager != null && servantManager.hasServant(_current.id)) - { - replyStatus = ReplyStatus.replyFacetNotExist; - } - else - { - replyStatus = ReplyStatus.replyObjectNotExist; - } + _servant = _locator.locate(_current, _cookie); } - else + catch(Ice.UserException ex) { - dispatchStatus = _servant.__dispatch(this, _current); - if(dispatchStatus == Ice.DispatchStatus.DispatchUserException) - { - replyStatus = ReplyStatus.replyUserException; - } + _os.writeUserException(ex); + replyStatus = ReplyStatus.replyUserException; + } + catch(java.lang.Exception ex) + { + __handleException(ex); + return; } } } - finally + } + + if(_servant != null) + { + try { - if(_locator != null && _servant != null && dispatchStatus != Ice.DispatchStatus.DispatchAsync) + assert(replyStatus == ReplyStatus.replyOK); + dispatchStatus = _servant.__dispatch(this, _current); + if(dispatchStatus == Ice.DispatchStatus.DispatchUserException) { - try - { - _locator.finished(_current, _servant, _cookie.value); - } - catch(Ice.UserException ex) + replyStatus = ReplyStatus.replyUserException; + } + + if(dispatchStatus != Ice.DispatchStatus.DispatchAsync) + { + if(_locator != null && !__servantLocatorFinished()) { - // - // The operation may have already marshaled a reply; we must overwrite that reply. - // - _os.endWriteEncaps(); - _os.resize(Protocol.headerSize + 5, false); // Byte following reply status. - _os.startWriteEncaps(); - _os.writeUserException(ex); - replyStatus = ReplyStatus.replyUserException; // Code below inserts the reply status. + return; } } } + catch(java.lang.Exception ex) + { + if(_locator != null && !__servantLocatorFinished()) + { + return; + } + __handleException(ex); + return; + } } - catch(java.lang.Exception ex) + else if(replyStatus == ReplyStatus.replyOK) { - __handleException(ex); - return; + if(servantManager != null && servantManager.hasServant(_current.id)) + { + replyStatus = ReplyStatus.replyFacetNotExist; + } + else + { + replyStatus = ReplyStatus.replyObjectNotExist; + } } // diff --git a/java/src/IceInternal/IncomingAsync.java b/java/src/IceInternal/IncomingAsync.java index 5e07fd43a78..d18b37d0a37 100644 --- a/java/src/IceInternal/IncomingAsync.java +++ b/java/src/IceInternal/IncomingAsync.java @@ -50,7 +50,7 @@ public class IncomingAsync extends IncomingBase { try { - if(!__servantLocatorFinished()) + if(_locator != null && !__servantLocatorFinished()) { return; } @@ -92,7 +92,7 @@ public class IncomingAsync extends IncomingBase try { - if(!__servantLocatorFinished()) + if(_locator != null && !__servantLocatorFinished()) { return; } @@ -105,47 +105,6 @@ public class IncomingAsync extends IncomingBase } } - final private boolean - __servantLocatorFinished() - { - try - { - if(_locator != null && _servant != null) - { - try - { - _locator.finished(_current, _servant, _cookie.value); - } - catch(Ice.UserException ex) - { - // The operation may have already marshaled a reply; we must overwrite that reply. - // - if(_response) - { - _os.endWriteEncaps(); - _os.resize(Protocol.headerSize + 4, false); // Reply status position. - _os.writeByte(ReplyStatus.replyUserException); - _os.startWriteEncaps(); - _os.writeUserException(ex); - _os.endWriteEncaps(); - _connection.sendResponse(_os, _compress); - } - else - { - _connection.sendNoResponse(); - } - return false; - } - } - return true; - } - catch(java.lang.Exception ex) - { - __handleException(ex); - return false; - } - } - final protected boolean __validateResponse(boolean ok) { @@ -158,10 +117,10 @@ public class IncomingAsync extends IncomingBase { if(_interceptorAsyncCallbackList != null) { - java.util.Iterator p = _interceptorAsyncCallbackList.iterator(); + java.util.Iterator<Ice.DispatchInterceptorAsyncCallback> p = _interceptorAsyncCallbackList.iterator(); while(p.hasNext()) { - Ice.DispatchInterceptorAsyncCallback cb = (Ice.DispatchInterceptorAsyncCallback)p.next(); + Ice.DispatchInterceptorAsyncCallback cb = p.next(); if(cb.response(ok) == false) { return false; diff --git a/java/src/IceInternal/IncomingBase.java b/java/src/IceInternal/IncomingBase.java index 2a2c5a29145..c093284e35e 100644 --- a/java/src/IceInternal/IncomingBase.java +++ b/java/src/IceInternal/IncomingBase.java @@ -153,6 +153,42 @@ public class IncomingBase _os.instance().initializationData().logger.warning(sw.toString()); } + final protected boolean + __servantLocatorFinished() + { + assert(_locator != null && _servant != null); + try + { + _locator.finished(_current, _servant, _cookie.value); + return true; + } + catch(Ice.UserException ex) + { + // + // The operation may have already marshaled a reply; we must overwrite that reply. + // + if(_response) + { + _os.endWriteEncaps(); + _os.resize(Protocol.headerSize + 4, false); // Reply status position. + _os.writeByte(ReplyStatus.replyUserException); + _os.startWriteEncaps(); + _os.writeUserException(ex); + _os.endWriteEncaps(); + _connection.sendResponse(_os, _compress); + } + else + { + _connection.sendNoResponse(); + } + } + catch(java.lang.Exception ex) + { + __handleException(ex); + } + return false; + } + final protected void __handleException(java.lang.Exception exc) { diff --git a/java/src/IceInternal/IncomingConnectionFactory.java b/java/src/IceInternal/IncomingConnectionFactory.java index bfcc28b62a1..83012ac9578 100644 --- a/java/src/IceInternal/IncomingConnectionFactory.java +++ b/java/src/IceInternal/IncomingConnectionFactory.java @@ -412,7 +412,6 @@ public final class IncomingConnectionFactory extends EventHandler implements Ice _endpoint = _endpoint.compress(defaultsAndOverrides.overrideCompressValue); } - Ice.ObjectAdapterI adapterImpl = (Ice.ObjectAdapterI)_adapter; try { EndpointIHolder h = new EndpointIHolder(); @@ -588,17 +587,6 @@ public final class IncomingConnectionFactory extends EventHandler implements Ice _instance.initializationData().logger.warning(s); } - private void - error(String msg, Exception ex) - { - java.io.StringWriter sw = new java.io.StringWriter(); - java.io.PrintWriter pw = new java.io.PrintWriter(sw); - ex.printStackTrace(pw); - pw.flush(); - String s = msg + ":\n" + toString() + "\n" + sw.toString(); - _instance.initializationData().logger.error(s); - } - private Acceptor _acceptor; private final Transceiver _transceiver; private EndpointI _endpoint; diff --git a/java/src/IceInternal/InputStreamWrapper.java b/java/src/IceInternal/InputStreamWrapper.java new file mode 100644 index 00000000000..aa12dda716c --- /dev/null +++ b/java/src/IceInternal/InputStreamWrapper.java @@ -0,0 +1,94 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2008 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. +// +// ********************************************************************** + +package IceInternal; + +import java.io.*; + +// +// Class to provide a java.io.InputStream on top of a BasicStream. +// We use this to deserialize arbitrary Java serializable classes from +// a Slice byte sequence. This class is a wrapper around a BasicStream +// that passes all methods through. +// + +public class InputStreamWrapper extends java.io.InputStream +{ + public + InputStreamWrapper(int size, BasicStream s) + { + _s = s; + _markPos = 0; + } + + public int + read() throws IOException + { + try + { + return _s.getBuffer().b.get(); + } + catch(java.lang.Exception ex) + { + throw new IOException(ex.toString()); + } + } + + public int + read(byte[] b) throws IOException + { + return read(b, 0, b.length); + } + + public int + read(byte[] b, int offset, int count) throws IOException + { + try + { + _s.getBuffer().b.get(b, offset, count); + } + catch(java.lang.Exception ex) + { + throw new IOException(ex.toString()); + } + return count; + } + + public int + available() + { + return _s.getBuffer().b.remaining(); + } + + public void + mark(int readlimit) + { + _markPos = _s.pos(); + } + + public void + reset() throws IOException + { + _s.pos(_markPos); + } + + public boolean + markSupported() + { + return true; + } + + public void + close() throws IOException + { + } + + private BasicStream _s; + private int _markPos; +} diff --git a/java/src/IceInternal/Instance.java b/java/src/IceInternal/Instance.java index 8b2bc03ddcd..a870ac7d3de 100644 --- a/java/src/IceInternal/Instance.java +++ b/java/src/IceInternal/Instance.java @@ -429,29 +429,35 @@ public final class Instance // (can't call again getAdmin() after fixing the problem) // since all the facets (servants) in the adapter are lost // + adapter.destroy(); synchronized(this) { _adminAdapter = null; - adapter.destroy(); } throw ex; } + Ice.ObjectPrx admin = adapter.createProxy(_adminIdentity); if(defaultLocator != null && serverId.length() > 0) { - Ice.ProcessPrx process = Ice.ProcessPrxHelper.uncheckedCast( - adapter.createProxy(_adminIdentity).ice_facet("Process")); + Ice.ProcessPrx process = Ice.ProcessPrxHelper.uncheckedCast(admin.ice_facet("Process")); try { + // + // Note that as soon as the process proxy is registered, the communicator might be + // shutdown by a remote client and admin facets might start receiving calls. + // defaultLocator.getRegistry().setServerProcessProxy(serverId, process); } catch(Ice.ServerNotFoundException ex) { if(_traceLevels.location >= 1) { - StringBuffer s = new StringBuffer(); - s.append("couldn't register server `" + serverId + "' with the locator registry:\n"); + StringBuilder s = new StringBuilder(128); + s.append("couldn't register server `"); + s.append(serverId); + s.append("' with the locator registry:\n"); s.append("the server is not known to the locator registry"); _initData.logger.trace(_traceLevels.locationCat, s.toString()); } @@ -462,8 +468,11 @@ public final class Instance { if(_traceLevels.location >= 1) { - StringBuffer s = new StringBuffer(); - s.append("couldn't register server `" + serverId + "' with the locator registry:\n" + ex); + StringBuilder s = new StringBuilder(128); + s.append("couldn't register server `"); + s.append(serverId); + s.append("' with the locator registry:\n"); + s.append(ex.toString()); _initData.logger.trace(_traceLevels.locationCat, s.toString()); } throw ex; @@ -471,12 +480,14 @@ public final class Instance if(_traceLevels.location >= 1) { - StringBuffer s = new StringBuffer(); - s.append("registered server `" + serverId + "' with the locator registry"); + StringBuilder s = new StringBuilder(128); + s.append("registered server `"); + s.append(serverId); + s.append("' with the locator registry"); _initData.logger.trace(_traceLevels.locationCat, s.toString()); } } - return adapter.createProxy(_adminIdentity); + return admin; } } @@ -827,11 +838,6 @@ public final class Instance { _referenceFactory = _referenceFactory.setDefaultLocator(loc); } - - if(_initData.properties.getPropertyAsIntWithDefault("Ice.Admin.DelayCreation", 0) <= 0) - { - getAdmin(); - } // // Start connection monitor if necessary. Set the check interval to @@ -860,7 +866,7 @@ public final class Instance } if(interval > 0) { - interval = java.lang.Math.min(300, java.lang.Math.max(1, (int)interval / 10)); + interval = java.lang.Math.min(300, java.lang.Math.max(5, (int)interval / 10)); } interval = _initData.properties.getPropertyAsIntWithDefault("Ice.MonitorConnections", interval); if(interval > 0) @@ -871,6 +877,16 @@ public final class Instance // // Server thread pool initialization is lazy in serverThreadPool(). // + + // + // This must be done last as this call creates the Ice.Admin object adapter + // and eventually registers a process proxy with the Ice locator (allowing + // remote clients to invoke on Ice.Admin facets as soon as it's registered). + // + if(_initData.properties.getPropertyAsIntWithDefault("Ice.Admin.DelayCreation", 0) <= 0) + { + getAdmin(); + } } // diff --git a/java/src/IceInternal/LocatorInfo.java b/java/src/IceInternal/LocatorInfo.java index bcf28e5865d..cfb06e9d0e7 100644 --- a/java/src/IceInternal/LocatorInfo.java +++ b/java/src/IceInternal/LocatorInfo.java @@ -545,15 +545,20 @@ public final class LocatorInfo { assert(ref.isIndirect()); - StringBuffer s = new StringBuffer(); - s.append(msg + "\n"); + StringBuilder s = new StringBuilder(128); + s.append(msg); + s.append("\n"); if(!ref.isWellKnown()) { - s.append("adapter = " + ref.getAdapterId() + "\n"); + s.append("adapter = "); + s.append(ref.getAdapterId()); + s.append("\n"); } else { - s.append("object = " + ref.getInstance().identityToString(ref.getIdentity()) + "\n"); + s.append("object = "); + s.append(ref.getInstance().identityToString(ref.getIdentity())); + s.append("\n"); } s.append("endpoints = "); @@ -584,9 +589,10 @@ public final class LocatorInfo final Instance instance = ref.getInstance(); if(instance.traceLevels().location >= 1) { - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(128); s.append("adapter not found\n"); - s.append("adapter = " + ref.getAdapterId()); + s.append("adapter = "); + s.append(ref.getAdapterId()); instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.toString()); } @@ -600,9 +606,10 @@ public final class LocatorInfo final Instance instance = ref.getInstance(); if(instance.traceLevels().location >= 1) { - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(128); s.append("object not found\n"); - s.append("object = " + instance.identityToString(ref.getIdentity())); + s.append("object = "); + s.append(instance.identityToString(ref.getIdentity())); instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.toString()); } @@ -620,15 +627,19 @@ public final class LocatorInfo final Instance instance = ref.getInstance(); if(instance.traceLevels().location >= 1) { - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(128); s.append("couldn't contact the locator to retrieve adapter endpoints\n"); if(ref.getAdapterId().length() > 0) { - s.append("adapter = " + ref.getAdapterId() + "\n"); + s.append("adapter = "); + s.append(ref.getAdapterId()); + s.append("\n"); } else { - s.append("object = " + instance.identityToString(ref.getIdentity()) + "\n"); + s.append("object = "); + s.append(instance.identityToString(ref.getIdentity())); + s.append("\n"); } s.append("reason = " + ex); instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.toString()); @@ -658,17 +669,21 @@ public final class LocatorInfo else { final Instance instance = ref.getInstance(); - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(128); s.append("no endpoints configured for "); if(ref.getAdapterId().length() > 0) { s.append("adapter\n"); - s.append("adapter = " + ref.getAdapterId() + "\n"); + s.append("adapter = "); + s.append(ref.getAdapterId()); + s.append("\n"); } else { s.append("object\n"); - s.append("object = " + instance.identityToString(ref.getIdentity()) + "\n"); + s.append("object = "); + s.append(instance.identityToString(ref.getIdentity())); + s.append("\n"); } instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.toString()); } @@ -680,8 +695,9 @@ public final class LocatorInfo if(ref.getInstance().traceLevels().location >= 1) { Instance instance = ref.getInstance(); - StringBuffer s = new StringBuffer(); - s.append("searching for adapter by id\nadapter="); + StringBuilder s = new StringBuilder(128); + s.append("searching for adapter by id\n"); + s.append("adapter = "); s.append(ref.getAdapterId()); instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.toString()); } @@ -702,8 +718,9 @@ public final class LocatorInfo if(ref.getInstance().traceLevels().location >= 1) { Instance instance = ref.getInstance(); - StringBuffer s = new StringBuffer(); - s.append("searching for object by id\nobject = "); + StringBuilder s = new StringBuilder(128); + s.append("searching for object by id\n"); + s.append("object = "); s.append(instance.identityToString(ref.getIdentity())); instance.initializationData().logger.trace(instance.traceLevels().locationCat, s.toString()); } diff --git a/java/src/IceInternal/Network.java b/java/src/IceInternal/Network.java index 3eb8a840d14..f93ef8b4264 100644 --- a/java/src/IceInternal/Network.java +++ b/java/src/IceInternal/Network.java @@ -443,8 +443,7 @@ public final class Network { try { - java.nio.channels.SelectionKey key = - fd.register(selector, java.nio.channels.SelectionKey.OP_ACCEPT); + fd.register(selector, java.nio.channels.SelectionKey.OP_ACCEPT); int n; if(timeout > 0) { @@ -772,7 +771,7 @@ public final class Network // } - if(addr == null || isValidAddr(addr, protocol)) + if(addr == null || !isValidAddr(addr, protocol)) { // // Iterate over the network interfaces and pick an IP @@ -1104,7 +1103,7 @@ public final class Network public static String addressesToString(java.net.InetAddress localAddr, int localPort, java.net.InetAddress remoteAddr, int remotePort) { - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(128); s.append("local address = "); s.append(localAddr.getHostAddress()); s.append(':'); @@ -1127,7 +1126,7 @@ public final class Network public static String addrToString(java.net.InetSocketAddress addr) { - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(128); s.append(addr.getAddress().getHostAddress()); s.append(':'); s.append(addr.getPort()); diff --git a/java/src/IceInternal/OutgoingConnectionFactory.java b/java/src/IceInternal/OutgoingConnectionFactory.java index 0a5bdec8c86..563368f9f22 100644 --- a/java/src/IceInternal/OutgoingConnectionFactory.java +++ b/java/src/IceInternal/OutgoingConnectionFactory.java @@ -188,9 +188,10 @@ public final class OutgoingConnectionFactory // DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides(); java.util.Iterator<ConnectorInfo> q = connectors.iterator(); + ConnectorInfo ci = null; while(q.hasNext()) { - ConnectorInfo ci = q.next(); + ci = q.next(); try { connection = createConnection(ci.connector.connect(), ci); @@ -204,7 +205,7 @@ public final class OutgoingConnectionFactory { compress.value = ci.endpoint.compress(); } - + connection.activate(); break; } catch(Ice.CommunicatorDestroyedException ex) @@ -226,7 +227,14 @@ public final class OutgoingConnectionFactory // Finish creating the connection (this removes the connectors from the _pending // list and notifies any waiting threads). // - finishGetConnection(connectors, null, connection); + if(connection != null) + { + finishGetConnection(connectors, ci, connection, null); + } + else + { + finishGetConnection(connectors, exception, null); + } if(connection == null) { @@ -324,16 +332,7 @@ public final class OutgoingConnectionFactory Ice.ConnectionI connection = q.next(); if(connection.endpoint() == endpoint) { - try - { - connection.setAdapter(adapter); - } - catch(Ice.LocalException ex) - { - // - // Ignore, the connection is being closed or closed. - // - } + connection.setAdapter(adapter); } } } @@ -359,16 +358,7 @@ public final class OutgoingConnectionFactory Ice.ConnectionI connection = q.next(); if(connection.getAdapter() == adapter) { - try - { - connection.setAdapter(null); - } - catch(Ice.LocalException ex) - { - // - // Ignore, the connection is being closed or closed. - // - } + connection.setAdapter(null); } } } @@ -507,6 +497,11 @@ public final class OutgoingConnectionFactory while(p.hasNext()) { ConnectorInfo ci = p.next(); + if(_pending.containsKey(ci)) + { + continue; + } + java.util.List<Ice.ConnectionI> connectionList = _connections.get(ci); if(connectionList == null) { @@ -637,64 +632,23 @@ public final class OutgoingConnectionFactory // finish if one of them is currently establishing a connection to one // of our connectors. // - while(!_destroyed) + while(true) { + if(_destroyed) + { + throw new Ice.CommunicatorDestroyedException(); + } + // // Search for a matching connection. If we find one, we're done. // Ice.ConnectionI connection = findConnection(connectors, compress); if(connection != null) { - if(cb != null) - { - // - // This might not be the first getConnection call for the callback. We need - // to ensure that the callback isn't registered with any other pending - // connectors since we just found a connection and therefore don't need to - // wait anymore for other pending connectors. - // - java.util.Iterator<ConnectorInfo> p = connectors.iterator(); - while(p.hasNext()) - { - java.util.Set<ConnectCallback> cbs = _pending.get(p.next()); - if(cbs != null) - { - cbs.remove(cb); - } - } - } return connection; } - - // - // Determine whether another thread is currently attempting to connect to one of our endpoints; - // if so we wait until it's done. - // - java.util.Iterator<ConnectorInfo> p = connectors.iterator(); - boolean found = false; - while(p.hasNext()) - { - java.util.Set<ConnectCallback> cbs = _pending.get(p.next()); - if(cbs != null) - { - found = true; - if(cb != null) - { - cbs.add(cb); // Add the callback to each pending connector. - } - } - } - if(!found) - { - // - // If no thread is currently establishing a connection to one of our connectors, - // we get out of this loop and start the connection establishment to one of the - // given connectors. - // - break; - } - else + if(addToPending(cb, connectors)) { // // If a callback is not specified we wait until another thread notifies us about a @@ -717,25 +671,14 @@ public final class OutgoingConnectionFactory return null; } } - } - - if(_destroyed) - { - throw new Ice.CommunicatorDestroyedException(); - } - - // - // No connection to any of our endpoints exists yet; we add the given connectors to - // the _pending set to indicate that we're attempting connection establishment to - // these connectors. We might attempt to connect to the same connector multiple times. - // - java.util.Iterator<ConnectorInfo> p = connectors.iterator(); - while(p.hasNext()) - { - ConnectorInfo obj = p.next(); - if(!_pending.containsKey(obj)) + else { - _pending.put(obj, new java.util.HashSet<ConnectCallback>()); + // + // If no thread is currently establishing a connection to one of our connectors, + // we get out of this loop and start the connection establishment to one of the + // given connectors. + // + break; } } } @@ -804,46 +747,180 @@ public final class OutgoingConnectionFactory } private void - finishGetConnection(java.util.List<ConnectorInfo> connectors, ConnectCallback cb, Ice.ConnectionI connection) + finishGetConnection(java.util.List<ConnectorInfo> connectors, + ConnectorInfo ci, + Ice.ConnectionI connection, + ConnectCallback cb) { - java.util.Set<ConnectCallback> callbacks = new java.util.HashSet<ConnectCallback>(); + java.util.Set<ConnectCallback> connectionCallbacks = new java.util.HashSet<ConnectCallback>(); + if(cb != null) + { + connectionCallbacks.add(cb); + } + java.util.Set<ConnectCallback> callbacks = new java.util.HashSet<ConnectCallback>(); synchronized(this) { - // - // We're done trying to connect to the given connectors so we remove the - // connectors from the pending list and notify waiting threads. We also - // notify the pending connect callbacks (outside the synchronization). - // - java.util.Iterator<ConnectorInfo> p = connectors.iterator(); while(p.hasNext()) { - java.util.Set<ConnectCallback> cbs = _pending.remove(p.next()); + ConnectorInfo c = p.next(); + java.util.Set<ConnectCallback> cbs = _pending.remove(c); if(cbs != null) { - callbacks.addAll(cbs); + for(ConnectCallback cc : cbs) + { + if(cc.hasConnector(ci)) + { + connectionCallbacks.add(cc); + } + else + { + callbacks.add(cc); + } + } } } + + for(ConnectCallback cc : connectionCallbacks) + { + cc.removeFromPending(); + callbacks.remove(cc); + } + for(ConnectCallback cc : callbacks) + { + cc.removeFromPending(); + } notifyAll(); + } + + boolean compress; + DefaultsAndOverrides defaultsAndOverrides = _instance.defaultsAndOverrides(); + if(defaultsAndOverrides.overrideCompress) + { + compress = defaultsAndOverrides.overrideCompressValue; + } + else + { + compress = ci.endpoint.compress(); + } - // - // If the connect attempt succeeded and the communicator is not destroyed, - // activate the connection! - // - if(connection != null && !_destroyed) + for(ConnectCallback cc : callbacks) + { + cc.getConnection(); + } + for(ConnectCallback cc : connectionCallbacks) + { + cc.setConnection(connection, compress); + } + } + + private void + finishGetConnection(java.util.List<ConnectorInfo> connectors, Ice.LocalException ex, ConnectCallback cb) + { + java.util.Set<ConnectCallback> failedCallbacks = new java.util.HashSet<ConnectCallback>(); + if(cb != null) + { + failedCallbacks.add(cb); + } + + java.util.Set<ConnectCallback> callbacks = new java.util.HashSet<ConnectCallback>(); + synchronized(this) + { + java.util.Iterator<ConnectorInfo> p = connectors.iterator(); + while(p.hasNext()) { - connection.activate(); + ConnectorInfo c = p.next(); + java.util.Set<ConnectCallback> cbs = _pending.remove(c); + if(cbs != null) + { + for(ConnectCallback cc : cbs) + { + if(cc.removeConnectors(connectors)) + { + failedCallbacks.add(cc); + } + else + { + callbacks.add(cc); + } + } + } + } + + for(ConnectCallback cc : callbacks) + { + assert(!failedCallbacks.contains(cc)); + cc.removeFromPending(); } + notifyAll(); } + for(ConnectCallback cc : callbacks) + { + cc.getConnection(); + } + for(ConnectCallback cc : failedCallbacks) + { + cc.setException(ex); + } + } + + private boolean + addToPending(ConnectCallback cb, java.util.List<ConnectorInfo> connectors) + { + // + // Add the callback to each connector pending list. + // + java.util.Iterator<ConnectorInfo> p = connectors.iterator(); + boolean found = false; + while(p.hasNext()) + { + java.util.Set<ConnectCallback> cbs = _pending.get(p.next()); + if(cbs != null) + { + found = true; + if(cb != null) + { + cbs.add(cb); // Add the callback to each pending connector. + } + } + } + + if(found) + { + return true; + } + // - // Notify any waiting callbacks. + // If there's no pending connection for the given connectors, we're + // responsible for its establishment. We add empty pending lists, + // other callbacks to the same connectors will be queued. // - java.util.Iterator<ConnectCallback> p = callbacks.iterator(); + p = connectors.iterator(); + while(p.hasNext()) + { + ConnectorInfo obj = p.next(); + if(!_pending.containsKey(obj)) + { + _pending.put(obj, new java.util.HashSet<ConnectCallback>()); + } + } + + return false; + } + + private void + removeFromPending(ConnectCallback cb, java.util.List<ConnectorInfo> connectors) + { + java.util.Iterator<ConnectorInfo> p = connectors.iterator(); while(p.hasNext()) { - p.next().getConnection(); + java.util.Set<ConnectCallback> cbs = _pending.get(p.next()); + if(cbs != null) + { + cbs.remove(cb); + } } } @@ -853,7 +930,7 @@ public final class OutgoingConnectionFactory TraceLevels traceLevels = _instance.traceLevels(); if(traceLevels.retry >= 2) { - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(128); s.append("connection to endpoint failed"); if(ex instanceof Ice.CommunicatorDestroyedException) { @@ -913,7 +990,7 @@ public final class OutgoingConnectionFactory TraceLevels traceLevels = _instance.traceLevels(); if(traceLevels.retry >= 2) { - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(128); s.append("couldn't resolve endpoint host"); if(ex instanceof Ice.CommunicatorDestroyedException) { @@ -972,27 +1049,15 @@ public final class OutgoingConnectionFactory _selType = selType; _endpointsIter = _endpoints.iterator(); } - + // // Methods from ConnectionI.StartCallback // public void connectionStartCompleted(Ice.ConnectionI connection) { - boolean compress; - DefaultsAndOverrides defaultsAndOverrides = _factory._instance.defaultsAndOverrides(); - if(defaultsAndOverrides.overrideCompress) - { - compress = defaultsAndOverrides.overrideCompressValue; - } - else - { - compress = _current.endpoint.compress(); - } - - _factory.finishGetConnection(_connectors, this, connection); - _callback.setConnection(connection, compress); - _factory.decPendingConnectCount(); // Must be called last. + connection.activate(); + _factory.finishGetConnection(_connectors, _current, connection, this); } public void @@ -1003,9 +1068,7 @@ public final class OutgoingConnectionFactory _factory.handleException(ex, _current, connection, _hasMore || _iter.hasNext()); if(ex instanceof Ice.CommunicatorDestroyedException) // No need to continue. { - _factory.finishGetConnection(_connectors, this, null); - _callback.setException(ex); - _factory.decPendingConnectCount(); // Must be called last. + _factory.finishGetConnection(_connectors, ex, this); } else if(_iter.hasNext()) // Try the next connector. { @@ -1013,9 +1076,7 @@ public final class OutgoingConnectionFactory } else { - _factory.finishGetConnection(_connectors, this, null); - _callback.setException(ex); - _factory.decPendingConnectCount(); // Must be called last. + _factory.finishGetConnection(_connectors, ex, this); } } @@ -1080,6 +1141,47 @@ public final class OutgoingConnectionFactory } } + public void + setConnection(Ice.ConnectionI connection, boolean compress) + { + // + // Callback from the factory: the connection to one of the callback + // connectors has been established. + // + _callback.setConnection(connection, compress); + _factory.decPendingConnectCount(); // Must be called last. + } + + public void + setException(Ice.LocalException ex) + { + // + // Callback from the factory: connection establishment failed. + // + _callback.setException(ex); + _factory.decPendingConnectCount(); // Must be called last. + } + + public boolean + hasConnector(ConnectorInfo ci) + { + return _connectors.contains(ci); + } + + public boolean + removeConnectors(java.util.List<ConnectorInfo> connectors) + { + _connectors.removeAll(connectors); + _iter = _connectors.iterator(); + return _connectors.isEmpty(); + } + + public void + removeFromPending() + { + _factory.removeFromPending(this, _connectors); + } + void getConnectors() { diff --git a/java/src/IceInternal/OutputStreamWrapper.java b/java/src/IceInternal/OutputStreamWrapper.java new file mode 100644 index 00000000000..471eef7358c --- /dev/null +++ b/java/src/IceInternal/OutputStreamWrapper.java @@ -0,0 +1,173 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2008 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. +// +// ********************************************************************** + +package IceInternal; + +import java.io.*; + +// +// Class to provide a java.io.OutputStream on top of a BasicStream. +// We use this to serialize arbitrary Java serializable classes into +// +// Slice sequences are encoded on the wire as a count of elements, followed +// by the sequence contents. For arbitrary Java classes, we do not know how +// big the sequence that is eventually written will be. To avoid excessive +// data copying, this class mantains a private _bytes array of 254 bytes and, +// initially, writes data into that array. If more than 254 bytes end up being +// written, we write a dummy sequence size of 255 (which occupies five bytes +// on the wire) into the BasicStream and, once this stream is closed, patch +// that size to match the actual size. Otherwise, if the _bytes buffer contains +// fewer than 255 bytes when this stream is closed, we write the sequence size +// as a single byte, followed by the contents of the _bytes buffer. +// + +public class OutputStreamWrapper extends java.io.OutputStream +{ + public + OutputStreamWrapper(BasicStream s) + { + _s = s; + _spos = s.pos(); + _bytes = new byte[254]; + _pos = 0; + } + + public void + write(int b) throws IOException + { + try + { + if(_bytes != null) + { + // + // If we can fit the data into the first 254 bytes, write it to _bytes. + // + if(_pos < _bytes.length) + { + _bytes[_pos++] = (byte)b; + return; + } + + _s.writeSize(255); // Dummy size, until we know how big the stream + // really is and can patch the size. + + if(_pos > 0) + { + // + // Write the current contents of _bytes. + // + _s.expand(_pos); + _s.getBuffer().b.put(_bytes, 0, _pos); + } + _bytes = null; + } + + // + // Write data passed by caller. + // + _s.expand(1); + _s.getBuffer().b.put((byte)b); + _pos += 1; + } + catch(java.lang.Exception ex) + { + throw new IOException(ex.toString()); + } + } + + public void + write(byte[] b) throws IOException + { + write(b, 0, b.length); + } + + public void + write(byte[] bytes, int offset, int count) throws IOException + { + try + { + if(_bytes != null) + { + // + // If we can fit the data into the first 254 bytes, write it to _bytes. + // + if(count <= _bytes.length - _pos) + { + System.arraycopy(bytes, offset, _bytes, _pos, count); + _pos += count; + return; + } + + _s.writeSize(255); // Dummy size, until we know how big the stream + // really is and can patch the size. + + if(_pos > 0) + { + // + // Write the current contents of _bytes. + // + _s.expand(_pos); + _s.getBuffer().b.put(_bytes, 0, _pos); + } + _bytes = null; + } + + // + // Write data passed by caller. + // + _s.expand(count); + _s.getBuffer().b.put(bytes, offset, count); + _pos += count; + } + catch(java.lang.Exception ex) + { + throw new IOException(ex.toString()); + } + } + + public void + flush() throws IOException + { + // This does nothing because we do not know the final size of a writable stream until it is closed, + // and we cannot write to the BasicStream until we know whether the final size is < 255 or not. + } + + public void + close() throws IOException + { + try + { + if(_bytes != null) + { + assert(_pos <= _bytes.length); + _s.pos(_spos); + _s.writeSize(_pos); + _s.expand(_pos); + _s.getBuffer().b.put(_bytes, 0, _pos); + _bytes = null; + } + else + { + int currentPos = _s.pos(); + _s.pos(_spos); + _s.writeSize(_pos); // Patch previously-written dummy value. + _s.pos(currentPos); + } + } + catch(java.lang.Exception ex) + { + throw new IOException(ex.toString()); + } + } + + private BasicStream _s; + private int _spos; + private byte[] _bytes; + private int _pos; +} diff --git a/java/src/IceInternal/PropertyNames.java b/java/src/IceInternal/PropertyNames.java index 3a7990d01cc..77852f04384 100644 --- a/java/src/IceInternal/PropertyNames.java +++ b/java/src/IceInternal/PropertyNames.java @@ -8,7 +8,7 @@ // ********************************************************************** // -// Generated by makeprops.py from file ../config/PropertyNames.xml, Tue Jan 20 15:47:00 2009 +// Generated by makeprops.py from file ../config/PropertyNames.xml, Thu Feb 19 14:25:55 2009 // IMPORTANT: Do not edit this file -- any edits made here will be lost! @@ -75,7 +75,7 @@ public final class PropertyNames new Property("Ice\\.ImplicitContext", false, null), new Property("Ice\\.InitPlugins", false, null), new Property("Ice\\.MessageSizeMax", false, null), - new Property("Ice\\.MonitorConnections", true, null), + new Property("Ice\\.MonitorConnections", false, null), new Property("Ice\\.Nohup", false, null), new Property("Ice\\.NullHandleAbort", false, null), new Property("Ice\\.Override\\.Compress", false, null), @@ -268,15 +268,7 @@ public final class PropertyNames new Property("IceGrid\\.Registry\\.CryptPasswords", false, null), new Property("IceGrid\\.Registry\\.Data", false, null), new Property("IceGrid\\.Registry\\.DefaultTemplates", false, null), - new Property("IceGrid\\.Registry\\.Discard\\.Interval", false, null), new Property("IceGrid\\.Registry\\.DynamicRegistration", false, null), - new Property("IceGrid\\.Registry\\.Election\\.ElectionTimeout", false, null), - new Property("IceGrid\\.Registry\\.Election\\.MasterTimeout", false, null), - new Property("IceGrid\\.Registry\\.Election\\.ResponseTimeout", false, null), - new Property("IceGrid\\.Registry\\.Flush\\.Timeout", false, null), - new Property("IceGrid\\.Registry\\.IceStormAdmin\\.TopicManager\\.Default", false, null), - new Property("IceGrid\\.Registry\\.IceStormAdmin\\.TopicManager\\.[^\\s]+", false, null), - new Property("IceGrid\\.Registry\\.InstanceName", false, null), new Property("IceGrid\\.Registry\\.Internal\\.AdapterId", false, null), new Property("IceGrid\\.Registry\\.Internal\\.Endpoints", false, null), new Property("IceGrid\\.Registry\\.Internal\\.Locator", false, null), @@ -290,9 +282,6 @@ public final class PropertyNames new Property("IceGrid\\.Registry\\.Internal\\.ThreadPool\\.SizeWarn", false, null), new Property("IceGrid\\.Registry\\.Internal\\.ThreadPool\\.StackSize", false, null), new Property("IceGrid\\.Registry\\.Internal\\.ThreadPool\\.Serialize", false, null), - new Property("IceGrid\\.Registry\\.Node\\.[^\\s]+", false, null), - new Property("IceGrid\\.Registry\\.NodeId", false, null), - new Property("IceGrid\\.Registry\\.Nodes\\.id", false, null), new Property("IceGrid\\.Registry\\.NodeSessionTimeout", false, null), new Property("IceGrid\\.Registry\\.PermissionsVerifier\\.EndpointSelection", false, null), new Property("IceGrid\\.Registry\\.PermissionsVerifier\\.ConnectionCached", false, null), @@ -303,12 +292,8 @@ public final class PropertyNames new Property("IceGrid\\.Registry\\.PermissionsVerifier\\.CollocationOptimization", true, "IceGrid.Registry.PermissionsVerifier.CollocationOptimized"), new Property("IceGrid\\.Registry\\.PermissionsVerifier\\.CollocationOptimized", false, null), new Property("IceGrid\\.Registry\\.PermissionsVerifier", false, null), - new Property("IceGrid\\.Registry\\.Publish\\.[^\\s]+", false, null), new Property("IceGrid\\.Registry\\.ReplicaName", false, null), new Property("IceGrid\\.Registry\\.ReplicaSessionTimeout", false, null), - new Property("IceGrid\\.Registry\\.ReplicatedPublishEndpoints", false, null), - new Property("IceGrid\\.Registry\\.ReplicatedTopicManagerEndpoints", false, null), - new Property("IceGrid\\.Registry\\.Send\\.Timeout", false, null), new Property("IceGrid\\.Registry\\.Server\\.AdapterId", false, null), new Property("IceGrid\\.Registry\\.Server\\.Endpoints", false, null), new Property("IceGrid\\.Registry\\.Server\\.Locator", false, null), @@ -346,22 +331,18 @@ public final class PropertyNames new Property("IceGrid\\.Registry\\.SSLPermissionsVerifier\\.CollocationOptimization", true, "IceGrid.Registry.SSLPermissionsVerifier.CollocationOptimized"), new Property("IceGrid\\.Registry\\.SSLPermissionsVerifier\\.CollocationOptimized", false, null), new Property("IceGrid\\.Registry\\.SSLPermissionsVerifier", false, null), - new Property("IceGrid\\.Registry\\.TopicManager\\.[^\\s]+", false, null), new Property("IceGrid\\.Registry\\.Trace\\.Application", false, null), new Property("IceGrid\\.Registry\\.Trace\\.Adapter", false, null), - new Property("IceGrid\\.Registry\\.Trace\\.Election", false, null), new Property("IceGrid\\.Registry\\.Trace\\.Locator", false, null), new Property("IceGrid\\.Registry\\.Trace\\.Node", false, null), new Property("IceGrid\\.Registry\\.Trace\\.Object", false, null), new Property("IceGrid\\.Registry\\.Trace\\.Patch", false, null), new Property("IceGrid\\.Registry\\.Trace\\.Replica", false, null), - new Property("IceGrid\\.Registry\\.Trace\\.Replication", false, null), new Property("IceGrid\\.Registry\\.Trace\\.Server", false, null), new Property("IceGrid\\.Registry\\.Trace\\.Session", false, null), new Property("IceGrid\\.Registry\\.Trace\\.Subscriber", false, null), new Property("IceGrid\\.Registry\\.Trace\\.Topic", false, null), new Property("IceGrid\\.Registry\\.Trace\\.TopicManager", false, null), - new Property("IceGrid\\.Registry\\.Transient", false, null), new Property("IceGrid\\.Registry\\.UserAccounts", false, null), null }; diff --git a/java/src/IceInternal/ProxyFactory.java b/java/src/IceInternal/ProxyFactory.java index 45d3ea2c557..b70d70f9511 100644 --- a/java/src/IceInternal/ProxyFactory.java +++ b/java/src/IceInternal/ProxyFactory.java @@ -105,20 +105,7 @@ public final class ProxyFactory { Ice.ObjectNotExistException one = (Ice.ObjectNotExistException)ex; - LocatorInfo li = ref.getLocatorInfo(); - if(li != null && ref.isIndirect()) - { - // - // We retry ObjectNotExistException if the reference is - // indirect. - // - - if(ref.isWellKnown()) - { - li.clearCache(ref); - } - } - else if(ref.getRouterInfo() != null && one.operation.equals("ice_add_proxy")) + if(ref.getRouterInfo() != null && one.operation.equals("ice_add_proxy")) { // // If we have a router, an ObjectNotExistException with an @@ -140,6 +127,22 @@ public final class ProxyFactory } return cnt; // We must always retry, so we don't look at the retry count. } + else if(ref.isIndirect()) + { + // + // We retry ObjectNotExistException if the reference is + // indirect. + // + + if(ref.isWellKnown()) + { + LocatorInfo li = ref.getLocatorInfo(); + if(li != null) + { + li.clearCache(ref); + } + } + } else { // @@ -220,7 +223,7 @@ public final class ProxyFactory // try { - Thread.currentThread().sleep(interval); + Thread.sleep(interval); } catch(InterruptedException ex1) { diff --git a/java/src/IceInternal/Reference.java b/java/src/IceInternal/Reference.java index 7e9a8acc4d2..037b5508cac 100644 --- a/java/src/IceInternal/Reference.java +++ b/java/src/IceInternal/Reference.java @@ -257,7 +257,7 @@ public abstract class Reference implements Cloneable // these features. Please review for all features that depend on the // format of proxyToString() before changing this and related code. // - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(128); // // If the encoded identity string contains characters which diff --git a/java/src/IceInternal/RoutableReference.java b/java/src/IceInternal/RoutableReference.java index 2e84f1bb2d7..1f17b9cb854 100644 --- a/java/src/IceInternal/RoutableReference.java +++ b/java/src/IceInternal/RoutableReference.java @@ -280,7 +280,7 @@ public class RoutableReference extends Reference // these features. Please review for all features that depend on the // format of proxyToString() before changing this and related code. // - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(128); s.append(super.toString()); if(_endpoints.length > 0) { diff --git a/java/src/IceInternal/RouterInfo.java b/java/src/IceInternal/RouterInfo.java index d7858a1dba9..404f7fa0568 100644 --- a/java/src/IceInternal/RouterInfo.java +++ b/java/src/IceInternal/RouterInfo.java @@ -93,7 +93,6 @@ public final class RouterInfo return; } - final RouterInfo self = this; _router.getClientProxy_async(new Ice.AMI_Router_getClientProxy() { public void diff --git a/java/src/IceInternal/Selector.java b/java/src/IceInternal/Selector.java index 49c7ce5c809..bbb642f09dd 100644 --- a/java/src/IceInternal/Selector.java +++ b/java/src/IceInternal/Selector.java @@ -302,7 +302,7 @@ public final class Selector // try { - Thread.currentThread().sleep(1); + Thread.sleep(1); } catch(java.lang.InterruptedException ex) { diff --git a/java/src/IceInternal/SelectorThread.java b/java/src/IceInternal/SelectorThread.java index ae532792540..c7a50688a1c 100644 --- a/java/src/IceInternal/SelectorThread.java +++ b/java/src/IceInternal/SelectorThread.java @@ -219,7 +219,7 @@ public class SelectorThread status = cb.socketReady(); } } - catch(Ice.LocalException ex) + catch(java.lang.Exception ex) { java.io.StringWriter sw = new java.io.StringWriter(); java.io.PrintWriter pw = new java.io.PrintWriter(sw); @@ -288,22 +288,13 @@ public class SelectorThread { SelectorThread.this.run(); } - catch(Ice.LocalException ex) - { - java.io.StringWriter sw = new java.io.StringWriter(); - java.io.PrintWriter pw = new java.io.PrintWriter(sw); - ex.printStackTrace(pw); - pw.flush(); - String s = "exception in selector thread " + getName() + ":\n" + sw.toString(); - _instance.initializationData().logger.error(s); - } catch(java.lang.Exception ex) { java.io.StringWriter sw = new java.io.StringWriter(); java.io.PrintWriter pw = new java.io.PrintWriter(sw); ex.printStackTrace(pw); pw.flush(); - String s = "unknown exception in selector thread " + getName() + ":\n" + sw.toString(); + String s = "exception in selector thread " + getName() + ":\n" + sw.toString(); _instance.initializationData().logger.error(s); } } diff --git a/java/src/IceInternal/SequencePatcher.java b/java/src/IceInternal/SequencePatcher.java index 9b8b7b82407..94d907c982b 100644 --- a/java/src/IceInternal/SequencePatcher.java +++ b/java/src/IceInternal/SequencePatcher.java @@ -12,7 +12,7 @@ package IceInternal; public class SequencePatcher implements Patcher, Ice.ReadObjectCallback { public - SequencePatcher(java.lang.Object[] seq, Class cls, String type, int index) + SequencePatcher(java.lang.Object[] seq, Class<?> cls, String type, int index) { _seq = seq; _cls = cls; @@ -51,7 +51,7 @@ public class SequencePatcher implements Patcher, Ice.ReadObjectCallback } private java.lang.Object[] _seq; - private Class _cls; + private Class<?> _cls; private String _type; private int _index; } diff --git a/java/src/IceInternal/TcpAcceptor.java b/java/src/IceInternal/TcpAcceptor.java index 2f6f8707b5f..03c93766063 100644 --- a/java/src/IceInternal/TcpAcceptor.java +++ b/java/src/IceInternal/TcpAcceptor.java @@ -130,5 +130,4 @@ class TcpAcceptor implements Acceptor private java.nio.channels.ServerSocketChannel _fd; private int _backlog; private java.net.InetSocketAddress _addr; - private java.nio.channels.Selector _selector; } diff --git a/java/src/IceInternal/TcpConnector.java b/java/src/IceInternal/TcpConnector.java index 3e524736f13..ae5d618be99 100644 --- a/java/src/IceInternal/TcpConnector.java +++ b/java/src/IceInternal/TcpConnector.java @@ -9,7 +9,7 @@ package IceInternal; -final class TcpConnector implements Connector, java.lang.Comparable +final class TcpConnector implements Connector { public Transceiver connect() @@ -83,18 +83,9 @@ final class TcpConnector implements Connector, java.lang.Comparable _hashCode = 5 * _hashCode + _connectionId.hashCode(); } - // - // Compare connectors for sorting purposes - // public boolean equals(java.lang.Object obj) { - return compareTo(obj) == 0; - } - - public int - compareTo(java.lang.Object obj) // From java.lang.Comparable - { TcpConnector p = null; try @@ -103,46 +94,27 @@ final class TcpConnector implements Connector, java.lang.Comparable } catch(ClassCastException ex) { - try - { - Connector c = (Connector)obj; - return type() < c.type() ? -1 : 1; - } - catch(ClassCastException ee) - { - assert(false); - } + return false; } if(this == p) { - return 0; + return true; } - if(_timeout < p._timeout) - { - return -1; - } - else if(p._timeout < _timeout) + if(_timeout != p._timeout) { - return 1; + return false; } if(!_connectionId.equals(p._connectionId)) { - return _connectionId.compareTo(p._connectionId); + return false; } - return Network.compareAddress(_addr, p._addr); + return Network.compareAddress(_addr, p._addr) == 0; } - protected synchronized void - finalize() - throws Throwable - { - super.finalize(); - } - private Instance _instance; private TraceLevels _traceLevels; private Ice.Logger _logger; diff --git a/java/src/IceInternal/ThreadPool.java b/java/src/IceInternal/ThreadPool.java index ea80b046a77..4a84278ab6c 100644 --- a/java/src/IceInternal/ThreadPool.java +++ b/java/src/IceInternal/ThreadPool.java @@ -524,7 +524,6 @@ public final class ThreadPool } catch(Ice.DatagramLimitException ex) // Expected. { - handler._stream.pos(0); handler._stream.resize(0, true); continue; } @@ -550,7 +549,6 @@ public final class ThreadPool _instance.initializationData().logger.warning( "datagram connection exception:\n" + ex + "\n" + handler.toString()); } - handler._stream.pos(0); handler._stream.resize(0, true); } else @@ -618,83 +616,93 @@ public final class ThreadPool handler._serializing = false; } - // - // First we reap threads that have been - // destroyed before. - // - int sz = _threads.size(); - assert(_running <= sz); - if(_running < sz) + + if(_size < _sizeMax) // Dynamic thread pool { - java.util.Iterator<EventHandlerThread> i = _threads.iterator(); - while(i.hasNext()) + // + // First we reap threads that have been + // destroyed before. + // + int sz = _threads.size(); + assert(_running <= sz); + if(_running < sz) { - EventHandlerThread thread = i.next(); - - if(!thread.isAlive()) + java.util.Iterator<EventHandlerThread> i = _threads.iterator(); + while(i.hasNext()) { - try - { - thread.join(); - i.remove(); - } - catch(InterruptedException ex) + EventHandlerThread thread = i.next(); + + if(!thread.isAlive()) { + try + { + thread.join(); + i.remove(); + } + catch(InterruptedException ex) + { + } } } } - } - // - // Now we check if this thread can be destroyed, based - // on a load factor. - // - - // - // The load factor jumps immediately to the number of - // threads that are currently in use, but decays - // exponentially if the number of threads in use is - // smaller than the load factor. This reflects that we - // create threads immediately when they are needed, - // but want the number of threads to slowly decline to - // the configured minimum. - // - double inUse = (double)_inUse; - if(_load < inUse) - { - _load = inUse; - } - else - { - final double loadFactor = 0.05; // TODO: Configurable? - final double oneMinusLoadFactor = 1 - loadFactor; - _load = _load * oneMinusLoadFactor + _inUse * loadFactor; - } - - if(_running > _size) - { - int load = (int)(_load + 0.5); + // + // Now we check if this thread can be destroyed, based + // on a load factor. + // // - // We add one to the load factor because one - // additional thread is needed for select(). + // The load factor jumps immediately to the number of + // threads that are currently in use, but decays + // exponentially if the number of threads in use is + // smaller than the load factor. This reflects that we + // create threads immediately when they are needed, + // but want the number of threads to slowly decline to + // the configured minimum. // - if(load + 1 < _running) + double inUse = (double)_inUse; + if(_load < inUse) { - assert(_inUse > 0); - --_inUse; + _load = inUse; + } + else + { + final double loadFactor = 0.05; // TODO: Configurable? + final double oneMinusLoadFactor = 1 - loadFactor; + _load = _load * oneMinusLoadFactor + _inUse * loadFactor; + } + + if(_running > _size) + { + int load = (int)(_load + 0.5); + + // + // We add one to the load factor because one + // additional thread is needed for select(). + // + if(load + 1 < _running) + { + assert(_inUse > 0); + --_inUse; - assert(_running > 0); - --_running; + assert(_running > 0); + --_running; - return false; + return false; + } } } - + assert(_inUse > 0); --_inUse; } + // + // Do not wait to be promoted again to release these objects. + // + handler = null; + workItem = null; + while(!_promote) { try @@ -793,8 +801,8 @@ public final class ThreadPool throw e; } - byte messageType = stream.readByte(); - byte compress = stream.readByte(); + stream.readByte(); // messageType + stream.readByte(); // compress int size = stream.readInt(); if(size < Protocol.headerSize) { @@ -962,23 +970,13 @@ public final class ThreadPool { promote = ThreadPool.this.run(stream); } - catch(Ice.LocalException ex) - { - java.io.StringWriter sw = new java.io.StringWriter(); - java.io.PrintWriter pw = new java.io.PrintWriter(sw); - ex.printStackTrace(pw); - pw.flush(); - String s = "exception in `" + _prefix + "' thread " + getName() + ":\n" + sw.toString(); - _instance.initializationData().logger.error(s); - promote = true; - } catch(java.lang.Exception ex) { java.io.StringWriter sw = new java.io.StringWriter(); java.io.PrintWriter pw = new java.io.PrintWriter(sw); ex.printStackTrace(pw); pw.flush(); - String s = "unknown exception in `" + _prefix + "' thread " + getName() + ":\n" + sw.toString(); + String s = "exception in `" + _prefix + "' thread " + getName() + ":\n" + sw.toString(); _instance.initializationData().logger.error(s); promote = true; } diff --git a/java/src/IceInternal/Timer.java b/java/src/IceInternal/Timer.java index b76842d368e..87050899976 100644 --- a/java/src/IceInternal/Timer.java +++ b/java/src/IceInternal/Timer.java @@ -248,7 +248,7 @@ public final class Timer extends Thread } } - static private class Token implements Comparable + static private class Token implements Comparable<Token> { public Token(long scheduledTime, int id, long delay, TimerTask task) @@ -260,12 +260,11 @@ public final class Timer extends Thread } public int - compareTo(Object o) + compareTo(Token r) { // // Token are sorted by scheduled time and token id. // - Token r = (Token)o; if(scheduledTime < r.scheduledTime) { return -1; diff --git a/java/src/IceInternal/TraceUtil.java b/java/src/IceInternal/TraceUtil.java index 39eaa1d3e92..13e447c9065 100644 --- a/java/src/IceInternal/TraceUtil.java +++ b/java/src/IceInternal/TraceUtil.java @@ -78,8 +78,6 @@ public final class TraceUtil public static void dumpStream(BasicStream stream) { - final int inc = 8; - int pos = stream.pos(); stream.pos(0); @@ -356,19 +354,22 @@ public final class TraceUtil private static byte printHeader(java.io.Writer out, BasicStream stream) { - byte magic; - magic = stream.readByte(); // Don't bother printing the magic number - magic = stream.readByte(); - magic = stream.readByte(); - magic = stream.readByte(); + stream.readByte(); // Don't bother printing the magic number + stream.readByte(); + stream.readByte(); + stream.readByte(); - byte pMajor = stream.readByte(); - byte pMinor = stream.readByte(); -// out.write("\nprotocol version = " + (int)pMajor + "." + (int)pMinor); +// byte pMajor = stream.readByte(); +// byte pMinor = stream.readByte(); +// out.write("\nprotocol version = " + (int)pMajor + "." + (int)pMinor); + stream.readByte(); // major + stream.readByte(); // minor - byte eMajor = stream.readByte(); - byte eMinor = stream.readByte(); -// out.write("\nencoding version = " + (int)eMajor + "." + (int)eMinor); +// byte eMajor = stream.readByte(); +// byte eMinor = stream.readByte(); +// out.write("\nencoding version = " + (int)eMajor + "." + (int)eMinor); + stream.readByte(); // major + stream.readByte(); // minor byte type = stream.readByte(); diff --git a/java/src/IceInternal/UdpConnector.java b/java/src/IceInternal/UdpConnector.java index 3ad920f5e87..5ef3ada65bc 100644 --- a/java/src/IceInternal/UdpConnector.java +++ b/java/src/IceInternal/UdpConnector.java @@ -9,7 +9,7 @@ package IceInternal; -final class UdpConnector implements Connector, java.lang.Comparable +final class UdpConnector implements Connector { public Transceiver connect() @@ -49,8 +49,6 @@ final class UdpConnector implements Connector, java.lang.Comparable byte protocolMajor, byte protocolMinor, byte encodingMajor, byte encodingMinor, String connectionId) { _instance = instance; - _traceLevels = instance.traceLevels(); - _logger = instance.initializationData().logger; _addr = addr; _mcastInterface = mcastInterface; _mcastTtl = mcastTtl; @@ -67,18 +65,9 @@ final class UdpConnector implements Connector, java.lang.Comparable _hashCode = 5 * _hashCode + _connectionId.hashCode(); } - // - // Compare connectors for sorting purposes - // public boolean equals(java.lang.Object obj) { - return compareTo(obj) == 0; - } - - public int - compareTo(java.lang.Object obj) // From java.lang.Comparable - { UdpConnector p = null; try @@ -87,84 +76,53 @@ final class UdpConnector implements Connector, java.lang.Comparable } catch(ClassCastException ex) { - try - { - Connector c = (Connector)obj; - return type() < c.type() ? -1 : 1; - } - catch(ClassCastException ee) - { - assert(false); - } + return false; } if(this == p) { - return 0; + return false; } if(!_connectionId.equals(p._connectionId)) { - return _connectionId.compareTo(p._connectionId); + return false; } - if(_protocolMajor < p._protocolMajor) - { - return -1; - } - else if(p._protocolMajor < _protocolMajor) + if(_protocolMajor != p._protocolMajor) { - return 1; + return false; } - if(_protocolMinor < p._protocolMinor) + if(_protocolMinor != p._protocolMinor) { - return -1; - } - else if(p._protocolMinor < _protocolMinor) - { - return 1; + return false; } - if(_encodingMajor < p._encodingMajor) - { - return -1; - } - else if(p._encodingMajor < _encodingMajor) + if(_encodingMajor != p._encodingMajor) { - return 1; + return false; } - if(_encodingMinor < p._encodingMinor) + if(_encodingMinor != p._encodingMinor) { - return -1; - } - else if(p._encodingMinor < _encodingMinor) - { - return 1; + return false; } - if(_mcastTtl < p._mcastTtl) - { - return -1; - } - else if(p._mcastTtl < _mcastTtl) + if(_mcastTtl != p._mcastTtl) { - return 1; + return false; } - int rc = _mcastInterface.compareTo(p._mcastInterface); - if(rc != 0) + if(_mcastInterface.compareTo(p._mcastInterface) != 0) { - return rc; + return false; } - return Network.compareAddress(_addr, p._addr); + return Network.compareAddress(_addr, p._addr) == 0; } private Instance _instance; - private TraceLevels _traceLevels; - private Ice.Logger _logger; private java.net.InetSocketAddress _addr; private String _mcastInterface; private int _mcastTtl; diff --git a/java/src/IceInternal/UdpTransceiver.java b/java/src/IceInternal/UdpTransceiver.java index c23a695c79a..14349800477 100644 --- a/java/src/IceInternal/UdpTransceiver.java +++ b/java/src/IceInternal/UdpTransceiver.java @@ -257,7 +257,6 @@ final class UdpTransceiver implements Transceiver _traceLevels = instance.traceLevels(); _logger = instance.initializationData().logger; _stats = instance.initializationData().stats; - _incoming = false; _connect = true; _warn = instance.initializationData().properties.getPropertyAsInt("Ice.Warn.Datagrams") > 0; _addr = addr; @@ -295,7 +294,6 @@ final class UdpTransceiver implements Transceiver _traceLevels = instance.traceLevels(); _logger = instance.initializationData().logger; _stats = instance.initializationData().stats; - _incoming = true; _connect = connect; _warn = instance.initializationData().properties.getPropertyAsInt("Ice.Warn.Datagrams") > 0; @@ -315,6 +313,10 @@ final class UdpTransceiver implements Transceiver Network.setReuseAddress(_fd, true); _mcastAddr = _addr; _addr = Network.doBind(_fd, Network.getAddress("0.0.0.0", port, Network.EnableIPv4)); + if(port == 0) + { + _mcastAddr = new java.net.InetSocketAddress(_mcastAddr.getAddress(), _addr.getPort()); + } configureMulticast(_mcastAddr, mcastInterface, -1); } else @@ -431,8 +433,8 @@ final class UdpTransceiver implements Transceiver { try { - java.lang.reflect.Constructor c = - Class.forName("java.net.PlainDatagramSocketImpl").getDeclaredConstructor((Class[])null); + java.lang.reflect.Constructor<?> c = + Class.forName("java.net.PlainDatagramSocketImpl").getDeclaredConstructor((Class<?>[])null); c.setAccessible(true); java.net.DatagramSocketImpl socketImpl = (java.net.DatagramSocketImpl)c.newInstance((Object[])null); @@ -441,7 +443,7 @@ final class UdpTransceiver implements Transceiver // that this hack works properly when IPv6 is enabled on Windows. // java.lang.reflect.Method m = - Class.forName("java.net.PlainDatagramSocketImpl").getDeclaredMethod("create", (Class[])null); + Class.forName("java.net.PlainDatagramSocketImpl").getDeclaredMethod("create", (Class<?>[])null); m.setAccessible(true); m.invoke(socketImpl); @@ -468,7 +470,7 @@ final class UdpTransceiver implements Transceiver if(group != null) { - Class[] types = new Class[]{ java.net.SocketAddress.class, java.net.NetworkInterface.class }; + Class<?>[] types = new Class<?>[]{ java.net.SocketAddress.class, java.net.NetworkInterface.class }; m = socketImpl.getClass().getDeclaredMethod("joinGroup", types); m.setAccessible(true); Object[] args = new Object[]{ group, intf }; @@ -476,7 +478,7 @@ final class UdpTransceiver implements Transceiver } else if(intf != null) { - Class[] types = new Class[]{ Integer.TYPE, Object.class }; + Class<?>[] types = new Class<?>[]{ Integer.TYPE, Object.class }; m = socketImpl.getClass().getDeclaredMethod("setOption", types); m.setAccessible(true); Object[] args = new Object[]{ new Integer(java.net.SocketOptions.IP_MULTICAST_IF2), intf }; @@ -485,7 +487,7 @@ final class UdpTransceiver implements Transceiver if(ttl != -1) { - Class[] types = new Class[]{ Integer.TYPE }; + Class<?>[] types = new Class<?>[]{ Integer.TYPE }; m = java.net.DatagramSocketImpl.class.getDeclaredMethod("setTimeToLive", types); m.setAccessible(true); Object[] args = new Object[]{ new Integer(ttl) }; @@ -505,11 +507,6 @@ final class UdpTransceiver implements Transceiver } } - private void - closeSocket() - { - } - protected synchronized void finalize() throws Throwable @@ -522,7 +519,6 @@ final class UdpTransceiver implements Transceiver private TraceLevels _traceLevels; private Ice.Logger _logger; private Ice.Stats _stats; - private boolean _incoming; private boolean _connect; private final boolean _warn; private int _rcvSize; diff --git a/java/src/IceInternal/ValueWriter.java b/java/src/IceInternal/ValueWriter.java index 2cad6527af7..e9d5fc76d44 100644 --- a/java/src/IceInternal/ValueWriter.java +++ b/java/src/IceInternal/ValueWriter.java @@ -130,7 +130,7 @@ public final class ValueWriter { break; } - java.lang.reflect.Method valueMethod = c.getDeclaredMethod("value", new Class[0]); + java.lang.reflect.Method valueMethod = c.getDeclaredMethod("value", new Class<?>[0]); if(!valueMethod.getReturnType().equals(Integer.TYPE) || !java.lang.reflect.Modifier.isPublic(valueMethod.getModifiers()) || java.lang.reflect.Modifier.isStatic(valueMethod.getModifiers())) @@ -179,7 +179,7 @@ public final class ValueWriter } private static void - writeFields(String name, java.lang.Object obj, Class c, + writeFields(String name, java.lang.Object obj, Class<?> c, java.util.Map<java.lang.Object, java.lang.Object> objectTable, IceUtilInternal.OutputBase out) { if(!c.equals(java.lang.Object.class)) diff --git a/java/src/IceSSL/ConnectorI.java b/java/src/IceSSL/ConnectorI.java index 847cb173d0a..1cdaccb5019 100644 --- a/java/src/IceSSL/ConnectorI.java +++ b/java/src/IceSSL/ConnectorI.java @@ -9,7 +9,7 @@ package IceSSL; -final class ConnectorI implements IceInternal.Connector, java.lang.Comparable +final class ConnectorI implements IceInternal.Connector { public IceInternal.Transceiver connect() @@ -94,18 +94,9 @@ final class ConnectorI implements IceInternal.Connector, java.lang.Comparable _hashCode = 5 * _hashCode + _connectionId.hashCode(); } - // - // Compare connectors for sorting purposes - // public boolean equals(java.lang.Object obj) { - return compareTo(obj) == 0; - } - - public int - compareTo(java.lang.Object obj) // From java.lang.Comparable - { ConnectorI p = null; try @@ -114,44 +105,25 @@ final class ConnectorI implements IceInternal.Connector, java.lang.Comparable } catch(ClassCastException ex) { - try - { - IceInternal.Connector c = (IceInternal.Connector)obj; - return type() < c.type() ? -1 : 1; - } - catch(ClassCastException ee) - { - assert(false); - } + return false; } if(this == p) { - return 0; + return false; } - if(_timeout < p._timeout) - { - return -1; - } - else if(p._timeout < _timeout) + if(_timeout != p._timeout) { - return 1; + return false; } if(!_connectionId.equals(p._connectionId)) { - return _connectionId.compareTo(p._connectionId); + return false; } - return IceInternal.Network.compareAddress(_addr, p._addr); - } - - protected synchronized void - finalize() - throws Throwable - { - super.finalize(); + return IceInternal.Network.compareAddress(_addr, p._addr) == 0; } private Instance _instance; diff --git a/java/src/IceSSL/Instance.java b/java/src/IceSSL/Instance.java index afddf43071a..efa1256ad48 100644 --- a/java/src/IceSSL/Instance.java +++ b/java/src/IceSSL/Instance.java @@ -13,8 +13,6 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.List; -import Ice.Logger; - class Instance { Instance(Ice.Communicator communicator) @@ -108,7 +106,7 @@ class Instance throw e; } - Class cls = null; + Class<?> cls = null; try { cls = Class.forName(certVerifierClass); @@ -147,7 +145,7 @@ class Instance throw e; } - Class cls = null; + Class<?> cls = null; try { cls = Class.forName(passwordCallbackClass); @@ -209,22 +207,22 @@ class Instance final String[] arr = seedFiles.split(java.io.File.pathSeparator); for(int i = 0; i < arr.length; ++i) { - Ice.StringHolder seedFile = new Ice.StringHolder(arr[i]); - if(!checkPath(seedFile, false)) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: random seed file not found:\n" + arr[i]; - throw e; - } - java.io.File f = new java.io.File(seedFile.value); try { - _seeds.add(new java.io.FileInputStream(f)); + java.io.InputStream seedStream = openResource(arr[i]); + if(seedStream == null) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: random seed file not found:\n" + arr[i]; + throw e; + } + + _seeds.add(seedStream); } catch(java.io.IOException ex) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: error while reading random seed file:\n" + arr[i]; + e.reason = "IceSSL: unable to access random seed file:\n" + arr[i]; e.initCause(ex); throw e; } @@ -275,7 +273,7 @@ class Instance // // The keystore holds private keys and associated certificates. // - Ice.StringHolder keystorePath = new Ice.StringHolder(properties.getProperty(prefix + "Keystore")); + String keystorePath = properties.getProperty(prefix + "Keystore"); // // The password for the keys. @@ -302,7 +300,7 @@ class Instance // // The truststore holds the certificates of trusted CAs. // - Ice.StringHolder truststorePath = new Ice.StringHolder(properties.getProperty(prefix + "Truststore")); + String truststorePath = properties.getProperty(prefix + "Truststore"); // // The password for the truststore. @@ -322,17 +320,27 @@ class Instance // javax.net.ssl.KeyManager[] keyManagers = null; java.security.KeyStore keys = null; - if(_keystoreStream != null || keystorePath.value.length() > 0) + if(_keystoreStream != null || keystorePath.length() > 0) { - if(_keystoreStream == null && !checkPath(keystorePath, false)) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: keystore file not found:\n" + keystorePath.value; - throw e; - } - keys = java.security.KeyStore.getInstance(keystoreType); + java.io.InputStream keystoreStream = null; try { + if(_keystoreStream != null) + { + keystoreStream = _keystoreStream; + } + else + { + keystoreStream = openResource(keystorePath); + if(keystoreStream == null) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: keystore not found:\n" + keystorePath; + throw e; + } + } + + keys = java.security.KeyStore.getInstance(keystoreType); char[] passwordChars = null; if(keystorePassword.length() > 0) { @@ -348,16 +356,7 @@ class Instance passwordChars = new char[0]; } - java.io.InputStream bis; - if(_keystoreStream != null) - { - bis = _keystoreStream; - } - else - { - bis = new java.io.BufferedInputStream(new java.io.FileInputStream(keystorePath.value)); - } - keys.load(bis, passwordChars); + keys.load(keystoreStream, passwordChars); if(passwordChars != null) { @@ -368,10 +367,24 @@ class Instance catch(java.io.IOException ex) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: unable to load keystore:\n" + keystorePath.value; + e.reason = "IceSSL: unable to load keystore:\n" + keystorePath; e.initCause(ex); throw e; } + finally + { + if(keystoreStream != null) + { + try + { + keystoreStream.close(); + } + catch(java.io.IOException e) + { + // Ignore. + } + } + } String algorithm = javax.net.ssl.KeyManagerFactory.getDefaultAlgorithm(); javax.net.ssl.KeyManagerFactory kmf = javax.net.ssl.KeyManagerFactory.getInstance(algorithm); @@ -416,31 +429,41 @@ class Instance // Collect the trust managers. // javax.net.ssl.TrustManager[] trustManagers = null; - if(_truststoreStream != null || truststorePath.value.length() > 0) + if(_truststoreStream != null || truststorePath.length() > 0) { - if(_truststoreStream == null && !checkPath(truststorePath, false)) - { - Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: truststore file not found:\n" + truststorePath.value; - throw e; - } - // // If the trust store and the key store are the same input // stream or file, don't create another key store. // java.security.KeyStore ts; if((_truststoreStream != null && _truststoreStream == _keystoreStream) || - (truststorePath.value.length() > 0 && truststorePath.value.equals(keystorePath.value))) + (truststorePath.length() > 0 && truststorePath.equals(keystorePath))) { assert keys != null; ts = keys; } else { - ts = java.security.KeyStore.getInstance(truststoreType); + java.io.InputStream truststoreStream = null; try { + if(_truststoreStream != null) + { + truststoreStream = _truststoreStream; + } + else + { + truststoreStream = openResource(truststorePath); + if(truststoreStream == null) + { + Ice.PluginInitializationException e = new Ice.PluginInitializationException(); + e.reason = "IceSSL: truststore not found:\n" + truststorePath; + throw e; + } + } + + ts = java.security.KeyStore.getInstance(truststoreType); + char[] passwordChars = null; if(truststorePassword.length() > 0) { @@ -456,17 +479,7 @@ class Instance passwordChars = new char[0]; } - java.io.InputStream bis; - if(_truststoreStream != null) - { - bis = _truststoreStream; - } - else - { - bis = new java.io.BufferedInputStream( - new java.io.FileInputStream(truststorePath.value)); - } - ts.load(bis, passwordChars); + ts.load(truststoreStream, passwordChars); if(passwordChars != null) { @@ -477,10 +490,24 @@ class Instance catch(java.io.IOException ex) { Ice.PluginInitializationException e = new Ice.PluginInitializationException(); - e.reason = "IceSSL: unable to load truststore:\n" + truststorePath.value; + e.reason = "IceSSL: unable to load truststore:\n" + truststorePath; e.initCause(ex); throw e; } + finally + { + if(truststoreStream != null) + { + try + { + truststoreStream.close(); + } + catch(java.io.IOException e) + { + // Ignore. + } + } + } } String algorithm = javax.net.ssl.TrustManagerFactory.getDefaultAlgorithm(); @@ -681,11 +708,12 @@ class Instance if(_securityTraceLevel >= 1) { - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(128); s.append("enabling SSL ciphersuites:"); for(int i = 0; i < cipherSuites.length; ++i) { - s.append("\n " + cipherSuites[i]); + s.append("\n "); + s.append(cipherSuites[i]); } _logger.trace(_securityTraceCategory, s.toString()); } @@ -898,14 +926,15 @@ class Instance // if(!certNameOK && (_checkCertName || (_securityTraceLevel >= 1 && _verifier == null))) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(128); sb.append("IceSSL: "); if(!_checkCertName) { sb.append("ignoring "); } - sb.append("certificate validation failure:\npeer certificate does not contain `" + - address + "' in its subjectAltName extension"); + sb.append("certificate validation failure:\npeer certificate does not contain `"); + sb.append(address); + sb.append("' in its subjectAltName extension"); if(!dnsNames.isEmpty()) { sb.append("\nDNS names found in certificate: "); @@ -1057,33 +1086,60 @@ class Instance cipherList.toArray(_ciphers); } - private boolean - checkPath(Ice.StringHolder path, boolean dir) + private java.io.InputStream + openResource(String path) + throws java.io.IOException { // - // Check if file exists. If not, try prepending the default - // directory and check again. If the file is found, the - // string argument is modified and true is returned. Otherwise - // false is returned. + // We resolve the path as follows: + // + // 1. Try to open it as a class path resource + // 2. Try to open it in the file system + // 3. Prepend the value of IceSSL.DefaultDir (if defined) and try to open + // it in the file system + // + + // + // Calling getResourceAsStream on the class loader means all paths are absolute, + // whereas calling it on the class requires you to prepend "/" to the path in + // order to make it absolute, otherwise the path is interpreted relative to the + // class. + // + // getResourceAsStream returns null if the resource can't be found. // - java.io.File f = new java.io.File(path.value); - if(f.exists()) + java.io.InputStream stream = getClass().getClassLoader().getResourceAsStream(path); + if(stream != null) { - return dir ? f.isDirectory() : f.isFile(); + stream = new java.io.BufferedInputStream(stream); } - - if(_defaultDir.length() > 0) + else { - String s = _defaultDir + java.io.File.separator + path.value; - f = new java.io.File(s); - if(f.exists() && ((!dir && f.isFile()) || (dir && f.isDirectory()))) + try + { + java.io.File f = new java.io.File(path); + if(f.exists()) + { + stream = new java.io.BufferedInputStream(new java.io.FileInputStream(f)); + } + else + { + if(_defaultDir.length() > 0) + { + f = new java.io.File(_defaultDir + java.io.File.separator + path); + if(f.exists()) + { + stream = new java.io.BufferedInputStream(new java.io.FileInputStream(f)); + } + } + } + } + catch(java.lang.SecurityException ex) { - path.value = s; - return true; + // Ignore - a security manager may forbid access to the local file system. } } - return false; + return stream; } private static class CipherExpression diff --git a/java/src/IceSSL/TransceiverI.java b/java/src/IceSSL/TransceiverI.java index 7d683839f59..b3e166826c8 100644 --- a/java/src/IceSSL/TransceiverI.java +++ b/java/src/IceSSL/TransceiverI.java @@ -515,11 +515,6 @@ final class TransceiverI implements IceInternal.Transceiver } } - private void - shutdown() - { - } - private IceInternal.SocketStatus writeNonBlocking(ByteBuffer buf) { diff --git a/java/src/IceUtilInternal/Base64.java b/java/src/IceUtilInternal/Base64.java index 8a06de57f76..ae8211bafee 100644 --- a/java/src/IceUtilInternal/Base64.java +++ b/java/src/IceUtilInternal/Base64.java @@ -20,12 +20,11 @@ encode(byte[] plainSeq) return ""; } - StringBuffer retval = new StringBuffer(); int base64Bytes = (((plainSeq.length * 4) / 3) + 1); int newlineBytes = (((base64Bytes * 2) / 76) + 1); int totalBytes = base64Bytes + newlineBytes; - retval.ensureCapacity(totalBytes); + StringBuilder retval = new StringBuilder(totalBytes); int by1; int by2; @@ -78,8 +77,7 @@ encode(byte[] plainSeq) } } - StringBuffer outString = new StringBuffer(); - outString.ensureCapacity(totalBytes); + StringBuilder outString = new StringBuilder(totalBytes); int iter = 0; while((retval.length() - iter) > 76) @@ -97,9 +95,7 @@ encode(byte[] plainSeq) public static byte[] decode(String str) { - StringBuffer newStr = new StringBuffer(); - - newStr.ensureCapacity(str.length()); + StringBuilder newStr = new StringBuilder(str.length()); for(int j = 0; j < str.length(); j++) { diff --git a/java/src/IceUtilInternal/Options.java b/java/src/IceUtilInternal/Options.java index 7751443e594..fb1d4f9e7d9 100644 --- a/java/src/IceUtilInternal/Options.java +++ b/java/src/IceUtilInternal/Options.java @@ -37,7 +37,7 @@ public final class Options int state = NormalState; - StringBuffer arg = new StringBuffer(); + StringBuilder arg = new StringBuilder(128); java.util.List<String> vec = new java.util.ArrayList<String>(); for(int i = 0; i < line.length(); ++i) @@ -113,7 +113,7 @@ public final class Options if(IFS.indexOf(line.charAt(i)) != -1) { vec.add(arg.toString()); - arg = new StringBuffer(); + arg = new StringBuilder(128); // // Move to start of next argument. diff --git a/java/src/IceUtilInternal/StringUtil.java b/java/src/IceUtilInternal/StringUtil.java index 236e3c64b0a..9ff9d80cfd2 100644 --- a/java/src/IceUtilInternal/StringUtil.java +++ b/java/src/IceUtilInternal/StringUtil.java @@ -82,7 +82,7 @@ public final class StringUtil // characters, b is preceded by a backslash in sb. // private static void - encodeChar(byte b, StringBuffer sb, String special) + encodeChar(byte b, StringBuilder sb, String special) { switch(b) { @@ -189,7 +189,7 @@ public final class StringUtil return null; } - StringBuffer result = new StringBuffer(bytes.length); + StringBuilder result = new StringBuilder(bytes.length); for(int i = 0; i < bytes.length; i++) { encodeChar(bytes[i], result, special); @@ -313,7 +313,7 @@ public final class StringUtil // Return true if successful, false otherwise. // private static void - decodeString(String s, int start, int end, StringBuffer sb) + decodeString(String s, int start, int end, StringBuilder sb) { Ice.IntHolder nextStart = new Ice.IntHolder(); while(start < end) @@ -344,7 +344,7 @@ public final class StringUtil try { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(end - start); decodeString(s, start, end, sb); String decodedString = sb.toString(); diff --git a/java/src/ant/Slice2FreezeJTask.java b/java/src/ant/Slice2FreezeJTask.java index 139230ff3ae..49f2f0f97d3 100644 --- a/java/src/ant/Slice2FreezeJTask.java +++ b/java/src/ant/Slice2FreezeJTask.java @@ -182,20 +182,24 @@ public class Slice2FreezeJTask extends SliceTask // Add the --dict options. // p = _dicts.iterator(); - StringBuffer dictString = new StringBuffer(); + StringBuilder dictString = new StringBuilder(128); while(p.hasNext()) { Dict d = (Dict)p.next(); dictString.append(" --dict "); - dictString.append(d.getName() + "," + d.getKey() + "," + d.getValue()); + dictString.append(d.getName()); + dictString.append(","); + dictString.append(d.getKey()); + dictString.append(","); + dictString.append(d.getValue()); } // // Add the --dict-index options. // p = _dictIndices.iterator(); - StringBuffer dictIndexString = new StringBuffer(); + StringBuilder dictIndexString = new StringBuilder(128); while(p.hasNext()) { Dictindex d = (Dictindex)p.next(); @@ -204,11 +208,12 @@ public class Slice2FreezeJTask extends SliceTask dictIndexString.append(d.getName()); if(d.getMember() != null) { - dictIndexString.append("," + d.getMember()); + dictIndexString.append(","); + dictIndexString.append(d.getMember()); } if(d.getCasesensitive() == false) { - dictIndexString.append("," + "case-insensitive"); + dictIndexString.append(",case-insensitive"); } } @@ -216,16 +221,20 @@ public class Slice2FreezeJTask extends SliceTask // Add the --index options. // p = _indices.iterator(); - StringBuffer indexString = new StringBuffer(); + StringBuilder indexString = new StringBuilder(); while(p.hasNext()) { Index i = (Index)p.next(); indexString.append(" --index "); - indexString.append(i.getName() + "," + i.getType() + "," + i.getMember()); + indexString.append(i.getName()); + indexString.append(","); + indexString.append(i.getType()); + indexString.append(","); + indexString.append(i.getMember()); if(i.getCasesensitive() == false) { - indexString.append("," + "case-insensitive"); + indexString.append(",case-insensitive"); } } @@ -238,7 +247,7 @@ public class Slice2FreezeJTask extends SliceTask // // Run the translator // - StringBuffer cmd = new StringBuffer(); + StringBuilder cmd = new StringBuilder(256); // // Add --ice @@ -308,17 +317,17 @@ public class Slice2FreezeJTask extends SliceTask // // Add the --dict options. // - cmd.append(dictString); + cmd.append(dictString.toString()); // // Add the --dict-index options. // - cmd.append(dictIndexString); + cmd.append(dictIndexString.toString()); // // Add the --index options. // - cmd.append(indexString); + cmd.append(indexString.toString()); // // Add the --meta options. @@ -379,7 +388,8 @@ public class Slice2FreezeJTask extends SliceTask // if(!sliceFiles.isEmpty()) { - cmd = new StringBuffer("--depend"); + cmd = new StringBuilder(256); + cmd.append("--depend"); // // Add include directives @@ -392,7 +402,9 @@ public class Slice2FreezeJTask extends SliceTask cmd.append(" -I"); if(dirs[i].indexOf(' ') != -1) { - cmd.append('"' + dirs[i] + '"'); + cmd.append('"'); + cmd.append(dirs[i]); + cmd.append('"'); } else { @@ -404,17 +416,17 @@ public class Slice2FreezeJTask extends SliceTask // // Add the --dict options. // - cmd.append(dictString); + cmd.append(dictString.toString()); // // Add the --dict-index options. // - cmd.append(dictIndexString); + cmd.append(dictIndexString.toString()); // // Add the --index options. // - cmd.append(indexString); + cmd.append(indexString.toString()); // // Add the slice files. @@ -427,7 +439,9 @@ public class Slice2FreezeJTask extends SliceTask String s = f.toString(); if(s.indexOf(' ') != -1) { - cmd.append('"' + s + '"'); + cmd.append('"'); + cmd.append(s); + cmd.append('"'); } else { @@ -435,7 +449,6 @@ public class Slice2FreezeJTask extends SliceTask } } - // // It's not possible anymore to re-use the same output property since Ant 1.5.x. so we use a // unique property name here. Perhaps we should output the dependencies to a file instead. diff --git a/java/src/ant/Slice2JavaTask.java b/java/src/ant/Slice2JavaTask.java index a55b2ddf6aa..09f3b07e797 100644 --- a/java/src/ant/Slice2JavaTask.java +++ b/java/src/ant/Slice2JavaTask.java @@ -175,7 +175,7 @@ public class Slice2JavaTask extends SliceTask translator = _translator.toString(); } - StringBuffer cmd = new StringBuffer(); + StringBuilder cmd = new StringBuilder(256); // // Add --output-dir @@ -197,7 +197,9 @@ public class Slice2JavaTask extends SliceTask cmd.append(" -I"); if(dirs[i].indexOf(' ') != -1) { - cmd.append('"' + dirs[i] + '"'); + cmd.append('"'); + cmd.append(dirs[i]); + cmd.append('"'); } else { @@ -239,7 +241,8 @@ public class Slice2JavaTask extends SliceTask // if(_checksum != null && _checksum.length() > 0) { - cmd.append(" --checksum " + _checksum); + cmd.append(" --checksum "); + cmd.append(_checksum); } // @@ -259,7 +262,8 @@ public class Slice2JavaTask extends SliceTask while(i.hasNext()) { SliceMeta m = (SliceMeta)i.next(); - cmd.append(" --meta " + m.getValue()); + cmd.append(" --meta "); + cmd.append(m.getValue()); } } @@ -289,7 +293,9 @@ public class Slice2JavaTask extends SliceTask String s = f.toString(); if(s.indexOf(' ') != -1) { - cmd.append('"' + s + '"'); + cmd.append('"'); + cmd.append(s); + cmd.append('"'); } else { @@ -312,7 +318,8 @@ public class Slice2JavaTask extends SliceTask // // Update the dependencies. // - cmd = new StringBuffer("--depend"); + cmd = new StringBuilder(256); + cmd.append("--depend"); // // Add include directives @@ -325,7 +332,9 @@ public class Slice2JavaTask extends SliceTask cmd.append(" -I"); if(dirs[i].indexOf(' ') != -1) { - cmd.append('"' + dirs[i] + '"'); + cmd.append('"'); + cmd.append(dirs[i]); + cmd.append('"'); } else { @@ -344,7 +353,9 @@ public class Slice2JavaTask extends SliceTask String s = f.toString(); if(s.indexOf(' ') != -1) { - cmd.append('"' + s + '"'); + cmd.append('"'); + cmd.append(s); + cmd.append('"'); } else { diff --git a/java/src/ant/SliceTask.java b/java/src/ant/SliceTask.java index 9edc75b9f84..a778eb6c13a 100644 --- a/java/src/ant/SliceTask.java +++ b/java/src/ant/SliceTask.java @@ -213,7 +213,7 @@ public class SliceTask extends org.apache.tools.ant.Task try { BufferedReader in = new BufferedReader(new StringReader(allDependencies)); - StringBuffer depline = new StringBuffer(); + StringBuilder depline = new StringBuilder(1024); String line; while((line = in.readLine()) != null) @@ -261,7 +261,7 @@ public class SliceTask extends org.apache.tools.ant.Task // (e.g., "C\:/Program\ Files/..."). // java.util.ArrayList l = new java.util.ArrayList(); - StringBuffer file = new StringBuffer(); + StringBuilder file = new StringBuilder(128); pos = 0; while(pos < chars.length) { @@ -270,7 +270,7 @@ public class SliceTask extends org.apache.tools.ant.Task if(file.length() > 0) { l.add(file.toString()); - file = new StringBuffer(); + file = new StringBuilder(128); } } else if(chars[pos] != '\\') // Skip backslash of an escaped character. @@ -301,7 +301,7 @@ public class SliceTask extends org.apache.tools.ant.Task } dependencies.add(depend); - depline = new StringBuffer(); + depline = new StringBuilder(1024); } } } |