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 | |
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')
197 files changed, 6056 insertions, 1378 deletions
diff --git a/java/INSTALL b/java/INSTALL index 3a78294a206..0758d4f959e 100644 --- a/java/INSTALL +++ b/java/INSTALL @@ -102,10 +102,10 @@ Java support. For Linux, this is done by specifying the --enable-java option when running the configure script. On Windows, you must select the project "db_java -- Win32 Release". -Make sure to add db.jar to your CLASSPATH, and verify that the -Berkeley DB shared libraries are in your java.library.path. On Linux, -this can be achieved by adding <Berkeley DB home>/lib to your -LD_LIBRARY_PATH, for example: +In order to run an application that uses Freeze, you must add db.jar +to your CLASSPATH and verify that the Berkeley DB shared libraries are +in your java.library.path. On Linux, this can be achieved by adding +<Berkeley DB home>/lib to your LD_LIBRARY_PATH, for example: $ export LD_LIBRARY_PATH=/opt/db46/lib:$LD_LIBRARY_PATH @@ -153,7 +153,7 @@ ProGuard is available here: http://proguard.sourceforge.net -Ice for Java has been tested with ProGuard 4.1. +Ice for Java has been tested with ProGuard 4.1 and 4.3. ====================================================================== @@ -169,11 +169,20 @@ is available at the link below: http://ant.apache.org/ -To successfully compile Ice for Java, the Java run time for Berkeley -DB (db.jar) must be in your CLASSPATH. The build system also requires -the Slice translators from Ice for C++. If you have not built Ice for -C++ in this source distribution, you must set the ICE_HOME environment -variable with the path name of your Ice installation. For example: +This source distribution cannot be compiled successfully without the +Berkeley DB run time for Java (db.jar). On Unix platforms, the build +system searches for this file in two locations: + + * /usr/share/java/db-4.6.21.jar + * /opt/Ice-@ver@/lib/db.jar + +If neither of these files is present on your system, or if you are not +using a Unix platform, you must add db.jar to your CLASSPATH. + +The build system also requires the Slice translators from Ice for C++. +If you have not built Ice for C++ in this source distribution, you +must set the ICE_HOME environment variable with the path name of your +Ice installation. For example: # On Unix. $ export ICE_HOME=/opt/Ice-@ver@ (For local build) diff --git a/java/allDemos.py b/java/allDemos.py index 955bd9cae40..06030ff7a90 100755 --- a/java/allDemos.py +++ b/java/allDemos.py @@ -33,6 +33,7 @@ demos = [ "Ice/minimal", "Ice/multicast", "Ice/nested", + "Ice/serialize", "Ice/session", "Ice/throughput", "Ice/value", @@ -52,5 +53,9 @@ demos = [ "book/lifecycle", ] +protoDemos = [ + "Ice/protobuf" +] + if __name__ == "__main__": - Util.run(demos) + Util.run(demos, protoDemos) diff --git a/java/allTests.py b/java/allTests.py index 8b89de12648..68c2cae18d1 100755 --- a/java/allTests.py +++ b/java/allTests.py @@ -28,6 +28,7 @@ tests = [ ("IceUtil/inputUtil", ["once"]), ("Ice/proxy", ["core"]), ("Ice/operations", ["core"]), + ("Ice/seqMapping", ["core"]), ("Ice/exceptions", ["core"]), ("Ice/inheritance", ["core"]), ("Ice/facets", ["core"]), @@ -49,6 +50,7 @@ tests = [ ("Ice/servantLocator", ["core"]), ("Ice/interceptor", ["core"]), ("Ice/udp", ["core"]), + ("Ice/serialize", ["core"]), ("IceBox/configuration", ["core", "noipv6"]), ("Freeze/dbmap", ["once"]), ("Freeze/complex", ["once"]), diff --git a/java/build.xml b/java/build.xml index 0c011cbf2dd..4ba03729fa1 100644 --- a/java/build.xml +++ b/java/build.xml @@ -177,7 +177,8 @@ source="1.5" debug="${debug}" excludes="IceGridGUI/**" includes="**" - deprecation="on"> + deprecation="on" + classpathref="db.classpath"> <compilerarg value="${javac.lint}"/> </javac> </target> @@ -238,6 +239,9 @@ <jar jarfile="${lib.dir}/IceGridGUI.jar" manifest="${lib.dir}/icegridgui.mf" basedir="${lib.dir}"> <include name="IceGridGUI/**"/> </jar> + <jar jarfile="${lib.dir}/IceGridGUI.jar" basedir="resources" update="true"> + <include name="icons/**"/> + </jar> <delete file="${lib.dir}/icegridgui.mf" /> </target> @@ -249,7 +253,7 @@ <!-- Library jar files for Sun JDK --> <available file="${java.home}/lib/rt.jar"/> </condition> - <condition property="library.jarfiles" value="vm.jar,core.jar,graphics.jar,security.jar"> + <condition property="library.jarfiles" value="vm.jar,core.jar,graphics.jar,security.jar,server.jar"> <!-- Library jar files for IBM J9 (from Linux SuSE) --> <available file="${java.home}/lib/vm.jar"/> </condition> diff --git a/java/config/common.xml b/java/config/common.xml index f40a9c9cead..5e0169431f6 100644 --- a/java/config/common.xml +++ b/java/config/common.xml @@ -195,6 +195,27 @@ <isset property="ice.src.dist"/> </condition> + <!-- Set db.jar.file to the path name of the Berkeley DB JAR file, but only if it's + not already present in the class path. --> + <condition property="db.jar.file" value="/usr/share/java/db-${db.version}.jar"> + <and> + <not><available classname="com.sleepycat.db.Database"/></not> + <available file="/usr/share/java/db-${db.version}.jar"/> + </and> + </condition> + <condition property="db.jar.file" value="/opt/Ice-${ice.version}/lib/db.jar"> + <and> + <not><os family="windows"/></not> + <not><isset property="db.jar.file"/></not> + <not><available classname="com.sleepycat.db.Database"/></not> + <available file="/opt/Ice-${ice.version}/lib/db.jar"/> + </and> + </condition> + + <path id="db.classpath"> + <pathelement path="${db.jar.file}"/> + </path> + <target name="config-init-warn" if="ice.warn.duplicate.translator"> <echo message="Found ${slice.translator} in both ${ice.cpp.dir}/bin and ${ice.dir}/cpp/bin, ${ice.cpp.dir}/bin/${slice.translator} will be used!" level="warning"/> </target> @@ -256,6 +277,9 @@ <fileset file="${dist.jar.file}"/> </path> + <condition property="certs.dir" value="${ice.top.dir}/certs" else="${ice.top.dir}/../certs"> + <available file="${ice.top.dir}/certs/client.jks"/> + </condition> </target> <!-- Install the Slice ant tasks. --> diff --git a/java/config/icegridgui.pro b/java/config/icegridgui.pro index 65b8b30ab91..0000afe394e 100644 --- a/java/config/icegridgui.pro +++ b/java/config/icegridgui.pro @@ -20,6 +20,10 @@ -keepattributes *Annotation* +# Parse non-public libraries to prevent undefined symbol errors on some platforms. + +-dontskipnonpubliclibraryclasses + # Preserve all native method names and the names of their classes. -keepclasseswithmembernames class * { diff --git a/java/demo/Database/README b/java/demo/Database/README new file mode 100644 index 00000000000..676202f8cf8 --- /dev/null +++ b/java/demo/Database/README @@ -0,0 +1,6 @@ +Demos in this directory: + +- library + + This demo shows how to implement an Ice server that uses mysql through + a JDBC API. diff --git a/java/demo/Database/library/LibraryI.java b/java/demo/Database/library/LibraryI.java index 81bae5c6de7..9ec48815b36 100644 --- a/java/demo/Database/library/LibraryI.java +++ b/java/demo/Database/library/LibraryI.java @@ -90,7 +90,8 @@ class LibraryI extends _LibraryDisp } // Build a query that finds all books by these authors. - StringBuffer sb = new StringBuffer("("); + StringBuilder sb = new StringBuilder(128); + sb.append("("); boolean front = true; do { diff --git a/java/demo/Database/library/Scanner.java b/java/demo/Database/library/Scanner.java index 879396725b4..ecf325de077 100644 --- a/java/demo/Database/library/Scanner.java +++ b/java/demo/Database/library/Scanner.java @@ -151,7 +151,7 @@ class Scanner return null; } - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(128); if(c == ';' || c == '\n') { diff --git a/java/demo/Database/library/Server.java b/java/demo/Database/library/Server.java index b2e66386ffa..4763f589010 100644 --- a/java/demo/Database/library/Server.java +++ b/java/demo/Database/library/Server.java @@ -9,7 +9,7 @@ import Demo.*; -class LibraryServer extends Ice.Application +class Server extends Ice.Application { static class LocatorI implements Ice.ServantLocator { @@ -129,14 +129,11 @@ class LibraryServer extends Ice.Application return 0; } -} -public class Server -{ static public void main(String[] args) { - LibraryServer app = new LibraryServer(); + Server app = new Server(); app.main("demo.Database.library.Server", args, "config.server"); } } diff --git a/java/demo/Freeze/bench/build.xml b/java/demo/Freeze/bench/build.xml index 420ed9850c5..309f7c9ed9c 100644 --- a/java/demo/Freeze/bench/build.xml +++ b/java/demo/Freeze/bench/build.xml @@ -57,7 +57,10 @@ <mkdir dir="${class.dir}"/> <javac srcdir="${generated.dir}" destdir="${class.dir}" debug="${debug}"> - <classpath refid="ice.classpath"/> + <classpath> + <path refid="ice.classpath"/> + <path refid="db.classpath"/> + </classpath> <compilerarg value="${javac.lint}"/> </javac> <javac srcdir="." destdir="${class.dir}" diff --git a/java/demo/Freeze/casino/Client.java b/java/demo/Freeze/casino/Client.java index d5e5965c31f..0f0fd53bf95 100644 --- a/java/demo/Freeze/casino/Client.java +++ b/java/demo/Freeze/casino/Client.java @@ -9,6 +9,14 @@ public class Client extends Ice.Application { + // + // Number of bets placed by each player + // You can (should) increase these values by a factor of 5 or more + // on a fast system + // + static final int betCount1 = 100; + static final int betCount2 = 20; + private void printBalances(Casino.PlayerPrx[] players) { @@ -79,10 +87,10 @@ public class Client extends Ice.Application System.out.println("All chips accounted for? " + (bank.checkAllChips() ? "yes" : "no")); - System.out.print("Create 500 10-chips bets... "); + System.out.print("Create " + betCount1 + " 10-chips bets... "); System.out.flush(); - for(int b = 0; b < 500; ++b) + for(int b = 0; b < betCount1; ++b) { Casino.BetPrx bet = bank.createBet(10, 200 + random.nextInt(4000)); for(int i = 0; i < players.length; ++i) @@ -147,10 +155,10 @@ public class Client extends Ice.Application System.out.println("Live bets: " + bank.getLiveBetCount()); - System.out.print("Create 100 10-chips bets... "); + System.out.print("Create " + betCount2 + " 10-chips bets... "); System.out.flush(); - for(int b = 0; b < 100; ++b) + for(int b = 0; b < betCount2; ++b) { Casino.BetPrx bet = bank.createBet(10, 200 + random.nextInt(4000)); for(int i = 0; i < players.length; ++i) diff --git a/java/demo/Freeze/casino/build.xml b/java/demo/Freeze/casino/build.xml index cec4df18549..c5e1ed1536f 100644 --- a/java/demo/Freeze/casino/build.xml +++ b/java/demo/Freeze/casino/build.xml @@ -39,7 +39,10 @@ </javac> <javac srcdir="." destdir="${class.dir}" excludes="generated/**" debug="${debug}"> - <classpath refid="ice.classpath"/> + <classpath> + <path refid="ice.classpath"/> + <path refid="db.classpath"/> + </classpath> <compilerarg value="${javac.lint}"/> </javac> </target> diff --git a/java/demo/Freeze/library/Collocated.java b/java/demo/Freeze/library/Collocated.java index 7e275e1d229..8629e894d7a 100644 --- a/java/demo/Freeze/library/Collocated.java +++ b/java/demo/Freeze/library/Collocated.java @@ -64,7 +64,7 @@ class Collocated extends Ice.Application // Create and install a factory and initializer for books. // Ice.ObjectFactory bookFactory = new BookFactory(library); - communicator().addObjectFactory(bookFactory, "::Demo::Book"); + communicator().addObjectFactory(bookFactory, Demo.Book.ice_staticId()); // // Everything ok, let's go. diff --git a/java/demo/Freeze/library/Scanner.java b/java/demo/Freeze/library/Scanner.java index 975eaece2dd..ff61f1289da 100644 --- a/java/demo/Freeze/library/Scanner.java +++ b/java/demo/Freeze/library/Scanner.java @@ -155,7 +155,7 @@ class Scanner return null; } - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(128); if(c == ';' || c == '\n') { diff --git a/java/demo/Freeze/library/Server.java b/java/demo/Freeze/library/Server.java index 2edfb823034..7af7e3a8a61 100644 --- a/java/demo/Freeze/library/Server.java +++ b/java/demo/Freeze/library/Server.java @@ -47,7 +47,7 @@ class Server extends Ice.Application // Create and install a factory for books. // Ice.ObjectFactory bookFactory = new BookFactory(library); - communicator().addObjectFactory(bookFactory, "::Demo::Book"); + communicator().addObjectFactory(bookFactory, Demo.Book.ice_staticId()); // // Everything ok, let's go. diff --git a/java/demo/Freeze/library/build.xml b/java/demo/Freeze/library/build.xml index ae9ae29f883..41ec51eeafa 100644 --- a/java/demo/Freeze/library/build.xml +++ b/java/demo/Freeze/library/build.xml @@ -49,7 +49,10 @@ </javac> <javac srcdir="." destdir="${class.dir}" excludes="generated/**" debug="${debug}"> - <classpath refid="ice.classpath"/> + <classpath> + <path refid="ice.classpath"/> + <path refid="db.classpath"/> + </classpath> <compilerarg value="${javac.lint}"/> </javac> </target> diff --git a/java/demo/Freeze/phonebook/Collocated.java b/java/demo/Freeze/phonebook/Collocated.java index 47abe391520..9d1b316ddfd 100644 --- a/java/demo/Freeze/phonebook/Collocated.java +++ b/java/demo/Freeze/phonebook/Collocated.java @@ -41,7 +41,7 @@ class Collocated extends Ice.Application // Create and install a factory for contacts. // ContactFactory contactFactory = new ContactFactory(); - communicator().addObjectFactory(contactFactory, "::Demo::Contact"); + communicator().addObjectFactory(contactFactory, Demo.Contact.ice_staticId()); // // Create an object adapter diff --git a/java/demo/Freeze/phonebook/Scanner.java b/java/demo/Freeze/phonebook/Scanner.java index db438f8fe5f..790a672f7b0 100644 --- a/java/demo/Freeze/phonebook/Scanner.java +++ b/java/demo/Freeze/phonebook/Scanner.java @@ -155,7 +155,7 @@ class Scanner return null; } - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(128); if(c == ';' || c == '\n') { diff --git a/java/demo/Freeze/phonebook/Server.java b/java/demo/Freeze/phonebook/Server.java index 3dbf0d0d0d1..692b465da7f 100644 --- a/java/demo/Freeze/phonebook/Server.java +++ b/java/demo/Freeze/phonebook/Server.java @@ -24,7 +24,7 @@ class Server extends Ice.Application // Create and install a factory for contacts. // ContactFactory contactFactory = new ContactFactory(); - communicator().addObjectFactory(contactFactory, "::Demo::Contact"); + communicator().addObjectFactory(contactFactory, Demo.Contact.ice_staticId()); // // Create an object adapter diff --git a/java/demo/Freeze/phonebook/build.xml b/java/demo/Freeze/phonebook/build.xml index 233435b6cde..c5616897bdd 100644 --- a/java/demo/Freeze/phonebook/build.xml +++ b/java/demo/Freeze/phonebook/build.xml @@ -41,12 +41,19 @@ <mkdir dir="${class.dir}"/> <javac srcdir="${generated.dir}" destdir="${class.dir}" debug="${debug}"> - <classpath refid="ice.classpath"/> + <classpath> + <path refid="ice.classpath"/> + <path refid="db.classpath"/> + </classpath> <compilerarg value="${javac.lint}"/> </javac> <javac srcdir="." destdir="${class.dir}" excludes="generated/**" debug="${debug}"> <classpath refid="ice.classpath"/> + <classpath> + <path refid="ice.classpath"/> + <path refid="db.classpath"/> + </classpath> <compilerarg value="${javac.lint}"/> </javac> </target> diff --git a/java/demo/Freeze/transform/build.xml b/java/demo/Freeze/transform/build.xml index cf84d604e26..0250da01c04 100644 --- a/java/demo/Freeze/transform/build.xml +++ b/java/demo/Freeze/transform/build.xml @@ -43,7 +43,10 @@ <mkdir dir="${class.dir}"/> <javac srcdir="${generated.dir}" destdir="${class.dir}" debug="${debug}"> - <classpath refid="ice.classpath"/> + <classpath> + <path refid="ice.classpath"/> + <path refid="db.classpath"/> + </classpath> <compilerarg value="${javac.lint}"/> </javac> <javac srcdir="." destdir="${class.dir}" diff --git a/java/demo/Glacier2/callback/CallbackI.java b/java/demo/Glacier2/callback/CallbackI.java index 2013f349ded..1dd07491790 100644 --- a/java/demo/Glacier2/callback/CallbackI.java +++ b/java/demo/Glacier2/callback/CallbackI.java @@ -17,7 +17,7 @@ public final class CallbackI extends _CallbackDisp System.out.println("initiating callback to: " + current.adapter.getCommunicator().proxyToString(proxy)); try { - proxy.callback(current.ctx); + proxy.callback(); } catch(Ice.LocalException ex) { diff --git a/java/demo/Ice/README b/java/demo/Ice/README index 6a9eceee376..5714a88aa20 100644 --- a/java/demo/Ice/README +++ b/java/demo/Ice/README @@ -52,6 +52,11 @@ Demos in this directory: A demo to illustrate how nested callbacks work, and how the size of the thread pool affects the maximum nesting depth. +- serialize + + This demo illustrates how to transfer serializable Java classes + with Ice. + - session This demo shows how to use sessions to clean up client-specific diff --git a/java/demo/Ice/applet/HelloApplet.java b/java/demo/Ice/applet/HelloApplet.java index 504f775a148..dd351a7918d 100644 --- a/java/demo/Ice/applet/HelloApplet.java +++ b/java/demo/Ice/applet/HelloApplet.java @@ -46,24 +46,10 @@ public class HelloApplet extends JApplet initData.properties.setProperty("Ice.Trace.Network", "3"); initData.properties.setProperty("IceSSL.Trace.Security", "3"); initData.properties.setProperty("IceSSL.Password", "password"); - initData.properties.setProperty("Ice.InitPlugins", "0"); + initData.properties.setProperty("IceSSL.Keystore", "client.jks"); + initData.properties.setProperty("IceSSL.Truststore", "client.jks"); initData.properties.setProperty("Ice.Plugin.IceSSL", "IceSSL.PluginFactory"); _communicator = Ice.Util.initialize(initData); - - // - // We delayed the initialization of the IceSSL plug-in by setting Ice.InitPlugins=0. - // Now we obtain a reference to the plugin so that we can supply a keystore and - // truststore using a resource file. - // - IceSSL.Plugin plugin = (IceSSL.Plugin)_communicator.getPluginManager().getPlugin("IceSSL"); - java.io.InputStream certs = getClass().getClassLoader().getResourceAsStream("client.jks"); - plugin.setKeystoreStream(certs); - plugin.setTruststoreStream(certs); - - // - // Finally, we're ready to complete the initialization. - // - _communicator.getPluginManager().initializePlugins(); } catch(Throwable ex) { diff --git a/java/demo/Ice/applet/README b/java/demo/Ice/applet/README index dbf2e18ff20..9bda261e7c3 100644 --- a/java/demo/Ice/applet/README +++ b/java/demo/Ice/applet/README @@ -1,8 +1,15 @@ +Introduction +------------ + This demo presents an unsigned applet that shows how to make asynchronous Ice invocations in a graphical application. It also demonstrates how to configure IceSSL using a resource file as the keystore. + +Preparing the applet +-------------------- + The demo includes a start page (hello.html) that you will need to publish on a web server. This page assumes that the demo applet is stored in a fully self-contained archive named Hello.jar. In order to @@ -11,7 +18,7 @@ with ProGuard in your CLASSPATH. After a successful build, copy Hello.jar from this subdirectory to the same directory as hello.html on your web server. -NOTE: We recommend using ProGuard 4.3 or later. +NOTE: If you use ProGuard, you must use version 4.3 or later. If you did not build the applet with ProGuard in your CLASSPATH, the Hello.jar archive contains only the applet classes. In this case you @@ -26,19 +33,63 @@ applet with the following commands: ant clean ant -To run the demo, you must start a "hello" server on the web server -host. You can use the hello server from the ../hello directory or -a hello server from any other Ice language mapping. Note that you may -need to temporarily relax the firewall restrictions on your web server -host to allow the applet to establish connections to the hello server. -Next, start a web browser and open the hello.html page on your web -server. + +Preparing the Ice server +------------------------ + +The applet requires a "hello" server. You can use the Java server +from the ../hello directory or a hello server from any other Ice +language mapping. You may need to temporarily relax the firewall +restrictions on your server host to allow the applet to establish +connections to the hello server. + + +Loading the applet locally +-------------------------- + +The simplest way to use the applet is to open the start page +(hello.html) as a local file directly from your browser. In this case, +you must start the hello server on the same host and enter "localhost" +or "127.0.0.1" as the server host name in the applet. + +Note however that the applet security manager in some versions of Java +may prevent the applet from connecting to the local host. If the +applet reports a SocketException error in its status bar, open the +Java console and review the exception stack trace. The most likely +occurrence is an "access denied" error, which indicates that the +security manager rejected the applet's connection attempt. You can +solve this issue by temporarily granting for the applet to connect to +the local machine. For example, if you are using JRE6 on Windows, open +the following file: + + C:\Program Files\Java\jre6\lib\security\java.policy + +In the "grant" section, add the line shown below: + + permission java.net.SocketPermission "localhost:1024-", "connect,resolve"; + +Restart your browser and try the applet again. If the applet still +cannot establish a connection, try loading it from a web server +instead. + + +Loading the applet from a web server +------------------------------------ + +Start a hello server on the web server host. Next, start a web browser +and open the start page (hello.html) on your web server. Once the applet has started, verify that the name of your web server -host is correct in the "Hostname" field and press the "Hello World!" -button. You will notice that the server prints a "Hello World!" -message to the console for each invocation. To make other types of Ice -invocations, select a different mode from the combobox. +host is shown correctly in the "Hostname" field. + + +Using the applet +---------------- + +Press the "Hello World!" button. You will notice that the server +prints a "Hello World!" message to the console for each invocation. To +make other types of Ice invocations, select a different mode from the +combobox. The two sliders allow you to experiment with various timeout settings. The "Timeout" slider determines how long the Ice run time will wait diff --git a/java/demo/Ice/applet/build.xml b/java/demo/Ice/applet/build.xml index 495021109ad..adfc97057af 100644 --- a/java/demo/Ice/applet/build.xml +++ b/java/demo/Ice/applet/build.xml @@ -52,7 +52,7 @@ <include name="Demo/**"/> <include name="HelloApplet*"/> </jar> - <jar jarfile="Hello.jar" update="true" basedir="${top.dir}/../certs"> + <jar jarfile="Hello.jar" update="true" basedir="${certs.dir}"> <include name="client.jks"/> </jar> </target> @@ -80,7 +80,7 @@ <proguard configuration="applet.pro"> <injar path="${class.dir}"/> - <injar path="${top.dir}/../certs/client.jks"/> + <injar path="${certs.dir}/client.jks"/> <injar refid="ice.classpath" filter="!META-INF/**"/> <outjar path="Hello.jar"/> <libraryjar path="${library.jars}"/> diff --git a/java/demo/Ice/applet/hello.html b/java/demo/Ice/applet/hello.html index c0a48d8f38f..4ebae2dce92 100644 --- a/java/demo/Ice/applet/hello.html +++ b/java/demo/Ice/applet/hello.html @@ -7,7 +7,7 @@ <object classid = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" codebase = "http://java.sun.com/update/1.5.0/jinstall-1_5-windows-i586.cab#Version=1,5,0,0" - WIDTH = 300 HEIGHT = 175 > + WIDTH = 350 HEIGHT = 215 > <PARAM NAME = CODE VALUE = "HelloApplet" > <param name = "type" value = "application/x-java-applet;version=1.5"> <param name = "scriptable" value = "false"> @@ -18,8 +18,8 @@ type = "application/x-java-applet;version=1.5" \ CODE = "HelloApplet" \ ARCHIVE = "Hello.jar" \ - WIDTH = 300 \ - HEIGHT = 175 + WIDTH = 350 \ + HEIGHT = 215 scriptable = false pluginspage = "http://java.sun.com/products/plugin/index.html#download"> <noembed> diff --git a/java/demo/Ice/build.xml b/java/demo/Ice/build.xml index a8f43061344..c101f7c9627 100644 --- a/java/demo/Ice/build.xml +++ b/java/demo/Ice/build.xml @@ -22,6 +22,7 @@ <ant dir="minimal"/> <ant dir="multicast"/> <ant dir="nested"/> + <ant dir="serialize"/> <ant dir="session"/> <ant dir="throughput"/> <ant dir="value"/> @@ -38,6 +39,7 @@ <ant dir="minimal" target="clean"/> <ant dir="multicast" target="clean"/> <ant dir="nested" target="clean"/> + <ant dir="serialize" target="clean"/> <ant dir="session" target="clean"/> <ant dir="throughput" target="clean"/> <ant dir="value" target="clean"/> diff --git a/java/demo/Ice/callback/CallbackSenderI.java b/java/demo/Ice/callback/CallbackSenderI.java index d30d40b5ce6..fe86e7beb9e 100644 --- a/java/demo/Ice/callback/CallbackSenderI.java +++ b/java/demo/Ice/callback/CallbackSenderI.java @@ -17,7 +17,7 @@ public final class CallbackSenderI extends _CallbackSenderDisp System.out.println("initiating callback"); try { - proxy.callback(current.ctx); + proxy.callback(); } catch(Ice.LocalException ex) { diff --git a/java/demo/Ice/nested/NestedI.java b/java/demo/Ice/nested/NestedI.java index 023cffce52f..7ba7cfabbdf 100644 --- a/java/demo/Ice/nested/NestedI.java +++ b/java/demo/Ice/nested/NestedI.java @@ -22,7 +22,7 @@ class NestedI extends _NestedDisp System.out.println("" + level); if(--level > 0) { - proxy.nestedCall(level, _self, current.ctx); + proxy.nestedCall(level, _self); } } diff --git a/java/demo/Ice/protobuf/Client.java b/java/demo/Ice/protobuf/Client.java new file mode 100644 index 00000000000..cbdbb7aca2b --- /dev/null +++ b/java/demo/Ice/protobuf/Client.java @@ -0,0 +1,127 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +import Demo.*; + +public class Client extends Ice.Application +{ + class ShutdownHook extends Thread + { + public void + run() + { + try + { + communicator().destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + } + } + } + + private static void + menu() + { + System.out.println( + "usage:\n" + + "t: send greeting\n" + + "s: shutdown server\n" + + "x: exit\n" + + "?: help\n"); + } + + public int + run(String[] args) + { + if(args.length > 0) + { + System.err.println(appName() + ": too many arguments"); + return 1; + } + + // + // Since this is an interactive demo we want to clear the + // Application installed interrupt callback and install our + // own shutdown hook. + // + setInterruptHook(new ShutdownHook()); + + HelloPrx hello = HelloPrxHelper.checkedCast(communicator().propertyToProxy("Hello.Proxy")); + if(hello == null) + { + System.err.println("invalid proxy"); + return 1; + } + + tutorial.PersonPB.Person p = tutorial.PersonPB.Person.newBuilder(). + setId(1).setName("Fred Jones").setEmail("fred@jones.com").build(); + + menu(); + + java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); + + String line = null; + do + { + try + { + System.out.print("==> "); + System.out.flush(); + line = in.readLine(); + if(line == null) + { + break; + } + if(line.equals("t")) + { + hello.sayHello(p); + } + else if(line.equals("s")) + { + hello.shutdown(); + } + else if(line.equals("x")) + { + // Nothing to do + } + else if(line.equals("?")) + { + menu(); + } + else + { + System.out.println("unknown command `" + line + "'"); + menu(); + } + } + catch(java.io.IOException ex) + { + ex.printStackTrace(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + } + } + while(!line.equals("x")); + + return 0; + } + + public static void + main(String[] args) + { + Client app = new Client(); + int status = app.main("Client", args, "config.client"); + System.exit(status); + } +} + diff --git a/java/demo/Ice/protobuf/Hello.ice b/java/demo/Ice/protobuf/Hello.ice new file mode 100644 index 00000000000..8ddbbbd34ae --- /dev/null +++ b/java/demo/Ice/protobuf/Hello.ice @@ -0,0 +1,27 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +#ifndef HELLO_ICE +#define HELLO_ICE + +module Demo +{ + +["cpp:protobuf:tutorial::Person", "java:protobuf:tutorial.PersonPB.Person", "python:protobuf:Person_pb2.Person"] +sequence<byte> Person; + +interface Hello +{ + idempotent void sayHello(Person p); + void shutdown(); +}; + +}; + +#endif diff --git a/java/demo/Ice/protobuf/HelloI.java b/java/demo/Ice/protobuf/HelloI.java new file mode 100644 index 00000000000..e3fcf7008bb --- /dev/null +++ b/java/demo/Ice/protobuf/HelloI.java @@ -0,0 +1,26 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +import Demo.*; + +public class HelloI extends _HelloDisp +{ + public void + sayHello(tutorial.PersonPB.Person p, Ice.Current current) + { + System.out.println("Hello World from " + p); + } + + public void + shutdown(Ice.Current current) + { + System.out.println("Shutting down..."); + current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/demo/Ice/protobuf/Person.proto b/java/demo/Ice/protobuf/Person.proto new file mode 100644 index 00000000000..6ee58a3f246 --- /dev/null +++ b/java/demo/Ice/protobuf/Person.proto @@ -0,0 +1,18 @@ +// ********************************************************************** +// +// 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 tutorial; + +option java_outer_classname = "PersonPB"; + +message Person { + required int32 id = 1; + required string name = 2; + optional string email = 3; +} diff --git a/java/demo/Ice/protobuf/README b/java/demo/Ice/protobuf/README new file mode 100644 index 00000000000..5ab7020aa68 --- /dev/null +++ b/java/demo/Ice/protobuf/README @@ -0,0 +1,41 @@ +This demo shows how to integrate Google Protocol Buffers with Ice. + +The Protocol Buffers distribution and documentation can be found at + + http://code.google.com/apis/protocolbuffers/ + +This demo was tested with Protocol Buffers version 2.0.3. + +We have added new metadata that makes it possible for you to specify +protocol buffers message types in your Slice definitions, with Ice +handling the serialization chores for you automatically. The metadata, +which may only be used on a sequence<byte> type, has the following +syntax in Java: + + java:protobuf:protoc-generated-class + +For example: + + ["java:protobuf:tutorial.PersonPB.Person"] sequence<byte> Person; + +The type name specified in this example, tutorial.PersonPB.Person, +corresponds to the Java class generated by the Protocol Buffers +compiler (protoc) for the definition shown below: + + package tutorial; + option java_outer_classname = "PersonPB"; + message Person { ... }; + +This demo uses an ant build task, located in the "ant" subdirectory, +for compiling .proto files. + +Prior to building the demo, you should add protoc to your PATH and +protobuf-java-2.0.3.jar to your CLASSPATH. + +To run the demo, first start the server: + + $ java Server + +In a separate window, start the client: + + $ java Client diff --git a/java/demo/Ice/protobuf/Server.java b/java/demo/Ice/protobuf/Server.java new file mode 100644 index 00000000000..6ffab5d02fb --- /dev/null +++ b/java/demo/Ice/protobuf/Server.java @@ -0,0 +1,37 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +import Demo.*; + +public class Server extends Ice.Application +{ + public int + run(String[] args) + { + if(args.length > 0) + { + System.err.println(appName() + ": too many arguments"); + return 1; + } + + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("Hello"); + adapter.add(new HelloI(), communicator().stringToIdentity("hello")); + adapter.activate(); + communicator().waitForShutdown(); + return 0; + } + + public static void + main(String[] args) + { + Server app = new Server(); + int status = app.main("Server", args, "config.server"); + System.exit(status); + } +} diff --git a/java/demo/Ice/protobuf/ant/ProtocTask.java b/java/demo/Ice/protobuf/ant/ProtocTask.java new file mode 100644 index 00000000000..b102cb9fccd --- /dev/null +++ b/java/demo/Ice/protobuf/ant/ProtocTask.java @@ -0,0 +1,367 @@ +// ********************************************************************** +// +// 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 Ice.Ant; + +import org.apache.tools.ant.Task; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.DirectoryScanner; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.ant.taskdefs.ExecTask; +import org.apache.tools.ant.taskdefs.Execute; +import org.apache.tools.ant.taskdefs.PumpStreamHandler; +import org.apache.tools.ant.types.Commandline; +import org.apache.tools.ant.types.Commandline.Argument; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.types.Reference; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.StringReader; +import java.io.BufferedReader; +import java.io.BufferedWriter; + +/** + * An ant task for protoc. + * + * Attributes specific to protoc: + * + * translator - The pathname of the translator (default: "protoc"). + * protocpath - The value for the --proto_path translator option. + * outputdir - The value for the --java_out translator option. + * dependencyfile - The file in which dependencies are stored (default: ".pbdepend"). + * + * Example: + * + * <project ...> + * <taskdef name="protoc" classname="ProtocTask" /> + * <property name="protoc.dir" value="../include/protoc"/> + * <target name="generate"> + * <mkdir dir="tags" /> + * <protoc tagdir="tags" outputdir="out"> + * <fileset dir="${protoc.dir}"> + * <include name="*.ice" /> + * </fileset> + * </protoc> + * </target> + * </project> + * + * The <taskdef> element installs the protoctask task. + */ +public class ProtocTask extends org.apache.tools.ant.Task +{ + public + ProtocTask() + { + _translator = null; + _outputDir = null; + _protocPath = null; + _outputDirString = null; + } + + public void + setDependencyFile(File file) + { + _dependencyFile = file; + } + + public void + setOutputdir(File dir) + { + _outputDir = dir; + _outputDirString = _outputDir.toString(); + if(_outputDirString.indexOf(' ') != -1) + { + _outputDirString = '"' + _outputDirString + '"'; + } + } + + public void + setProtocpath(File dir) + { + _protocPath = dir.toString(); + } + + public void + setTranslator(File prog) + { + _translator = prog; + } + + public FileSet + createFileset() + { + FileSet fileset = new FileSet(); + _fileSets.add(fileset); + + return fileset; + } + + public void + execute() + throws BuildException + { + if(_fileSets.isEmpty()) + { + throw new BuildException("No fileset specified"); + } + + // + // Read the set of dependencies for this task. + // + java.util.HashMap dependencies = readDependencies(); + + // + // Compose a list of the files that need to be translated. A + // file needs to translated if we can't find a dependency in + // the dependency table or if its dependency is not up-to-date + // anymore (the proto file changed since the dependency was + // last updated) + // + java.util.Vector buildList = new java.util.Vector(); + java.util.Vector skipList = new java.util.Vector(); + java.util.Iterator p = _fileSets.iterator(); + while(p.hasNext()) + { + FileSet fileset = (FileSet)p.next(); + + DirectoryScanner scanner = fileset.getDirectoryScanner(getProject()); + scanner.scan(); + String[] files = scanner.getIncludedFiles(); + for(int i = 0; i < files.length; i++) + { + File proto = new File(fileset.getDir(getProject()), files[i]); + + ProtoDependency depend = (ProtoDependency)dependencies.get(getTargetKey(proto.toString())); + if(depend == null || !depend.isUpToDate()) + { + buildList.addElement(proto); + } + else + { + skipList.addElement(proto); + } + } + + java.util.Iterator i = skipList.iterator(); + while(i.hasNext()) + { + File file = (File)i.next(); + log("skipping " + file.getName()); + } + } + + // + // Run the translator + // + if(!buildList.isEmpty()) + { + String translator; + if(_translator == null) + { + translator = "protoc"; + } + else + { + translator = _translator.toString(); + } + + StringBuilder cmd = new StringBuilder(128); + + // + // Add --java_out. + // + if(_outputDir != null) + { + cmd.append(" --java_out="); + cmd.append(stripDriveLetter(_outputDirString)); + } + + // + // Add --proto_path + // + if(_protocPath != null) + { + cmd.append(" --proto_path="); + cmd.append(stripDriveLetter(_protocPath)); + } + + // + // Add files to be translated + // + for(int i = 0; i < buildList.size(); i++) + { + File f = (File)buildList.elementAt(i); + cmd.append(" "); + String s = stripDriveLetter(f.toString()); + if(s.indexOf(' ') != -1) + { + cmd.append('"' + s + '"'); + } + else + { + cmd.append(s); + } + } + + // + // Execute + // + log(translator + " " + cmd); + ExecTask task = (ExecTask)getProject().createTask("exec"); + task.setFailonerror(true); + Argument arg = task.createArg(); + arg.setLine(cmd.toString()); + task.setExecutable(translator); + task.execute(); + + // + // Update dependency file. + // + for(int i = 0; i < buildList.size(); i++) + { + ProtoDependency depend = new ProtoDependency(); + depend._timeStamp = new java.util.Date().getTime(); + depend._dependency = ((File)buildList.elementAt(i)).toString(); + dependencies.put(getTargetKey(depend._dependency), depend); + } + + writeDependencies(dependencies); + } + } + + private String + getTargetKey(String proto) + { + // + // Since the dependency file can be shared by several proto + // tasks we need to make sure that each dependency has a + // unique key. We use the name of the task, the output + // directory and the name of the proto file to be compiled. + // + // If there's two protoc tasks using the same dependency + // file, with the same output dir and which compiles the same + // protoc file they'll use the same dependency. + // + return "protoc " + _outputDir.toString() + " " + proto; + } + + // This is to work around a bug with protoc, where it does not + // accept drive letters in path names. See + // http://bugzilla/bugzilla/show_bug.cgi?id=3349 + // + private String + stripDriveLetter(String s) + { + if(s.length() > 1 && s.charAt(1) == ':') + { + return s.substring(2); + } + return s; + } + + // + // Read the dependency file. + // + private java.util.HashMap + readDependencies() + { + if(_dependencyFile == null) + { + if(_outputDir != null) + { + _dependencyFile = new File(_outputDir, ".pbdepend"); + } + else + { + _dependencyFile = new File(".pbdepend"); + } + } + + try + { + java.io.ObjectInputStream in = new java.io.ObjectInputStream(new java.io.FileInputStream(_dependencyFile)); + java.util.HashMap dependencies = (java.util.HashMap)in.readObject(); + in.close(); + return dependencies; + } + catch(java.io.IOException ex) + { + } + catch(java.lang.ClassNotFoundException ex) + { + } + + return new java.util.HashMap(); + } + + private void + writeDependencies(java.util.HashMap dependencies) + { + try + { + java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(new FileOutputStream(_dependencyFile)); + out.writeObject(dependencies); + out.close(); + } + catch(java.io.IOException ex) + { + throw new BuildException("Unable to write dependencies in file " + _dependencyFile.getPath() + ": " + ex); + } + } + + // + // A proto dependency. + // + // * the _timeStamp attribute contains the last time the proto + // file was compiled. + // + // * the _dependency attribute contains the .proto file. + // + private class ProtoDependency implements java.io.Serializable + { + private void writeObject(java.io.ObjectOutputStream out) + throws java.io.IOException + { + out.writeObject(_dependency); + out.writeLong(_timeStamp); + } + + private void readObject(java.io.ObjectInputStream in) + throws java.io.IOException, java.lang.ClassNotFoundException + { + _dependency = (String)in.readObject(); + _timeStamp = in.readLong(); + } + + public boolean + isUpToDate() + { + File dep = new File(_dependency); + if(!dep.exists() || _timeStamp < dep.lastModified()) + { + return false; + } + + return true; + } + + public String _dependency; + public long _timeStamp; + } + + private File _translator; + private File _dependencyFile; + private File _outputDir; + private String _outputDirString; + private String _protocPath; + private java.util.List _fileSets = new java.util.LinkedList(); +} diff --git a/java/demo/Ice/protobuf/build.xml b/java/demo/Ice/protobuf/build.xml new file mode 100644 index 00000000000..aa336420300 --- /dev/null +++ b/java/demo/Ice/protobuf/build.xml @@ -0,0 +1,63 @@ +<!-- + ********************************************************************** + + 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. + + ********************************************************************** +--> + +<project name="demo_Ice_protobuf" default="all" basedir="."> + + <!-- set global properties for this build --> + <property name="top.dir" value="../../.."/> + + <!-- import common definitions --> + <import file="${top.dir}/config/common.xml"/> + + <target name="protoc" depends="init"> + <!-- Build protoc task --> + <mkdir dir="${class.dir}"/> + <javac srcdir="ant" destdir="${class.dir}" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> + </target> + + <target name="generate" depends="protoc"> + <!-- Add the protoc task --> + <taskdef name="protoc" classpath="${class.dir}" classname="ProtocTask" /> + <!-- Create the output directory for generated code --> + <mkdir dir="${generated.dir}"/> + <slice2java outputdir="${generated.dir}"> + <meta value="${java2metadata}"/> + <fileset dir="." includes="Hello.ice"/> + </slice2java> + <protoc outputdir="${generated.dir}" protocpath="."> + <fileset dir="." includes="Person.proto"/> + </protoc> + </target> + + <target name="compile" depends="generate"> + <mkdir dir="${class.dir}"/> + <javac srcdir="${generated.dir}" destdir="${class.dir}" + debug="${debug}"> + <classpath refid="ice.classpath"/> + <compilerarg value="${javac.lint}"/> + </javac> + <javac srcdir="." destdir="${class.dir}" + excludes="generated/**, ant/**" debug="${debug}"> + <classpath refid="ice.classpath"/> + <compilerarg value="${javac.lint}"/> + </javac> + </target> + + <target name="all" depends="compile"/> + + <target name="clean"> + <delete dir="${generated.dir}"/> + <delete dir="${class.dir}"/> + </target> + +</project> diff --git a/java/demo/Ice/protobuf/config.client b/java/demo/Ice/protobuf/config.client new file mode 100644 index 00000000000..a02cab0f4cb --- /dev/null +++ b/java/demo/Ice/protobuf/config.client @@ -0,0 +1,23 @@ +# +# The client reads this property to create the reference to the +# "hello" object in the server. +# +Hello.Proxy=hello:tcp -p 10000 + +# +# Network Tracing +# +# 0 = no network tracing +# 1 = trace connection establishment and closure +# 2 = like 1, but more detailed +# 3 = like 2, but also trace data transfer +# +#Ice.Trace.Network=1 + +# +# Protocol Tracing +# +# 0 = no protocol tracing +# 1 = trace protocol messages +# +#Ice.Trace.Protocol=1 diff --git a/java/demo/Ice/protobuf/config.server b/java/demo/Ice/protobuf/config.server new file mode 100644 index 00000000000..309db9731b2 --- /dev/null +++ b/java/demo/Ice/protobuf/config.server @@ -0,0 +1,24 @@ +# +# The server creates one single object adapter with the name +# "Hello". The following line sets the endpoints for this +# adapter. +# +Hello.Endpoints=tcp -p 10000 + +# +# Network Tracing +# +# 0 = no network tracing +# 1 = trace connection establishment and closure +# 2 = like 1, but more detailed +# 3 = like 2, but also trace data transfer +# +#Ice.Trace.Network=1 + +# +# Protocol Tracing +# +# 0 = no protocol tracing +# 1 = trace protocol messages +# +#Ice.Trace.Protocol=1 diff --git a/java/demo/Ice/protobuf/expect.py b/java/demo/Ice/protobuf/expect.py new file mode 100755 index 00000000000..60dabda57bf --- /dev/null +++ b/java/demo/Ice/protobuf/expect.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# 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. +# +# ********************************************************************** + +import sys, os + +path = [ ".", "..", "../..", "../../..", "../../../.." ] +head = os.path.dirname(sys.argv[0]) +if len(head) > 0: + path = [os.path.join(head, p) for p in path] +path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ] +if len(path) == 0: + raise "can't find toplevel directory!" +sys.path.append(path[0]) + +from demoscript import * +from demoscript.Ice import protobuf + +server = Util.spawn('java Server --Ice.PrintAdapterReady --Ice.Warn.Connections=0') +server.expect('.* ready') +client = Util.spawn('java Client --Ice.Warn.Connections=0') +client.expect('.*==>') + +protobuf.run(client, server) diff --git a/java/demo/Ice/serialize/Client.java b/java/demo/Ice/serialize/Client.java new file mode 100644 index 00000000000..e5c6ce82fb0 --- /dev/null +++ b/java/demo/Ice/serialize/Client.java @@ -0,0 +1,142 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +import Demo.*; + +public class Client extends Ice.Application +{ + class ShutdownHook extends Thread + { + public void + run() + { + try + { + communicator().destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + } + } + } + + private static void + menu() + { + System.out.println( + "usage:\n" + + "g: send greeting\n" + + "t: toggle null greeting\n" + + "s: shutdown server\n" + + "x: exit\n" + + "?: help\n"); + } + + public int + run(String[] args) + { + if(args.length > 0) + { + System.err.println(appName() + ": too many arguments"); + return 1; + } + + // + // Since this is an interactive demo we want to clear the + // Application installed interrupt callback and install our + // own shutdown hook. + // + setInterruptHook(new ShutdownHook()); + + GreetPrx greet = GreetPrxHelper.checkedCast(communicator().propertyToProxy("Greet.Proxy")); + if(greet == null) { + + System.err.println("invalid proxy"); + return 1; + } + + MyGreeting greeting = new MyGreeting(); + greeting.text = "Hello there!"; + MyGreeting nullGreeting = null; + + boolean sendNull = false; + + menu(); + + java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); + + String line = null; + do + { + try + { + System.out.print("==> "); + System.out.flush(); + line = in.readLine(); + if(line == null) + { + break; + } + if(line.equals("g")) + { + if(sendNull) + { + greet.sendGreeting(nullGreeting); + } + else + { + greet.sendGreeting(greeting); + } + } + else if(line.equals("t")) + { + sendNull = !sendNull; + } + else if(line.equals("s")) + { + greet.shutdown(); + } + else if(line.equals("x")) + { + // Nothing to do + } + else if(line.equals("?")) + { + menu(); + } + else + { + System.out.println("unknown command `" + line + "'"); + menu(); + } + } + catch(java.io.IOException ex) + { + ex.printStackTrace(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + } + } + while(!line.equals("x")); + + return 0; + } + + public static void + main(String[] args) + { + Client app = new Client(); + int status = app.main("Client", args, "config.client"); + System.exit(status); + } +} + diff --git a/java/demo/Ice/serialize/Demo/MyGreeting.java b/java/demo/Ice/serialize/Demo/MyGreeting.java new file mode 100644 index 00000000000..bbefc3e687b --- /dev/null +++ b/java/demo/Ice/serialize/Demo/MyGreeting.java @@ -0,0 +1,15 @@ +// ********************************************************************** +// +// 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 Demo; + +public class MyGreeting implements java.io.Serializable +{ + public String text; +} diff --git a/java/demo/Ice/serialize/Greet.ice b/java/demo/Ice/serialize/Greet.ice new file mode 100644 index 00000000000..e06d9d04f6d --- /dev/null +++ b/java/demo/Ice/serialize/Greet.ice @@ -0,0 +1,26 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +#ifndef GREET_ICE +#define GREET_ICE + +module Demo +{ + +["java:serializable:Demo.MyGreeting"] sequence<byte> Greeting; + +interface Greet +{ + idempotent void sendGreeting(Greeting g); + void shutdown(); +}; + +}; + +#endif diff --git a/java/demo/Ice/serialize/GreetI.java b/java/demo/Ice/serialize/GreetI.java new file mode 100644 index 00000000000..855af5173f5 --- /dev/null +++ b/java/demo/Ice/serialize/GreetI.java @@ -0,0 +1,33 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +import Demo.*; + +public class GreetI extends _GreetDisp +{ + public void + sendGreeting(MyGreeting greeting, Ice.Current current) + { + if(greeting != null) + { + System.out.println(greeting.text); + } + else + { + System.out.println("Received null greeting"); + } + } + + public void + shutdown(Ice.Current current) + { + System.out.println("Shutting down..."); + current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/demo/Ice/serialize/README b/java/demo/Ice/serialize/README new file mode 100644 index 00000000000..c472c81bef0 --- /dev/null +++ b/java/demo/Ice/serialize/README @@ -0,0 +1,37 @@ +This demo illustrates how to transfer serializable Java classes +with Ice. + +The Java classes are transferred as byte sequences by Ice. It was +always possible to do this, but required you to explicitly serialize +your class into a byte sequence and then pass that sequence to your +operations to be deserialized by the receiver. You can now accomplish +the same thing more conveniently via metadata. + +In your Slice definitions, you must declare a byte sequence using the +"java:serializable" metadata and specify the Java class name, as shown +below: + +["java:serializable:JavaClassName"] sequence<byte> SliceType; + +Now, wherever you use the declared Slice type in your operations or +data types, you can supply an instance of the designated Java class +and Ice automatically converts it to and from the byte sequence that +is passed over the wire. (The Java class you pass must derive from +java.io.Serializable.) + +With the "java:serializable" metadata, if you have a serializable +class as an out-parameter, the out-parameter is passed as +Ice.Holder<JavaClassName>. For example, if you have a Java class +MyPackage.Car as an out-parameter, the out-parameter is passed as +Ice.Holder<MyPackage.Car>. + +To run the demo, first start the server: + +$ java Server + +In a separate window, start the client: + +$ java Client + +The client allows you to toggle between sending a real class instance +and sending a null value, to show that passing null is supported. diff --git a/java/demo/Ice/serialize/Server.java b/java/demo/Ice/serialize/Server.java new file mode 100644 index 00000000000..6550ea79a6d --- /dev/null +++ b/java/demo/Ice/serialize/Server.java @@ -0,0 +1,37 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +import Demo.*; + +public class Server extends Ice.Application +{ + public int + run(String[] args) + { + if(args.length > 0) + { + System.err.println(appName() + ": too many arguments"); + return 1; + } + + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("Greet"); + adapter.add(new GreetI(), communicator().stringToIdentity("greet")); + adapter.activate(); + communicator().waitForShutdown(); + return 0; + } + + public static void + main(String[] args) + { + Server app = new Server(); + int status = app.main("Server", args, "config.server"); + System.exit(status); + } +} diff --git a/java/demo/Ice/serialize/build.xml b/java/demo/Ice/serialize/build.xml new file mode 100644 index 00000000000..96b3470fb12 --- /dev/null +++ b/java/demo/Ice/serialize/build.xml @@ -0,0 +1,52 @@ +<!-- + ********************************************************************** + + 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. + + ********************************************************************** +--> + +<project name="demo_Ice_serialize" default="all" basedir="."> + + <!-- set global properties for this build --> + <property name="top.dir" value="../../.."/> + + <!-- import common definitions --> + <import file="${top.dir}/config/common.xml"/> + + <target name="generate" depends="init"> + <!-- Create the output directory for generated code --> + <mkdir dir="${generated.dir}"/> + <slice2java outputdir="${generated.dir}"> + <meta value="${java2metadata}"/> + <fileset dir="." includes="Greet.ice"/> + </slice2java> + </target> + + <target name="compile" depends="generate"> + <mkdir dir="${class.dir}"/> + <javac srcdir="." destdir="${class.dir}" includes="Demo/**" debug="${debug}"> + <classpath refid="ice.classpath"/> + <compilerarg value="${javac.lint}"/> + </javac> + <javac srcdir="${generated.dir}" destdir="${class.dir}" debug="${debug}"> + <classpath refid="ice.classpath"/> + <compilerarg value="${javac.lint}"/> + </javac> + <javac srcdir="." destdir="${class.dir}" excludes="generated/**,Serialize/**" debug="${debug}"> + <classpath refid="ice.classpath"/> + <compilerarg value="${javac.lint}"/> + </javac> + </target> + + <target name="all" depends="compile"/> + + <target name="clean"> + <delete dir="${generated.dir}"/> + <delete dir="${class.dir}"/> + </target> + +</project> diff --git a/java/demo/Ice/serialize/config.client b/java/demo/Ice/serialize/config.client new file mode 100644 index 00000000000..cdf6f093e41 --- /dev/null +++ b/java/demo/Ice/serialize/config.client @@ -0,0 +1,28 @@ +# +# The client reads this property to create the reference to the +# "greet" object in the server. +# +Greet.Proxy=greet:tcp -p 10000 + +# +# Warn about connection exceptions. +# +Ice.Warn.Connections=1 + +# +# Network Tracing +# +# 0 = no network tracing +# 1 = trace connection establishment and closure +# 2 = like 1, but more detailed +# 3 = like 2, but also trace data transfer +# +#Ice.Trace.Network=1 + +# +# Protocol Tracing +# +# 0 = no protocol tracing +# 1 = trace protocol messages +# +#Ice.Trace.Protocol=1 diff --git a/java/demo/Ice/serialize/config.server b/java/demo/Ice/serialize/config.server new file mode 100644 index 00000000000..41bfe6caa46 --- /dev/null +++ b/java/demo/Ice/serialize/config.server @@ -0,0 +1,29 @@ +# +# The server creates one single object adapter with the name +# "Greet". The following line sets the endpoints for this +# adapter. +# +Greet.Endpoints=tcp -p 10000 + +# +# Warn about connection exceptions. +# +Ice.Warn.Connections=1 + +# +# Network Tracing +# +# 0 = no network tracing +# 1 = trace connection establishment and closure +# 2 = like 1, but more detailed +# 3 = like 2, but also trace data transfer +# +#Ice.Trace.Network=1 + +# +# Protocol Tracing +# +# 0 = no protocol tracing +# 1 = trace protocol messages +# +#Ice.Trace.Protocol=1 diff --git a/java/demo/Ice/serialize/expect.py b/java/demo/Ice/serialize/expect.py new file mode 100755 index 00000000000..76bc8e43408 --- /dev/null +++ b/java/demo/Ice/serialize/expect.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# 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. +# +# ********************************************************************** + +import sys, os + +path = [ ".", "..", "../..", "../../..", "../../../.." ] +head = os.path.dirname(sys.argv[0]) +if len(head) > 0: + path = [os.path.join(head, p) for p in path] +path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "demoscript")) ] +if len(path) == 0: + raise "can't find toplevel directory!" +sys.path.append(path[0]) + +from demoscript import * +from demoscript.Ice import serialize + +server = Util.spawn('java Server --Ice.PrintAdapterReady --Ice.Warn.Connections=0') +server.expect('.* ready') +client = Util.spawn('java Client --Ice.Warn.Connections=0') +client.expect('.*==>') + +serialize.run(client, server) diff --git a/java/demo/Ice/value/Client.java b/java/demo/Ice/value/Client.java index dbac804ad37..58ee94fcdbc 100644 --- a/java/demo/Ice/value/Client.java +++ b/java/demo/Ice/value/Client.java @@ -104,7 +104,7 @@ public class Client extends Ice.Application readline(in); Ice.ObjectFactory factory = new ObjectFactory(); - communicator().addObjectFactory(factory, "::Demo::Printer"); + communicator().addObjectFactory(factory, Demo.Printer.ice_staticId()); initial.getPrinter(printer, printerProxy); System.out.println("==> " + printer.value.message); @@ -136,7 +136,7 @@ public class Client extends Ice.Application Printer derivedAsBase = initial.getDerivedPrinter(); System.out.println("==> The type ID of the received object is \"" + derivedAsBase.ice_id() + "\""); - assert(derivedAsBase.ice_id().equals("::Demo::Printer")); + assert(derivedAsBase.ice_id().equals(Demo.Printer.ice_staticId())); System.out.println(); System.out.println("Now we install a factory for the derived class, and try again."); @@ -145,7 +145,7 @@ public class Client extends Ice.Application System.out.println("[press enter]"); readline(in); - communicator().addObjectFactory(factory, "::Demo::DerivedPrinter"); + communicator().addObjectFactory(factory, Demo.DerivedPrinter.ice_staticId()); derivedAsBase = initial.getDerivedPrinter(); DerivedPrinter derived = (Demo.DerivedPrinter)derivedAsBase; diff --git a/java/demo/book/README b/java/demo/book/README index bbace203f6d..3d58a2ba06f 100644 --- a/java/demo/book/README +++ b/java/demo/book/README @@ -6,6 +6,15 @@ Demos in this directory: the Ice Run Time chapter. You can copy and modify this code to suit your needs. +- freeze_filesystem + + An implementation of the persistent version of the file system + example described in the Freeze chapter. + +- lifecycle + + An implementation of the file system that supports life cycle operations. + - printer An implementation of the simple printer example at the beginning of @@ -15,12 +24,3 @@ Demos in this directory: An implementation of the simple (non-persistent, non-life-cycle) version of the file system example. - -- lifecycle - - An implementation of the file system that supports life cycle operations. - -- freeze_filesystem - - An implementation of the persistent version of the file system - example described in the Freeze chapter. diff --git a/java/demo/book/freeze_filesystem/Client.java b/java/demo/book/freeze_filesystem/Client.java index b665940d541..2c0056e1451 100644 --- a/java/demo/book/freeze_filesystem/Client.java +++ b/java/demo/book/freeze_filesystem/Client.java @@ -79,9 +79,10 @@ public class Client extends Ice.Application // // Create a file called "README" in the root directory. // + FilePrx readme = null; try { - FilePrx readme = rootDir.createFile("README"); + readme = rootDir.createFile("README"); String[] text = new String[1]; text[0] = "This file system contains a collection of poetry."; readme.write(text); @@ -89,9 +90,9 @@ public class Client extends Ice.Application } catch(NameInUse ex) { - // - // Ignore - file already exists. - // + NodeDesc desc = rootDir.find("README"); + readme = FilePrxHelper.checkedCast(desc.proxy); + assert(readme != null); } // @@ -113,9 +114,10 @@ public class Client extends Ice.Application // // Create a file called "Kubla_Khan" in the Coleridge directory. // + FilePrx file = null; try { - FilePrx file = coleridge.createFile("Kubla_Khan"); + file = coleridge.createFile("Kubla_Khan"); String[] text = new String[5]; text[0] = "In Xanadu did Kubla Khan"; text[1] = "A stately pleasure-dome decree:"; @@ -127,9 +129,9 @@ public class Client extends Ice.Application } catch(NameInUse ex) { - // - // Ignore - file already exists. - // + NodeDesc desc = coleridge.find("Kubla_Khan"); + file = FilePrxHelper.checkedCast(desc.proxy); + assert(file != null); } System.out.println("Contents of filesystem:"); @@ -138,13 +140,12 @@ public class Client extends Ice.Application // // Destroy the filesystem. // - NodeDesc[] contents = rootDir.list(); - for(int i = 0; i < contents.length; ++i) - { - NodeDesc d = contents[i]; - System.out.println("Destroying " + d.name); - d.proxy.destroy(); - } + System.out.println("Destroying " + file.name()); + file.destroy(); + System.out.println("Destroying " + readme.name()); + readme.destroy(); + System.out.println("Destroying " + coleridge.name()); + coleridge.destroy(); } catch(Ice.UserException ex) { diff --git a/java/demo/book/freeze_filesystem/DirectoryI.java b/java/demo/book/freeze_filesystem/DirectoryI.java index 03d9d3039c2..2a3ca7c9c17 100644 --- a/java/demo/book/freeze_filesystem/DirectoryI.java +++ b/java/demo/book/freeze_filesystem/DirectoryI.java @@ -42,34 +42,22 @@ public final class DirectoryI extends PersistentDirectory { if(parent == null) { - throw new PermissionDenied("cannot remove root directory"); + throw new PermissionDenied("cannot destroy root directory"); } - java.util.Map children = null; - synchronized(this) { if(_destroyed) { throw new Ice.ObjectNotExistException(current.id, current.facet, current.operation); } - - children = (java.util.Map)((java.util.HashMap)nodes).clone(); - _destroyed = true; - } - - // - // For consistency with C++, we iterate over the children outside of synchronization. - // - java.util.Iterator p = children.values().iterator(); - while(p.hasNext()) - { - NodeDesc desc = (NodeDesc)p.next(); - desc.proxy.destroy(); + if(!nodes.isEmpty()) + { + throw new PermissionDenied("cannot destroy non-empty directory"); + } + _destroyed = true; } - assert(nodes.isEmpty()); - parent.removeNode(nodeName); _evictor.remove(_id); } diff --git a/java/demo/book/freeze_filesystem/FileI.java b/java/demo/book/freeze_filesystem/FileI.java index 12c92654a1b..8b84ae13b34 100644 --- a/java/demo/book/freeze_filesystem/FileI.java +++ b/java/demo/book/freeze_filesystem/FileI.java @@ -14,17 +14,24 @@ public final class FileI extends PersistentFile public FileI() { + _destroyed = false; } public FileI(Ice.Identity id) { _id = id; + _destroyed = false; } - public String + public synchronized String name(Ice.Current current) { + if(_destroyed) + { + throw new Ice.ObjectNotExistException(current.id, current.facet, current.operation); + } + return nodeName; } @@ -32,6 +39,15 @@ public final class FileI extends PersistentFile destroy(Ice.Current current) throws PermissionDenied { + synchronized(this) + { + if(_destroyed) + { + throw new Ice.ObjectNotExistException(current.id, current.facet, current.operation); + } + _destroyed = true; + } + parent.removeNode(nodeName); _evictor.remove(_id); } @@ -39,6 +55,11 @@ public final class FileI extends PersistentFile public synchronized String[] read(Ice.Current current) { + if(_destroyed) + { + throw new Ice.ObjectNotExistException(current.id, current.facet, current.operation); + } + return (String[])text.clone(); } @@ -46,9 +67,15 @@ public final class FileI extends PersistentFile write(String[] text, Ice.Current current) throws GenericError { + if(_destroyed) + { + throw new Ice.ObjectNotExistException(current.id, current.facet, current.operation); + } + this.text = text; } public static Freeze.Evictor _evictor; public Ice.Identity _id; + private boolean _destroyed; } diff --git a/java/demo/book/freeze_filesystem/Server.java b/java/demo/book/freeze_filesystem/Server.java index 10deb39e8a6..da37b3d4664 100644 --- a/java/demo/book/freeze_filesystem/Server.java +++ b/java/demo/book/freeze_filesystem/Server.java @@ -38,7 +38,8 @@ public class Server extends Ice.Application // static member). // Freeze.ServantInitializer init = new NodeInitializer(); - Freeze.Evictor evictor = Freeze.Util.createBackgroundSaveEvictor(adapter, _envName, "evictorfs", init, null, true); + Freeze.Evictor evictor = Freeze.Util.createTransactionalEvictor(adapter, _envName, "evictorfs", + null, init, null, true); DirectoryI._evictor = evictor; FileI._evictor = evictor; diff --git a/java/demo/book/freeze_filesystem/build.xml b/java/demo/book/freeze_filesystem/build.xml index 3b0e0824433..51564430850 100644 --- a/java/demo/book/freeze_filesystem/build.xml +++ b/java/demo/book/freeze_filesystem/build.xml @@ -39,7 +39,10 @@ </javac> <javac srcdir="." destdir="${class.dir}" excludes="generated/**" debug="${debug}"> - <classpath refid="ice.classpath"/> + <classpath> + <path refid="ice.classpath"/> + <path refid="db.classpath"/> + </classpath> <compilerarg value="${javac.lint}"/> </javac> </target> diff --git a/java/demo/book/lifecycle/FilesystemI/DirectoryI.java b/java/demo/book/lifecycle/FilesystemI/DirectoryI.java index f1745305e0b..410bbafcd9d 100644 --- a/java/demo/book/lifecycle/FilesystemI/DirectoryI.java +++ b/java/demo/book/lifecycle/FilesystemI/DirectoryI.java @@ -12,7 +12,7 @@ package FilesystemI; import Ice.*; import Filesystem.*; -public class DirectoryI extends _DirectoryDisp implements NodeI, _DirectoryOperations +public class DirectoryI extends _DirectoryDisp implements NodeI { // Slice name() operation. @@ -37,115 +37,91 @@ public class DirectoryI extends _DirectoryDisp implements NodeI, _DirectoryOpera // Slice list() operation. - public NodeDesc[] + public synchronized NodeDesc[] list(Current c) { - synchronized(this) + if(_destroyed) { - if(_destroyed) - { - throw new ObjectNotExistException(); - } + throw new ObjectNotExistException(); } - synchronized(_lcMutex) + NodeDesc[] ret = new NodeDesc[_contents.size()]; + java.util.Iterator<java.util.Map.Entry<String, NodeI> > pos = _contents.entrySet().iterator(); + for(int i = 0; i < _contents.size(); ++i) { - reap(); - - NodeDesc[] ret = new NodeDesc[_contents.size()]; - java.util.Iterator<java.util.Map.Entry<String, NodeI> > pos = _contents.entrySet().iterator(); - for(int i = 0; i < _contents.size(); ++i) - { - java.util.Map.Entry<String, NodeI> e = pos.next(); - NodeI p = e.getValue(); - ret[i] = new NodeDesc(); - ret[i].name = e.getKey(); - ret[i].type = p instanceof FileI ? NodeType.FileType : NodeType.DirType; - ret[i].proxy = NodePrxHelper.uncheckedCast(c.adapter.createProxy(p.id())); - } - return ret; + java.util.Map.Entry<String, NodeI> e = pos.next(); + NodeI p = e.getValue(); + ret[i] = new NodeDesc(); + ret[i].name = e.getKey(); + ret[i].type = p instanceof FileI ? NodeType.FileType : NodeType.DirType; + ret[i].proxy = NodePrxHelper.uncheckedCast(c.adapter.createProxy(p.id())); } + return ret; } // Slice find() operation. - public NodeDesc + public synchronized NodeDesc find(String name, Current c) throws NoSuchName { - synchronized(this) + if(_destroyed) { - if(_destroyed) - { - throw new ObjectNotExistException(); - } + throw new ObjectNotExistException(); } - synchronized(_lcMutex) + NodeI p = _contents.get(name); + if(p == null) { - reap(); - - NodeI p = (NodeI)_contents.get(name); - if(p == null) - { - throw new NoSuchName(name); - } - - NodeDesc d = new NodeDesc(); - d.name = name; - d.type = p instanceof FileI ? NodeType.FileType : NodeType.DirType; - d.proxy = NodePrxHelper.uncheckedCast(c.adapter.createProxy(p.id())); - return d; + throw new NoSuchName(name); } + + NodeDesc d = new NodeDesc(); + d.name = name; + d.type = p instanceof FileI ? NodeType.FileType : NodeType.DirType; + d.proxy = NodePrxHelper.uncheckedCast(c.adapter.createProxy(p.id())); + return d; } // Slice createFile() operation. - public FilePrx + public synchronized FilePrx createFile(String name, Current c) throws NameInUse { - synchronized(this) + if(_destroyed) { - if(_destroyed) - { - throw new ObjectNotExistException(); - } + throw new ObjectNotExistException(); } - synchronized(_lcMutex) + if(name.length() == 0 || _contents.containsKey(name)) { - reap(); - - if(_contents.containsKey(name)) - { - throw new NameInUse(name); - } - return new FileI(name, this).activate(c.adapter); + throw new NameInUse(name); } + + FileI f = new FileI(name, this); + ObjectPrx node = c.adapter.add(f, f.id()); + _contents.put(name, f); + return FilePrxHelper.uncheckedCast(node); } // Slice createDirectory() operation. - public DirectoryPrx + public synchronized DirectoryPrx createDirectory(String name, Current c) throws NameInUse { - synchronized(this) + if(_destroyed) { - if(_destroyed) - { - throw new ObjectNotExistException(); - } + throw new ObjectNotExistException(); } - synchronized(_lcMutex) + if(name.length() == 0 || _contents.containsKey(name)) { - reap(); - - if(_contents.containsKey(name)) - { - throw new NameInUse(name); - } - return new DirectoryI(name, this).activate(c.adapter); + throw new NameInUse(name); } + + DirectoryI d = new DirectoryI(name, this); + ObjectPrx node = c.adapter.add(d, d.id()); + _contents.put(name, d); + return DirectoryPrxHelper.uncheckedCast(node); } // Slice destroy() operation. @@ -165,20 +141,16 @@ public class DirectoryI extends _DirectoryDisp implements NodeI, _DirectoryOpera throw new ObjectNotExistException(); } - synchronized(_lcMutex) + if(_contents.size() != 0) { - reap(); - - if(_contents.size() != 0) - { - throw new PermissionDenied("Cannot destroy non-empty directory"); - } - - c.adapter.remove(id()); - _parent.addReapEntry(_name); - _destroyed = true; + throw new PermissionDenied("Cannot destroy non-empty directory"); } + + c.adapter.remove(id()); + _destroyed = true; } + + _parent.removeEntry(_name); } // DirectoryI constructor for root directory. @@ -201,75 +173,17 @@ public class DirectoryI extends _DirectoryDisp implements NodeI, _DirectoryOpera _id.name = parent == null ? "RootDir" : java.util.UUID.randomUUID().toString(); } + // Remove the entry from the _contents map. - // Add servant to ASM and to parent's _contents map. - - public DirectoryPrx - activate(Ice.ObjectAdapter a) + public synchronized void + removeEntry(String name) { - DirectoryPrx node = DirectoryPrxHelper.uncheckedCast(a.add(this, _id)); - if(_parent != null) - { - _parent.addChild(_name, this); - } - return node; + _contents.remove(name); } - // Add the name-node pair to the _contents map. - - public void - addChild(String name, NodeI node) - { - _contents.put(name, node); - } - - // Add this directory and the name of a deleted entry to the reap map. - - public void - addReapEntry(String name) - { - java.util.List<String> l = _reapMap.get(this); - if(l != null) - { - l.add(name); - } - else - { - l = new java.util.ArrayList<String>(); - l.add(name); - _reapMap.put(this, l); - } - } - - // Remove all names in the reap map from the corresponding directory contents. - - private static void - reap() - { - java.util.Iterator<java.util.Map.Entry<DirectoryI, java.util.List<String> > > i = - _reapMap.entrySet().iterator(); - while(i.hasNext()) - { - java.util.Map.Entry<DirectoryI, java.util.List<String> > e = i.next(); - DirectoryI dir = e.getKey(); - java.util.List<String> l = e.getValue(); - java.util.Iterator<String> j = l.iterator(); - while(j.hasNext()) - { - dir._contents.remove(j.next()); - } - } - _reapMap.clear(); - } - - public static java.lang.Object _lcMutex = new java.lang.Object(); - private String _name; // Immutable private DirectoryI _parent; // Immutable private Identity _id; // Immutable private boolean _destroyed; private java.util.Map<String, NodeI> _contents; - - private static java.util.Map<DirectoryI, java.util.List<String> > _reapMap = - new java.util.HashMap<DirectoryI, java.util.List<String> >(); } diff --git a/java/demo/book/lifecycle/FilesystemI/FileI.java b/java/demo/book/lifecycle/FilesystemI/FileI.java index 0994fdc6e8f..4bc98683b12 100644 --- a/java/demo/book/lifecycle/FilesystemI/FileI.java +++ b/java/demo/book/lifecycle/FilesystemI/FileI.java @@ -13,7 +13,7 @@ import Ice.*; import Filesystem.*; import FilesystemI.*; -public class FileI extends _FileDisp implements NodeI, _FileOperations +public class FileI extends _FileDisp implements NodeI { public synchronized String name(Current c) @@ -62,14 +62,12 @@ public class FileI extends _FileDisp implements NodeI, _FileOperations { throw new ObjectNotExistException(); } - _destroyed = true; - } - synchronized(_parent._lcMutex) - { c.adapter.remove(id()); - _parent.addReapEntry(_name); + _destroyed = true; } + + _parent.removeEntry(_name); } public FileI(String name, DirectoryI parent) @@ -81,14 +79,6 @@ public class FileI extends _FileDisp implements NodeI, _FileOperations _id.name = java.util.UUID.randomUUID().toString(); } - public FilePrx - activate(Ice.ObjectAdapter a) - { - FilePrx node = FilePrxHelper.uncheckedCast(a.add(this, _id)); - _parent.addChild(_name, this); - return node; - } - private String _name; private DirectoryI _parent; private boolean _destroyed; diff --git a/java/demo/book/lifecycle/Parser.java b/java/demo/book/lifecycle/Parser.java index 3bf9e0965dd..96800a88040 100644 --- a/java/demo/book/lifecycle/Parser.java +++ b/java/demo/book/lifecycle/Parser.java @@ -50,7 +50,7 @@ class Parser void list(Filesystem.DirectoryPrx dir, boolean recursive, int depth) { - StringBuffer b = new StringBuffer(); + StringBuilder b = new StringBuilder(); for(int i = 0; i < depth; ++i) { b.append('\t'); diff --git a/java/demo/book/lifecycle/Scanner.java b/java/demo/book/lifecycle/Scanner.java index 3283176018d..c4c695fcd8b 100644 --- a/java/demo/book/lifecycle/Scanner.java +++ b/java/demo/book/lifecycle/Scanner.java @@ -151,7 +151,7 @@ class Scanner return null; } - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(128); if(c == ';' || c == '\n') { diff --git a/java/demo/book/lifecycle/Server.java b/java/demo/book/lifecycle/Server.java index afa26093a42..6e3286ebafb 100644 --- a/java/demo/book/lifecycle/Server.java +++ b/java/demo/book/lifecycle/Server.java @@ -27,15 +27,17 @@ class Server extends Ice.Application // Create the root directory. // DirectoryI root = new DirectoryI(); - root.activate(adapter); + Ice.Identity id = new Ice.Identity(); + id.name = "RootDir"; + adapter.add(root, id); // All objects are created, allow client requests now. // adapter.activate(); - // // Wait until we are done. + // communicator().waitForShutdown(); if(interrupted()) { diff --git a/java/demo/book/simple_filesystem/Filesystem/DirectoryI.java b/java/demo/book/simple_filesystem/Filesystem/DirectoryI.java index 5b7ee2e8668..f52f8f28a38 100644 --- a/java/demo/book/simple_filesystem/Filesystem/DirectoryI.java +++ b/java/demo/book/simple_filesystem/Filesystem/DirectoryI.java @@ -21,7 +21,8 @@ public final class DirectoryI extends _DirectoryDisp // Create an identity. The root directory has the fixed identity "RootDir" // - _id = communicator.stringToIdentity(_parent != null ? java.util.UUID.randomUUID().toString() : "RootDir"); + _id = new Ice.Identity(); + _id.name = _parent != null ? java.util.UUID.randomUUID().toString() : "RootDir"; } diff --git a/java/demo/book/simple_filesystem/Filesystem/FileI.java b/java/demo/book/simple_filesystem/Filesystem/FileI.java index a90f681be86..69bb0684363 100644 --- a/java/demo/book/simple_filesystem/Filesystem/FileI.java +++ b/java/demo/book/simple_filesystem/Filesystem/FileI.java @@ -23,7 +23,8 @@ public class FileI extends _FileDisp // Create an identity // - _id = communicator.stringToIdentity(java.util.UUID.randomUUID().toString()); + _id = new Ice.Identity(); + _id.name = java.util.UUID.randomUUID().toString(); } // Slice Node::name() operation 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); } } } diff --git a/java/test/Freeze/complex/Parser.java b/java/test/Freeze/complex/Parser.java index c654fa371e6..8f4f7e4ec4d 100644 --- a/java/test/Freeze/complex/Parser.java +++ b/java/test/Freeze/complex/Parser.java @@ -128,7 +128,7 @@ public class Parser return; } - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(128); // // Get the next character diff --git a/java/test/Freeze/complex/run.py b/java/test/Freeze/complex/run.py index f293046a8fb..6ebf89e573f 100755 --- a/java/test/Freeze/complex/run.py +++ b/java/test/Freeze/complex/run.py @@ -29,13 +29,15 @@ dbdir = os.path.join(os.getcwd(), "db") TestUtil.cleanDbDir(dbdir) print "starting populate...", -populateProc = TestUtil.startClient("Client", " --dbdir %s populate" % os.getcwd()) +populateProc = TestUtil.startClient("Client", " --dbdir %s populate" % os.getcwd(), startReader = False) print "ok" +populateProc.startReader() populateProc.waitTestSuccess() print "starting verification client...", -clientProc = TestUtil.startClient("Client", " --dbdir %s validate" % os.getcwd()) +clientProc = TestUtil.startClient("Client", " --dbdir %s validate" % os.getcwd(), startReader = False) print "ok" +clientProc.startReader() clientProc.waitTestSuccess() diff --git a/java/test/Freeze/dbmap/build.xml b/java/test/Freeze/dbmap/build.xml index 70870f6f315..30167c9d4fe 100644 --- a/java/test/Freeze/dbmap/build.xml +++ b/java/test/Freeze/dbmap/build.xml @@ -56,7 +56,11 @@ <target name="compile" depends="generate"> <mkdir dir="${class.dir}"/> <javac srcdir="${generated.dir}" destdir="${class.dir}" - classpathref="ice.classpath" debug="${debug}"> + debug="${debug}"> + <classpath> + <path refid="ice.classpath"/> + <path refid="db.classpath"/> + </classpath> <compilerarg value="${javac.lint}"/> </javac> <javac srcdir="." destdir="${class.dir}" diff --git a/java/test/Freeze/dbmap/run.py b/java/test/Freeze/dbmap/run.py index 9b242c82d04..045d0e62c99 100755 --- a/java/test/Freeze/dbmap/run.py +++ b/java/test/Freeze/dbmap/run.py @@ -26,6 +26,7 @@ dbdir = os.path.join(os.getcwd(), "db") TestUtil.cleanDbDir(dbdir) print "starting client...", -clientProc = TestUtil.startClient("Client", os.getcwd()) +clientProc = TestUtil.startClient("Client", os.getcwd(), startReader = False) print "ok" +clientProc.startReader() clientProc.waitTestSuccess() diff --git a/java/test/Freeze/evictor/build.xml b/java/test/Freeze/evictor/build.xml index 10713da3f3b..6a3c9920197 100644 --- a/java/test/Freeze/evictor/build.xml +++ b/java/test/Freeze/evictor/build.xml @@ -36,7 +36,11 @@ <compilerarg value="${javac.lint}"/> </javac> <javac srcdir="." destdir="${class.dir}" - classpathref="ice.classpath" excludes="generated/**" debug="${debug}"> + excludes="generated/**" debug="${debug}"> + <classpath> + <path refid="ice.classpath"/> + <path refid="db.classpath"/> + </classpath> <compilerarg value="${javac.lint}"/> </javac> </target> diff --git a/java/test/Freeze/oldevictor/build.xml b/java/test/Freeze/oldevictor/build.xml index 38aae918d72..8245ff30d17 100644 --- a/java/test/Freeze/oldevictor/build.xml +++ b/java/test/Freeze/oldevictor/build.xml @@ -33,7 +33,11 @@ <compilerarg value="${javac.lint}"/> </javac> <javac srcdir="." destdir="${class.dir}" - classpathref="ice.classpath" excludes="generated/**" debug="${debug}"> + excludes="generated/**" debug="${debug}"> + <classpath> + <path refid="ice.classpath"/> + <path refid="db.classpath"/> + </classpath> <compilerarg value="${javac.lint}"/> </javac> </target> diff --git a/java/test/Ice/background/AllTests.java b/java/test/Ice/background/AllTests.java index 737f792c8d0..2c58e1a2ab6 100644 --- a/java/test/Ice/background/AllTests.java +++ b/java/test/Ice/background/AllTests.java @@ -229,13 +229,13 @@ public class AllTests public static Test.BackgroundPrx allTests(Ice.Communicator communicator, java.io.PrintStream out) { - String sref = "background:default -p 12010 -t 10000"; + String sref = "background:default -p 12010 -t 20000"; Ice.ObjectPrx obj = communicator.stringToProxy(sref); test(obj != null); BackgroundPrx background = BackgroundPrxHelper.uncheckedCast(obj); - sref = "backgroundController:tcp -p 12011 -t 10000"; + sref = "backgroundController:tcp -p 12011 -t 20000"; obj = communicator.stringToProxy(sref); test(obj != null); diff --git a/java/test/Ice/background/Connector.java b/java/test/Ice/background/Connector.java index 242d45ea7e4..b737a1400ef 100644 --- a/java/test/Ice/background/Connector.java +++ b/java/test/Ice/background/Connector.java @@ -7,7 +7,7 @@ // // ********************************************************************** -final class Connector implements IceInternal.Connector, java.lang.Comparable +final class Connector implements IceInternal.Connector { public IceInternal.Transceiver connect() @@ -43,18 +43,9 @@ final class Connector implements IceInternal.Connector, java.lang.Comparable _connector = connector; } - // - // 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 - { Connector p = null; try @@ -63,32 +54,17 @@ final class Connector 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 true; } - return _connector.compareTo(p._connector); + return _connector.equals(p._connector); } - protected synchronized void - finalize() - throws Throwable - { - super.finalize(); - } - final private IceInternal.Connector _connector; final private Configuration _configuration; } diff --git a/java/test/Ice/binding/AllTests.java b/java/test/Ice/binding/AllTests.java index 753837e762a..2c9db86d7c8 100644 --- a/java/test/Ice/binding/AllTests.java +++ b/java/test/Ice/binding/AllTests.java @@ -20,6 +20,24 @@ public class AllTests } } + static class NoOpGetAdapterNameCB extends AMI_TestIntf_getAdapterName + { + public + void ice_response(String name) + { + } + + public void + ice_exception(Ice.LocalException ex) + { + } + + public void + ice_exception(Ice.UserException ex) + { + } + }; + static class GetAdapterNameCB extends AMI_TestIntf_getAdapterName { synchronized public void @@ -229,6 +247,106 @@ public class AllTests } System.out.println("ok"); + System.out.print("testing binding with multiple random endpoints... "); + System.out.flush(); + { + java.util.Random rand = new java.util.Random(); + + RemoteObjectAdapterPrx[] adapters = new RemoteObjectAdapterPrx[5]; + adapters[0] = com.createObjectAdapter("AdapterRandom11", "default"); + adapters[1] = com.createObjectAdapter("AdapterRandom12", "default"); + adapters[2] = com.createObjectAdapter("AdapterRandom13", "default"); + adapters[3] = com.createObjectAdapter("AdapterRandom14", "default"); + adapters[4] = com.createObjectAdapter("AdapterRandom15", "default"); + + int count; + if(System.getProperty("os.name").startsWith("Windows")) + { + count = 20; + } + else + { + count = 60; + } + + int adapterCount = adapters.length; + while(--count > 0) + { + TestIntfPrx[] proxies; + if(System.getProperty("os.name").startsWith("Windows")) + { + if(count == 10) + { + com.deactivateObjectAdapter(adapters[4]); + --adapterCount; + } + proxies = new TestIntfPrx[10]; + } + else + { + if(count < 60 && count % 10 == 0) + { + com.deactivateObjectAdapter(adapters[count / 10 - 1]); + --adapterCount; + } + proxies = new TestIntfPrx[40]; + } + + int i; + for(i = 0; i < proxies.length; ++i) + { + RemoteObjectAdapterPrx[] adpts = new RemoteObjectAdapterPrx[rand.nextInt(adapters.length)]; + if(adpts.length == 0) + { + adpts = new RemoteObjectAdapterPrx[1]; + } + for(int j = 0; j < adpts.length; ++j) + { + adpts[j] = adapters[rand.nextInt(adapters.length)]; + } + proxies[i] = createTestIntfPrx(java.util.Arrays.asList((adpts))); + } + + for(i = 0; i < proxies.length; i++) + { + proxies[i].getAdapterName_async(new NoOpGetAdapterNameCB()); + } + for(i = 0; i < proxies.length; i++) + { + try + { + proxies[i].ice_ping(); + } + catch(Ice.LocalException ex) + { + } + } + + java.util.Set<Ice.Connection> connections = new java.util.HashSet<Ice.Connection>(); + for(i = 0; i < proxies.length; i++) + { + if(proxies[i].ice_getCachedConnection() != null) + { + connections.add(proxies[i].ice_getCachedConnection()); + } + } + test(connections.size() <= adapterCount); + + for(RemoteObjectAdapterPrx a : adapters) + { + try + { + a.getTestIntf().ice_getConnection().close(false); + } + catch(Ice.LocalException ex) + { + // Expected if adapter is down. + } + } + } + } + System.out.println("ok"); + System.out.print("testing binding with multiple endpoints and AMI... "); System.out.flush(); { diff --git a/java/test/Ice/build.xml b/java/test/Ice/build.xml index af5f5fb57bb..6d3c477d5af 100644 --- a/java/test/Ice/build.xml +++ b/java/test/Ice/build.xml @@ -27,6 +27,8 @@ <ant dir="proxyAMD"/> <ant dir="operations"/> <ant dir="operationsAMD"/> + <ant dir="seqMapping"/> + <ant dir="seqMappingAMD"/> <ant dir="slicing"/> <ant dir="custom"/> <ant dir="translator"/> @@ -39,6 +41,7 @@ <ant dir="servantLocatorAMD"/> <ant dir="interceptor"/> <ant dir="udp"/> + <ant dir="serialize"/> </target> <target name="clean"> @@ -57,6 +60,8 @@ <ant dir="proxyAMD" target="clean"/> <ant dir="operations" target="clean"/> <ant dir="operationsAMD" target="clean"/> + <ant dir="seqMapping" target="clean"/> + <ant dir="seqMappingAMD" target="clean"/> <ant dir="slicing" target="clean"/> <ant dir="custom" target="clean"/> <ant dir="translator" target="clean"/> @@ -69,6 +74,7 @@ <ant dir="servantLocatorAMD" target="clean"/> <ant dir="interceptor" target="clean"/> <ant dir="udp" target="clean"/> + <ant dir="serialize" target="clean"/> </target> </project> diff --git a/java/test/Ice/faultTolerance/run.py b/java/test/Ice/faultTolerance/run.py index 19eae076894..f6938cbae86 100755 --- a/java/test/Ice/faultTolerance/run.py +++ b/java/test/Ice/faultTolerance/run.py @@ -35,8 +35,9 @@ ports = "" for i in range(0, num): ports = "%s %d" % (ports, base + i) print "starting client...", -clientProc = TestUtil.startClient("Client", ports) +clientProc = TestUtil.startClient("Client", ports, startReader = False) print "ok" +clientProc.startReader() clientProc.waitTestSuccess() for p in serverProc: diff --git a/java/test/Ice/interceptor/run.py b/java/test/Ice/interceptor/run.py index bd197e05b8f..e47acfdef1e 100755 --- a/java/test/Ice/interceptor/run.py +++ b/java/test/Ice/interceptor/run.py @@ -23,7 +23,8 @@ from scripts import * TestUtil.addClasspath(os.path.join(os.getcwd(), "classes")) print "starting client...", -clientProc = TestUtil.startClient("Client", "--Ice.Warn.Dispatch=0") +clientProc = TestUtil.startClient("Client", "--Ice.Warn.Dispatch=0", startReader = False) print "ok" +clientProc.startReader() clientProc.waitTestSuccess() diff --git a/java/test/Ice/location/AllTests.java b/java/test/Ice/location/AllTests.java index 13257baffec..74082fe0a85 100644 --- a/java/test/Ice/location/AllTests.java +++ b/java/test/Ice/location/AllTests.java @@ -111,6 +111,7 @@ public class AllTests } catch(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } System.out.println("ok"); @@ -126,6 +127,7 @@ public class AllTests } catch(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } System.out.println("ok"); @@ -141,6 +143,7 @@ public class AllTests } catch(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } try @@ -150,6 +153,7 @@ public class AllTests } catch(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } obj.shutdown(); @@ -161,6 +165,7 @@ public class AllTests } catch(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } try @@ -170,6 +175,7 @@ public class AllTests } catch(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } obj.shutdown(); @@ -181,6 +187,7 @@ public class AllTests } catch(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } obj.shutdown(); @@ -192,6 +199,7 @@ public class AllTests } catch(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } obj.shutdown(); @@ -203,6 +211,7 @@ public class AllTests } catch(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } @@ -310,6 +319,7 @@ public class AllTests public void ice_exception(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } @@ -320,7 +330,12 @@ public class AllTests }; hello.sayHello_async(new AMICallback()); } - test(locator.getRequestCount() > count && locator.getRequestCount() < count + 500); + hello.ice_ping(); + test(locator.getRequestCount() > count && locator.getRequestCount() < count + 999); + if(locator.getRequestCount() > count + 800) + { + System.out.print("queuing = " + (locator.getRequestCount() - count)); + } count = locator.getRequestCount(); hello = (HelloPrx)hello.ice_adapterId("unknown"); for(int i = 0; i < 1000; i++) @@ -341,7 +356,20 @@ public class AllTests }; hello.sayHello_async(new AMICallback()); } - test(locator.getRequestCount() > count && locator.getRequestCount() < count + 500); + try + { + hello.ice_ping(); + test(false); + } + catch(Ice.NotRegisteredException ex) + { + } + // We need to take into account the retries. + test(locator.getRequestCount() > count && locator.getRequestCount() < count + 1999); + if(locator.getRequestCount() > count + 800) + { + System.out.print("queuing = " + (locator.getRequestCount() - count)); + } System.out.println("ok"); System.out.print("testing adapter locator cache... "); @@ -383,6 +411,7 @@ public class AllTests } catch(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } @@ -418,6 +447,7 @@ public class AllTests } catch(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } System.out.println("ok"); @@ -471,6 +501,7 @@ public class AllTests } catch(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } @@ -490,6 +521,7 @@ public class AllTests } catch(Ice.LocalException ex) { + ex.printStackTrace(); test(false); } @@ -574,8 +606,8 @@ public class AllTests { } registry.addObject(communicator.stringToProxy("test3:tcp")); - ic.stringToProxy("test@TestAdapter5").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout. - ic.stringToProxy("test3").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout. + ic.stringToProxy("test@TestAdapter5").ice_locatorCacheTimeout(10).ice_ping(); // 10s timeout. + ic.stringToProxy("test3").ice_locatorCacheTimeout(10).ice_ping(); // 10s timeout. test(count == locator.getRequestCount()); try { diff --git a/java/test/Ice/location/ServerLocator.java b/java/test/Ice/location/ServerLocator.java index 644af6227dc..edea41c35f6 100644 --- a/java/test/Ice/location/ServerLocator.java +++ b/java/test/Ice/location/ServerLocator.java @@ -22,6 +22,15 @@ public class ServerLocator extends Test._TestLocatorDisp throws Ice.AdapterNotFoundException { ++_requestCount; + // We add a small delay to make sure locator request queuing gets tested when + // running the test on a fast machine + try + { + Thread.sleep(1); + } + catch(java.lang.InterruptedException ex) + { + } response.ice_response(_registry.getAdapter(adapter)); } @@ -30,6 +39,15 @@ public class ServerLocator extends Test._TestLocatorDisp throws Ice.ObjectNotFoundException { ++_requestCount; + // We add a small delay to make sure locator request queuing gets tested when + // running the test on a fast machine + try + { + Thread.sleep(1); + } + catch(java.lang.InterruptedException ex) + { + } response.ice_response(_registry.getObject(id)); } diff --git a/java/test/Ice/location/ServerManagerI.java b/java/test/Ice/location/ServerManagerI.java index 197b8abbe42..f1936dfe3be 100644 --- a/java/test/Ice/location/ServerManagerI.java +++ b/java/test/Ice/location/ServerManagerI.java @@ -1,3 +1,4 @@ + // ********************************************************************** // // Copyright (c) 2003-2009 ZeroC, Inc. All rights reserved. @@ -17,11 +18,9 @@ public class ServerManagerI extends _ServerManagerDisp _registry = registry; _communicators = new java.util.ArrayList<Ice.Communicator>(); _initData = initData; - - _initData.properties.setProperty("TestAdapter.Endpoints", "default"); + _initData.properties.setProperty("TestAdapter.AdapterId", "TestAdapter"); _initData.properties.setProperty("TestAdapter.ReplicaGroupId", "ReplicatedAdapter"); - _initData.properties.setProperty("TestAdapter2.Endpoints", "default"); _initData.properties.setProperty("TestAdapter2.AdapterId", "TestAdapter2"); } @@ -48,8 +47,14 @@ public class ServerManagerI extends _ServerManagerDisp Ice.Communicator serverCommunicator = Ice.Util.initialize(_initData); _communicators.add(serverCommunicator); - Ice.ObjectAdapter adapter = serverCommunicator.createObjectAdapter("TestAdapter"); + // + // Use fixed port to ensure that OA re-activation doesn't re-use previous port from + // another OA (e.g.: TestAdapter2 is re-activated using port of TestAdapter). + // + serverCommunicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p " + _nextPort++); + serverCommunicator.getProperties().setProperty("TestAdapter2.Endpoints", "default -p " + _nextPort++); + Ice.ObjectAdapter adapter = serverCommunicator.createObjectAdapter("TestAdapter"); Ice.ObjectAdapter adapter2 = serverCommunicator.createObjectAdapter("TestAdapter2"); Ice.ObjectPrx locator = serverCommunicator.stringToProxy("locator:default -p 12010 -t 30000"); @@ -80,4 +85,5 @@ public class ServerManagerI extends _ServerManagerDisp private ServerLocatorRegistry _registry; private java.util.List<Ice.Communicator> _communicators; private Ice.InitializationData _initData; + private int _nextPort = 12011; } diff --git a/java/test/Ice/operations/MyDerivedClassI.java b/java/test/Ice/operations/MyDerivedClassI.java index 13ea6a2c086..025b466dd58 100644 --- a/java/test/Ice/operations/MyDerivedClassI.java +++ b/java/test/Ice/operations/MyDerivedClassI.java @@ -284,6 +284,18 @@ public final class MyDerivedClassI extends Test.MyDerivedClass return r; } + public java.util.Map<Test.MyStruct, Test.MyEnum> + opMyStructMyEnumD(java.util.Map p1, java.util.Map p2, + Test.MyStructMyEnumDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<Test.MyStruct, Test.MyEnum> r = new java.util.HashMap<Test.MyStruct, Test.MyEnum>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + public int[] opIntS(int[] s, Ice.Current current) { diff --git a/java/test/Ice/operations/Test.ice b/java/test/Ice/operations/Test.ice index 447b3c8b17b..ea771c12ff3 100644 --- a/java/test/Ice/operations/Test.ice +++ b/java/test/Ice/operations/Test.ice @@ -60,11 +60,18 @@ sequence<MyClassS> MyClassSS; sequence<StringSS> StringSSS; +struct MyStruct +{ + int i; + int j; +}; + dictionary<byte, bool> ByteBoolD; dictionary<short, int> ShortIntD; dictionary<long, float> LongFloatD; dictionary<string, string> StringStringD; dictionary<string, MyEnum> StringMyEnumD; +dictionary<MyStruct, MyEnum> MyStructMyEnumD; ["ami"] class MyClass { @@ -143,6 +150,9 @@ dictionary<string, MyEnum> StringMyEnumD; StringMyEnumD opStringMyEnumD(StringMyEnumD p1, StringMyEnumD p2, out StringMyEnumD p3); + MyStructMyEnumD opMyStructMyEnumD(MyStructMyEnumD p1, MyStructMyEnumD p2, + out MyStructMyEnumD p3); + IntS opIntS(IntS s); void opByteSOneway(ByteS s); diff --git a/java/test/Ice/operations/Twoways.java b/java/test/Ice/operations/Twoways.java index fe316198d93..dff64d1eabd 100644 --- a/java/test/Ice/operations/Twoways.java +++ b/java/test/Ice/operations/Twoways.java @@ -599,6 +599,31 @@ class Twoways } { + Test.MyStruct s11 = new Test.MyStruct(1, 1); + Test.MyStruct s12 = new Test.MyStruct(1, 2); + java.util.Map<Test.MyStruct, Test.MyEnum> di1 = new java.util.HashMap<Test.MyStruct, Test.MyEnum>(); + di1.put(s11, Test.MyEnum.enum1); + di1.put(s12, Test.MyEnum.enum2); + + Test.MyStruct s22 = new Test.MyStruct(2, 2); + Test.MyStruct s23 = new Test.MyStruct(2, 3); + java.util.Map<Test.MyStruct, Test.MyEnum> di2 = new java.util.HashMap<Test.MyStruct, Test.MyEnum>(); + di2.put(s11, Test.MyEnum.enum1); + di2.put(s22, Test.MyEnum.enum3); + di2.put(s23, Test.MyEnum.enum2); + + Test.MyStructMyEnumDHolder _do = new Test.MyStructMyEnumDHolder(); + java.util.Map<Test.MyStruct, Test.MyEnum> ro = p.opMyStructMyEnumD(di1, di2, _do); + + test(_do.value.equals(di1)); + test(ro.size() == 4); + test(ro.get(s11) == Test.MyEnum.enum1); + test(ro.get(s12) == Test.MyEnum.enum2); + test(ro.get(s22) == Test.MyEnum.enum3); + test(ro.get(s23) == Test.MyEnum.enum2); + } + + { int[] lengths = { 0, 1, 2, 126, 127, 128, 129, 253, 254, 255, 256, 257, 1000 }; for(int l = 0; l < lengths.length; ++l) diff --git a/java/test/Ice/operations/TwowaysAMI.java b/java/test/Ice/operations/TwowaysAMI.java index 2aa9ed11b7d..600f7a31242 100644 --- a/java/test/Ice/operations/TwowaysAMI.java +++ b/java/test/Ice/operations/TwowaysAMI.java @@ -949,6 +949,45 @@ class TwowaysAMI private Callback callback = new Callback(); } + private static class AMI_MyClass_opMyStructMyEnumDI extends Test.AMI_MyClass_opMyStructMyEnumD + { + public void + ice_response(java.util.Map _ro, java.util.Map __do) + { + // TODO: Fix the parameters and remove the casts below when the Java2 mapping is removed. + Test.MyStruct s11 = new Test.MyStruct(1, 1); + Test.MyStruct s12 = new Test.MyStruct(1, 2); + java.util.Map<Test.MyStruct, Test.MyEnum> ro = (java.util.Map<Test.MyStruct, Test.MyEnum>)_ro; + java.util.Map<Test.MyStruct, Test.MyEnum> _do = (java.util.Map<Test.MyStruct, Test.MyEnum>)__do; + java.util.Map<Test.MyStruct, Test.MyEnum> di1 = new java.util.HashMap<Test.MyStruct, Test.MyEnum>(); + di1.put(s11, Test.MyEnum.enum1); + di1.put(s12, Test.MyEnum.enum2); + test(_do.equals(di1)); + Test.MyStruct s22 = new Test.MyStruct(2, 2); + Test.MyStruct s23 = new Test.MyStruct(2, 3); + test(ro.size() == 4); + test(ro.get(s11) == Test.MyEnum.enum1); + test(ro.get(s12) == Test.MyEnum.enum2); + test(ro.get(s22) == Test.MyEnum.enum3); + test(ro.get(s23) == Test.MyEnum.enum2); + callback.called(); + } + + public void + ice_exception(Ice.LocalException ex) + { + test(false); + } + + public boolean + check() + { + return callback.check(); + } + + private Callback callback = new Callback(); + } + private static class AMI_MyClass_opIntSI extends Test.AMI_MyClass_opIntS { AMI_MyClass_opIntSI(int l) @@ -1441,6 +1480,24 @@ class TwowaysAMI } { + Test.MyStruct s11 = new Test.MyStruct(1, 1); + Test.MyStruct s12 = new Test.MyStruct(1, 2); + java.util.Map<Test.MyStruct, Test.MyEnum> di1 = new java.util.HashMap<Test.MyStruct, Test.MyEnum>(); + di1.put(s11, Test.MyEnum.enum1); + di1.put(s12, Test.MyEnum.enum2); + Test.MyStruct s22 = new Test.MyStruct(2, 2); + Test.MyStruct s23 = new Test.MyStruct(2, 3); + java.util.Map<Test.MyStruct, Test.MyEnum> di2 = new java.util.HashMap<Test.MyStruct, Test.MyEnum>(); + di2.put(s11, Test.MyEnum.enum1); + di2.put(s22, Test.MyEnum.enum3); + di2.put(s23, Test.MyEnum.enum2); + + AMI_MyClass_opMyStructMyEnumDI cb = new AMI_MyClass_opMyStructMyEnumDI(); + p.opMyStructMyEnumD_async(cb, di1, di2); + test(cb.check()); + } + + { int[] lengths = { 0, 1, 2, 126, 127, 128, 129, 253, 254, 255, 256, 257, 1000 }; for(int l = 0; l < lengths.length; ++l) diff --git a/java/test/Ice/operationsAMD/MyDerivedClassI.java b/java/test/Ice/operationsAMD/MyDerivedClassI.java index 8a56485e129..d787e41965f 100644 --- a/java/test/Ice/operationsAMD/MyDerivedClassI.java +++ b/java/test/Ice/operationsAMD/MyDerivedClassI.java @@ -322,6 +322,18 @@ public final class MyDerivedClassI extends Test.MyDerivedClass } public void + opMyStructMyEnumD_async(Test.AMD_MyClass_opMyStructMyEnumD cb, + java.util.Map p1, java.util.Map p2, + Ice.Current current) + { + java.util.Map<Test.MyStruct, Test.MyEnum> p3 = p1; + java.util.Map<Test.MyStruct, Test.MyEnum> r = new java.util.HashMap<Test.MyStruct, Test.MyEnum>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + public void opIntS_async(Test.AMD_MyClass_opIntS cb, int[] s, Ice.Current current) { int[] r = new int[s.length]; diff --git a/java/test/Ice/operationsAMD/TestAMD.ice b/java/test/Ice/operationsAMD/TestAMD.ice index 6ad25e0be3c..ae666e15480 100644 --- a/java/test/Ice/operationsAMD/TestAMD.ice +++ b/java/test/Ice/operationsAMD/TestAMD.ice @@ -60,11 +60,18 @@ sequence<MyClassS> MyClassSS; sequence<StringSS> StringSSS; +struct MyStruct +{ + int i; + int j; +}; + dictionary<byte, bool> ByteBoolD; dictionary<short, int> ShortIntD; dictionary<long, float> LongFloatD; dictionary<string, string> StringStringD; dictionary<string, MyEnum> StringMyEnumD; +dictionary<MyStruct, MyEnum> MyStructMyEnumD; ["ami", "amd"] class MyClass { @@ -143,6 +150,9 @@ dictionary<string, MyEnum> StringMyEnumD; StringMyEnumD opStringMyEnumD(StringMyEnumD p1, StringMyEnumD p2, out StringMyEnumD p3); + MyStructMyEnumD opMyStructMyEnumD(MyStructMyEnumD p1, MyStructMyEnumD p2, + out MyStructMyEnumD p3); + IntS opIntS(IntS s); void opByteSOneway(ByteS s); diff --git a/java/test/Ice/protobuf/AllTests.java b/java/test/Ice/protobuf/AllTests.java new file mode 100644 index 00000000000..a5ce93d0fca --- /dev/null +++ b/java/test/Ice/protobuf/AllTests.java @@ -0,0 +1,162 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized boolean + check() + { + while(!_called) + { + try + { + wait(5000); + } + catch(InterruptedException ex) + { + continue; + } + + if(!_called) + { + return false; // Must be timeout. + } + } + + _called = false; + return true; + } + + public synchronized void + called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static class AMI_MyClass_opMessage extends Test.AMI_MyClass_opMessage + { + public void + ice_response(test.TestPB.Message r, test.TestPB.Message o) + { + test(o.getI() == 99); + test(r.getI() == 99); + callback.called(); + } + + public void + ice_exception(Ice.LocalException ex) + { + test(false); + } + + public boolean + check() + { + return callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class AMI_MyClass_opMessageAMD extends Test.AMI_MyClass_opMessageAMD + { + public void + ice_response(test.TestPB.Message r, test.TestPB.Message o) + { + test(o.getI() == 99); + test(r.getI() == 99); + callback.called(); + } + + public void + ice_exception(Ice.LocalException ex) + { + test(false); + } + + public boolean + check() + { + return callback.check(); + } + + private Callback callback = new Callback(); + } + + public static Test.MyClassPrx + allTests(Ice.Communicator communicator, boolean collocated) + { + String ref = "test:default -p 12010 -t 10000"; + Ice.ObjectPrx baseProxy = communicator.stringToProxy(ref); + Test.MyClassPrx cl = Test.MyClassPrxHelper.checkedCast(baseProxy); + + System.out.print("testing twoway operations... "); + { + test.TestPB.Message i = test.TestPB.Message.newBuilder().setI(99).build(); + Ice.Holder<test.TestPB.Message> o = new Ice.Holder<test.TestPB.Message>(); + test.TestPB.Message r; + + r = cl.opMessage(i, o); + + test(o.value.getI() == 99); + test(r.getI() == 99); + } + { + test.TestPB.Message i = test.TestPB.Message.newBuilder().setI(99).build(); + Ice.Holder<test.TestPB.Message> o = new Ice.Holder<test.TestPB.Message>(); + test.TestPB.Message r; + + r = cl.opMessageAMD(i, o); + + test(o.value.getI() == 99); + test(r.getI() == 99); + } + System.out.println("ok"); + + System.out.print("testing twoway AMI operations... "); + { + test.TestPB.Message i = test.TestPB.Message.newBuilder().setI(99).build(); + + AMI_MyClass_opMessage cb = new AMI_MyClass_opMessage(); + cl.opMessage_async(cb, i); + test(cb.check()); + } + { + test.TestPB.Message i = test.TestPB.Message.newBuilder().setI(99).build(); + + AMI_MyClass_opMessageAMD cb = new AMI_MyClass_opMessageAMD(); + cl.opMessageAMD_async(cb, i); + test(cb.check()); + } + System.out.println("ok"); + + return cl; + } +} diff --git a/java/test/Ice/protobuf/Client.java b/java/test/Ice/protobuf/Client.java new file mode 100644 index 00000000000..9381242aacf --- /dev/null +++ b/java/test/Ice/protobuf/Client.java @@ -0,0 +1,53 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +public class Client +{ + private static int + run(String[] args, Ice.Communicator communicator) + { + Test.MyClassPrx myClass = AllTests.allTests(communicator, false); + myClass.shutdown(); + return 0; + } + + public static void + main(String[] args) + { + int status = 0; + Ice.Communicator communicator = null; + + try + { + communicator = Ice.Util.initialize(args); + status = run(args, communicator); + } + catch(Exception ex) + { + ex.printStackTrace(); + status = 1; + } + + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + status = 1; + } + } + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/Ice/protobuf/Collocated.java b/java/test/Ice/protobuf/Collocated.java new file mode 100644 index 00000000000..64843c27243 --- /dev/null +++ b/java/test/Ice/protobuf/Collocated.java @@ -0,0 +1,57 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +public class Collocated +{ + private static int + run(String[] args, Ice.Communicator communicator) + { + communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010 -t 10000"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new MyClassI(), communicator.stringToIdentity("test")); + adapter.activate(); + + AllTests.allTests(communicator, true); + + return 0; + } + + public static void + main(String[] args) + { + int status = 0; + Ice.Communicator communicator = null; + + try + { + communicator = Ice.Util.initialize(args); + status = run(args, communicator); + } + catch(Exception ex) + { + ex.printStackTrace(); + status = 1; + } + + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + status = 1; + } + } + + System.exit(status); + } +} diff --git a/java/test/Ice/protobuf/MyClassI.java b/java/test/Ice/protobuf/MyClassI.java new file mode 100644 index 00000000000..29e637d532b --- /dev/null +++ b/java/test/Ice/protobuf/MyClassI.java @@ -0,0 +1,37 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +public final class MyClassI extends Test.MyClass +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + public test.TestPB.Message opMessage(test.TestPB.Message i, Ice.Holder<test.TestPB.Message> o, Ice.Current current) + { + o.value = i; + return i; + } + + public void opMessageAMD_async(Test.AMD_MyClass_opMessageAMD amdCB, test.TestPB.Message i, Ice.Current current) + { + amdCB.ice_response(i, i); + } +} diff --git a/java/test/Ice/protobuf/Server.java b/java/test/Ice/protobuf/Server.java new file mode 100644 index 00000000000..e77a401ddca --- /dev/null +++ b/java/test/Ice/protobuf/Server.java @@ -0,0 +1,57 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +public class Server +{ + private static int + run(String[] args, Ice.Communicator communicator) + { + communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new MyClassI(), communicator.stringToIdentity("test")); + adapter.activate(); + + communicator.waitForShutdown(); + return 0; + } + + public static void + main(String[] args) + { + int status = 0; + Ice.Communicator communicator = null; + + try + { + communicator = Ice.Util.initialize(args); + status = run(args, communicator); + } + catch(Exception ex) + { + ex.printStackTrace(); + status = 1; + } + + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + status = 1; + } + } + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/Ice/protobuf/Test.ice b/java/test/Ice/protobuf/Test.ice new file mode 100644 index 00000000000..f30fca97b31 --- /dev/null +++ b/java/test/Ice/protobuf/Test.ice @@ -0,0 +1,54 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +#ifndef TEST_ICE +#define TEST_ICE + +module Test +{ + +["java:protobuf:test.TestPB.Message"] sequence<byte> Message; + +["ami"] class MyClass +{ + void shutdown(); + + Message opMessage(Message i, out Message o); + + ["amd"] Message opMessageAMD(Message i, out Message o); +}; + +// Remaining type definitions are there to verify that the generated +// code compiles correctly. + +sequence<Message> SLS; +sequence<SLS> SLSS; +dictionary<int, Message> SLD; +dictionary<int, SLS> SLSD; +struct Foo +{ + Message SLmem; + SLS SLSmem; +}; + +exception Bar +{ + Message SLmem; + SLS SLSmem; +}; + +class Baz +{ + Message SLmem; + SLS SLSmem; +}; + +}; + +#endif diff --git a/java/test/Ice/protobuf/Test.proto b/java/test/Ice/protobuf/Test.proto new file mode 100644 index 00000000000..fea4c801ddd --- /dev/null +++ b/java/test/Ice/protobuf/Test.proto @@ -0,0 +1,16 @@ +// ********************************************************************** +// +// 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 test; + +option java_outer_classname = "TestPB"; + +message Message { + required int32 i = 1; +} diff --git a/java/test/Ice/protobuf/ant/ProtocTask.java b/java/test/Ice/protobuf/ant/ProtocTask.java new file mode 100644 index 00000000000..d1ea695bbb4 --- /dev/null +++ b/java/test/Ice/protobuf/ant/ProtocTask.java @@ -0,0 +1,369 @@ +// ********************************************************************** +// +// 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 Ice.Ant; + +import org.apache.tools.ant.Task; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.DirectoryScanner; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.ant.taskdefs.ExecTask; +import org.apache.tools.ant.taskdefs.Execute; +import org.apache.tools.ant.taskdefs.PumpStreamHandler; +import org.apache.tools.ant.types.Commandline; +import org.apache.tools.ant.types.Commandline.Argument; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.types.Reference; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.StringReader; +import java.io.BufferedReader; +import java.io.BufferedWriter; + +/** + * An ant task for protoc. + * + * Attributes specific to protoc: + * + * translator - The pathname of the translator (default: "protoc"). + * protocpath - The value for the --proto_path translator option. + * outputdir - The value for the --java_out translator option. + * dependencyfile - The file in which dependencies are stored (default: ".pbdepend"). + * + * Example: + * + * <project ...> + * <taskdef name="protoc" classname="ProtocTask" /> + * <property name="protoc.dir" value="../include/protoc"/> + * <target name="generate"> + * <mkdir dir="tags" /> + * <protoc tagdir="tags" outputdir="out"> + * <fileset dir="${protoc.dir}"> + * <include name="*.ice" /> + * </fileset> + * </protoc> + * </target> + * </project> + * + * The <taskdef> element installs the protoctask task. + */ +public class ProtocTask extends org.apache.tools.ant.Task +{ + public + ProtocTask() + { + _translator = null; + _outputDir = null; + _protocPath = null; + _outputDirString = null; + } + + public void + setDependencyFile(File file) + { + _dependencyFile = file; + } + + public void + setOutputdir(File dir) + { + _outputDir = dir; + _outputDirString = _outputDir.toString(); + if(_outputDirString.indexOf(' ') != -1) + { + _outputDirString = '"' + _outputDirString + '"'; + } + } + + public void + setProtocpath(File dir) + { + _protocPath = dir.toString(); + } + + public void + setTranslator(File prog) + { + _translator = prog; + } + + public FileSet + createFileset() + { + FileSet fileset = new FileSet(); + _fileSets.add(fileset); + + return fileset; + } + + public void + execute() + throws BuildException + { + if(_fileSets.isEmpty()) + { + throw new BuildException("No fileset specified"); + } + + // + // Read the set of dependencies for this task. + // + java.util.HashMap dependencies = readDependencies(); + + // + // Compose a list of the files that need to be translated. A + // file needs to translated if we can't find a dependency in + // the dependency table or if its dependency is not up-to-date + // anymore (the proto file changed since the dependency was + // last updated) + // + java.util.Vector buildList = new java.util.Vector(); + java.util.Vector skipList = new java.util.Vector(); + java.util.Iterator p = _fileSets.iterator(); + while(p.hasNext()) + { + FileSet fileset = (FileSet)p.next(); + + DirectoryScanner scanner = fileset.getDirectoryScanner(getProject()); + scanner.scan(); + String[] files = scanner.getIncludedFiles(); + for(int i = 0; i < files.length; i++) + { + File proto = new File(fileset.getDir(getProject()), files[i]); + + ProtoDependency depend = (ProtoDependency)dependencies.get(getTargetKey(proto.toString())); + if(depend == null || !depend.isUpToDate()) + { + buildList.addElement(proto); + } + else + { + skipList.addElement(proto); + } + } + + java.util.Iterator i = skipList.iterator(); + while(i.hasNext()) + { + File file = (File)i.next(); + log("skipping " + file.getName()); + } + } + + // + // Run the translator + // + if(!buildList.isEmpty()) + { + String translator; + if(_translator == null) + { + translator = "protoc"; + } + else + { + translator = _translator.toString(); + } + + StringBuilder cmd = new StringBuilder(128); + + // + // Add --java_out. + // + if(_outputDir != null) + { + cmd.append(" --java_out="); + cmd.append(stripDriveLetter(_outputDirString)); + } + + // + // Add --proto_path + // + if(_protocPath != null) + { + cmd.append(" --proto_path="); + cmd.append(stripDriveLetter(_protocPath)); + } + + // + // Add files to be translated + // + for(int i = 0; i < buildList.size(); i++) + { + File f = (File)buildList.elementAt(i); + cmd.append(" "); + String s = stripDriveLetter(f.toString()); + if(s.indexOf(' ') != -1) + { + cmd.append('"'); + cmd.append(s); + cmd.append('"'); + } + else + { + cmd.append(s); + } + } + + // + // Execute + // + log(translator + " " + cmd); + ExecTask task = (ExecTask)getProject().createTask("exec"); + task.setFailonerror(true); + Argument arg = task.createArg(); + arg.setLine(cmd.toString()); + task.setExecutable(translator); + task.execute(); + + // + // Update dependency file. + // + for(int i = 0; i < buildList.size(); i++) + { + ProtoDependency depend = new ProtoDependency(); + depend._timeStamp = new java.util.Date().getTime(); + depend._dependency = ((File)buildList.elementAt(i)).toString(); + dependencies.put(getTargetKey(depend._dependency), depend); + } + + writeDependencies(dependencies); + } + } + + private String + getTargetKey(String proto) + { + // + // Since the dependency file can be shared by several proto + // tasks we need to make sure that each dependency has a + // unique key. We use the name of the task, the output + // directory and the name of the proto file to be compiled. + // + // If there's two protoc tasks using the same dependency + // file, with the same output dir and which compiles the same + // protoc file they'll use the same dependency. + // + return "protoc " + _outputDir.toString() + " " + proto; + } + + // This is to work around a bug with protoc, where it does not + // accept drive letters in path names. See + // http://bugzilla/bugzilla/show_bug.cgi?id=3349 + // + private String + stripDriveLetter(String s) + { + if(s.length() > 1 && s.charAt(1) == ':') + { + return s.substring(2); + } + return s; + } + + // + // Read the dependency file. + // + private java.util.HashMap + readDependencies() + { + if(_dependencyFile == null) + { + if(_outputDir != null) + { + _dependencyFile = new File(_outputDir, ".pbdepend"); + } + else + { + _dependencyFile = new File(".pbdepend"); + } + } + + try + { + java.io.ObjectInputStream in = new java.io.ObjectInputStream(new java.io.FileInputStream(_dependencyFile)); + java.util.HashMap dependencies = (java.util.HashMap)in.readObject(); + in.close(); + return dependencies; + } + catch(java.io.IOException ex) + { + } + catch(java.lang.ClassNotFoundException ex) + { + } + + return new java.util.HashMap(); + } + + private void + writeDependencies(java.util.HashMap dependencies) + { + try + { + java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(new FileOutputStream(_dependencyFile)); + out.writeObject(dependencies); + out.close(); + } + catch(java.io.IOException ex) + { + throw new BuildException("Unable to write dependencies in file " + _dependencyFile.getPath() + ": " + ex); + } + } + + // + // A proto dependency. + // + // * the _timeStamp attribute contains the last time the proto + // file was compiled. + // + // * the _dependency attribute contains the .proto file. + // + private class ProtoDependency implements java.io.Serializable + { + private void writeObject(java.io.ObjectOutputStream out) + throws java.io.IOException + { + out.writeObject(_dependency); + out.writeLong(_timeStamp); + } + + private void readObject(java.io.ObjectInputStream in) + throws java.io.IOException, java.lang.ClassNotFoundException + { + _dependency = (String)in.readObject(); + _timeStamp = in.readLong(); + } + + public boolean + isUpToDate() + { + File dep = new File(_dependency); + if(!dep.exists() || _timeStamp < dep.lastModified()) + { + return false; + } + + return true; + } + + public String _dependency; + public long _timeStamp; + } + + private File _translator; + private File _dependencyFile; + private File _outputDir; + private String _outputDirString; + private String _protocPath; + private java.util.List _fileSets = new java.util.LinkedList(); +} diff --git a/java/test/Ice/protobuf/build.xml b/java/test/Ice/protobuf/build.xml new file mode 100644 index 00000000000..8e992925cee --- /dev/null +++ b/java/test/Ice/protobuf/build.xml @@ -0,0 +1,68 @@ +<!-- + ********************************************************************** + + 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. + + ********************************************************************** +--> + +<project name="test_Ice_seqMapping" default="all" basedir="."> + + <!-- set global properties for this build --> + <property name="top.dir" value="../../.."/> + + <!-- import common definitions --> + <import file="${top.dir}/config/common.xml"/> + + <target name="protoc" depends="init"> + <!-- Build protoc task --> + <mkdir dir="${class.dir}"/> + <javac srcdir="ant" destdir="${class.dir}" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> + </target> + + <target name="generate" depends="protoc"> + <!-- Add the protoc task --> + <taskdef name="protoc" classpath="${class.dir}" classname="ProtocTask" /> + <!-- Create the output directory for generated code --> + <mkdir dir="${generated.dir}"/> + <slice2java outputdir="${generated.dir}"> + <meta value="${java2metadata}"/> + <fileset dir="." includes="Test.ice"/> + <includepath> + <pathelement path="${slice.dir}" /> + </includepath> + </slice2java> + <protoc outputdir="${generated.dir}" protocpath="."> + <fileset dir="." includes="Test.proto"/> + </protoc> + </target> + + <target name="compile" depends="generate"> + <mkdir dir="${class.dir}"/> + <javac srcdir="." destdir="${class.dir}" includes="Serialize/**" + classpathref="ice.classpath" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> + <javac srcdir="${generated.dir}" destdir="${class.dir}" + classpathref="ice.classpath" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> + <javac srcdir="." destdir="${class.dir}" + classpathref="ice.classpath" excludes="generated/**,Serialize/**" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> + </target> + + <target name="all" depends="compile"/> + + <target name="clean"> + <delete dir="${generated.dir}"/> + <delete dir="${class.dir}"/> + </target> + +</project> diff --git a/java/test/Ice/protobuf/run.py b/java/test/Ice/protobuf/run.py new file mode 100755 index 00000000000..70bca77e564 --- /dev/null +++ b/java/test/Ice/protobuf/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# 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. +# +# ********************************************************************** + +import os, sys + +path = [ ".", "..", "../..", "../../..", "../../../.." ] +head = os.path.dirname(sys.argv[0]) +if len(head) > 0: + path = [os.path.join(head, p) for p in path] +path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] +if len(path) == 0: + raise "can't find toplevel directory!" +sys.path.append(os.path.join(path[0])) +from scripts import * + +TestUtil.clientServerTest() + diff --git a/java/test/Ice/seqMapping/AllTests.java b/java/test/Ice/seqMapping/AllTests.java new file mode 100644 index 00000000000..e95f38943cc --- /dev/null +++ b/java/test/Ice/seqMapping/AllTests.java @@ -0,0 +1,34 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +public class AllTests +{ + public static Test.MyClassPrx + allTests(Ice.Communicator communicator, boolean collocated) + { + String ref = "test:default -p 12010 -t 10000"; + Ice.ObjectPrx baseProxy = communicator.stringToProxy(ref); + Test.MyClassPrx cl = Test.MyClassPrxHelper.checkedCast(baseProxy); + + System.out.print("testing twoway operations... "); + System.out.flush(); + Twoways.twoways(communicator, cl); + System.out.println("ok"); + + if(!collocated) + { + System.out.print("testing twoway operations with AMI... "); + System.out.flush(); + TwowaysAMI.twowaysAMI(communicator, cl); + System.out.println("ok"); + } + + return cl; + } +} diff --git a/java/test/Ice/seqMapping/Client.java b/java/test/Ice/seqMapping/Client.java new file mode 100644 index 00000000000..dff52ec6dd6 --- /dev/null +++ b/java/test/Ice/seqMapping/Client.java @@ -0,0 +1,58 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +public class Client +{ + private static int + run(String[] args, Ice.Communicator communicator) + { + Test.MyClassPrx myClass = AllTests.allTests(communicator, false); + + System.out.print("shutting down server... "); + System.out.flush(); + myClass.shutdown(); + System.out.println("ok"); + + return 0; + } + + public static void + main(String[] args) + { + int status = 0; + Ice.Communicator communicator = null; + + try + { + communicator = Ice.Util.initialize(args); + status = run(args, communicator); + } + catch(Exception ex) + { + ex.printStackTrace(); + status = 1; + } + + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + status = 1; + } + } + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/Ice/seqMapping/Collocated.java b/java/test/Ice/seqMapping/Collocated.java new file mode 100644 index 00000000000..64843c27243 --- /dev/null +++ b/java/test/Ice/seqMapping/Collocated.java @@ -0,0 +1,57 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +public class Collocated +{ + private static int + run(String[] args, Ice.Communicator communicator) + { + communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010 -t 10000"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new MyClassI(), communicator.stringToIdentity("test")); + adapter.activate(); + + AllTests.allTests(communicator, true); + + return 0; + } + + public static void + main(String[] args) + { + int status = 0; + Ice.Communicator communicator = null; + + try + { + communicator = Ice.Util.initialize(args); + status = run(args, communicator); + } + catch(Exception ex) + { + ex.printStackTrace(); + status = 1; + } + + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + status = 1; + } + } + + System.exit(status); + } +} diff --git a/java/test/Ice/seqMapping/MyClassI.java b/java/test/Ice/seqMapping/MyClassI.java new file mode 100644 index 00000000000..5622e7415d2 --- /dev/null +++ b/java/test/Ice/seqMapping/MyClassI.java @@ -0,0 +1,44 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +public final class MyClassI extends Test.MyClass +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + public Serialize.Small opSerialSmallJava(Serialize.Small i, Ice.Holder<Serialize.Small> o, Ice.Current current) + { + o.value = i; + return i; + } + + public Serialize.Large opSerialLargeJava(Serialize.Large i, Ice.Holder<Serialize.Large> o, Ice.Current current) + { + o.value = i; + return i; + } + + public Serialize.Struct opSerialStructJava(Serialize.Struct i, Ice.Holder<Serialize.Struct> o, Ice.Current current) + { + o.value = i; + return i; + } +} diff --git a/java/test/Ice/seqMapping/Serialize/Large.java b/java/test/Ice/seqMapping/Serialize/Large.java new file mode 100644 index 00000000000..188bbe59fac --- /dev/null +++ b/java/test/Ice/seqMapping/Serialize/Large.java @@ -0,0 +1,24 @@ +// ********************************************************************** +// +// 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 Serialize; + +public class Large implements java.io.Serializable // More than 254 bytes when serialized. +{ + public double d1; + public double d2; + public double d3; + public double d4; + public double d5; + public double d6; + public double d7; + public double d8; + public double d9; + public double d10; +} diff --git a/java/test/Ice/seqMapping/Serialize/Small.java b/java/test/Ice/seqMapping/Serialize/Small.java new file mode 100644 index 00000000000..be92e68edea --- /dev/null +++ b/java/test/Ice/seqMapping/Serialize/Small.java @@ -0,0 +1,15 @@ +// ********************************************************************** +// +// 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 Serialize; + +public class Small implements java.io.Serializable // Fewer than 254 bytes when serialized. +{ + public int i; +} diff --git a/java/test/Ice/seqMapping/Serialize/Struct.java b/java/test/Ice/seqMapping/Serialize/Struct.java new file mode 100644 index 00000000000..c40d95b3c75 --- /dev/null +++ b/java/test/Ice/seqMapping/Serialize/Struct.java @@ -0,0 +1,18 @@ +// ********************************************************************** +// +// 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 Serialize; + +public class Struct implements java.io.Serializable // Used to test that null members marshal correctly. +{ + public Object o; + public Object o2; + public String s; + public String s2; +} diff --git a/java/test/Ice/seqMapping/Server.java b/java/test/Ice/seqMapping/Server.java new file mode 100644 index 00000000000..e77a401ddca --- /dev/null +++ b/java/test/Ice/seqMapping/Server.java @@ -0,0 +1,57 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +public class Server +{ + private static int + run(String[] args, Ice.Communicator communicator) + { + communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new MyClassI(), communicator.stringToIdentity("test")); + adapter.activate(); + + communicator.waitForShutdown(); + return 0; + } + + public static void + main(String[] args) + { + int status = 0; + Ice.Communicator communicator = null; + + try + { + communicator = Ice.Util.initialize(args); + status = run(args, communicator); + } + catch(Exception ex) + { + ex.printStackTrace(); + status = 1; + } + + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + status = 1; + } + } + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/Ice/seqMapping/Test.ice b/java/test/Ice/seqMapping/Test.ice new file mode 100644 index 00000000000..3ffe3a4140b --- /dev/null +++ b/java/test/Ice/seqMapping/Test.ice @@ -0,0 +1,56 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +#ifndef TEST_ICE +#define TEST_ICE + +module Test +{ + +["java:serializable:Serialize.Small"] sequence<byte> SerialSmall; +["java:serializable:Serialize.Large"] sequence<byte> SerialLarge; +["java:serializable:Serialize.Struct"] sequence<byte> SerialStruct; + +["ami"] class MyClass +{ + void shutdown(); + + SerialSmall opSerialSmallJava(SerialSmall i, out SerialSmall o); + SerialLarge opSerialLargeJava(SerialLarge i, out SerialLarge o); + SerialStruct opSerialStructJava(SerialStruct i, out SerialStruct o); +}; + +// Remaining type definitions are there to verify that the generated +// code compiles correctly. + +sequence<SerialLarge> SLS; +sequence<SLS> SLSS; +dictionary<int, SerialLarge> SLD; +dictionary<int, SLS> SLSD; +struct Foo +{ + SerialLarge SLmem; + SLS SLSmem; +}; + +exception Bar +{ + SerialLarge SLmem; + SLS SLSmem; +}; + +class Baz +{ + SerialLarge SLmem; + SLS SLSmem; +}; + +}; + +#endif diff --git a/java/test/Ice/seqMapping/Twoways.java b/java/test/Ice/seqMapping/Twoways.java new file mode 100644 index 00000000000..4e88edaa74d --- /dev/null +++ b/java/test/Ice/seqMapping/Twoways.java @@ -0,0 +1,132 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +class Twoways +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static void + twoways(Ice.Communicator communicator, Test.MyClassPrx p) + { + { + Serialize.Small i = null; + Ice.Holder<Serialize.Small> o = new Ice.Holder<Serialize.Small>(); + Serialize.Small r; + + r = p.opSerialSmallJava(i, o); + + test(o.value == null); + test(r == null); + } + + { + Serialize.Small i = new Serialize.Small(); + i.i = 99; + Ice.Holder<Serialize.Small> o = new Ice.Holder<Serialize.Small>(); + Serialize.Small r; + + try + { + r = p.opSerialSmallJava(i, o); + + test(o.value.i == 99); + test(r.i == 99); + } + catch(Ice.OperationNotExistException ex) + { + // OK, talking to non-Java server. + } + } + + { + Serialize.Large i = new Serialize.Large(); + i.d1 = 1.0; + i.d2 = 2.0; + i.d3 = 3.0; + i.d4 = 4.0; + i.d5 = 5.0; + i.d6 = 6.0; + i.d7 = 7.0; + i.d8 = 8.0; + i.d9 = 9.0; + i.d10 = 10.0; + Ice.Holder<Serialize.Large> o = new Ice.Holder<Serialize.Large>(); + Serialize.Large r; + + try + { + r = p.opSerialLargeJava(i, o); + + test(o.value.d1 == 1.0); + test(o.value.d2 == 2.0); + test(o.value.d3 == 3.0); + test(o.value.d4 == 4.0); + test(o.value.d5 == 5.0); + test(o.value.d6 == 6.0); + test(o.value.d7 == 7.0); + test(o.value.d8 == 8.0); + test(o.value.d9 == 9.0); + test(o.value.d10 == 10.0); + test(r.d1 == 1.0); + test(r.d2 == 2.0); + test(r.d3 == 3.0); + test(r.d4 == 4.0); + test(r.d5 == 5.0); + test(r.d6 == 6.0); + test(r.d7 == 7.0); + test(r.d8 == 8.0); + test(r.d9 == 9.0); + test(r.d10 == 10.0); + } + catch(Ice.OperationNotExistException ex) + { + // OK, talking to non-Java server. + } + } + + { + Serialize.Struct i = new Serialize.Struct(); + i.o = null; + i.o2 = i; + i.s = null; + i.s2 = "Hello"; + Ice.Holder<Serialize.Struct> o = new Ice.Holder<Serialize.Struct>(); + Serialize.Struct r; + + try + { + r = p.opSerialStructJava(i, o); + + test(o.value.o == null); + test(o.value.o2 != null); + test(((Serialize.Struct)(o.value.o2)).o == null); + test(((Serialize.Struct)(o.value.o2)).o2 == o.value.o2); + test(o.value.s == null); + test(o.value.s2.equals("Hello")); + test(r.o == null); + test(r.o2 != null); + test(((Serialize.Struct)(r.o2)).o == null); + test(((Serialize.Struct)(r.o2)).o2 == r.o2); + test(r.s == null); + test(r.s2.equals("Hello")); + } + catch(Ice.OperationNotExistException ex) + { + // OK, talking to non-Java server. + } + } + } +} diff --git a/java/test/Ice/seqMapping/TwowaysAMI.java b/java/test/Ice/seqMapping/TwowaysAMI.java new file mode 100644 index 00000000000..ca3af245cb5 --- /dev/null +++ b/java/test/Ice/seqMapping/TwowaysAMI.java @@ -0,0 +1,241 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +class TwowaysAMI +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized boolean + check() + { + while(!_called) + { + try + { + wait(5000); + } + catch(InterruptedException ex) + { + continue; + } + + if(!_called) + { + return false; // Must be timeout. + } + } + + _called = false; + return true; + } + + public synchronized void + called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static class AMI_MyClass_opSerialSmallJavaNull extends Test.AMI_MyClass_opSerialSmallJava + { + public void + ice_response(Serialize.Small r, Serialize.Small o) + { + test(o == null); + test(r == null); + callback.called(); + } + + public void + ice_exception(Ice.LocalException ex) + { + test(ex instanceof Ice.OperationNotExistException); // OK, talking to non-Java server. + } + + public boolean + check() + { + return callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class AMI_MyClass_opSerialSmallJava extends Test.AMI_MyClass_opSerialSmallJava + { + public void + ice_response(Serialize.Small r, Serialize.Small o) + { + test(o.i == 99); + test(r.i == 99); + callback.called(); + } + + public void + ice_exception(Ice.LocalException ex) + { + test(ex instanceof Ice.OperationNotExistException); // OK, talking to non-Java server. + } + + public boolean + check() + { + return callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class AMI_MyClass_opSerialLargeJava extends Test.AMI_MyClass_opSerialLargeJava + { + public void + ice_response(Serialize.Large r, Serialize.Large o) + { + test(o.d1 == 1.0); + test(o.d2 == 2.0); + test(o.d3 == 3.0); + test(o.d4 == 4.0); + test(o.d5 == 5.0); + test(o.d6 == 6.0); + test(o.d7 == 7.0); + test(o.d8 == 8.0); + test(o.d9 == 9.0); + test(o.d10 == 10.0); + test(r.d1 == 1.0); + test(r.d2 == 2.0); + test(r.d3 == 3.0); + test(r.d4 == 4.0); + test(r.d5 == 5.0); + test(r.d6 == 6.0); + test(r.d7 == 7.0); + test(r.d8 == 8.0); + test(r.d9 == 9.0); + test(r.d10 == 10.0); + callback.called(); + } + + public void + ice_exception(Ice.LocalException ex) + { + test(ex instanceof Ice.OperationNotExistException); // OK, talking to non-Java server. + } + + public boolean + check() + { + return callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class AMI_MyClass_opSerialStructJava extends Test.AMI_MyClass_opSerialStructJava + { + public void + ice_response(Serialize.Struct r, Serialize.Struct o) + { + test(o.o == null); + test(o.o2 != null); + test(((Serialize.Struct)(o.o2)).o == null); + test(((Serialize.Struct)(o.o2)).o2 == o.o2); + test(o.s == null); + test(o.s2.equals("Hello")); + test(r.o == null); + test(r.o2 != null); + test(((Serialize.Struct)(r.o2)).o == null); + test(((Serialize.Struct)(r.o2)).o2 == r.o2); + test(r.s == null); + test(r.s2.equals("Hello")); + callback.called(); + } + + public void + ice_exception(Ice.LocalException ex) + { + test(ex instanceof Ice.OperationNotExistException); // OK, talking to non-Java server. + } + + public boolean + check() + { + return callback.check(); + } + + private Callback callback = new Callback(); + } + + static void + twowaysAMI(Ice.Communicator communicator, Test.MyClassPrx p) + { + { + Serialize.Small i = null; + + AMI_MyClass_opSerialSmallJavaNull cb = new AMI_MyClass_opSerialSmallJavaNull(); + p.opSerialSmallJava_async(cb, i); + test(cb.check()); + } + + { + Serialize.Small i = new Serialize.Small(); + i.i = 99; + + AMI_MyClass_opSerialSmallJava cb = new AMI_MyClass_opSerialSmallJava(); + p.opSerialSmallJava_async(cb, i); + test(cb.check()); + } + + { + Serialize.Large i = new Serialize.Large(); + i.d1 = 1.0; + i.d2 = 2.0; + i.d3 = 3.0; + i.d4 = 4.0; + i.d5 = 5.0; + i.d6 = 6.0; + i.d7 = 7.0; + i.d8 = 8.0; + i.d9 = 9.0; + i.d10 = 10.0; + + AMI_MyClass_opSerialLargeJava cb = new AMI_MyClass_opSerialLargeJava(); + p.opSerialLargeJava_async(cb, i); + test(cb.check()); + } + + { + Serialize.Struct i = new Serialize.Struct(); + i.o = null; + i.o2 = i; + i.s = null; + i.s2 = "Hello"; + + AMI_MyClass_opSerialStructJava cb = new AMI_MyClass_opSerialStructJava(); + p.opSerialStructJava_async(cb, i); + test(cb.check()); + } + } +} diff --git a/java/test/Ice/seqMapping/build.xml b/java/test/Ice/seqMapping/build.xml new file mode 100644 index 00000000000..a12392802de --- /dev/null +++ b/java/test/Ice/seqMapping/build.xml @@ -0,0 +1,55 @@ +<!-- + ********************************************************************** + + 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. + + ********************************************************************** +--> + +<project name="test_Ice_seqMapping" default="all" basedir="."> + + <!-- set global properties for this build --> + <property name="top.dir" value="../../.."/> + + <!-- import common definitions --> + <import file="${top.dir}/config/common.xml"/> + + <target name="generate" depends="init"> + <!-- Create the output directory for generated code --> + <mkdir dir="${generated.dir}"/> + <slice2java outputdir="${generated.dir}"> + <meta value="${java2metadata}"/> + <fileset dir="." includes="Test.ice"/> + <includepath> + <pathelement path="${slice.dir}" /> + </includepath> + </slice2java> + </target> + + <target name="compile" depends="generate"> + <mkdir dir="${class.dir}"/> + <javac srcdir="." destdir="${class.dir}" includes="Serialize/**" + classpathref="ice.classpath" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> + <javac srcdir="${generated.dir}" destdir="${class.dir}" + classpathref="ice.classpath" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> + <javac srcdir="." destdir="${class.dir}" + classpathref="ice.classpath" excludes="generated/**,Serialize/**" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> + </target> + + <target name="all" depends="compile"/> + + <target name="clean"> + <delete dir="${generated.dir}"/> + <delete dir="${class.dir}"/> + </target> + +</project> diff --git a/java/test/Ice/seqMapping/run.py b/java/test/Ice/seqMapping/run.py new file mode 100755 index 00000000000..09d700b9f48 --- /dev/null +++ b/java/test/Ice/seqMapping/run.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# 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. +# +# ********************************************************************** + +import os, sys + +path = [ ".", "..", "../..", "../../..", "../../../.." ] +head = os.path.dirname(sys.argv[0]) +if len(head) > 0: + path = [os.path.join(head, p) for p in path] +path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] +if len(path) == 0: + raise "can't find toplevel directory!" +sys.path.append(os.path.join(path[0])) +from scripts import * + +print "tests with regular server." +TestUtil.clientServerTest() + +print "tests with AMD server." +import copy +amdenv = copy.deepcopy(os.environ) +TestUtil.addClasspath(os.path.join(os.getcwd(), "..", "seqMappingAMD", "classes"), amdenv) +TestUtil.clientServerTest(serverenv = amdenv) + +print "tests with collocated server." +TestUtil.collocatedTest() diff --git a/java/test/Ice/seqMappingAMD/MyClassI.java b/java/test/Ice/seqMappingAMD/MyClassI.java new file mode 100644 index 00000000000..61bbde13d70 --- /dev/null +++ b/java/test/Ice/seqMappingAMD/MyClassI.java @@ -0,0 +1,42 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +public final class MyClassI extends Test.MyClass +{ + public void + shutdown_async(Test.AMD_MyClass_shutdown cb, + Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + cb.ice_response(); + } + + public void + opSerialSmallJava_async(Test.AMD_MyClass_opSerialSmallJava cb, + Serialize.Small i, + Ice.Current current) + { + cb.ice_response(i, i); + } + + public void + opSerialLargeJava_async(Test.AMD_MyClass_opSerialLargeJava cb, + Serialize.Large i, + Ice.Current current) + { + cb.ice_response(i, i); + } + + public void opSerialStructJava_async(Test.AMD_MyClass_opSerialStructJava cb, + Serialize.Struct i, + Ice.Current current) + { + cb.ice_response(i, i); + } +} diff --git a/java/test/Ice/seqMappingAMD/Serialize/Large.java b/java/test/Ice/seqMappingAMD/Serialize/Large.java new file mode 100644 index 00000000000..188bbe59fac --- /dev/null +++ b/java/test/Ice/seqMappingAMD/Serialize/Large.java @@ -0,0 +1,24 @@ +// ********************************************************************** +// +// 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 Serialize; + +public class Large implements java.io.Serializable // More than 254 bytes when serialized. +{ + public double d1; + public double d2; + public double d3; + public double d4; + public double d5; + public double d6; + public double d7; + public double d8; + public double d9; + public double d10; +} diff --git a/java/test/Ice/seqMappingAMD/Serialize/Small.java b/java/test/Ice/seqMappingAMD/Serialize/Small.java new file mode 100644 index 00000000000..be92e68edea --- /dev/null +++ b/java/test/Ice/seqMappingAMD/Serialize/Small.java @@ -0,0 +1,15 @@ +// ********************************************************************** +// +// 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 Serialize; + +public class Small implements java.io.Serializable // Fewer than 254 bytes when serialized. +{ + public int i; +} diff --git a/java/test/Ice/seqMappingAMD/Serialize/SmallHolder.java b/java/test/Ice/seqMappingAMD/Serialize/SmallHolder.java new file mode 100644 index 00000000000..66776ade146 --- /dev/null +++ b/java/test/Ice/seqMappingAMD/Serialize/SmallHolder.java @@ -0,0 +1,15 @@ +// ********************************************************************** +// +// 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 Serialize; + +public class SmallHolder +{ + public Small value; +} diff --git a/java/test/Ice/seqMappingAMD/Serialize/Struct.java b/java/test/Ice/seqMappingAMD/Serialize/Struct.java new file mode 100644 index 00000000000..c40d95b3c75 --- /dev/null +++ b/java/test/Ice/seqMappingAMD/Serialize/Struct.java @@ -0,0 +1,18 @@ +// ********************************************************************** +// +// 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 Serialize; + +public class Struct implements java.io.Serializable // Used to test that null members marshal correctly. +{ + public Object o; + public Object o2; + public String s; + public String s2; +} diff --git a/java/test/Ice/seqMappingAMD/Serialize/StructHolder.java b/java/test/Ice/seqMappingAMD/Serialize/StructHolder.java new file mode 100644 index 00000000000..8bf50b75215 --- /dev/null +++ b/java/test/Ice/seqMappingAMD/Serialize/StructHolder.java @@ -0,0 +1,15 @@ +// ********************************************************************** +// +// 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 Serialize; + +public class StructHolder +{ + public Struct value; +} diff --git a/java/test/Ice/seqMappingAMD/Server.java b/java/test/Ice/seqMappingAMD/Server.java new file mode 100644 index 00000000000..ab531a55a60 --- /dev/null +++ b/java/test/Ice/seqMappingAMD/Server.java @@ -0,0 +1,57 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +public class Server +{ + private static int + run(String[] args, Ice.Communicator communicator) + { + communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010 -t 10000:udp"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new MyClassI(), communicator.stringToIdentity("test")); + adapter.activate(); + + communicator.waitForShutdown(); + return 0; + } + + public static void + main(String[] args) + { + int status = 0; + Ice.Communicator communicator = null; + + try + { + communicator = Ice.Util.initialize(args); + status = run(args, communicator); + } + catch(Exception ex) + { + ex.printStackTrace(); + status = 1; + } + + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + status = 1; + } + } + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/Ice/seqMappingAMD/TestAMD.ice b/java/test/Ice/seqMappingAMD/TestAMD.ice new file mode 100644 index 00000000000..88a987c9eec --- /dev/null +++ b/java/test/Ice/seqMappingAMD/TestAMD.ice @@ -0,0 +1,56 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +#ifndef TEST_ICE +#define TEST_ICE + +module Test +{ + +["java:serializable:Serialize.Small"] sequence<byte> SerialSmall; +["java:serializable:Serialize.Large"] sequence<byte> SerialLarge; +["java:serializable:Serialize.Struct"] sequence<byte> SerialStruct; + +["ami", "amd"] class MyClass +{ + void shutdown(); + + SerialSmall opSerialSmallJava(SerialSmall i, out SerialSmall o); + SerialLarge opSerialLargeJava(SerialLarge i, out SerialLarge o); + SerialStruct opSerialStructJava(SerialStruct i, out SerialStruct o); +}; + +// Remaining type definitions are there to verify that the generated +// code compiles correctly. + +sequence<SerialLarge> SLS; +sequence<SLS> SLSS; +dictionary<int, SerialLarge> SLD; +dictionary<int, SLS> SLSD; +struct Foo +{ + SerialLarge SLmem; + SLS SLSmem; +}; + +exception Bar +{ + SerialLarge SLmem; + SLS SLSmem; +}; + +class Baz +{ + SerialLarge SLmem; + SLS SLSmem; +}; + +}; + +#endif diff --git a/java/test/Ice/seqMappingAMD/build.xml b/java/test/Ice/seqMappingAMD/build.xml new file mode 100644 index 00000000000..e98924112fc --- /dev/null +++ b/java/test/Ice/seqMappingAMD/build.xml @@ -0,0 +1,55 @@ +<!-- + ********************************************************************** + + 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. + + ********************************************************************** +--> + +<project name="test_Ice_seqMappingAMD" default="all" basedir="."> + + <!-- set global properties for this build --> + <property name="top.dir" value="../../.."/> + + <!-- import common definitions --> + <import file="${top.dir}/config/common.xml"/> + + <target name="generate" depends="init"> + <!-- Create the output directory for generated code --> + <mkdir dir="${generated.dir}"/> + <slice2java outputdir="${generated.dir}"> + <meta value="${java2metadata}"/> + <fileset dir="." includes="TestAMD.ice"/> + <includepath> + <pathelement path="${slice.dir}" /> + </includepath> + </slice2java> + </target> + + <target name="compile" depends="generate"> + <mkdir dir="${class.dir}"/> + <javac srcdir="." destdir="${class.dir}" includes="Serialize/**" + classpathref="ice.classpath" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> + <javac srcdir="${generated.dir}" destdir="${class.dir}" + classpathref="ice.classpath" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> + <javac srcdir="." destdir="${class.dir}" + classpathref="ice.classpath" excludes="generated/**,Serialize/**" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> + </target> + + <target name="all" depends="compile"/> + + <target name="clean"> + <delete dir="${generated.dir}"/> + <delete dir="${class.dir}"/> + </target> + +</project> diff --git a/java/test/Ice/serialize/AllTests.java b/java/test/Ice/serialize/AllTests.java new file mode 100644 index 00000000000..2a540d546df --- /dev/null +++ b/java/test/Ice/serialize/AllTests.java @@ -0,0 +1,148 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +import Test.*; +import java.io.*; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static InitialPrx + allTests(Ice.Communicator communicator, boolean collocated) + { + String ref = "initial:default -p 12010 -t 10000"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + InitialPrx initial = InitialPrxHelper.checkedCast(base); + + System.out.print("testing serialization... "); + System.out.flush(); + + // + // Call getStruct1 and force an error. + // + try + { + // + // We expect this test to raise an exception: we are attempting to deserialize + // an instance of Struct1 using java.io.ObjectInputStream. However, we must + // use Ice.ObjectInputStream instead because Struct1 contains a proxy. + // + byte[] bytes = initial.getStruct1(); + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + ObjectInputStream ois = new ObjectInputStream(bais); + ois.readObject(); + test(false); + } + catch(IOException ex) + { + // Expected. + } + catch(Throwable ex) + { + test(false); + } + + // + // Call getStruct1. + // + try + { + byte[] bytes = initial.getStruct1(); + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + Ice.ObjectInputStream ois = new Ice.ObjectInputStream(communicator, bais); + Struct1 s = (Struct1)ois.readObject(); + checkStruct1(s); + } + catch(Throwable ex) + { + test(false); + } + + // + // Call getBase. + // + try + { + byte[] bytes = initial.getBase(); + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + Ice.ObjectInputStream ois = new Ice.ObjectInputStream(communicator, bais); + Base b = (Base)ois.readObject(); + checkBase(b); + } + catch(Throwable ex) + { + test(false); + } + + // + // Call getEx. + // + try + { + byte[] bytes = initial.getEx(); + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + Ice.ObjectInputStream ois = new Ice.ObjectInputStream(communicator, bais); + Ex ex = (Ex)ois.readObject(); + checkStruct1(ex.s); + checkBase(ex.b); + } + catch(Throwable ex) + { + test(false); + } + + System.out.println("ok"); + + return initial; + } + + private static void + checkStruct1(Struct1 s) + { + test(s.bo); + test(s.by == (byte)1); + test(s.sh == (short)2); + test(s.i == 3); + test(s.l == 4); + test(s.f == (float)5.0); + test(s.d == 6.0); + test(s.str.equals("7")); + test(s.e == MyEnum.enum2); + test(s.p != null); + s.p.ice_ping(); // Make sure the deserialized proxy is usable. + } + + private static void + checkBase(Base b) + { + test(b.b == b); + test(b.o == b); + checkStruct1(b.s); + test(java.util.Arrays.equals(b.seq1, new byte[] { 0, 1, 2, 3, 4 })); + test(java.util.Arrays.equals(b.seq2, new int[] { 5, 6, 7, 8, 9 })); + test(java.util.Arrays.equals(b.seq3, new MyEnum[] { MyEnum.enum3, MyEnum.enum2, MyEnum.enum1 })); + test(java.util.Arrays.equals(b.seq4, new Base[] { b })); + test(b.d1.get(new Byte((byte)1)).equals(Boolean.TRUE)); + test(b.d2.get(new Short((short)2)).equals(new Integer(3))); + test(b.d3.get("enum3") == MyEnum.enum3); + test(b.d4.get("b") == b); + test(b instanceof Derived); + Derived d = (Derived)b; + test(d.p != null); + d.p.ice_ping(); + } +} diff --git a/java/test/Ice/serialize/Client.java b/java/test/Ice/serialize/Client.java new file mode 100644 index 00000000000..74ab7531339 --- /dev/null +++ b/java/test/Ice/serialize/Client.java @@ -0,0 +1,55 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +import Test.*; + +public class Client +{ + private static int + run(String[] args, Ice.Communicator communicator) + { + InitialPrx initial = AllTests.allTests(communicator, false); + initial.shutdown(); + return 0; + } + + public static void + main(String[] args) + { + int status = 0; + Ice.Communicator communicator = null; + + try + { + communicator = Ice.Util.initialize(args); + status = run(args, communicator); + } + catch(Exception ex) + { + ex.printStackTrace(); + status = 1; + } + + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + status = 1; + } + } + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/Ice/serialize/InitialI.java b/java/test/Ice/serialize/InitialI.java new file mode 100644 index 00000000000..7973076b65e --- /dev/null +++ b/java/test/Ice/serialize/InitialI.java @@ -0,0 +1,114 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +import Test.*; +import java.io.*; + +public final class InitialI extends _InitialDisp +{ + InitialI(Ice.ObjectAdapter adapter, Ice.Identity ident) + { + _s = new Struct1(); + _s.bo = true; + _s.by = (byte)1; + _s.sh = (short)2; + _s.i = 3; + _s.l = 4; + _s.f = (float)5.0; + _s.d = 6.0; + _s.str = "7"; + _s.e = Test.MyEnum.enum2; + _s.p = Test.InitialPrxHelper.uncheckedCast(adapter.createProxy(ident)); + + _d = new Derived(); + _d.b = _d; + _d.o = _d; + _d.s = _s; + _d.seq1 = new byte[] { 0, 1, 2, 3, 4 }; + _d.seq2 = new int[] { 5, 6, 7, 8, 9 }; + _d.seq3 = new MyEnum[] { MyEnum.enum3, MyEnum.enum2, MyEnum.enum1 }; + _d.seq4 = new Base[] { _d }; + _d.d1 = new java.util.HashMap<Byte, Boolean>(); + _d.d1.put((byte)1, true); + _d.d2 = new java.util.HashMap<Short, Integer>(); + _d.d2.put((short)2, 3); + _d.d3 = new java.util.HashMap<String, MyEnum>(); + _d.d3.put("enum3", MyEnum.enum3); + _d.d4 = new java.util.HashMap<String, Base>(); + _d.d4.put("b", _d); + _d.p = _s.p; + } + + public byte[] + getStruct1(Ice.Current current) + { + try + { + ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + ObjectOutputStream stream = new ObjectOutputStream(byteStream); + stream.writeObject(_s); + return byteStream.toByteArray(); + } + catch(IOException ex) + { + Ice.UnknownException e = new Ice.UnknownException(); + e.initCause(ex); + throw e; + } + } + + public byte[] + getBase(Ice.Current current) + { + try + { + ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + ObjectOutputStream stream = new ObjectOutputStream(byteStream); + stream.writeObject(_d); + return byteStream.toByteArray(); + } + catch(IOException ex) + { + Ice.UnknownException e = new Ice.UnknownException(); + e.initCause(ex); + throw e; + } + } + + public byte[] + getEx(Ice.Current current) + { + try + { + Ex ex = new Ex(); + ex.s = _s; + ex.b = _d; + + ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + ObjectOutputStream stream = new ObjectOutputStream(byteStream); + stream.writeObject(ex); + return byteStream.toByteArray(); + } + catch(IOException ex) + { + Ice.UnknownException e = new Ice.UnknownException(); + e.initCause(ex); + throw e; + } + } + + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + private Struct1 _s; + private Derived _d; +} diff --git a/java/test/Ice/serialize/Server.java b/java/test/Ice/serialize/Server.java new file mode 100644 index 00000000000..23e27a80f7d --- /dev/null +++ b/java/test/Ice/serialize/Server.java @@ -0,0 +1,58 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +public class Server +{ + private static int + run(String[] args, Ice.Communicator communicator) + { + communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010 -t 10000"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Identity ident = communicator.stringToIdentity("initial"); + Ice.Object object = new InitialI(adapter, ident); + adapter.add(object, ident); + adapter.activate(); + communicator.waitForShutdown(); + return 0; + } + + public static void + main(String[] args) + { + int status = 0; + Ice.Communicator communicator = null; + + try + { + communicator = Ice.Util.initialize(args); + status = run(args, communicator); + } + catch(Exception ex) + { + ex.printStackTrace(); + status = 1; + } + + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + status = 1; + } + } + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/Ice/serialize/Test.ice b/java/test/Ice/serialize/Test.ice new file mode 100644 index 00000000000..bb64105b0cd --- /dev/null +++ b/java/test/Ice/serialize/Test.ice @@ -0,0 +1,86 @@ +// ********************************************************************** +// +// 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. +// +// ********************************************************************** + +#ifndef TEST_ICE +#define TEST_ICE + +module Test +{ + +enum MyEnum +{ + enum1, + enum2, + enum3 +}; + +interface Initial; +class Base; + +struct Struct1 +{ + bool bo; + byte by; + short sh; + int i; + long l; + float f; + double d; + string str; + MyEnum e; + Initial* p; +}; + +sequence<byte> ByteS; +sequence<int> IntS; +sequence<MyEnum> MyEnumS; +sequence<Base> BaseS; + +dictionary<byte, bool> ByteBoolD; +dictionary<short, int> ShortIntD; +dictionary<string, MyEnum> StringMyEnumD; +dictionary<string, Base> StringBaseD; + +class Base +{ + Base b; + Object o; + Struct1 s; + ByteS seq1; + IntS seq2; + MyEnumS seq3; + BaseS seq4; + ByteBoolD d1; + ShortIntD d2; + StringMyEnumD d3; + StringBaseD d4; +}; + +class Derived extends Base +{ + Object* p; +}; + +exception Ex +{ + Struct1 s; + Base b; +}; + +interface Initial +{ + ByteS getStruct1(); + ByteS getBase(); + ByteS getEx(); + void shutdown(); +}; + +}; + +#endif diff --git a/java/test/Ice/serialize/build.xml b/java/test/Ice/serialize/build.xml new file mode 100644 index 00000000000..1e4d16935c6 --- /dev/null +++ b/java/test/Ice/serialize/build.xml @@ -0,0 +1,48 @@ +<!-- + ********************************************************************** + + 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. + + ********************************************************************** +--> + +<project name="test_Ice_objects" default="all" basedir="."> + + <!-- set global properties for this build --> + <property name="top.dir" value="../../.."/> + + <!-- import common definitions --> + <import file="${top.dir}/config/common.xml"/> + + <target name="generate" depends="init"> + <!-- Create the output directory for generated code --> + <mkdir dir="${generated.dir}"/> + <slice2java stream="on" outputdir="${generated.dir}"> + <meta value="${java2metadata}"/> + <fileset dir="." includes="Test.ice"/> + </slice2java> + </target> + + <target name="compile" depends="generate"> + <mkdir dir="${class.dir}"/> + <javac srcdir="${generated.dir}" destdir="${class.dir}" + classpathref="ice.classpath" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> + <javac srcdir="." destdir="${class.dir}" + classpathref="ice.classpath" excludes="generated/**" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> + </target> + + <target name="all" depends="compile"/> + + <target name="clean"> + <delete dir="${generated.dir}"/> + <delete dir="${class.dir}"/> + </target> + +</project> diff --git a/java/test/Ice/serialize/run.py b/java/test/Ice/serialize/run.py new file mode 100755 index 00000000000..bb34e7d35b7 --- /dev/null +++ b/java/test/Ice/serialize/run.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# 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. +# +# ********************************************************************** + +import os, sys + +path = [ ".", "..", "../..", "../../..", "../../../.." ] +head = os.path.dirname(sys.argv[0]) +if len(head) > 0: + path = [os.path.join(head, p) for p in path] +path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] +if len(path) == 0: + raise "can't find toplevel directory!" +sys.path.append(os.path.join(path[0])) +from scripts import * + +TestUtil.clientServerTest() diff --git a/java/test/Ice/stream/Client.java b/java/test/Ice/stream/Client.java index 8c1993fc612..ebeb12378df 100644 --- a/java/test/Ice/stream/Client.java +++ b/java/test/Ice/stream/Client.java @@ -325,6 +325,19 @@ public class Client } { + Serialize.Small small = new Serialize.Small(); + small.i = 99; + out = Ice.Util.createOutputStream(communicator); + out.writeSerializable(small); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(communicator, data); + Serialize.Small small2 = (Serialize.Small)in.readSerializable(); + test(small2.i == 99); + out.destroy(); + in.destroy(); + } + + { final short[] arr = { (short)0x01, diff --git a/java/test/Ice/stream/Serialize/Small.java b/java/test/Ice/stream/Serialize/Small.java new file mode 100644 index 00000000000..be92e68edea --- /dev/null +++ b/java/test/Ice/stream/Serialize/Small.java @@ -0,0 +1,15 @@ +// ********************************************************************** +// +// 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 Serialize; + +public class Small implements java.io.Serializable // Fewer than 254 bytes when serialized. +{ + public int i; +} diff --git a/java/test/Ice/stream/Test.ice b/java/test/Ice/stream/Test.ice index dafd2f02d41..03ac2d92dc3 100644 --- a/java/test/Ice/stream/Test.ice +++ b/java/test/Ice/stream/Test.ice @@ -22,6 +22,8 @@ enum MyEnum class MyClass; +["java:serializable:Serialize.Small"] sequence<byte> SerialSmall; + struct SmallStruct { bool bo; @@ -34,6 +36,7 @@ struct SmallStruct string str; MyEnum e; MyClass* p; + SerialSmall ss; }; sequence<bool> BoolS; diff --git a/java/test/Ice/stream/build.xml b/java/test/Ice/stream/build.xml index f3283a483ba..e719c890777 100644 --- a/java/test/Ice/stream/build.xml +++ b/java/test/Ice/stream/build.xml @@ -28,12 +28,16 @@ <target name="compile" depends="generate"> <mkdir dir="${class.dir}"/> + <javac srcdir="." destdir="${class.dir}" includes="Serialize/**" + classpathref="ice.classpath" debug="${debug}"> + <compilerarg value="${javac.lint}"/> + </javac> <javac srcdir="${generated.dir}" destdir="${class.dir}" classpathref="ice.classpath" debug="${debug}"> <compilerarg value="${javac.lint}"/> </javac> - <javac srcdir="." destdir="${class.dir}" - classpathref="ice.classpath" excludes="generated/**" debug="${debug}"> + <javac srcdir="." destdir="${class.dir}" excludes="${generated.dir}/** Serialize/**" + classpathref="ice.classpath" debug="${debug}"> <compilerarg value="${javac.lint}"/> </javac> </target> diff --git a/java/test/Ice/stream/run.py b/java/test/Ice/stream/run.py index 2ba8e124049..47e0b8dafab 100755 --- a/java/test/Ice/stream/run.py +++ b/java/test/Ice/stream/run.py @@ -23,7 +23,8 @@ from scripts import * TestUtil.addClasspath(os.path.join(os.getcwd(), "classes")) print "starting test...", -clientProc = TestUtil.startClient("Client") +clientProc = TestUtil.startClient("Client", startReader = False) print "ok" +clientProc.startReader() clientProc.waitTestSuccess() diff --git a/java/test/Ice/timeout/AllTests.java b/java/test/Ice/timeout/AllTests.java index 73cf9dffb5c..1f827eb9e47 100644 --- a/java/test/Ice/timeout/AllTests.java +++ b/java/test/Ice/timeout/AllTests.java @@ -190,7 +190,7 @@ public class AllTests // Expect success. // timeout.op(); // Ensure adapter is active. - TimeoutPrx to = TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(1000)); + TimeoutPrx to = TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(2000)); to.holdAdapter(500); to.ice_getConnection().close(true); // Force a reconnect. try diff --git a/java/test/Ice/udp/AllTests.java b/java/test/Ice/udp/AllTests.java index e374478f2ea..53f10f5a633 100644 --- a/java/test/Ice/udp/AllTests.java +++ b/java/test/Ice/udp/AllTests.java @@ -76,11 +76,25 @@ public class AllTests Ice.ObjectPrx base = communicator.stringToProxy("test:udp -p 12010").ice_datagram(); Test.TestIntfPrx obj = Test.TestIntfPrxHelper.uncheckedCast(base); - replyI.reset(); - obj.ping(reply); - obj.ping(reply); - obj.ping(reply); - boolean ret = replyI.waitReply(3, 2000); + int nRetry = 5; + boolean ret = false; + while(nRetry-- > 0) + { + replyI.reset(); + obj.ping(reply); + obj.ping(reply); + obj.ping(reply); + ret = replyI.waitReply(3, 2000); + if(ret) + { + break; // Success + } + + // If the 3 datagrams were not received within the 2 seconds, we try again to + // receive 3 new datagrams using a new object. We give up after 5 retries. + replyI = new PingReplyI(); + reply =(Test.PingReplyPrx)Test.PingReplyPrxHelper.uncheckedCast(adapter.addWithUUID(replyI)).ice_datagram(); + } test(ret == true); if(communicator.getProperties().getPropertyAsInt("Ice.Override.Compress") == 0) diff --git a/java/test/Ice/udp/run.py b/java/test/Ice/udp/run.py index 1ba78b079a2..108318b7896 100755 --- a/java/test/Ice/udp/run.py +++ b/java/test/Ice/udp/run.py @@ -31,8 +31,9 @@ for i in range(0, num): print "ok" print "starting client...", -clientProc = TestUtil.startClient("Client") +clientProc = TestUtil.startClient("Client", startReader = False) print "ok" +clientProc.startReader() clientProc.waitTestSuccess() for p in serverProc: diff --git a/java/test/IceBox/configuration/AllTests.java b/java/test/IceBox/configuration/AllTests.java index 488fe4f7c7f..7c71df16120 100644 --- a/java/test/IceBox/configuration/AllTests.java +++ b/java/test/IceBox/configuration/AllTests.java @@ -59,13 +59,13 @@ public class AllTests test(service3.getProperty("Service").equals("4")); test(service3.getProperty("Prop").equals("")); test(service3.getProperty("Service3.Prop").equals("1")); - test(service3.getProperty("Ice.Trace.Network").equals("3")); + test(service3.getProperty("Ice.Trace.Slicing").equals("3")); test(service4.getProperty("Ice.ProgramName").equals("IceBox-SharedCommunicator")); test(service4.getProperty("Service").equals("4")); test(service4.getProperty("Prop").equals("")); test(service4.getProperty("Service3.Prop").equals("1")); - test(service4.getProperty("Ice.Trace.Network").equals("3")); + test(service4.getProperty("Ice.Trace.Slicing").equals("3")); String[] args4 = {"--Service3.Prop=2"}; test(java.util.Arrays.equals(service4.getArgs(), args4)); diff --git a/java/test/IceBox/configuration/config.icebox b/java/test/IceBox/configuration/config.icebox index 0cc9851d84c..fc46a5c60e3 100644 --- a/java/test/IceBox/configuration/config.icebox +++ b/java/test/IceBox/configuration/config.icebox @@ -8,6 +8,6 @@ IceBox.Service.Service2=TestServiceI --Ice.Config=config.service2 --Service1.Arg IceBox.UseSharedCommunicator.Service3=1 IceBox.Service.Service3=TestServiceI --Ice.Config=config.service3 IceBox.UseSharedCommunicator.Service4=1 -IceBox.Service.Service4=TestServiceI --Ice.Config=config.service4 --Service3.Prop=2 --Ice.Trace.Network=3 +IceBox.Service.Service4=TestServiceI --Ice.Config=config.service4 --Service3.Prop=2 --Ice.Trace.Slicing=3 IceBox.LoadOrder=Service1 Service2 Service3 Service4 diff --git a/java/test/IceBox/configuration/config.service3 b/java/test/IceBox/configuration/config.service3 index f1930e3d8fb..c93ed144701 100644 --- a/java/test/IceBox/configuration/config.service3 +++ b/java/test/IceBox/configuration/config.service3 @@ -5,4 +5,4 @@ Service=3 Prop=2 Service3.Prop=1 -Ice.Trace.Network=2 +Ice.Trace.Slicing=2 diff --git a/java/test/IceSSL/certs/makecerts.py b/java/test/IceSSL/certs/makecerts.py index 5e6fbb7300f..f81f472105f 100755 --- a/java/test/IceSSL/certs/makecerts.py +++ b/java/test/IceSSL/certs/makecerts.py @@ -12,7 +12,7 @@ import os, sys, shutil for toplevel in [".", "..", "../..", "../../..", "../../../..", "../../../../.."]: toplevel = os.path.normpath(toplevel) - if os.path.exists(os.path.join(toplevel, "config", "TestUtil.py")): + if os.path.exists(os.path.join(toplevel, "scripts", "TestUtil.py")): break else: raise "can't find toplevel directory!" diff --git a/java/test/IceUtil/inputUtil/run.py b/java/test/IceUtil/inputUtil/run.py index cae7681d14d..71b051bbc73 100755 --- a/java/test/IceUtil/inputUtil/run.py +++ b/java/test/IceUtil/inputUtil/run.py @@ -23,6 +23,7 @@ from scripts import * TestUtil.addClasspath(os.path.join(os.getcwd(), "classes")) print "starting client...", -clientProc = TestUtil.startClient("Client") +clientProc = TestUtil.startClient("Client", startReader = False) print "ok" +clientProc.startReader() clientProc.waitTestSuccess() diff --git a/java/test/Slice/keyword/Key.ice b/java/test/Slice/keyword/Key.ice index f1ce1a558a9..173b28832e6 100644 --- a/java/test/Slice/keyword/Key.ice +++ b/java/test/Slice/keyword/Key.ice @@ -32,6 +32,7 @@ interface default class else { + int if; ["ami"] void foo(default* equals, out int final); }; diff --git a/java/test/Slice/keyword/run.py b/java/test/Slice/keyword/run.py index cae7681d14d..71b051bbc73 100755 --- a/java/test/Slice/keyword/run.py +++ b/java/test/Slice/keyword/run.py @@ -23,6 +23,7 @@ from scripts import * TestUtil.addClasspath(os.path.join(os.getcwd(), "classes")) print "starting client...", -clientProc = TestUtil.startClient("Client") +clientProc = TestUtil.startClient("Client", startReader = False) print "ok" +clientProc.startReader() clientProc.waitTestSuccess() |