diff options
Diffstat (limited to 'java/test/src')
548 files changed, 73611 insertions, 0 deletions
diff --git a/java/test/src/main/java/test/Freeze/complex/.gitignore b/java/test/src/main/java/test/Freeze/complex/.gitignore new file mode 100644 index 00000000000..ca51e824975 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/complex/.gitignore @@ -0,0 +1,2 @@ +db/* + diff --git a/java/test/src/main/java/test/Freeze/complex/Client.java b/java/test/src/main/java/test/Freeze/complex/Client.java new file mode 100644 index 00000000000..e98b4ebb6fb --- /dev/null +++ b/java/test/src/main/java/test/Freeze/complex/Client.java @@ -0,0 +1,241 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.complex; +import test.Freeze.complex.Complex.*; + +import Freeze.*; + +public class Client +{ + final static String progName = "test.Freeze.complex.Client"; + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private int + validate(String dbName) + throws DatabaseException + { + ComplexDict m = new ComplexDict(_connection, dbName, true); + + try + { + Parser parser = new Parser(); + + System.out.print("testing database expressions... "); + java.util.Iterator<java.util.Map.Entry<Key, Node>> p = m.entrySet().iterator(); + while(p.hasNext()) + { + java.util.Map.Entry<Key, Node> e = p.next(); + + Key key = e.getKey(); + + // + // Verify the stored record is correct. + // + test(key.result == e.getValue().calc()); + + // + // Verify that the expression & result again. + // + Node root = parser.parse(key.expression); + test(root.calc(null) == key.result); + } + System.out.println("ok"); + } + catch(ParseError e) + { + e.printStackTrace(); + test(false); + } + + m.close(); + + return 0; + } + + private int + populate(String dbName) + throws DatabaseException + { + String[] expressions = + { + "2", + "10", + "2+(5*3)", + "5*(2+3)", + "10+(10+(20+(8*(2*(3*2+4+5+6)))))" + }; + + ComplexDict m = new ComplexDict(_connection, dbName, true); + + try + { + Parser parser = new Parser(); + + System.out.print("populating the database... "); + for(String expr : expressions) + { + Node root = parser.parse(expr); + assert(root != null); + Key k = new Key(); + k.expression = expr; + k.result = root.calc(null); + m.put(k, root); + } + System.out.println("ok"); + } + catch(ParseError e) + { + e.printStackTrace(); + test(false); + } + + m.close(); + return 0; + } + + static void + usage(String name) + { + System.out.println("Usage: " + name + " [options] validate|populate"); + System.out.println("Options:"); + System.out.println("--dbdir Location of the database directory."); + } + + private int + run(String[] args, String dbName) + throws DatabaseException + { + // + // Register a factory for the node types. + // + Ice.ObjectFactory factory = new ObjectFactoryI(); + _communicator.addObjectFactory(factory, "::Complex::NumberNode"); + _communicator.addObjectFactory(factory, "::Complex::AddNode"); + _communicator.addObjectFactory(factory, "::Complex::MultiplyNode"); + + if(args.length != 0 && args[0].equals("populate")) + { + return populate(dbName); + } + if(args.length != 0 && args[0].equals("validate")) + { + return validate(dbName); + } + usage(progName); + + return 0; + } + + private void + close() + { + _connection.close(); + } + + private + Client(Ice.Communicator communicator, String envName) + { + _communicator = communicator; + _connection = Freeze.Util.createConnection(communicator, envName); + } + + static public void + main(String[] args) + { + int status; + Ice.Communicator communicator = null; + String envName = "db"; + + try + { + // + // Scan for --dbdir command line argument. + // + int i = 0; + while(i < args.length) + { + if(args[i].equals("--dbdir")) + { + if(i +1 >= args.length) + { + usage(progName); + System.exit(1); + } + + envName = args[i+1]; + envName += "/"; + envName += "db"; + + // + // Consume arguments + // + String[] arr = new String[args.length - 2]; + System.arraycopy(args, 0, arr, 0, i); + if(i < args.length - 2) + { + System.arraycopy(args, i + 2, arr, i, args.length - i - 2); + } + args = arr; + } + else + { + ++i; + } + } + + Ice.StringSeqHolder holder = new Ice.StringSeqHolder(); + holder.value = args; + communicator = Ice.Util.initialize(holder); + args = holder.value; + Client client = new Client(communicator, envName); + try + { + status = client.run(args, "test"); + } + finally + { + client.close(); + } + } + catch(Exception ex) + { + ex.printStackTrace(); + System.err.println(ex); + status = 1; + } + + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Exception ex) + { + System.err.println(ex); + status = 1; + } + } + + System.gc(); + System.exit(status); + } + + private Ice.Communicator _communicator; + private Freeze.Connection _connection; +} diff --git a/java/test/src/main/java/test/Freeze/complex/Complex.ice b/java/test/src/main/java/test/Freeze/complex/Complex.ice new file mode 100644 index 00000000000..1953e7e3caa --- /dev/null +++ b/java/test/src/main/java/test/Freeze/complex/Complex.ice @@ -0,0 +1,52 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Freeze.complex"]] +module Complex +{ + +// +// The database key (the expression and the result). Naturally, this +// is not a very good key - but this is only a test :) +// +struct Key +{ + string expression; + int result; +}; + +// +// A set of classes that represents a numeric parse tree. +// +class Node { + int calc(); +}; + +class NumberNode extends Node +{ + int number; +}; + +class BinaryNode extends Node +{ + Node left; + Node right; +}; + +class AddNode extends BinaryNode +{ +}; + +class MultiplyNode extends BinaryNode +{ +}; + +}; diff --git a/java/test/src/main/java/test/Freeze/complex/Complex/AddNodeI.java b/java/test/src/main/java/test/Freeze/complex/Complex/AddNodeI.java new file mode 100644 index 00000000000..d380923382a --- /dev/null +++ b/java/test/src/main/java/test/Freeze/complex/Complex/AddNodeI.java @@ -0,0 +1,31 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.complex.Complex; + +public class AddNodeI extends AddNode +{ + public + AddNodeI() + { + } + + public + AddNodeI(Node left, Node right) + { + this.left = left; + this.right = right; + } + + public int + calc(Ice.Current current) + { + return left.calc(current) + right.calc(current); + } +} diff --git a/java/test/src/main/java/test/Freeze/complex/Complex/MultiplyNodeI.java b/java/test/src/main/java/test/Freeze/complex/Complex/MultiplyNodeI.java new file mode 100644 index 00000000000..67dab5d7b71 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/complex/Complex/MultiplyNodeI.java @@ -0,0 +1,31 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.complex.Complex; + +public class MultiplyNodeI extends MultiplyNode +{ + public + MultiplyNodeI() + { + } + + public + MultiplyNodeI(Node left, Node right) + { + this.left = left; + this.right = right; + } + + public int + calc(Ice.Current current) + { + return left.calc(current) * right.calc(current); + } +} diff --git a/java/test/src/main/java/test/Freeze/complex/Complex/NumberNodeI.java b/java/test/src/main/java/test/Freeze/complex/Complex/NumberNodeI.java new file mode 100644 index 00000000000..308f59b6170 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/complex/Complex/NumberNodeI.java @@ -0,0 +1,30 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.complex.Complex; + +public class NumberNodeI extends NumberNode +{ + public + NumberNodeI() + { + } + + public + NumberNodeI(int number) + { + this.number = number; + } + + public int + calc(Ice.Current current) + { + return number; + } +} diff --git a/java/test/src/main/java/test/Freeze/complex/Complex/ObjectFactoryI.java b/java/test/src/main/java/test/Freeze/complex/Complex/ObjectFactoryI.java new file mode 100644 index 00000000000..66c92bfbf7b --- /dev/null +++ b/java/test/src/main/java/test/Freeze/complex/Complex/ObjectFactoryI.java @@ -0,0 +1,40 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.complex.Complex; + +public class ObjectFactoryI implements Ice.ObjectFactory +{ + public Ice.Object + create(String type) + { + if(type.equals("::Complex::MultiplyNode")) + { + return new MultiplyNodeI(); + } + if(type.equals("::Complex::AddNode")) + { + return new AddNodeI(); + } + if(type.equals("::Complex::NumberNode")) + { + return new NumberNodeI(); + } + + System.err.println( "create: " + type); + assert(false); + return null; + } + + public void + destroy() + { + // Nothing to do + } +} diff --git a/java/test/src/main/java/test/Freeze/complex/ParseError.java b/java/test/src/main/java/test/Freeze/complex/ParseError.java new file mode 100644 index 00000000000..05b510c7093 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/complex/ParseError.java @@ -0,0 +1,18 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.complex; + +public class ParseError extends Exception +{ + public ParseError(String msg) + { + super(msg); + } +} diff --git a/java/test/src/main/java/test/Freeze/complex/Parser.java b/java/test/src/main/java/test/Freeze/complex/Parser.java new file mode 100644 index 00000000000..87edceea504 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/complex/Parser.java @@ -0,0 +1,166 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.complex; +import test.Freeze.complex.Complex.*; + +public class Parser +{ + public Node + parse(String buf) + throws ParseError + { + _buf = buf; + _pos = 0; + _token = null; + + return start(); + } + + private Node + start() + throws ParseError + { + nextToken(); + Node node = expr(); + if(_token != null) + { + throw new ParseError("Extra garbage: " + _token); + } + return node; + } + + private Node + expr() + throws ParseError + { + try + { + if(_token == null) + { + return null; + } + + // + // '(' expr ')' + // + if(_token.charAt(0) == '(') + { + nextToken(); + + Node node = expr(); + if(_token.charAt(0) != ')') + { + throw new ParseError("Expected ')'"); + } + + nextToken(); + return node; + } + + // + // expr | expr '+' expr | expr '*' expr + // + if(!Character.isDigit(_token.charAt(0))) + { + throw new ParseError("Expected number"); + } + + NumberNode number = new NumberNodeI(Integer.parseInt(_token)); + Node result = number; + + // + // expr? + // + nextToken(); + if(_token != null) + { + // + // expr '+' expr + // + if(_token.charAt(0) == '+') + { + nextToken(); + Node right = expr(); + result = new AddNodeI(number, right); + } + + // + // expr '*' expr + // + else if(_token.charAt(0) == '*') + { + nextToken(); + Node right = expr(); + result = new MultiplyNodeI(number, right); + } + } + return result; + } + catch(NumberFormatException e) + { + ParseError ex = new ParseError("Error parsing number"); + ex.initCause(e); + throw ex; + } + } + + private void + nextToken() + { + // + // Eat any whitespace. + // + while(_pos < _buf.length() && Character.isWhitespace(_buf.charAt(_pos))) + { + _pos++; + } + + // + // At the end-of-buffer? + // + if(_pos >= _buf.length()) + { + _token = null; + return; + } + + StringBuilder buf = new StringBuilder(128); + + // + // Get the next character + // + char c = _buf.charAt(_pos); + + // + // '(', ')', '+' and '*' are tokens. + // + if(c == '(' || c == ')' || c == '+' || c == '*') + { + buf.append(c); + ++_pos; + } + else + { + // + // Otherwise it's a number. + // + while(_pos < _buf.length() && Character.isDigit(_buf.charAt(_pos))) + { + buf.append(_buf.charAt(_pos++)); + } + } + + _token = buf.toString(); + } + + private String _buf; + private int _pos; + private String _token; +} diff --git a/java/test/src/main/java/test/Freeze/complex/db/.gitignore b/java/test/src/main/java/test/Freeze/complex/db/.gitignore new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/java/test/src/main/java/test/Freeze/complex/db/.gitignore diff --git a/java/test/src/main/java/test/Freeze/complex/run.py b/java/test/src/main/java/test/Freeze/complex/run.py new file mode 100755 index 00000000000..1fdd637162c --- /dev/null +++ b/java/test/src/main/java/test/Freeze/complex/run.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +# +# Clean the contents of the database directory. +# +dbdir = os.path.join(os.getcwd(), "db") +TestUtil.cleanDbDir(dbdir) + +sys.stdout.write("starting populate... ") +sys.stdout.flush() +populateProc = TestUtil.startClient("test.Freeze.complex.Client", ' --dbdir "%s" populate' % os.getcwd(), + startReader=False) +print("ok") +populateProc.startReader() + +populateProc.waitTestSuccess() + +sys.stdout.write("starting verification client... ") +sys.stdout.flush() +clientProc = TestUtil.startClient("test.Freeze.complex.Client", ' --dbdir "%s" validate' % os.getcwd(), startReader=False) + +print("ok") +clientProc.startReader() +clientProc.waitTestSuccess() diff --git a/java/test/src/main/java/test/Freeze/dbmap/.gitignore b/java/test/src/main/java/test/Freeze/dbmap/.gitignore new file mode 100644 index 00000000000..9c39416c539 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/dbmap/.gitignore @@ -0,0 +1 @@ +db/* diff --git a/java/test/src/main/java/test/Freeze/dbmap/Client.java b/java/test/src/main/java/test/Freeze/dbmap/Client.java new file mode 100644 index 00000000000..fe6c9a06680 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/dbmap/Client.java @@ -0,0 +1,2189 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.dbmap; + +import Freeze.*; + +public class Client +{ + static class ReadThread extends Thread + { + @Override + public void + run() + { + try + { + for(int i = 0; i < 10; ++i) + { + for(;;) + { + Transaction tx = _connection.beginTransaction(); + + try + { + java.util.Iterator<java.util.Map.Entry<Byte, Integer>> p = _map.entrySet().iterator(); + while(p.hasNext()) + { + java.util.Map.Entry<Byte, Integer> e = p.next(); + byte v = e.getKey().byteValue(); + test(e.getValue().equals(new Integer(v - (byte)'a'))); + } + + break; + } + catch(DeadlockException ex) + { + // System.err.print("r"); + // + // Try again + // + } + finally + { + tx.rollback(); + } + } + } + } + catch(Exception ex) + { + ex.printStackTrace(); + System.err.println(ex); + } + finally + { + ((Freeze.Map<Byte, Integer>)_map).close(); + _connection.close(); + } + } + + ReadThread(Ice.Communicator communicator, String envName, String dbName) + { + _connection = Freeze.Util.createConnection(communicator, envName); + _map = new ByteIntMap(_connection, dbName, true); + } + + private Freeze.Connection _connection; + private java.util.Map<Byte, Integer> _map; + } + + static class WriteThread extends Thread + { + @Override + public void + run() + { + try + { + for(int i = 0; i < 4; ++i) + { + for(;;) + { + Transaction tx = _connection.beginTransaction(); + + try + { + java.util.Iterator<java.util.Map.Entry<Byte, Integer>> p = _map.entrySet().iterator(); + while(p.hasNext()) + { + java.util.Map.Entry<Byte, Integer> e = p.next(); + int v = e.getValue().intValue() + 1; + e.setValue(v); + p.remove(); + } + + tx.commit(); + tx = null; + + break; + } + catch(DeadlockException ex) + { + // System.err.print("w"); + // + // Try again + // + } + finally + { + if(tx != null) + { + tx.rollback(); + } + } + } + populateDB(_connection, _map); + } + } + catch(Exception ex) + { + ex.printStackTrace(); + System.err.println(ex); + } + finally + { + ((Freeze.Map<Byte, Integer>)_map).close(); + _connection.close(); + } + } + + WriteThread(Ice.Communicator communicator, String envName, String dbName) + { + _connection = Freeze.Util.createConnection(communicator, envName); + _map = new ByteIntMap(_connection, dbName, true); + } + + private Freeze.Connection _connection; + private java.util.Map<Byte, Integer> _map; + } + + static String alphabet = "abcdefghijklmnopqrstuvwxyz"; + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static void + populateDB(Freeze.Connection connection, java.util.Map<Byte, Integer> m) + throws DatabaseException + { + int length = alphabet.length(); + + for(;;) + { + + try + { + Transaction tx = connection.beginTransaction(); + for(int j = 0; j < length; ++j) + { + m.put((byte)alphabet.charAt(j), j); + } + tx.commit(); + break; // for(;;) + } + catch(Freeze.DeadlockException dx) + { + length = length / 2; + // System.err.print("t"); + // + // Try again + // + } + finally + { + if(connection.currentTransaction() != null) + { + connection.currentTransaction().rollback(); + } + } + } + } + + private static int + run(String[] args, Ice.Communicator communicator, String envName, String dbName) + throws DatabaseException + { + Freeze.Connection connection = Freeze.Util.createConnection(communicator, envName); + + // + // Open/close db within transaction + // + { + Transaction tx = connection.beginTransaction(); + ByteIntMap m = new ByteIntMap(connection, dbName, true); + + m.put((byte)'a', 1); + m.close(); + tx.rollback(); + } + + java.util.Map<Byte, Integer> m = new ByteIntMap(connection, dbName, true); + + // + // Populate the database with the alphabet. + // + populateDB(connection, m); + + int j; + + System.out.print("testing populate... "); + System.out.flush(); + for(j = 0; j < alphabet.length(); ++j) + { + Integer value = m.get((byte)alphabet.charAt(j)); + test(value != null); + } + test(m.get((byte)'0') == null); + for(j = 0; j < alphabet.length(); ++j) + { + test(m.containsKey((byte)alphabet.charAt(j))); + } + test(!m.containsKey((byte)'0')); + for(j = 0; j < alphabet.length(); ++j) + { + test(m.containsValue(j)); + } + test(!m.containsValue(-1)); + test(m.size() == alphabet.length()); + test(!m.isEmpty()); + System.out.println("ok"); + + System.out.print("testing erase... "); + System.out.flush(); + m.remove((byte)'a'); + m.remove((byte)'b'); + m.remove((byte)'c'); + for(j = 3; j < alphabet.length(); ++j) + { + Integer value = m.get((byte)alphabet.charAt(j)); + test(value != null); + } + test(m.get((byte)'a') == null); + test(m.get((byte)'b') == null); + test(m.get((byte)'c') == null); + test(((ByteIntMap)m).fastRemove((byte)'d') == true); + test(((ByteIntMap)m).fastRemove((byte)'d') == false); + System.out.println("ok"); + + // + // Re-populate. + // + populateDB(connection, m); + + { + System.out.print("testing keySet... "); + System.out.flush(); + java.util.Set<Byte> keys = m.keySet(); + test(keys.size() == alphabet.length()); + test(!keys.isEmpty()); + java.util.Iterator<Byte> p = keys.iterator(); + while(p.hasNext()) + { + Byte b = p.next(); + test(keys.contains(b)); + test(m.containsKey(b)); + } + + // + // The iterator should have already been closed when we reached the last entry. + // + int count = ((Freeze.Map<Byte, Integer>)m).closeAllIterators(); + test(count == 0); + + try + { + keys.remove((byte)'a'); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - no transaction. + } + + count = ((Freeze.Map<Byte, Integer>)m).closeAllIterators(); + test(count == 1); // Opened by keys.remove() + + Transaction tx = connection.beginTransaction(); + + test(keys.size() == alphabet.length()); + test(keys.remove((byte)'a') == true); + + // Verify that size is transactional + test(keys.size() == alphabet.length() - 1); + test(keys.remove((byte)'a') == false); + tx.commit(); + test(m.containsKey((byte)'a') == false); + + System.out.println("ok"); + } + + // + // Re-populate. + // + populateDB(connection, m); + + { + System.out.print("testing values... "); + System.out.flush(); + java.util.Collection<Integer> values = m.values(); + test(values.size() == alphabet.length()); + test(!values.isEmpty()); + java.util.Iterator<Integer> p = values.iterator(); + while(p.hasNext()) + { + Integer i = p.next(); + test(values.contains(i)); + test(m.containsValue(i)); + } + + // + // The iterator should have already been closed when we reached the last entry. + // + int count = ((Freeze.Map<Byte, Integer>)m).closeAllIterators(); + test(count == 0); + + try + { + values.remove(0); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - no transaction. + } + + count = ((Freeze.Map<Byte, Integer>)m).closeAllIterators(); + test(count == 1); // Opened by keys.remove() + + Transaction tx = connection.beginTransaction(); + test(values.remove(0) == true); + test(values.remove(0) == false); + tx.commit(); + test(m.containsKey((byte)'a') == false); + + System.out.println("ok"); + } + + // + // Re-populate. + // + populateDB(connection, m); + + { + System.out.print("testing entrySet... "); + System.out.flush(); + java.util.Set<java.util.Map.Entry<Byte, Integer>> entrySet = m.entrySet(); + test(entrySet.size() == alphabet.length()); + test(!entrySet.isEmpty()); + java.util.Iterator<java.util.Map.Entry<Byte, Integer>> p = entrySet.iterator(); + while(p.hasNext()) + { + java.util.Map.Entry<Byte, Integer> e = p.next(); + test(entrySet.contains(e)); + test(m.containsKey(e.getKey())); + test(m.containsValue(e.getValue())); + } + + // + // The iterator should have already been closed when we reached the last entry. + // + int count = ((Freeze.Map<Byte, Integer>)m).closeAllIterators(); + test(count == 0); + System.out.println("ok"); + } + + { + System.out.print("testing unsorted map... "); + System.out.flush(); + + NavigableMap<Byte, Integer> nm = (NavigableMap<Byte, Integer>)m; + final byte firstByte = (byte)alphabet.charAt(0); + final byte lastByte = (byte)alphabet.charAt(alphabet.length() - 1); + final int length = alphabet.length(); + + // + // Keys + // + + Byte key; + + key = nm.firstKey(); + test(key != null); + test(key.byteValue() == firstByte); + + key = nm.lastKey(); + test(key != null); + test(key.byteValue() == lastByte); + + try + { + nm.ceilingKey((byte)0); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - a comparator is required. + } + + try + { + nm.floorKey((byte)0); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - a comparator is required. + } + + try + { + nm.higherKey((byte)0); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - a comparator is required. + } + + try + { + nm.lowerKey((byte)0); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - a comparator is required. + } + + m.clear(); + test(m.size() == 0); + try + { + nm.firstKey(); + test(false); + } + catch(java.util.NoSuchElementException ex) + { + // Expected. + } + try + { + nm.lastKey(); + test(false); + } + catch(java.util.NoSuchElementException ex) + { + // Expected. + } + + populateDB(connection, m); + + // + // Entries + // + + java.util.Map.Entry<Byte, Integer> e; + + e = nm.firstEntry(); + test(e != null); + test(e.getKey().byteValue() == firstByte); + test(e.getValue().intValue() == 0); + + e = nm.lastEntry(); + test(e != null); + test(e.getKey().byteValue() == lastByte); + test(e.getValue().intValue() == length - 1); + + try + { + nm.ceilingEntry((byte)0); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - a comparator is required. + } + + try + { + nm.floorEntry((byte)0); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - a comparator is required. + } + + try + { + nm.higherEntry((byte)0); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - a comparator is required. + } + + try + { + nm.lowerEntry((byte)0); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - a comparator is required. + } + + e = nm.pollFirstEntry(); + test(e != null); + test(e.getKey().byteValue() == firstByte); + test(e.getValue().intValue() == 0); + test(!nm.containsKey(firstByte)); + + e = nm.pollLastEntry(); + test(e != null); + test(e.getKey().byteValue() == lastByte); + test(e.getValue().intValue() == length - 1); + test(!nm.containsKey(lastByte)); + + ByteIntMap typedM = (ByteIntMap)m; + + try + { + typedM.headMapForValue(0); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - a comparator is required. + } + + try + { + typedM.tailMapForValue(0); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - a comparator is required. + } + + try + { + typedM.subMapForValue(0, 0); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - a comparator is required. + } + + try + { + typedM.mapForValue(); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected - a comparator is required. + } + + m.clear(); + test(nm.firstEntry() == null); + test(nm.lastEntry() == null); + populateDB(connection, m); + + System.out.println("ok"); + } + + { + System.out.print("testing for loop... "); + System.out.flush(); + for(java.util.Map.Entry<Byte, Integer> e : m.entrySet()) + { + test(m.containsKey(e.getKey())); + test(m.containsValue(e.getValue())); + } + + // + // The iterator should have already been closed when we reached the last entry. + // + int count = ((Freeze.Map<Byte, Integer>)m).closeAllIterators(); + test(count == 0); + + System.out.println("ok"); + } + + { + System.out.print("testing iterator.remove... "); + System.out.flush(); + + Freeze.Map<Byte, Integer> fm = (Freeze.Map<Byte, Integer>)m; + java.util.Iterator<java.util.Map.Entry<Byte, Integer>> p; + Transaction tx; + int count; + + test(m.size() == 26); + test(m.get((byte)'b') != null); + test(m.get((byte)'n') != null); + test(m.get((byte)'z') != null); + + // + // Verify that remove fails without a transaction. + // + p = m.entrySet().iterator(); + test(p.hasNext()); + p.next(); + try + { + p.remove(); + } + catch(UnsupportedOperationException ex) + { + // Expected. + } + + count = fm.closeAllIterators(); + test(count == 1); + + tx = connection.beginTransaction(); + p = m.entrySet().iterator(); + while(p.hasNext()) + { + java.util.Map.Entry<Byte, Integer> e = p.next(); + Byte b = e.getKey(); + byte v = b.byteValue(); + if(v == (byte)'b' || v == (byte)'n' || v == (byte)'z') + { + p.remove(); + try + { + p.remove(); + } + catch(IllegalStateException ex) + { + // Expected. + } + } + } + tx.commit(); + count = fm.closeAllIterators(); // Committing the transaction should close the iterator. + test(count == 0); + + test(m.size() == 23); + test(m.get((byte)'b') == null); + test(m.get((byte)'n') == null); + test(m.get((byte)'z') == null); + + // + // Re-populate. + // + populateDB(connection, m); + + test(m.size() == 26); + + tx = connection.beginTransaction(); + p = m.entrySet().iterator(); + while(p.hasNext()) + { + java.util.Map.Entry<Byte, Integer> e = p.next(); + byte v = e.getKey().byteValue(); + if(v == (byte)'a' || v == (byte)'b' || v == (byte)'c') + { + p.remove(); + } + } + tx.commit(); + count = fm.closeAllIterators(); // Committing the transaction should close the iterator. + test(count == 0); + + test(m.size() == 23); + test(m.get((byte)'a') == null); + test(m.get((byte)'b') == null); + test(m.get((byte)'c') == null); + System.out.println("ok"); + } + + { + System.out.print("testing entry.setValue... "); + System.out.flush(); + + // + // Re-populate. + // + populateDB(connection, m); + + Freeze.Map<Byte, Integer> fm = (Freeze.Map<Byte, Integer>)m; + java.util.Iterator<java.util.Map.Entry<Byte, Integer>> p; + Transaction tx; + java.util.Map.Entry<Byte, Integer> e; + + // + // Verify that setValue on an iterator fails without a transaction. + // + p = m.entrySet().iterator(); + test(p.hasNext()); + try + { + e = p.next(); + e.setValue(0); + } + catch(UnsupportedOperationException ex) + { + // Expected. + } + + tx = connection.beginTransaction(); + p = m.entrySet().iterator(); + while(p.hasNext()) + { + e = p.next(); + byte v = e.getKey().byteValue(); + if(v == (byte)'b' || v == (byte)'n' || v == (byte)'z') + { + e.setValue(v + 100); + } + } + tx.commit(); + test(m.size() == 26); + test(m.get((byte)'b') != null); + test(m.get((byte)'n') != null); + test(m.get((byte)'z') != null); + + p = m.entrySet().iterator(); + while(p.hasNext()) + { + e = p.next(); + byte v = e.getKey().byteValue(); + if(v == (byte)'b' || v == (byte)'n' || v == (byte)'z') + { + test(e.getValue().equals(new Integer(v + 100))); + } + else + { + test(e.getValue().equals(new Integer(v - (byte)'a'))); + } + } + + // + // No transaction is necessary for entries obtained without an iterator. + // + e = fm.firstEntry(); + test(e != null); + e.setValue(-1); + test(e.getValue().intValue() == -1); + e = fm.firstEntry(); + test(e != null); + test(e.getValue().intValue() == -1); + + System.out.println("ok"); + } + + { + System.out.print("testing clear... "); + System.out.flush(); + test(m.size() > 0); + m.clear(); + test(m.size() == 0); + System.out.println("ok"); + } + + { + System.out.print("testing index... "); + System.out.flush(); + + // + // Re-populate. + // + populateDB(connection, m); + + ByteIntMap typedM = (ByteIntMap)m; + + java.util.Map.Entry<Byte, Integer> e; + java.util.Iterator<java.util.Map.Entry<Byte, Integer>> p; + Transaction tx; + + int length = alphabet.length(); + + for(int k = 0; k < length; ++k) + { + p = typedM.findByValue(k); + test(p.hasNext()); + e = p.next(); + test(e.getKey().byteValue() == (byte)alphabet.charAt(k)); + test(!p.hasNext()); + } + + // + // Change the value associated with key 21 to 17. + // + m.put((byte)alphabet.charAt(21), 17); + + // + // Verify that the index no longer has an entry for value 21. + // + p = typedM.findByValue(21); + test(!p.hasNext()); + + // + // Verify that the iterator returns two entries for value 17. + // + p = typedM.findByValue(17); + test(p.hasNext()); + e = p.next(); + byte v = e.getKey().byteValue(); + test(v == (byte)alphabet.charAt(17) || v == (byte)alphabet.charAt(21)); + + test(p.hasNext()); + e = p.next(); + v = e.getKey().byteValue(); + test(v == (byte)alphabet.charAt(17) || v == (byte)alphabet.charAt(21)); + + test(!p.hasNext()); // Iterator defaults to returning only exact matches. + test(typedM.valueCount(17) == 2); + + // + // Cannot remove without a transaction. + // + p = typedM.findByValue(17); + test(p.hasNext()); + p.next(); + try + { + p.remove(); + } + catch(UnsupportedOperationException ex) + { + // Expected. + } + + tx = connection.beginTransaction(); + p = typedM.findByValue(17); + test(p.hasNext()); + p.next(); + p.remove(); + test(p.hasNext()); + e = p.next(); + v = e.getKey().byteValue(); + test(v == (byte)alphabet.charAt(17) || v == (byte)alphabet.charAt(21)); + test(!p.hasNext()); + tx.commit(); + + int count = typedM.closeAllIterators(); + test(count == 0); // Committing the transaction also closes the iterators. + + test(typedM.valueCount(17) == 1); + + p = typedM.findByValue(17); + test(p.hasNext()); + e = p.next(); + + // + // Cannot set a value on an index iterator. + // + try + { + e.setValue(18); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected. + } + + v = e.getKey().byteValue(); + test(v == (byte)alphabet.charAt(17) || v == (byte)alphabet.charAt(21)); + test(typedM.valueCount(17) == 1); + + m.put((byte)alphabet.charAt(21), 17); + + // + // Non-exact match + // + p = typedM.findByValue(21); + test(!p.hasNext()); + + test(typedM.valueCount(21) == 0); + + p = typedM.findByValue(21, false); + test(!p.hasNext()); + + p = typedM.findByValue(22, false); + int previous = 21; + count = 0; + while(p.hasNext()) + { + e = p.next(); + + int val = e.getValue().intValue(); + + test(val > previous); + previous = val; + count++; + } + test(count == 4); + + System.out.println("ok"); + } + + ((Freeze.Map<Byte, Integer>)m).closeAllIterators(); + + { + System.out.print("testing concurrent access... "); + System.out.flush(); + + m.clear(); + populateDB(connection, m); + + java.util.List<Thread> l = new java.util.ArrayList<Thread>(); + + // + // Create each thread. + // + for(int i = 0; i < 5; ++i) + { + l.add(new ReadThread(communicator, envName, dbName)); + l.add(new WriteThread(communicator, envName, dbName)); + } + + // + // Start each thread. + // + for(Thread t : l) + { + t.start(); + } + + // + // Wait for each thread to terminate. + // + for(Thread t : l) + { + while(t.isAlive()) + { + try + { + t.join(); + } + catch(InterruptedException e) + { + } + } + } + + System.out.println("ok"); + } + + System.out.print("testing index creation... "); + System.out.flush(); + + { + IntIdentityMap iim = new IntIdentityMap(connection, "intIdentity", true); + + Ice.Identity odd = new Ice.Identity(); + odd.name = "foo"; + odd.category = "odd"; + + Ice.Identity even = new Ice.Identity(); + even.name = "bar"; + even.category = "even"; + + Transaction tx = connection.beginTransaction(); + for(int i = 0; i < 1000; i++) + { + if(i % 2 == 0) + { + iim.fastPut(i, even); + } + else + { + iim.fastPut(i, odd); + } + } + tx.commit(); + iim.closeDb(); + } + + { + // + // Need true to create the index + // + IntIdentityMapWithIndex iim = new IntIdentityMapWithIndex(connection, "intIdentity", true); + + test(iim.categoryCount("even") == 500); + test(iim.categoryCount("odd") == 500); + + int count = 0; + java.util.Iterator<java.util.Map.Entry<Integer, Ice.Identity>> p = iim.findByCategory("even"); + while(p.hasNext()) + { + java.util.Map.Entry<Integer, Ice.Identity> e = p.next(); + int k = e.getKey().intValue(); + test(k % 2 == 0); + ++count; + } + test(count == 500); + + count = 0; + p = iim.findByCategory("odd"); + while(p.hasNext()) + { + java.util.Map.Entry<Integer, Ice.Identity> e = p.next(); + int k = e.getKey().intValue(); + test(k % 2 == 1); + ++count; + } + test(count == 500); + + iim.destroy(); + } + System.out.println("ok"); + + // + // Sorting + // + + final java.util.Comparator<Integer> less = new java.util.Comparator<Integer>() + { + @Override + public int compare(Integer i1, Integer i2) + { + if(i1 == i2) + { + return 0; + } + else if(i1 == null) + { + return -i2.compareTo(i1); + } + else + { + return i1.compareTo(i2); + } + } + }; + + java.util.Comparator<String> greater = new java.util.Comparator<String>() + { + @Override + public int compare(String s1, String s2) + { + if(s1 == s2) + { + return 0; + } + else if(s1 == null) + { + return s2.compareTo(s1); + } + else + { + return -s1.compareTo(s2); + } + } + }; + + SortedMap.IndexComparators indexComparators = new SortedMap.IndexComparators(); + indexComparators.categoryComparator = greater; + java.util.Random rand = new java.util.Random(); + + { + SortedMap sm = new SortedMap(connection, "sortedMap", true, less, indexComparators); + + Transaction tx = connection.beginTransaction(); + for(int i = 0; i < 500; i++) + { + int k = rand.nextInt(1000); + Ice.Identity id = new Ice.Identity("foo", String.valueOf(alphabet.charAt(k % 26))); + sm.fastPut(k, id); + } + tx.commit(); + sm.close(); + } + + { + SortedMap sm = new SortedMap(connection, "sortedMap", true, less, indexComparators); + NavigableMap<Integer, Ice.Identity> sub = null; + + System.out.print("testing sorting with primary key... "); + System.out.flush(); + + testSortedMap(sm, true); + + { + final Integer first = sm.firstKey(); + + // + // fastRemove + // + sub = sm.headMap(first, true); + + Ice.Identity id = sub.get(first); + test(sub.fastRemove(first) == true); + test(sub.fastRemove(first) == false); + test(sm.containsKey(first) == false); + sm.put(first, id); + test(sm.containsKey(first) == true); + } + + System.out.println("ok"); + + // + // Category index + // + + { + System.out.print("testing sorting with secondary key... "); + System.out.flush(); + + NavigableMap<String, java.util.Set<java.util.Map.Entry<Integer, Ice.Identity>>> isub = null; + + isub = sm.mapForCategory(); + + { + Transaction tx = connection.beginTransaction(); + + Ice.Identity id = sm.get(sm.firstKey()); + int sz = isub.get(id.category).size(); + test(sz > 0); + + + test(sm.fastRemove(sm.firstKey()) == true); + + + if(sz == 1) + { + test(isub.get(id.category) == null); + } + else + { + // System.out.println("Check size within tx"); + test(isub.get(id.category).size() == sz -1); + } + tx.rollback(); + test(isub.get(id.category).size() == sz); + } + + final String first = isub.firstKey(); + final String last = isub.lastKey(); + + // + // Head map + // + isub = sm.headMapForCategory(last); + test(greater.compare(isub.lastKey(), last) < 0); + isub = sm.headMapForCategory(last, true); + test(greater.compare(isub.lastKey(), last) == 0); + isub = sm.headMapForCategory(first); + test(isub.firstEntry() == null); // map is empty + isub = sm.headMapForCategory(first, true); + test(greater.compare(isub.firstKey(), first) == 0); + test(greater.compare(isub.lastKey(), first) == 0); + + sm.headMapForCategory(first, true).headMap(first, true); + sm.headMapForCategory(first, true).headMap(first); + sm.headMapForCategory(first).headMap(first); + try + { + sm.headMapForCategory(first).headMap(first, true); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + + { + String category = null; + while(true) + { + int k = rand.nextInt(1000); + category = String.valueOf(alphabet.charAt(k % 26)); + isub = sm.headMapForCategory(category); + if(isub.firstEntry() != null) // Make sure submap isn't empty. + { + break; + } + } + + testSecondaryKey(isub, null, false, category, false); + + try + { + isub.tailMap(category); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + } + + { + String category = null; + while(true) + { + int k = rand.nextInt(1000); + category = String.valueOf(alphabet.charAt(k % 26)); + isub = sm.headMapForCategory(category, true); + if(isub.firstEntry() != null) // Make sure submap isn't empty. + { + break; + } + } + + testSecondaryKey(isub, null, false, category, true); + + try + { + String invalid = String.valueOf(category.charAt(0) + 1); + isub.tailMap(invalid); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + } + + // + // Tail map + // + isub = sm.tailMapForCategory(first); + test(greater.compare(isub.firstKey(), first) == 0); + isub = sm.tailMapForCategory(first, false); + test(greater.compare(isub.firstKey(), first) > 0); + isub = sm.tailMapForCategory(last); + test(greater.compare(isub.firstKey(), last) == 0); + test(greater.compare(isub.lastKey(), last) == 0); + isub = sm.tailMapForCategory(last, false); + test(isub.firstEntry() == null); // map is empty + + sm.tailMapForCategory(last).tailMap(last); + sm.tailMapForCategory(last).tailMap(last, false); + try + { + sm.tailMapForCategory(last, false).tailMap(last); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + + { + String category = null; + while(true) + { + int k = rand.nextInt(1000); + category = String.valueOf(alphabet.charAt(k % 26)); + isub = sm.tailMapForCategory(category); + if(isub.firstEntry() != null) // Make sure submap isn't empty. + { + break; + } + } + + testSecondaryKey(isub, category, true, null, false); + + try + { + String invalid = String.valueOf((char)(category.charAt(0) + 1)); + isub.headMap(invalid); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + } + + { + String category = null; + while(true) + { + int k = rand.nextInt(1000); + category = String.valueOf(alphabet.charAt(k % 26)); + isub = sm.tailMapForCategory(category, false); + if(isub.firstEntry() != null) // Make sure submap isn't empty. + { + break; + } + } + + testSecondaryKey(isub, category, false, null, false); + + try + { + isub.headMap(category); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + } + + // + // Sub map + // + isub = sm.subMapForCategory(first, last); + test(greater.compare(isub.firstKey(), first) == 0); + test(greater.compare(isub.lastKey(), last) < 0); + isub = sm.subMapForCategory(first, false, last, false); + test(greater.compare(isub.firstKey(), first) > 0); + isub = sm.subMapForCategory(first, true, last, true); + test(greater.compare(isub.firstKey(), first) == 0); + test(greater.compare(isub.lastKey(), last) == 0); + + try + { + sm.subMapForCategory(first, false, first, false); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + + NavigableMap<String, java.util.Set<java.util.Map.Entry<Integer, Ice.Identity>>> isubsub = null; + + isubsub = isub.subMap(first, true, last, true); + test(greater.compare(isubsub.firstKey(), first) == 0); + test(greater.compare(isubsub.lastKey(), last) == 0); + + isubsub = isub.subMap(first, false, last, false); + test(greater.compare(isubsub.firstKey(), first) > 0); + test(greater.compare(isubsub.lastKey(), last) < 0); + + try + { + isubsub.subMap(first, true, last, false); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + + try + { + isubsub.subMap(first, false, last, true); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + + { + final boolean fromInclusive[] = { false, false, true, true }; + final boolean toInclusive[] = { false, true, false, true }; + for(int i = 0; i < 4; ++i) + { + String from = null, to = null; + while(true) + { + int f = rand.nextInt(1000) % 26; + int t = rand.nextInt(1000) % 26; + int f1 = Math.max(f, t); + int t1 = Math.min(f, t); + if(f1 - t1 < 10) + { + continue; + } + from = String.valueOf(alphabet.charAt(f1 % 26)); + to = String.valueOf(alphabet.charAt(t1 % 26)); + isub = sm.subMapForCategory(from, fromInclusive[i], to, toInclusive[i]); + if(isub.firstEntry() != null) // Make sure submap isn't empty. + { + break; + } + } + + testSecondaryKey(isub, from, fromInclusive[i], to, toInclusive[i]); + } + } + + // + // fastRemove + // + isub = sm.headMapForCategory(first, true); + try + { + isub.fastRemove(first); + test(false); + } + catch(UnsupportedOperationException ex) + { + // Expected. + } + + System.out.println("ok"); + } + + sm.close(); + } + + { + SortedMap sm = new SortedMap(connection, "sortedMap", true, less, indexComparators); + + System.out.print("testing descending map... "); + System.out.flush(); + + { + NavigableMap<Integer, Ice.Identity> dmap = sm.descendingMap(); + + testSortedMap(dmap, false); + testSortedMap(dmap.descendingMap(), true); // Ascending submap. + + } + + int finc, tinc; // Inclusive flags + + for(tinc = 0; tinc < 2; ++tinc) + { + while(true) + { + NavigableMap<Integer, Ice.Identity> sub = sm.headMap(rand.nextInt(1000), tinc == 0); + if(sub.firstEntry() == null) + { + continue; + } + NavigableMap<Integer, Ice.Identity> dmap = sub.descendingMap(); + test(dmap.firstKey().equals(sub.lastKey())); + test(dmap.lastKey().equals(sub.firstKey())); + break; + } + } + + for(finc = 0; finc < 2; ++finc) + { + while(true) + { + NavigableMap<Integer, Ice.Identity> sub = sm.tailMap(rand.nextInt(1000), finc == 0); + if(sub.firstEntry() == null) + { + continue; + } + NavigableMap<Integer, Ice.Identity> dmap = sub.descendingMap(); + test(dmap.firstKey().equals(sub.lastKey())); + test(dmap.lastKey().equals(sub.firstKey())); + break; + } + } + + for(finc = 0; finc < 2; ++finc) + { + for(tinc = 0; tinc < 2; ++tinc) + { + while(true) + { + int f = rand.nextInt(1000); + int t = rand.nextInt(1000); + int from = Math.min(f, t); + int to = Math.max(f, t); + if(to - from < 100) + { + continue; + } + NavigableMap<Integer, Ice.Identity> sub = sm.subMap(from, finc == 0, to, tinc == 0); + if(sub.firstEntry() == null) + { + continue; + } + NavigableMap<Integer, Ice.Identity> dmap = sub.descendingMap(); + test(dmap.firstKey().equals(sub.lastKey())); + test(dmap.lastKey().equals(sub.firstKey())); + break; + } + } + } + + { + NavigableMap<String, java.util.Set<java.util.Map.Entry<Integer, Ice.Identity>>> isub, dmap; + java.util.Comparator<? super String> c; + + isub = sm.mapForCategory(); // An iterator for this map visits keys in descending order. + dmap = isub.descendingMap(); // An iterator for this map visits keys in ascending order. + test(dmap.firstKey().equals(isub.lastKey())); + test(dmap.lastKey().equals(isub.firstKey())); + c = dmap.comparator(); + String prev = null; + for(java.util.Map.Entry<String, java.util.Set<java.util.Map.Entry<Integer, Ice.Identity>>> e : + dmap.entrySet()) + { + if(prev != null) + { + test(c.compare(e.getKey(), prev) > 0); + } + prev = e.getKey(); + } + + dmap = dmap.descendingMap(); + test(dmap.firstKey().equals(isub.firstKey())); + test(dmap.lastKey().equals(isub.lastKey())); + } + + for(tinc = 0; tinc < 2; ++tinc) + { + while(true) + { + String category = String.valueOf(alphabet.charAt(rand.nextInt(1000) % 26)); + NavigableMap<String, java.util.Set<java.util.Map.Entry<Integer, Ice.Identity>>> isub = + sm.headMapForCategory(category, tinc == 0); + if(isub.firstEntry() == null) + { + continue; + } + NavigableMap<String, java.util.Set<java.util.Map.Entry<Integer, Ice.Identity>>> dmap = + isub.descendingMap(); + test(dmap.firstKey().equals(isub.lastKey())); + test(dmap.lastKey().equals(isub.firstKey())); + break; + } + } + + for(finc = 0; finc < 2; ++finc) + { + while(true) + { + String category = String.valueOf(alphabet.charAt(rand.nextInt(1000) % 26)); + NavigableMap<String, java.util.Set<java.util.Map.Entry<Integer, Ice.Identity>>> isub = + sm.tailMapForCategory(category, finc == 0); + if(isub.firstEntry() == null) + { + continue; + } + NavigableMap<String, java.util.Set<java.util.Map.Entry<Integer, Ice.Identity>>> dmap = + isub.descendingMap(); + test(dmap.firstKey().equals(isub.lastKey())); + test(dmap.lastKey().equals(isub.firstKey())); + break; + } + } + + for(finc = 0; finc < 2; ++finc) + { + for(tinc = 0; tinc < 2; ++tinc) + { + while(true) + { + int f = rand.nextInt(1000) % 26; + int t = rand.nextInt(1000) % 26; + int f1 = Math.max(f, t); + int t1 = Math.min(f, t); + if(f1 - t1 < 10) + { + continue; + } + String from = String.valueOf(alphabet.charAt(f1 % 26)); + String to = String.valueOf(alphabet.charAt(t1 % 26)); + NavigableMap<String, java.util.Set<java.util.Map.Entry<Integer, Ice.Identity>>> isub = + sm.subMapForCategory(from, finc == 0, to, tinc == 0); + if(isub.firstEntry() == null) + { + continue; + } + NavigableMap<String, java.util.Set<java.util.Map.Entry<Integer, Ice.Identity>>> dmap = + isub.descendingMap(); + test(dmap.firstKey().equals(isub.lastKey())); + test(dmap.lastKey().equals(isub.firstKey())); + break; + } + } + } + + { + java.util.Set<Integer> keys = sm.descendingKeySet(); + Integer prev = null; + for(Integer i : keys) + { + if(prev != null) + { + test(i.compareTo(prev) < 0); + } + prev = i; + } + } + + { + java.util.Set<String> keys = sm.mapForCategory().descendingKeySet(); + String prev = null; + for(String category : keys) + { + if(prev != null) + { + test(category.compareTo(prev) > 0); + } + prev = category; + } + } + + sm.close(); + + System.out.println("ok"); + } + + { + SortedMap sm = new SortedMap(connection, "sortedMap", true, less, indexComparators); + + System.out.print("testing empty map... "); + System.out.flush(); + + sm.clear(); + + testEmptyMap(sm); + testEmptyMap(sm.headMap(0, false)); + testEmptyMap(sm.headMap(0, false).headMap(0, false)); + testEmptyMap(sm.tailMap(0, false)); + testEmptyMap(sm.tailMap(0, false).tailMap(0, false)); + testEmptyMap(sm.subMap(0, false, 1000, false)); + testEmptyMap(sm.subMap(0, false, 1000, false).subMap(0, false, 1000, false)); + + sm.close(); + + System.out.println("ok"); + } + + connection.close(); + + return 0; + } + + static void + testSortedMap(NavigableMap<Integer, Ice.Identity> sm, boolean ascending) + { + java.util.Comparator<? super Integer> c = sm.comparator(); + java.util.Random rand = new java.util.Random(); + NavigableMap<Integer, Ice.Identity> sub = null; + + final int first = sm.firstKey().intValue(); + final int last = sm.lastKey().intValue(); + + testPrimaryKey(sm, null, false, null, false); + + // + // Head map + // + sub = (NavigableMap<Integer, Ice.Identity>)sm.headMap(last); + test(c.compare(sub.lastKey(), last) < 0); + sub = sm.headMap(last, true); + test(c.compare(sub.lastKey(), last) == 0); + sub = (NavigableMap<Integer, Ice.Identity>)sm.headMap(first); + test(sub.firstEntry() == null); // map is empty + sub = sm.headMap(first, true); + test(c.compare(sub.firstKey(), first) == 0); + test(c.compare(sub.lastKey(), first) == 0); + + sm.headMap(first, true).headMap(first, true); + sm.headMap(first, true).headMap(first); + sm.headMap(first).headMap(first); + try + { + ((NavigableMap<Integer, Ice.Identity>)sm.headMap(first)).headMap(first, true); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + + { + int k = 0; + while(true) + { + k = rand.nextInt(1000); + sub = (NavigableMap<Integer, Ice.Identity>)sm.headMap(k); + if(sub.firstEntry() != null) // Make sure submap isn't empty. + { + break; + } + } + + testPrimaryKey(sub, null, false, k, false); + + try + { + sub.tailMap(k); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + } + + { + int k = 0; + while(true) + { + k = rand.nextInt(1000); + sub = sm.headMap(k, true); + if(sub.firstEntry() != null) // Make sure submap isn't empty. + { + break; + } + } + + testPrimaryKey(sub, null, false, k, true); + + try + { + sub.tailMap(k, false); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + } + + // + // Tail map + // + sub = (NavigableMap<Integer, Ice.Identity>)sm.tailMap(first); + test(c.compare(sub.firstKey(), first) == 0); + sub = sm.tailMap(first, false); + test(c.compare(sub.firstKey(), first) > 0); + sub = (NavigableMap<Integer, Ice.Identity>)sm.tailMap(last); + test(c.compare(sub.firstKey(), last) == 0); + test(c.compare(sub.lastKey(), last) == 0); + sub = sm.tailMap(last, false); + test(sub.firstEntry() == null); // map is empty + + sm.tailMap(last).tailMap(last); + ((NavigableMap<Integer, Ice.Identity>)sm.tailMap(last)).tailMap(last, false); + try + { + sm.tailMap(last, false).tailMap(last); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + + { + int k = 0; + while(true) + { + k = rand.nextInt(1000); + sub = (NavigableMap<Integer, Ice.Identity>)sm.tailMap(k); + if(sub.firstEntry() != null) // Make sure submap isn't empty. + { + break; + } + } + + testPrimaryKey(sub, k, true, null, false); + + try + { + sub.headMap(k); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + } + + { + int k = 0; + while(true) + { + k = rand.nextInt(1000); + sub = sm.tailMap(k, false); + if(sub.firstEntry() != null) // Make sure submap isn't empty. + { + break; + } + } + + testPrimaryKey(sub, k, false, null, false); + + try + { + sub.headMap(k); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + } + + // + // Sub map + // + sub = (NavigableMap<Integer, Ice.Identity>)sm.subMap(first, last); + test(c.compare(sub.firstKey(), first) == 0); + test(c.compare(sub.lastKey(), last) < 0); + sub = sm.subMap(first, false, last, false); + test(c.compare(sub.firstKey(), first) > 0); + sub = sm.subMap(first, true, last, true); + test(c.compare(sub.firstKey(), first) == 0); + test(c.compare(sub.lastKey(), last) == 0); + + try + { + sm.subMap(first, false, first, false); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + + NavigableMap<Integer, Ice.Identity> subsub = null; + + subsub = sub.subMap(first, true, last, true); + test(c.compare(subsub.firstKey(), first) == 0); + test(c.compare(subsub.lastKey(), last) == 0); + + subsub = sub.subMap(first, false, last, false); + test(c.compare(subsub.firstKey(), first) > 0); + test(c.compare(subsub.lastKey(), last) < 0); + + try + { + subsub.subMap(first, true, last, false); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + + try + { + subsub.subMap(first, false, last, true); + test(false); + } + catch(IllegalArgumentException ex) + { + // Expected. + } + + { + final boolean fromInclusive[] = { false, false, true, true }; + final boolean toInclusive[] = { false, true, false, true }; + for(int i = 0; i < 4; ++i) + { + int from = 0, to = 0; + while(true) + { + int f = rand.nextInt(1000); + int t = rand.nextInt(1000); + if(ascending) + { + from = Math.min(f, t); + to = Math.max(f, t); + } + else + { + from = Math.max(f, t); + to = Math.min(f, t); + } + if(Math.abs(to - from) < 100) + { + continue; + } + sub = sm.subMap(from, fromInclusive[i], to, toInclusive[i]); + if(sub.firstEntry() != null) // Make sure submap isn't empty. + { + break; + } + } + + testPrimaryKey(sub, from, fromInclusive[i], to, toInclusive[i]); + } + } + } + + static void + testPrimaryKey(NavigableMap<Integer, Ice.Identity> m, Integer from, boolean fromInclusive, Integer to, + boolean toInclusive) + { + java.util.Comparator<? super Integer> c = m.comparator(); + + Integer first = m.firstKey(); + Integer last = m.lastKey(); + + test(inRange(c, first, from, fromInclusive, to, toInclusive)); + test(inRange(c, last, from, fromInclusive, to, toInclusive)); + + java.util.Random rand = new java.util.Random(); + int i = 0; + while(i < 100) + { + int k = rand.nextInt(1000); + if(!inRange(c, k, from, fromInclusive, to, toInclusive)) + { + continue; + } + + java.util.Map.Entry<Integer, Ice.Identity> e; + Integer key; + + key = m.ceilingKey(k); + if(key == null) + { + test(c.compare(k, last) > 0); + } + else + { + test(c.compare(key, k) >= 0); + } + e = m.ceilingEntry(k); + test((key == null && e == null) || key.equals(e.getKey())); + + key = m.floorKey(k); + if(key == null) + { + test(c.compare(k, first) < 0); + } + else + { + test(c.compare(key, k) <= 0); + } + e = m.floorEntry(k); + test((key == null && e == null) || key.equals(e.getKey())); + + key = m.higherKey(k); + if(key == null) + { + test(c.compare(k, last) >= 0); + } + else + { + test(c.compare(key, k) > 0); + } + e = m.higherEntry(k); + test((key == null && e == null) || key.equals(e.getKey())); + + key = m.lowerKey(k); + if(key == null) + { + test(c.compare(k, first) <= 0); + } + else + { + test(c.compare(key, k) < 0); + } + e = m.lowerEntry(k); + test((key == null && e == null) || key.equals(e.getKey())); + + ++i; + } + + for(java.util.Map.Entry<Integer, Ice.Identity> p : m.entrySet()) + { + test(inRange(c, p.getKey(), from, fromInclusive, to, toInclusive)); + } + } + + static boolean + inRange(java.util.Comparator<? super Integer> c, Integer val, Integer from, boolean fromInclusive, Integer to, + boolean toInclusive) + { + if(from != null) + { + int cmp = c.compare(val, from); + if((fromInclusive && cmp < 0) || (!fromInclusive && cmp <= 0)) + { + return false; + } + } + if(to != null) + { + int cmp = c.compare(val, to); + if((toInclusive && cmp > 0) || (!toInclusive && cmp >= 0)) + { + return false; + } + } + return true; + } + + static void + testSecondaryKey(NavigableMap<String, java.util.Set<java.util.Map.Entry<Integer, Ice.Identity>>> m, String from, + boolean fromInclusive, String to, boolean toInclusive) + { + java.util.Comparator<? super String> c = m.comparator(); + + String first = m.firstKey(); + String last = m.lastKey(); + + test(inRange(c, first, from, fromInclusive, to, toInclusive)); + test(inRange(c, last, from, fromInclusive, to, toInclusive)); + + java.util.Random rand = new java.util.Random(); + int i = 0; + while(i < 100) + { + String category = String.valueOf(alphabet.charAt(rand.nextInt(1000) % 26)); + if(!inRange(c, category, from, fromInclusive, to, toInclusive)) + { + continue; + } + + java.util.Map.Entry<String, java.util.Set<java.util.Map.Entry<Integer, Ice.Identity>>> e; + String key; + + key = m.ceilingKey(category); + if(key == null) + { + test(c.compare(category, last) > 0); + } + else + { + test(c.compare(key, category) >= 0); + } + e = m.ceilingEntry(category); + test((key == null && e == null) || key.equals(e.getKey())); + + key = m.floorKey(category); + if(key == null) + { + test(c.compare(category, first) < 0); + } + else + { + test(c.compare(key, category) <= 0); + } + e = m.floorEntry(category); + test((key == null && e == null) || key.equals(e.getKey())); + + key = m.higherKey(category); + if(key == null) + { + test(c.compare(category, last) >= 0); + } + else + { + test(c.compare(key, category) > 0); + } + e = m.higherEntry(category); + test((key == null && e == null) || key.equals(e.getKey())); + + key = m.lowerKey(category); + if(key == null) + { + test(c.compare(category, first) <= 0); + } + else + { + test(c.compare(key, category) < 0); + } + e = m.lowerEntry(category); + test((key == null && e == null) || key.equals(e.getKey())); + + for(java.util.Map.Entry<String, java.util.Set<java.util.Map.Entry<Integer, Ice.Identity>>> p : m.entrySet()) + { + test(inRange(c, p.getKey(), from, fromInclusive, to, toInclusive)); + } + + ++i; + } + } + + static boolean + inRange(java.util.Comparator<? super String> c, String val, String from, boolean fromInclusive, String to, + boolean toInclusive) + { + if(from != null) + { + int cmp = c.compare(val, from); + if((fromInclusive && cmp < 0) || (!fromInclusive && cmp <= 0)) + { + return false; + } + } + if(to != null) + { + int cmp = c.compare(val, to); + if((toInclusive && cmp > 0) || (!toInclusive && cmp >= 0)) + { + return false; + } + } + return true; + } + + static private void + testEmptyMap(NavigableMap<Integer, Ice.Identity> m) + { + test(m.firstEntry() == null); + test(m.lastEntry() == null); + test(m.ceilingEntry(0) == null); + test(m.floorEntry(0) == null); + test(m.higherEntry(0) == null); + test(m.lowerEntry(0) == null); + test(m.pollFirstEntry() == null); + test(m.pollLastEntry() == null); + + try + { + m.firstKey(); + test(false); + } + catch(java.util.NoSuchElementException ex) + { + // Expected. + } + try + { + m.lastKey(); + test(false); + } + catch(java.util.NoSuchElementException ex) + { + // Expected. + } + + test(m.ceilingKey(0) == null); + test(m.floorKey(0) == null); + test(m.higherKey(0) == null); + test(m.lowerKey(0) == null); + } + + static public void + main(String[] args) + { + int status; + Ice.Communicator communicator = null; + String envName = "db"; + + try + { + Ice.StringSeqHolder holder = new Ice.StringSeqHolder(); + holder.value = args; + communicator = Ice.Util.initialize(holder); + args = holder.value; + if(args.length > 0) + { + envName = args[0]; + envName += "/"; + envName += "db"; + } + + status = run(args, communicator, envName, "binary"); + } + catch(Exception ex) + { + ex.printStackTrace(); + status = 1; + } + + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Exception ex) + { + System.err.println(ex); + status = 1; + } + } + + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Freeze/dbmap/db/.gitignore b/java/test/src/main/java/test/Freeze/dbmap/db/.gitignore new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/java/test/src/main/java/test/Freeze/dbmap/db/.gitignore diff --git a/java/test/src/main/java/test/Freeze/dbmap/run.py b/java/test/src/main/java/test/Freeze/dbmap/run.py new file mode 100755 index 00000000000..d2ed1ebbb13 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/dbmap/run.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +dbdir = os.path.join(os.getcwd(), "db") +TestUtil.cleanDbDir(dbdir) + +sys.stdout.write("starting client... ") +sys.stdout.flush() +clientProc = TestUtil.startClient("test.Freeze.dbmap.Client", '"' + os.getcwd() + '"', startReader=False) +print("ok") +clientProc.startReader() +clientProc.waitTestSuccess() diff --git a/java/test/src/main/java/test/Freeze/evictor/.gitignore b/java/test/src/main/java/test/Freeze/evictor/.gitignore new file mode 100644 index 00000000000..9c39416c539 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/evictor/.gitignore @@ -0,0 +1 @@ +db/* diff --git a/java/test/src/main/java/test/Freeze/evictor/AccountI.java b/java/test/src/main/java/test/Freeze/evictor/AccountI.java new file mode 100644 index 00000000000..55e754e2553 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/evictor/AccountI.java @@ -0,0 +1,195 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.evictor; +import test.Freeze.evictor.Test.*; + +public class AccountI extends Account +{ + public int + getBalance(Ice.Current current) + { + return balance; + } + + public void + deposit(int amount, Ice.Current current) + throws InsufficientFundsException + { + // + // No need to synchronize since everything occurs within its own transaction + // + int newBalance = balance + amount; + if(newBalance < 0) + { + throw new InsufficientFundsException(); + } + balance = newBalance; + } + + public void + transfer(int amount, AccountPrx toAccount, Ice.Current current) throws InsufficientFundsException + { + test(_evictor.getCurrentTransaction() != null); + + toAccount.deposit(amount); // collocated call + deposit(-amount, current); // direct call + } + + public void + transfer2_async(AMD_Account_transfer2 cb, int amount, AccountPrx toAccount, Ice.Current current) + { + // + // Here the dispatch thread does everything + // + test(_evictor.getCurrentTransaction() != null); + + try + { + toAccount.deposit(amount); // collocated call + deposit(-amount, current); // direct call + } + catch(InsufficientFundsException ex) + { + cb.ice_exception(ex); + return; + } + + cb.ice_response(); + } + + public void + transfer3_async(final AMD_Account_transfer3 cb, int amount, AccountPrx toAccount, Ice.Current current) + { + // + // Here the dispatch thread does the actual work, but a separate thread sends the response + // + + class ResponseThread extends Thread + { + synchronized void + response() + { + _response = true; + notify(); + } + + synchronized void + exception(Ice.UserException e) + { + _exception = e; + notify(); + } + + public synchronized void + run() + { + if(_response == false && _exception == null) + { + try + { + wait(1000); + } + catch(InterruptedException e) + { + } + } + try + { + test(_evictor.getCurrentTransaction() == null); + } + catch(Freeze.EvictorDeactivatedException ex) + { + // + // Clearly nobody is waiting for a response! + // + return; + } + + if(_response) + { + cb.ice_response(); + } + else if(_exception != null) + { + cb.ice_exception(_exception); + } + else + { + // + // We don't wait forever! + // + cb.ice_exception(new Ice.TimeoutException()); + } + } + + private boolean _response = false; + private Ice.UserException _exception; + }; + + ResponseThread thread = new ResponseThread(); + thread.setDaemon(true); + + test(_evictor.getCurrentTransaction() != null); + + try + { + toAccount.deposit(amount); // collocated call + deposit(-amount, current); // direct call + } + catch(Ice.UserException e) + { + thread.start(); + Thread.yield(); + + // + // Need to rollback here -- "rollback on user exception" does not work + // when the dispatch commits before it gets any response! + // + _evictor.getCurrentTransaction().rollback(); + + thread.exception(e); + return; + } + + thread.start(); + Thread.yield(); + thread.response(); + } + + public + AccountI(int initialBalance, Freeze.TransactionalEvictor evictor) + { + super(initialBalance); + _evictor = evictor; + } + + public + AccountI() + { + } + + public void + init(Freeze.TransactionalEvictor evictor) + { + assert _evictor == null; + _evictor = evictor; + } + + private Freeze.TransactionalEvictor _evictor; + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } +} diff --git a/java/test/src/main/java/test/Freeze/evictor/Client.java b/java/test/src/main/java/test/Freeze/evictor/Client.java new file mode 100644 index 00000000000..a5e649fdf48 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/evictor/Client.java @@ -0,0 +1,1052 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.evictor; +import test.Freeze.evictor.Test.*; +import java.io.PrintWriter; + +public class Client extends test.Util.Application +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static class ReadThread extends Thread + { + ReadThread(ServantPrx[] servants) + { + _servants = servants; + } + + public void + run() + { + int loops = 10; + while(loops-- > 0) + { + try + { + _servants[0].getValue(); + test(false); + } + catch(Ice.ObjectNotExistException e) + { + // Expected + } + catch(Exception e) + { + test(false); + } + + for(int i = 1; i < _servants.length; ++i) + { + test(_servants[i].getValue() == i); + } + } + } + + private ServantPrx[] _servants; + } + + public static final int StateRunning = 0; + public static final int StateDeactivating = 1; + public static final int StateDeactivated = 2; + + static class ReadForeverThread extends Thread + { + ReadForeverThread(ServantPrx[] servants) + { + _servants = servants; + } + + public void + run() + { + for(;;) + { + try + { + for(int i = 0; i < _servants.length; ++i) + { + if(getEvictorState() == StateDeactivated) + { + _servants[i].slowGetValue(); + test(false); + } + else + { + test(_servants[i].slowGetValue() == i); + } + } + } + catch(Ice.SocketException e) + { + // + // Expected + // + test(validEx()); + return; + } + catch(Ice.LocalException e) + { + System.err.println("Caught unexpected : " + e.toString()); + e.printStackTrace(); + test(false); + return; + } + catch(Exception e) + { + e.printStackTrace(); + test(false); + return; + } + } + } + + synchronized int + getEvictorState() + { + return _state; + } + + synchronized boolean + validEx() + { + return _state == StateDeactivating || _state == StateDeactivated; + } + + synchronized void + setEvictorState(int s) + { + _state = s; + } + + private ServantPrx[] _servants; + private int _state = StateRunning; + } + + static class AddForeverThread extends Thread + { + AddForeverThread(RemoteEvictorPrx evictor, int prefix) + { + _evictor = evictor; + _prefix = "" + prefix; + } + + public void + run() + { + int index = 0; + + for(;;) + { + try + { + String id = _prefix + "-" + index++; + if(getEvictorState() == StateDeactivated) + { + _evictor.createServant(id, 0); + test(false); + } + else + { + _evictor.createServant(id, 0); + } + } + catch(EvictorDeactivatedException e) + { + // + // Expected + // + test(validEx()); + return; + } + catch(Ice.ObjectNotExistException e) + { + // + // Expected + // + test(validEx()); + return; + } + catch(AlreadyRegisteredException e) + { + System.err.println("Caught unexpected AlreadyRegistedException:" + e.toString()); + System.err.println("index is " + index); + test(false); + return; + } + catch(Ice.LocalException e) + { + System.err.println("Caught unexpected : " + e.toString()); + e.printStackTrace(); + test(false); + return; + } + catch(Exception e) + { + e.printStackTrace(); + test(false); + return; + } + } + } + + synchronized int + getEvictorState() + { + return _state; + } + + synchronized boolean + validEx() + { + return _state == StateDeactivating || _state == StateDeactivated; + } + + synchronized void + setEvictorState(int s) + { + _state = s; + } + + private RemoteEvictorPrx _evictor; + private String _prefix; + private int _state = StateRunning; + } + + static class CreateDestroyThread extends Thread + { + CreateDestroyThread(RemoteEvictorPrx evictor, int id, int size) + { + _evictor = evictor; + _id = "" + id; + _size = size; + } + + public void + run() + { + try + { + int loops = 50; + while(loops-- > 0) + { + for(int i = 0; i < _size; i++) + { + String id = "" + i; + if(id.equals(_id)) + { + // + // Create when odd, destroy when even. + // + + if(loops % 2 == 0) + { + ServantPrx servant = _evictor.getServant(id); + servant.destroy(); + + // + // Twice + // + try + { + servant.destroy(); + test(false); + } + catch(Ice.ObjectNotExistException e) + { + // Expected + } + } + else + { + _evictor.createServant(id, i); + + // + // Twice + // + try + { + _evictor.createServant(id, 0); + test(false); + } + catch(AlreadyRegisteredException e) + { + // Expected + } + } + } + else + { + // + // Just read/write the value + // + ServantPrx servant = _evictor.getServant(id); + try + { + int val = servant.getValue(); + test(val == i || val == -i); + servant.setValue(-val); + } + catch(Ice.ObjectNotExistException e) + { + // Expected from time to time + } + } + } + } + } + catch(Exception e) + { + // + // Unexpected! + // + test(false); + } + } + + private RemoteEvictorPrx _evictor; + private String _id; + private int _size; + } + + static class TransferThread extends Thread + { + TransferThread(AccountPrx[] accounts, int count) + { + _accounts = accounts; + _random = new java.util.Random(count); + } + + public void + run() + { + int transferOp = 0; + + for(int i = 0; i < 1000; i++) + { + // + // Transfer 100 at random between two distinct accounts + // + AccountPrx from = _accounts[Math.abs(_random.nextInt() % _accounts.length)]; + + AccountPrx to = null; + do + { + to = _accounts[Math.abs(_random.nextInt() % _accounts.length)]; + } + while(from == to); + + try + { + // + // Alternate between transfer methods + // + switch(transferOp) + { + case 0: + { + from.transfer(100, to); + break; + } + case 1: + { + from.transfer2(100, to); + break; + } + case 2: + { + from.transfer3(100, to); + break; + } + default: + { + test(false); + } + } + transferOp++; + transferOp = transferOp % 3; + } + catch(InsufficientFundsException e) + { + // + // Expected from time to time + // + } + catch(Exception e) + { + // + // Unexpected + // + test(false); + } + + /* + if(i % 100 == 0) + { + System.err.print("."); + System.err.flush(); + } + */ + } + } + + private final AccountPrx[] _accounts; + private final java.util.Random _random; + } + + private int + run(String[] args, PrintWriter out, boolean transactional, boolean shutdown) + throws AlreadyRegisteredException, NotRegisteredException, EvictorDeactivatedException + { + Ice.Communicator communicator = communicator(); + String ref = "factory:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + RemoteEvictorFactoryPrx factory = RemoteEvictorFactoryPrxHelper.checkedCast(base); + + if(transactional) + { + out.print("testing transactional Freeze Evictor... "); + } + else + { + out.print("testing background-save Freeze Evictor... "); + } + out.flush(); + + final int size = 5; + + RemoteEvictorPrx evictor = factory.createEvictor("Test", transactional); + evictor.setSize(size); + + // + // Create some servants + // + ServantPrx[] servants = new ServantPrx[size]; + for(int i = 0; i < size; i++) + { + String id = "" + i; + servants[i] = evictor.createServant(id, i); + servants[i].ice_ping(); + + FacetPrx facet1 = FacetPrxHelper.uncheckedCast(servants[i], "facet1"); + try + { + facet1.ice_ping(); + test(false); + } + catch(Ice.FacetNotExistException e) + { + // + // Expected + // + } + servants[i].addFacet("facet1", "data"); + facet1.ice_ping(); + facet1 = FacetPrxHelper.checkedCast(servants[i], "facet1"); + test(facet1 != null); + facet1.setValue(10 * i); + facet1.addFacet("facet2", "moreData"); + FacetPrx facet2 = FacetPrxHelper.checkedCast(facet1, "facet2"); + test(facet2 != null); + facet2.setValue(100 * i); + } + + // + // Evict and verify values. + // + evictor.setSize(0); + evictor.setSize(size); + for(int i = 0; i < size; i++) + { + servants[i].ice_ping(); + test(servants[i].getValue() == i); + FacetPrx facet1 = FacetPrxHelper.checkedCast(servants[i], "facet1"); + test(facet1 != null); + test(facet1.getValue() == 10 * i); + test(facet1.getData().equals("data")); + FacetPrx facet2 = FacetPrxHelper.checkedCast(facet1, "facet2"); + test(facet2 != null); + test(facet2.getData().equals("moreData")); + } + + // + // Mutate servants. + // + for(int i = 0; i < size; i++) + { + servants[i].setValue(i + 100); + FacetPrx facet1 = FacetPrxHelper.checkedCast(servants[i], "facet1"); + test(facet1 != null); + facet1.setValue(10 * i + 100); + FacetPrx facet2 = FacetPrxHelper.checkedCast(facet1, "facet2"); + test(facet2 != null); + facet2.setValue(100 * i + 100); + } + + for(int i = 0; i < size; i++) + { + test(servants[i].getValue() == i + 100); + FacetPrx facet1 = FacetPrxHelper.checkedCast(servants[i], "facet1"); + test(facet1 != null); + test(facet1.getValue() == 10 * i + 100); + FacetPrx facet2 = FacetPrxHelper.checkedCast(facet1, "facet2"); + test(facet2 != null); + test(facet2.getValue() == 100 * i + 100); + } + + // + // Evict and verify values. + // + evictor.setSize(0); + evictor.setSize(size); + for(int i = 0; i < size; i++) + { + test(servants[i].getValue() == i + 100); + FacetPrx facet1 = FacetPrxHelper.checkedCast(servants[i], "facet1"); + test(facet1 != null); + test(facet1.getValue() == 10 * i + 100); + FacetPrx facet2 = FacetPrxHelper.checkedCast(facet1, "facet2"); + test(facet2 != null); + test(facet2.getValue() == 100 * i + 100); + } + + if(!transactional) + { + // + // Test saving while busy + // + for(int i = 0; i < size; i++) + { + // + // Start a mutating operation so that the object is not idle. + // + servants[i].begin_setValueAsync(i + 300); + + test(servants[i].getValue() == i + 100); + // + // This operation modifies the object state but is not saved + // because the setValueAsync operation is still pending. + // + servants[i].setValue(i + 200); + test(servants[i].getValue() == i + 200); + + // + // Force the response to setValueAsync + // + servants[i].releaseAsync(); + test(servants[i].getValue() == i + 300); + } + } + + // + // Add duplicate facet and catch corresponding exception + // + for(int i = 0; i < size; i++) + { + try + { + servants[i].addFacet("facet1", "foobar"); + test(false); + } + catch(AlreadyRegisteredException ex) + { + } + } + + // + // Remove a facet that does not exist + // + try + { + servants[0].removeFacet("facet3"); + test(false); + } + catch(NotRegisteredException ex) + { + } + + // + // Call an operation that does not exist on the servant + // + try + { + AccountPrxHelper.uncheckedCast(servants[0]).getBalance(); + test(false); + } + catch(Ice.OperationNotExistException ex) + { + } + + // + // Remove all facets + // + for(int i = 0; i < size; i++) + { + servants[i].removeFacet("facet1"); + servants[i].removeFacet("facet2"); + } + + evictor.setSize(0); + evictor.setSize(size); + + // + // Destroy servants and verify ObjectNotExistException. + // + for(int i = 0; i < size; i++) + { + servants[i].destroy(); + try + { + servants[i].getValue(); + test(false); + } + catch(Ice.ObjectNotExistException ex) + { + // Expected + } + + try + { + servants[i].ice_ping(); + test(false); + } + catch(Ice.ObjectNotExistException ex) + { + // Expected + } + } + + // + // Allocate space for size servants. + // + servants = new ServantPrx[size]; + + // + // Recreate servants, set transient value + // + for(int i = 0; i < size; i++) + { + String id = "" + i; + servants[i] = evictor.createServant(id, i); + servants[i].setTransientValue(i); + } + + // + // Evict + // + evictor.saveNow(); + evictor.setSize(0); + evictor.setSize(size); + + // + // Check the transient value + // + for(int i = 0; i < size; i++) + { + test(servants[i].getTransientValue() == -1); + } + + if(!transactional) + { + // + // Now with keep + // + for(int i = 0; i < size; i++) + { + servants[i].keepInCache(); + servants[i].keepInCache(); + servants[i].setTransientValue(i); + } + evictor.saveNow(); + evictor.setSize(0); + evictor.setSize(size); + + // + // Check the transient value + // + for(int i = 0; i < size; i++) + { + test(servants[i].getTransientValue() == i); + } + + // + // Again, after one release + // + for(int i = 0; i < size; i++) + { + servants[i].release(); + } + evictor.saveNow(); + evictor.setSize(0); + evictor.setSize(size); + for(int i = 0; i < size; i++) + { + test(servants[i].getTransientValue() == i); + } + + // + // Again, after a second release + // + for(int i = 0; i < size; i++) + { + servants[i].release(); + } + evictor.saveNow(); + evictor.setSize(0); + evictor.setSize(size); + + for(int i = 0; i < size; i++) + { + test(servants[i].getTransientValue() == -1); + } + + // + // Release one more time + // + for(int i = 0; i < size; i++) + { + try + { + servants[i].release(); + test(false); + } + catch(NotRegisteredException e) + { + // Expected + } + } + } + + if(transactional) + { + int totalBalance = servants[0].getTotalBalance(); + test(totalBalance == 0); + + AccountPrx[] accounts = servants[0].getAccounts(); + test(accounts.length > 0); + + totalBalance = servants[0].getTotalBalance(); + test(totalBalance > 0); + + int threadCount = accounts.length; + + Thread[] threads = new Thread[threadCount]; + for(int i = 0; i < threadCount; i++) + { + threads[i] = new TransferThread(accounts, i); + threads[i].start(); + } + + for(int i = 0; i < threadCount; i++) + { + try + { + threads[i].join(); + } + catch(InterruptedException e) + { + break; // for + } + } + + // + // Check that the total balance did not change! + // + test(totalBalance == servants[0].getTotalBalance()); + } + + // + // Deactivate and recreate evictor, to ensure that servants + // are restored properly after database close and reopen. + // + evictor.deactivate(); + evictor = factory.createEvictor("Test", transactional); + evictor.setSize(size); + for(int i = 0; i < size; i++) + { + String id = "" + i; + servants[i] = evictor.getServant(id); + test(servants[i].getValue() == i); + } + + // + // Test concurrent lookups with a smaller evictor + // size and one missing servant + // + evictor.setSize(size / 2); + servants[0].destroy(); + + { + int threadCount = size * 2; + + Thread[] threads = new Thread[threadCount]; + for(int i = 0; i < threadCount; i++) + { + threads[i] = new ReadThread(servants); + threads[i].start(); + } + + for(int i = 0; i < threadCount; i++) + { + for(;;) + { + try + { + threads[i].join(); + break; + } + catch(InterruptedException e) + { + } + } + } + } + + // + // Clean up. + // + evictor.destroyAllServants(""); + evictor.destroyAllServants("facet1"); + evictor.destroyAllServants("facet2"); + + // + // CreateDestroy threads + // + { + int threadCount = size; + + Thread[] threads = new Thread[threadCount]; + for(int i = 0; i < threadCount; i++) + { + threads[i] = new CreateDestroyThread(evictor, i, size); + threads[i].start(); + } + + for(int i = 0; i < threadCount; i++) + { + for(;;) + { + try + { + threads[i].join(); + break; + } + catch(InterruptedException e) + { + } + } + } + + // + // Verify all destroyed + // + for(int i = 0; i < size; i++) + { + try + { + servants[i].getValue(); + test(false); + } + catch(Ice.ObjectNotExistException e) + { + // Expected + } + } + } + + // + // Recreate servants. + // + servants = new ServantPrx[size]; + for(int i = 0; i < size; i++) + { + String id = "" + i; + servants[i] = evictor.createServant(id, i); + } + + // + // Deactivate in the middle of remote AMD operations + // (really testing Ice here) + // + { + int threadCount = size; + + Thread[] threads = new Thread[threadCount]; + for(int i = 0; i < threadCount; i++) + { + threads[i] = new ReadForeverThread(servants); + threads[i].start(); + } + + try + { + Thread.sleep(500); + } + catch(InterruptedException e) + { + } + + for(int i = 0; i < threadCount; i++) + { + ReadForeverThread t = (ReadForeverThread)threads[i]; + t.setEvictorState(StateDeactivating); + } + evictor.deactivate(); + for(int i = 0; i < threadCount; i++) + { + ReadForeverThread t = (ReadForeverThread)threads[i]; + t.setEvictorState(StateDeactivated); + } + + for(int i = 0; i < threadCount; i++) + { + for(;;) + { + try + { + threads[i].join(); + break; + } + catch(InterruptedException e) + { + } + } + } + } + + // + // Resurrect + // + evictor = factory.createEvictor("Test", transactional); + evictor.destroyAllServants(""); + + // + // Deactivate in the middle of adds + // + { + int threadCount = size; + + Thread[] threads = new Thread[threadCount]; + for(int i = 0; i < threadCount; i++) + { + threads[i] = new AddForeverThread(evictor, i); + threads[i].start(); + } + + try + { + Thread.sleep(500); + } + catch(InterruptedException e) + { + } + + for(int i = 0; i < threadCount; i++) + { + AddForeverThread t = (AddForeverThread)threads[i]; + t.setEvictorState(StateDeactivating); + } + evictor.deactivate(); + for(int i = 0; i < threadCount; i++) + { + AddForeverThread t = (AddForeverThread)threads[i]; + t.setEvictorState(StateDeactivated); + } + + for(int i = 0; i < threadCount; i++) + { + for(;;) + { + try + { + threads[i].join(); + break; + } + catch(InterruptedException e) + { + } + } + } + } + + // + // Clean up. + // + evictor = factory.createEvictor("Test", transactional); + evictor.destroyAllServants(""); + evictor.deactivate(); + + out.println("ok"); + + if(shutdown) + { + factory.shutdown(); + } + + return 0; + } + + public int + run(String[] args) + { + PrintWriter out = getWriter(); + int status = 0; + try + { + status = run(args, out, false, false); + if(status == 0) + { + status = run(args, out, true, true); + } + } + catch(AlreadyRegisteredException ex) + { + ex.printStackTrace(out); + status = 1; + } + catch(NotRegisteredException ex) + { + ex.printStackTrace(out); + status = 1; + } + catch(EvictorDeactivatedException ex) + { + ex.printStackTrace(out); + status = 1; + } + return status; + } + + protected Ice.InitializationData + getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Freeze.evictor"); + return initData; + } + + public static void + main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Freeze/evictor/FacetI.java b/java/test/src/main/java/test/Freeze/evictor/FacetI.java new file mode 100644 index 00000000000..46017f4d52a --- /dev/null +++ b/java/test/src/main/java/test/Freeze/evictor/FacetI.java @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.evictor; +import test.Freeze.evictor.Test.*; + +public class FacetI extends ServantI implements _FacetOperations +{ + FacetI(Facet tie) + { + super(tie); + } + + FacetI(Servant tie, RemoteEvictorI remoteEvictor, Freeze.Evictor evictor, int value, String data) + { + super(tie, remoteEvictor, evictor, value); + ((Facet)_tie).data = data; + } + + public String + getData(Ice.Current current) + { + synchronized(_tie) + { + return ((Facet)_tie).data; + } + } + + public void + setData(String data, Ice.Current current) + { + synchronized(_tie) + { + ((Facet)_tie).data = data; + } + } +} diff --git a/java/test/src/main/java/test/Freeze/evictor/RemoteEvictorFactoryI.java b/java/test/src/main/java/test/Freeze/evictor/RemoteEvictorFactoryI.java new file mode 100644 index 00000000000..dcec049d6af --- /dev/null +++ b/java/test/src/main/java/test/Freeze/evictor/RemoteEvictorFactoryI.java @@ -0,0 +1,36 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.evictor; +import test.Freeze.evictor.Test.*; + +public final class RemoteEvictorFactoryI extends _RemoteEvictorFactoryDisp +{ + RemoteEvictorFactoryI(String envName) + { + _envName = envName; + } + + public RemoteEvictorPrx + createEvictor(String name, boolean transactional, Ice.Current current) + { + RemoteEvictorI remoteEvictor = + new RemoteEvictorI(current.adapter.getCommunicator(), _envName, name, transactional); + return RemoteEvictorPrxHelper. + uncheckedCast(current.adapter.add(remoteEvictor, current.adapter.getCommunicator().stringToIdentity(name))); + } + + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + private String _envName; +} diff --git a/java/test/src/main/java/test/Freeze/evictor/RemoteEvictorI.java b/java/test/src/main/java/test/Freeze/evictor/RemoteEvictorI.java new file mode 100644 index 00000000000..d3667113863 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/evictor/RemoteEvictorI.java @@ -0,0 +1,185 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.evictor; +import test.Freeze.evictor.Test.*; + +public final class RemoteEvictorI extends _RemoteEvictorDisp +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static class Initializer implements Freeze.ServantInitializer + { + public void + initialize(Ice.ObjectAdapter adapter, Ice.Identity ident, String facet, Ice.Object servant) + { + if(servant instanceof AccountI) + { + AccountI account = (AccountI)servant; + account.init((Freeze.TransactionalEvictor)_evictor); + } + else if(facet.length() == 0) + { + ServantI servantImpl = (ServantI) ((_ServantTie) servant).ice_delegate(); + servantImpl.init(_remoteEvictor, _evictor); + } + else + { + ServantI servantImpl = (ServantI) ((_FacetTie) servant).ice_delegate(); + servantImpl.init(_remoteEvictor, _evictor); + } + } + + void init(RemoteEvictorI remoteEvictor, Freeze.Evictor evictor) + { + _remoteEvictor = remoteEvictor; + _evictor = evictor; + } + + private RemoteEvictorI _remoteEvictor; + private Freeze.Evictor _evictor; + } + + RemoteEvictorI(Ice.Communicator communicator, String envName, String category, boolean transactional) + { + _envName = envName; + _category = category; + + // + // NOTE: COMPILERBUG: The timeout here is required for OS X. It shouldn't be too low since + // some operations can take some time to complete on slow machines. + // + _evictorAdapter = communicator. + createObjectAdapterWithEndpoints(java.util.UUID.randomUUID().toString(), "default -t 60000"); + + Initializer initializer = new Initializer(); + + if(transactional) + { + _evictor = Freeze.Util.createTransactionalEvictor(_evictorAdapter, envName, category, null, initializer, + null, true); + } + else + { + _evictor = Freeze.Util.createBackgroundSaveEvictor(_evictorAdapter, envName, category, initializer, null, + true); + } + + // + // Check that we can get an iterator on a non-existing facet + // + Freeze.EvictorIterator p = _evictor.getIterator("foo", 1); + test(p.hasNext() == false); + + initializer.init(this, _evictor); + + _evictorAdapter.addServantLocator(_evictor, category); + _evictorAdapter.activate(); + } + + public void + setSize(int size, Ice.Current current) + { + _evictor.setSize(size); + } + + public ServantPrx + createServant(String id, int value, Ice.Current current) + throws AlreadyRegisteredException, EvictorDeactivatedException + { + Ice.Identity ident = new Ice.Identity(); + ident.category = _category; + ident.name = id; + _ServantTie tie = new _ServantTie(); + tie.ice_delegate(new ServantI(tie, this, _evictor, value)); + try + { + return ServantPrxHelper.uncheckedCast(_evictor.add(tie, ident)); + } + catch(Ice.AlreadyRegisteredException e) + { + throw new AlreadyRegisteredException(); + } + catch(Ice.ObjectAdapterDeactivatedException e) + { + throw new EvictorDeactivatedException(); + } + catch(Freeze.EvictorDeactivatedException e) + { + throw new EvictorDeactivatedException(); + } + catch(Ice.LocalException e) + { + System.out.println("Throwing " + e.toString()); + throw e; + } + } + + public ServantPrx + getServant(String id, Ice.Current current) + { + Ice.Identity ident = new Ice.Identity(); + ident.category = _category; + ident.name = id; + return ServantPrxHelper.uncheckedCast(_evictorAdapter.createProxy(ident)); + } + + public void + saveNow(Ice.Current current) + { + if(_evictor instanceof Freeze.BackgroundSaveEvictor) + { + _evictor.getIterator("", 1); + } + // + // Otherwise everything is always saved + // + } + + public void + deactivate(Ice.Current current) + { + _evictorAdapter.destroy(); + current.adapter.remove(current.adapter.getCommunicator().stringToIdentity(_category)); + } + + public void + destroyAllServants(String facet, Ice.Current current) + { + // + // Only for test purpose: don't use such a small value in + // a real application! + // + int batchSize = 2; + + Freeze.EvictorIterator p = _evictor.getIterator(facet, batchSize); + while(p.hasNext()) + { + _evictor.remove((Ice.Identity) p.next()); + } + } + + final public String + envName() + { + return _envName; + } + + private final String _envName; + private String _category; + private Freeze.Evictor _evictor; + private Ice.ObjectAdapter _evictorAdapter; +} diff --git a/java/test/src/main/java/test/Freeze/evictor/ServantI.java b/java/test/src/main/java/test/Freeze/evictor/ServantI.java new file mode 100644 index 00000000000..cff361d94e2 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/evictor/ServantI.java @@ -0,0 +1,297 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.evictor; +import test.Freeze.evictor.Test.*; + +public class ServantI implements _ServantOperations +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static class DelayedResponse extends Thread + { + DelayedResponse(AMD_Servant_slowGetValue cb, int val) + { + _cb = cb; + _val = val; + } + + public void + run() + { + try + { + sleep(500); + } + catch(InterruptedException e) + { + // Ignored + } + _cb.ice_response(_val); + } + + private AMD_Servant_slowGetValue _cb; + private int _val; + } + + ServantI(Servant tie) + { + _tie = tie; + } + + ServantI(Servant tie, RemoteEvictorI remoteEvictor, Freeze.Evictor evictor, int value) + { + _tie = tie; + _remoteEvictor = remoteEvictor; + _evictor = evictor; + _tie.value = value; + } + + void + init(RemoteEvictorI remoteEvictor, Freeze.Evictor evictor) + { + _remoteEvictor = remoteEvictor; + _evictor = evictor; + } + + public void + destroy(Ice.Current current) + { + _evictor.remove(current.id); + + // + // Need to remove the accounts as well! + // + if(_tie.accounts != null) + { + for(Ice.Identity id : _tie.accounts) + { + _evictor.remove(id); + } + } + } + + public int + getValue(Ice.Current current) + { + synchronized(_tie) + { + return _tie.value; + } + } + + public void + slowGetValue_async(AMD_Servant_slowGetValue cb, Ice.Current current) + { + synchronized(_tie) + { + Thread t = new DelayedResponse(cb, _tie.value); + t.setDaemon(true); + t.start(); + } + } + + public void + setValue(int value, Ice.Current current) + { + synchronized(_tie) + { + _tie.value = value; + } + } + + public void + setValueAsync_async(AMD_Servant_setValueAsync __cb, int value, Ice.Current current) + { + synchronized(_tie) + { + _setValueAsyncCB = __cb; + _setValueAsyncValue = value; + _tie.notify(); + } + } + + public void + releaseAsync(Ice.Current current) + { + synchronized(_tie) + { + while(_setValueAsyncCB == null) + { + try + { + _tie.wait(); + } + catch(InterruptedException ie) + { + break; + } + } + + _tie.value = _setValueAsyncValue; + _setValueAsyncCB.ice_response(); + _setValueAsyncCB = null; + } + } + + public void + addFacet(String name, String data, Ice.Current current) + throws AlreadyRegisteredException + { + _FacetTie tie = new _FacetTie(); + tie.ice_delegate(new FacetI(tie, _remoteEvictor, _evictor, 0, data)); + + try + { + _evictor.addFacet(tie, current.id, name); + } + catch(Ice.AlreadyRegisteredException ex) + { + throw new AlreadyRegisteredException(); + } + } + + public void + removeFacet(String name, Ice.Current current) + throws NotRegisteredException + { + try + { + _evictor.removeFacet(current.id, name); + } + catch(Ice.NotRegisteredException ex) + { + throw new NotRegisteredException(); + } + + } + + public synchronized int + getTransientValue(Ice.Current current) + { + return _transientValue; + } + + public synchronized void + setTransientValue(int val, Ice.Current current) + { + _transientValue = val; + } + + public void + keepInCache(Ice.Current current) + { + Freeze.BackgroundSaveEvictor bse = (Freeze.BackgroundSaveEvictor)_evictor; + bse.keep(current.id); + } + + public void + release(Ice.Current current) + throws NotRegisteredException + { + Freeze.BackgroundSaveEvictor bse = (Freeze.BackgroundSaveEvictor)_evictor; + + try + { + bse.release(current.id); + } + catch(Ice.NotRegisteredException e) + { + throw new NotRegisteredException(); + } + } + + public AccountPrx[] + getAccounts(Ice.Current current) + { + Freeze.TransactionalEvictor te = (Freeze.TransactionalEvictor)_evictor; + + if(te.getCurrentTransaction() != null) + { + if(_tie.accounts == null || _tie.accounts.length == 0) + { + _tie.accounts = new Ice.Identity[10]; + + for(int i = 0; i < _tie.accounts.length; ++i) + { + _tie.accounts[i] = new Ice.Identity(current.id.name + "-account#" + i, current.id.category); + _evictor.add(new AccountI(1000, te), _tie.accounts[i]); + } + } + else + { + te.getCurrentTransaction().rollback(); // not need to re-write this servant + } + } + + if(_tie.accounts == null || _tie.accounts.length == 0) + { + return new AccountPrx[0]; + } + + AccountPrx[] result = new AccountPrx[_tie.accounts.length]; + + for(int i = 0; i < _tie.accounts.length; ++i) + { + result[i] = AccountPrxHelper.uncheckedCast(current.adapter.createProxy(_tie.accounts[i])); + } + return result; + } + + public int + getTotalBalance(Ice.Current current) + { + AccountPrx[] accounts = getAccounts(current); + + // + // Need to start a transaction to ensure a consistent result + // + Freeze.TransactionalEvictor te = (Freeze.TransactionalEvictor)_evictor; + + for(;;) + { + test(te.getCurrentTransaction() == null); + Freeze.Connection con = + Freeze.Util.createConnection(current.adapter.getCommunicator(), _remoteEvictor.envName()); + te.setCurrentTransaction(con.beginTransaction()); + int total = 0; + try + { + for(AccountPrx account : accounts) + { + total += account.getBalance(); + } + return total; + } + catch(Freeze.TransactionalEvictorDeadlockException e) + { + // retry + } + finally + { + con.close(); + te.setCurrentTransaction(null); + } + } + } + + protected RemoteEvictorI _remoteEvictor; + protected Freeze.Evictor _evictor; + protected AMD_Servant_setValueAsync _setValueAsyncCB; + protected int _setValueAsyncValue; + protected Servant _tie; + private int _transientValue = -1; +} diff --git a/java/test/src/main/java/test/Freeze/evictor/Server.java b/java/test/src/main/java/test/Freeze/evictor/Server.java new file mode 100644 index 00000000000..e457fdf619e --- /dev/null +++ b/java/test/src/main/java/test/Freeze/evictor/Server.java @@ -0,0 +1,104 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.evictor; +import test.Freeze.evictor.Test.*; + +public class Server extends test.Util.Application +{ + static class AccountFactory implements Ice.ObjectFactory + { + public Ice.Object + create(String type) + { + assert(type.equals("::Test::Account")); + return new AccountI(); + } + + public void + destroy() + { + } + } + + static class ServantFactory implements Ice.ObjectFactory + { + public Ice.Object + create(String type) + { + assert(type.equals("::Test::Servant")); + _ServantTie tie = new _ServantTie(); + tie.ice_delegate(new ServantI(tie)); + return tie; + } + + public void + destroy() + { + } + } + + static class FacetFactory implements Ice.ObjectFactory + { + public Ice.Object + create(String type) + { + assert(type.equals("::Test::Facet")); + _FacetTie tie = new _FacetTie(); + tie.ice_delegate(new FacetI(tie)); + return tie; + } + + public void + destroy() + { + } + } + + public int + run(String[] args) + { + Ice.Communicator communicator = communicator(); + + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("Evictor"); + + communicator.addObjectFactory(new AccountFactory(), "::Test::Account"); + communicator.addObjectFactory(new ServantFactory(), "::Test::Servant"); + communicator.addObjectFactory(new FacetFactory(), "::Test::Facet"); + + RemoteEvictorFactoryI factory = new RemoteEvictorFactoryI("db"); + adapter.add(factory, communicator.stringToIdentity("factory")); + + adapter.activate(); + + communicator.waitForShutdown(); + + return 0; + } + + protected Ice.InitializationData + getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Evictor.Endpoints", "default -p 12010"); + initData.properties.setProperty("Ice.Package.Test", "test.Freeze.evictor"); + return initData; + } + + public static void + main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Freeze/evictor/Test.ice b/java/test/src/main/java/test/Freeze/evictor/Test.ice new file mode 100644 index 00000000000..c31effe8451 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/evictor/Test.ice @@ -0,0 +1,114 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/Identity.ice> + +[["java:package:test.Freeze.evictor"]] +module Test +{ + +exception AlreadyRegisteredException +{ +}; + +exception NotRegisteredException +{ +}; + +exception EvictorDeactivatedException +{ +}; + + +exception InsufficientFundsException +{ +}; + +class Account +{ + int getBalance(); + ["freeze:write"] void transfer(int amount, Account* toAccount) throws InsufficientFundsException; + + // + // Other implementations of transfer that we want to test as well + // + ["freeze:write", "amd"] void transfer2(int amount, Account* toAccount) throws InsufficientFundsException; + ["freeze:write", "amd"] void transfer3(int amount, Account* toAccount) throws InsufficientFundsException; + + // + // "Internal" operation + // + ["freeze:write:mandatory"] void deposit(int amount) throws InsufficientFundsException; + + int balance; +}; + +sequence<Account*> AccountPrxSeq; +sequence<Ice::Identity> AccountIdSeq; + +["freeze:write"] class Servant +{ + ["freeze:read", "cpp:const"] idempotent int getValue(); + ["amd", "freeze:read", "cpp:const"] idempotent int slowGetValue(); + + idempotent void setValue(int value); + + ["amd"] void setValueAsync(int value); + ["freeze:read", "cpp:const"] void releaseAsync(); + + ["freeze:read", "cpp:const"] void addFacet(string name, string data) throws AlreadyRegisteredException; + ["freeze:read", "cpp:const"] void removeFacet(string name) throws NotRegisteredException; + + ["freeze:read", "cpp:const"] int getTransientValue(); + idempotent void setTransientValue(int value); + idempotent void keepInCache(); + void release() throws NotRegisteredException; + + ["freeze:write"] AccountPrxSeq getAccounts(); + ["freeze:read"] int getTotalBalance(); + + void destroy(); + + int value; + AccountIdSeq accounts; +}; + +["freeze:write"] class Facet extends Servant +{ + ["freeze:read", "cpp:const"] idempotent string getData(); + idempotent void setData(string data); + + string data; +}; + + +interface RemoteEvictor +{ + idempotent void setSize(int size); + + Servant* createServant(string id, int value) + throws AlreadyRegisteredException, EvictorDeactivatedException; + + idempotent Servant* getServant(string id); + + void saveNow(); + + void deactivate(); + idempotent void destroyAllServants(string facet); +}; + +interface RemoteEvictorFactory +{ + RemoteEvictor* createEvictor(string name, bool transactional); + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Freeze/evictor/config b/java/test/src/main/java/test/Freeze/evictor/config new file mode 100644 index 00000000000..3fb2a18d86a --- /dev/null +++ b/java/test/src/main/java/test/Freeze/evictor/config @@ -0,0 +1,11 @@ +Freeze.Evictor.db.Test.SaveSizeTrigger=6 +Freeze.Evictor.db.Test.SavePeriod=2 + +#Freeze.Trace.Evictor=1 +#Freeze.Trace.Transactions=1 +#CFreeze.Trace.DbEnv=3 + +Ice.ThreadPool.Server.SizeMax=20 +Ice.ThreadPool.Server.SizeWarn=0 + +Freeze.Evictor.db.Test.RollbackOnUserException=1 diff --git a/java/test/src/main/java/test/Freeze/evictor/db/.gitignore b/java/test/src/main/java/test/Freeze/evictor/db/.gitignore new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/java/test/src/main/java/test/Freeze/evictor/db/.gitignore diff --git a/java/test/src/main/java/test/Freeze/evictor/run.py b/java/test/src/main/java/test/Freeze/evictor/run.py new file mode 100755 index 00000000000..ee33a5ae7ea --- /dev/null +++ b/java/test/src/main/java/test/Freeze/evictor/run.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +dbdir = os.path.join(os.getcwd(), "db") +TestUtil.cleanDbDir(dbdir) + +testOptions = ' --Freeze.Warn.Deadlocks=0 --Freeze.DbEnv.db.DbHome="%s/db" --Ice.Config="%s/config" ' % (os.getcwd(), os.getcwd()) + +TestUtil.clientServerTest(testOptions, testOptions) diff --git a/java/test/src/main/java/test/Freeze/fileLock/.gitignore b/java/test/src/main/java/test/Freeze/fileLock/.gitignore new file mode 100644 index 00000000000..9c39416c539 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/fileLock/.gitignore @@ -0,0 +1 @@ +db/* diff --git a/java/test/src/main/java/test/Freeze/fileLock/Client.java b/java/test/src/main/java/test/Freeze/fileLock/Client.java new file mode 100644 index 00000000000..8b8fd8c13a2 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/fileLock/Client.java @@ -0,0 +1,88 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.fileLock; + +import java.io.BufferedReader; +import java.io.InputStreamReader; + +public class Client +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static public void + main(String[] args) + { + Ice.Communicator communicator = null; + String envName = "db"; + + try + { + Ice.StringSeqHolder holder = new Ice.StringSeqHolder(); + holder.value = args; + communicator = Ice.Util.initialize(holder); + args = holder.value; + if(args.length > 0) + { + envName = args[0]; + envName += "/"; + envName += "db"; + } + + Freeze.Connection connection = Freeze.Util.createConnection(communicator, envName); + System.out.println("File lock acquired."); + System.out.println("Enter some input and press enter, to release the lock and terminate the program."); + // + // Block the test waiting for IO, so the file lock is preserved. + // + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + try + { + br.readLine(); + } + catch(java.io.IOException ex) + { + System.out.println("exception:\n" + ex.toString()); + test(false); + } + + if(connection != null) + { + connection.close(); + } + } + catch(Exception ex) + { + System.out.println("exception:\n" + ex.toString()); + test(false); + } + finally + { + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Exception ex) + { + System.err.println("exception:\n" + ex); + } + } + } + System.out.println("File lock released."); + } +} diff --git a/java/test/src/main/java/test/Freeze/fileLock/ClientFail.java b/java/test/src/main/java/test/Freeze/fileLock/ClientFail.java new file mode 100644 index 00000000000..2c589a90eb1 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/fileLock/ClientFail.java @@ -0,0 +1,73 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Freeze.fileLock; + +public class ClientFail +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static public void + main(String[] args) + { + Ice.Communicator communicator = null; + String envName = "db"; + + try + { + Ice.StringSeqHolder holder = new Ice.StringSeqHolder(); + holder.value = args; + communicator = Ice.Util.initialize(holder); + args = holder.value; + if(args.length > 0) + { + envName = args[0]; + envName += "/"; + envName += "db"; + } + + try + { + Freeze.Util.createConnection(communicator, envName); + test(false); + } + catch(IceUtil.FileLockException ex) + { + System.out.println("File lock not acquired."); + test(true); + } + } + catch(Exception ex) + { + System.out.println("exception:\n" + ex.toString()); + test(false); + } + finally + { + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Exception ex) + { + System.err.println("exception:\n" + ex); + } + } + } + } +} diff --git a/java/test/src/main/java/test/Freeze/fileLock/db/.gitignore b/java/test/src/main/java/test/Freeze/fileLock/db/.gitignore new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/java/test/src/main/java/test/Freeze/fileLock/db/.gitignore diff --git a/java/test/src/main/java/test/Freeze/fileLock/run.py b/java/test/src/main/java/test/Freeze/fileLock/run.py new file mode 100755 index 00000000000..8f7217a04e9 --- /dev/null +++ b/java/test/src/main/java/test/Freeze/fileLock/run.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +dbdir = os.path.join(os.getcwd(), "db") +TestUtil.cleanDbDir(dbdir) + +sys.stdout.write("testing Freeze file lock... ") +sys.stdout.flush() + +client = os.path.join("test.Freeze.fileLock.Client") +clientFail = os.path.join("test.Freeze.fileLock.ClientFail") + +clientExe = TestUtil.startClient(client, "", None, None, False) +clientExe.expect('File lock acquired.\.*') + +clientFailExe = TestUtil.startClient(clientFail, "", None, None, False) +clientFailExe.expect('File lock not acquired.') +clientFailExe.wait() + +# send some output to client to terminate it. +clientExe.sendline('go') +clientExe.expect('File lock released.') +clientExe.wait() + +# The lock is gone try to acquire it again. +clientExe = TestUtil.startClient(client, "", None, None, False) +clientExe.expect('File lock acquired.\.*') +clientExe.sendline('go') +clientExe.expect('File lock released.') +clientExe.wait() +print("ok") diff --git a/java/test/src/main/java/test/Glacier2/router/Callback.ice b/java/test/src/main/java/test/Glacier2/router/Callback.ice new file mode 100644 index 00000000000..68a40cb866c --- /dev/null +++ b/java/test/src/main/java/test/Glacier2/router/Callback.ice @@ -0,0 +1,40 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Glacier2.router"]] +module Test +{ + +exception CallbackException +{ + double someValue; + string someString; +}; + +interface CallbackReceiver +{ + void callback(); + + void callbackEx() + throws CallbackException; +}; + +interface Callback +{ + void initiateCallback(CallbackReceiver* proxy); + + void initiateCallbackEx(CallbackReceiver* proxy) + throws CallbackException; + + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Glacier2/router/CallbackI.java b/java/test/src/main/java/test/Glacier2/router/CallbackI.java new file mode 100644 index 00000000000..e9290aa6b3e --- /dev/null +++ b/java/test/src/main/java/test/Glacier2/router/CallbackI.java @@ -0,0 +1,40 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Glacier2.router; + +import test.Glacier2.router.Test.CallbackException; +import test.Glacier2.router.Test.CallbackReceiverPrx; +import test.Glacier2.router.Test._CallbackDisp; + +final class CallbackI extends _CallbackDisp +{ + CallbackI() + { + } + + public void + initiateCallback(CallbackReceiverPrx proxy, Ice.Current current) + { + proxy.callback(current.ctx); + } + + public void + initiateCallbackEx(CallbackReceiverPrx proxy, Ice.Current current) + throws CallbackException + { + proxy.callbackEx(current.ctx); + } + + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/test/src/main/java/test/Glacier2/router/CallbackReceiverI.java b/java/test/src/main/java/test/Glacier2/router/CallbackReceiverI.java new file mode 100644 index 00000000000..ecf7e1d62b2 --- /dev/null +++ b/java/test/src/main/java/test/Glacier2/router/CallbackReceiverI.java @@ -0,0 +1,59 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Glacier2.router; + +import test.Glacier2.router.Test.CallbackException; +import test.Glacier2.router.Test._CallbackReceiverDisp; + +final class CallbackReceiverI extends _CallbackReceiverDisp +{ + CallbackReceiverI() + { + _callback = false; + } + + public synchronized void + callback(Ice.Current current) + { + assert(!_callback); + _callback = true; + notify(); + } + + public void + callbackEx(Ice.Current current) + throws CallbackException + { + callback(current); + CallbackException ex = new CallbackException(); + ex.someValue = 3.14; + ex.someString = "3.14"; + throw ex; + } + + synchronized void + callbackOK() + { + while(!_callback) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _callback = false; + } + + private boolean _callback; +} diff --git a/java/test/src/main/java/test/Glacier2/router/Client.java b/java/test/src/main/java/test/Glacier2/router/Client.java new file mode 100644 index 00000000000..257e81c12cd --- /dev/null +++ b/java/test/src/main/java/test/Glacier2/router/Client.java @@ -0,0 +1,484 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Glacier2.router; + +import java.io.PrintWriter; + +import test.Glacier2.router.Test.CallbackException; +import test.Glacier2.router.Test.CallbackPrx; +import test.Glacier2.router.Test.CallbackPrxHelper; +import test.Glacier2.router.Test.CallbackReceiverPrx; +import test.Glacier2.router.Test.CallbackReceiverPrxHelper; + + +public class Client extends test.Util.Application +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public int + run(String[] args) + { + Ice.ObjectPrx routerBase; + + PrintWriter out = getWriter(); + { + out.print("testing stringToProxy for router... "); + out.flush(); + routerBase = communicator().stringToProxy("Glacier2/router:default -p 12347"); + out.println("ok"); + } + + Glacier2.RouterPrx router; + + { + out.print("testing checked cast for router... "); + out.flush(); + router = Glacier2.RouterPrxHelper.checkedCast(routerBase); + test(router != null); + out.println("ok"); + } + + { + out.print("testing router finder... "); + out.flush(); + Ice.RouterFinderPrx finder = Ice.RouterFinderPrxHelper.uncheckedCast( + communicator().stringToProxy("Ice/RouterFinder:default -p 12347")); + test(finder.getRouter().ice_getIdentity().equals(router.ice_getIdentity())); + out.println("ok"); + } + + { + out.print("installing router with communicator... "); + out.flush(); + communicator().setDefaultRouter(router); + out.println("ok"); + } + + { + out.print("getting the session timeout... "); + out.flush(); + long timeout = router.getSessionTimeout(); + test(timeout == 30); + out.println("ok"); + } + + Ice.ObjectPrx base; + + { + out.print("testing stringToProxy for server object... "); + out.flush(); + base = communicator().stringToProxy("c1/callback:tcp -p 12010"); + out.println("ok"); + } + + { + out.print("trying to ping server before session creation... "); + out.flush(); + try + { + base.ice_ping(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + out.println("ok"); + } + catch(Ice.SocketException ex) + { + // + // The JSSE implementation in the AIX JDK appears to have a + // bug that causes a "bad certificate" exception to be raised + // when the connection is forcefully dropped and a retry occurs. + // + if(System.getProperty("os.name").equals("AIX")) + { + out.println("ok"); + } + else + { + test(false); + } + } + } + + { + out.print("trying to create session with wrong password... "); + out.flush(); + try + { + router.createSession("userid", "xxx"); + test(false); + } + catch(Glacier2.PermissionDeniedException ex) + { + out.println("ok"); + } + catch(Glacier2.CannotCreateSessionException ex) + { + test(false); + } + } + + { + out.print("trying to destroy non-existing session... "); + out.flush(); + try + { + router.destroySession(); + test(false); + } + catch(Glacier2.SessionNotExistException ex) + { + out.println("ok"); + } + } + + { + out.print("creating session with correct password... "); + out.flush(); + try + { + router.createSession("userid", "abc123"); + } + catch(Glacier2.PermissionDeniedException ex) + { + test(false); + } + catch(Glacier2.CannotCreateSessionException ex) + { + test(false); + } + out.println("ok"); + } + + { + out.print("trying to create a second session... "); + out.flush(); + try + { + router.createSession("userid", "abc123"); + test(false); + } + catch(Glacier2.PermissionDeniedException ex) + { + test(false); + } + catch(Glacier2.CannotCreateSessionException ex) + { + out.println("ok"); + } + } + + { + out.print("pinging server after session creation... "); + out.flush(); + base.ice_ping(); + out.println("ok"); + } + + CallbackPrx twoway; + + { + out.print("testing checked cast for server object... "); + out.flush(); + twoway = CallbackPrxHelper.checkedCast(base); + test(twoway != null); + out.println("ok"); + } + + Ice.ObjectAdapter adapter; + + { + out.print("creating and activating callback receiver adapter... "); + out.flush(); + communicator().getProperties().setProperty("Ice.PrintAdapterReady", "0"); + adapter = communicator().createObjectAdapterWithRouter("CallbackReceiverAdapter", router); + adapter.activate(); + out.println("ok"); + } + + String category; + + { + out.print("getting category from router... "); + out.flush(); + category = router.getCategoryForClient(); + out.println("ok"); + } + + CallbackReceiverI callbackReceiverImpl; + Ice.Object callbackReceiver; + CallbackReceiverPrx twowayR; + CallbackReceiverPrx fakeTwowayR; + + { + out.print("creating and adding callback receiver object... "); + out.flush(); + callbackReceiverImpl = new CallbackReceiverI(); + callbackReceiver = callbackReceiverImpl; + Ice.Identity callbackReceiverIdent = new Ice.Identity(); + callbackReceiverIdent.name = "callbackReceiver"; + callbackReceiverIdent.category = category; + twowayR = CallbackReceiverPrxHelper.uncheckedCast(adapter.add(callbackReceiver, callbackReceiverIdent)); + Ice.Identity fakeCallbackReceiverIdent = new Ice.Identity(); + fakeCallbackReceiverIdent.name = "callbackReceiver"; + fakeCallbackReceiverIdent.category = "dummy"; + fakeTwowayR = CallbackReceiverPrxHelper.uncheckedCast( + adapter.add(callbackReceiver, fakeCallbackReceiverIdent)); + out.println("ok"); + } + + { + out.print("testing oneway callback... "); + out.flush(); + CallbackPrx oneway = CallbackPrxHelper.uncheckedCast(twoway.ice_oneway()); + CallbackReceiverPrx onewayR = CallbackReceiverPrxHelper.uncheckedCast(twowayR.ice_oneway()); + java.util.Map<String, String> context = new java.util.HashMap<String, String>(); + context.put("_fwd", "o"); + oneway.initiateCallback(onewayR, context); + callbackReceiverImpl.callbackOK(); + out.println("ok"); + } + + { + out.print("testing twoway callback... "); + out.flush(); + java.util.Map<String, String> context = new java.util.HashMap<String, String>(); + context.put("_fwd", "t"); + twoway.initiateCallback(twowayR, context); + callbackReceiverImpl.callbackOK(); + out.println("ok"); + } + + { + out.print("ditto, but with user exception... "); + out.flush(); + java.util.Map<String, String> context = new java.util.HashMap<String, String>(); + context.put("_fwd", "t"); + try + { + twoway.initiateCallbackEx(twowayR, context); + test(false); + } + catch(CallbackException ex) + { + test(ex.someValue == 3.14); + test(ex.someString.equals("3.14")); + } + callbackReceiverImpl.callbackOK(); + out.println("ok"); + } + + { + out.print("trying twoway callback with fake category... "); + out.flush(); + java.util.Map<String, String> context = new java.util.HashMap<String, String>(); + context.put("_fwd", "t"); + try + { + twoway.initiateCallback(fakeTwowayR, context); + test(false); + } + catch(Ice.ObjectNotExistException ex) + { + out.println("ok"); + } + } + + { + out.print("testing whether other allowed category is accepted... "); + out.flush(); + java.util.Map<String, String> context = new java.util.HashMap<String, String>(); + context.put("_fwd", "t"); + CallbackPrx otherCategoryTwoway = CallbackPrxHelper.uncheckedCast( + twoway.ice_identity(communicator().stringToIdentity("c2/callback"))); + otherCategoryTwoway.initiateCallback(twowayR, context); + callbackReceiverImpl.callbackOK(); + out.println("ok"); + } + + { + out.print("testing whether disallowed category gets rejected... "); + out.flush(); + java.util.Map<String, String> context = new java.util.HashMap<String, String>(); + context.put("_fwd", "t"); + try + { + CallbackPrx otherCategoryTwoway = CallbackPrxHelper.uncheckedCast( + twoway.ice_identity(communicator().stringToIdentity("c3/callback"))); + otherCategoryTwoway.initiateCallback(twowayR, context); + test(false); + } + catch(Ice.ObjectNotExistException ex) + { + out.println("ok"); + } + } + + { + out.print("testing whether user-id as category is accepted... "); + out.flush(); + java.util.Map<String, String> context = new java.util.HashMap<String, String>(); + context.put("_fwd", "t"); + CallbackPrx otherCategoryTwoway = CallbackPrxHelper.uncheckedCast( + twoway.ice_identity(communicator().stringToIdentity("_userid/callback"))); + otherCategoryTwoway.initiateCallback(twowayR, context); + callbackReceiverImpl.callbackOK(); + out.println("ok"); + } + + { + out.print("testing server shutdown... "); + out.flush(); + twoway.shutdown(); + // No ping, otherwise the router prints a warning message if it's + // started with --Ice.Warn.Connections. + out.println("ok"); + /* + try + { + base.ice_ping(); + test(false); + } + // If we use the glacier router, the exact exception reason gets + // lost. + catch(Ice.UnknownLocalException ex) + { + System.out.println("ok"); + } + */ + } + + { + out.print("destroying session... "); + out.flush(); + try + { + router.destroySession(); + } + catch(Glacier2.SessionNotExistException ex) + { + test(false); + } + catch(Ice.LocalException ex) + { + test(false); + } + out.println("ok"); + } + + { + out.print("trying to ping server after session destruction... "); + out.flush(); + try + { + base.ice_ping(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + out.println("ok"); + } + catch(Ice.SocketException ex) + { + // + // The JSSE implementation in the AIX JDK appears to have a + // bug that causes a "bad certificate" exception to be raised + // when the connection is forcefully dropped and a retry occurs. + // + if(System.getProperty("os.name").equals("AIX")) + { + out.println("ok"); + } + else + { + test(false); + } + } + } + + if(args.length >= 1 && args[0].equals("--shutdown")) + { + { + out.print("uninstalling router with communicator... "); + out.flush(); + communicator().setDefaultRouter(null); + out.println("ok"); + } + + Ice.ObjectPrx processBase; + + { + out.print("testing stringToProxy for process object... "); + processBase = communicator().stringToProxy("Glacier2/admin -f Process:tcp -h 127.0.0.1 -p 12348"); + out.println("ok"); + } + +/* + { + out.print("uninstalling router with process object... "); + processBase.ice_router(null); + out.println("ok"); + } +*/ + + Ice.ProcessPrx process; + + { + out.print("testing checked cast for admin object... "); + process = Ice.ProcessPrxHelper.checkedCast(processBase); + test(process != null); + out.println("ok"); + } + + out.print("testing Glacier2 shutdown... "); + process.shutdown(); + try + { + process.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + out.println("ok"); + } + } + + return 0; + } + + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("Ice.Warn.Connections", "0"); + initData.properties.setProperty("Ice.Package.Test", "test.Glacier2.router"); + + return initData; + } + + public static void + main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Glacier2/router/Server.java b/java/test/src/main/java/test/Glacier2/router/Server.java new file mode 100644 index 00000000000..78ad7b573ce --- /dev/null +++ b/java/test/src/main/java/test/Glacier2/router/Server.java @@ -0,0 +1,51 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Glacier2.router; + +public class Server extends test.Util.Application +{ + public int + run(String[] args) + { + communicator().getProperties().setProperty("CallbackAdapter.Endpoints", "tcp -p 12010"); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("CallbackAdapter"); + adapter.add(new CallbackI(), + communicator().stringToIdentity("c1/callback")); // The test allows "c1" as category. + adapter.add(new CallbackI(), + communicator().stringToIdentity("c2/callback")); // The test allows "c2" as category. + adapter.add(new CallbackI(), + communicator().stringToIdentity("c3/callback")); // The test rejects "c3" as category. + adapter.add(new CallbackI(), + communicator().stringToIdentity("_userid/callback")); // The test allows the prefixed userid. + adapter.activate(); + communicator().waitForShutdown(); + return 0; + } + + + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Glacier2.router"); + + return initData; + } + + public static void + main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Glacier2/router/passwords b/java/test/src/main/java/test/Glacier2/router/passwords new file mode 100644 index 00000000000..a1527dec2b9 --- /dev/null +++ b/java/test/src/main/java/test/Glacier2/router/passwords @@ -0,0 +1 @@ +userid xxMqsnnDcK8tw
\ No newline at end of file diff --git a/java/test/src/main/java/test/Glacier2/router/run.py b/java/test/src/main/java/test/Glacier2/router/run.py new file mode 100755 index 00000000000..0fe99c10f25 --- /dev/null +++ b/java/test/src/main/java/test/Glacier2/router/run.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +router = os.path.join(TestUtil.getCppBinDir(), "glacier2router") + +args = ' --Ice.Warn.Dispatch=0' + \ + ' --Ice.Warn.Connections=0' + \ + ' --Glacier2.Filter.Category.Accept="c1 c2"' + \ + ' --Glacier2.Filter.Category.AcceptUser="2"' + \ + ' --Glacier2.SessionTimeout="30"' + \ + ' --Glacier2.Client.Endpoints="default -p 12347"' + \ + ' --Glacier2.Server.Endpoints="tcp -h 127.0.0.1"' \ + ' --Ice.Admin.Endpoints="tcp -h 127.0.0.1 -p 12348"' + \ + ' --Ice.Admin.InstanceName=Glacier2' + \ + ' --Glacier2.CryptPasswords="' + os.path.join(os.getcwd(), "passwords") + '"' + +sys.stdout.write("starting router... ") +sys.stdout.flush() +routerConfig = TestUtil.DriverConfig("server") +routerConfig.lang = "cpp" +starterProc = TestUtil.startServer(router, args, count=2, config=routerConfig) +print("ok") + +TestUtil.clientServerTest() + +TestUtil.clientServerTest(additionalClientOptions=" --shutdown") + +starterProc.waitTestSuccess() diff --git a/java/test/src/main/java/test/Glacier2/sessionHelper/Callback.ice b/java/test/src/main/java/test/Glacier2/sessionHelper/Callback.ice new file mode 100644 index 00000000000..cd37cdb95df --- /dev/null +++ b/java/test/src/main/java/test/Glacier2/sessionHelper/Callback.ice @@ -0,0 +1,41 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Glacier2.sessionHelper"]] +module Test +{ + +exception CallbackException +{ + double someValue; + string someString; +}; + +interface CallbackReceiver +{ + void callback(); + + void callbackEx() + throws CallbackException; +}; + +interface Callback +{ + void initiateCallback(CallbackReceiver* proxy); + + void initiateCallbackEx(CallbackReceiver* proxy) + throws CallbackException; + + void shutdown(); +}; + +}; + diff --git a/java/test/src/main/java/test/Glacier2/sessionHelper/CallbackI.java b/java/test/src/main/java/test/Glacier2/sessionHelper/CallbackI.java new file mode 100644 index 00000000000..2cfacf26f5d --- /dev/null +++ b/java/test/src/main/java/test/Glacier2/sessionHelper/CallbackI.java @@ -0,0 +1,40 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Glacier2.sessionHelper; + +import test.Glacier2.sessionHelper.Test.CallbackException; +import test.Glacier2.sessionHelper.Test.CallbackReceiverPrx; +import test.Glacier2.sessionHelper.Test._CallbackDisp; + +final class CallbackI extends _CallbackDisp +{ + CallbackI() + { + } + + public void + initiateCallback(CallbackReceiverPrx proxy, Ice.Current current) + { + proxy.callback(current.ctx); + } + + public void + initiateCallbackEx(CallbackReceiverPrx proxy, Ice.Current current) + throws CallbackException + { + proxy.callbackEx(current.ctx); + } + + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/test/src/main/java/test/Glacier2/sessionHelper/Client.java b/java/test/src/main/java/test/Glacier2/sessionHelper/Client.java new file mode 100644 index 00000000000..f61f84d0051 --- /dev/null +++ b/java/test/src/main/java/test/Glacier2/sessionHelper/Client.java @@ -0,0 +1,440 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Glacier2.sessionHelper; + +import javax.swing.SwingUtilities; +import java.io.PrintWriter; +import test.Glacier2.sessionHelper.Test.CallbackPrx; +import test.Glacier2.sessionHelper.Test.CallbackPrxHelper; + +public class Client extends test.Util.Application +{ + Client() + { + out = getWriter(); + me = this; + } + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + _initData = new Ice.InitializationData(); + _initData.properties = Ice.Util.createProperties(argsH); + _initData.properties.setProperty("Ice.Default.Router", "Glacier2/router:default -p 12347"); + _initData.dispatcher = new Ice.Dispatcher() + { + @Override + public void + dispatch(Runnable runnable, Ice.Connection connection) + { + SwingUtilities.invokeLater(runnable); + } + }; + + return _initData; + } + + @Override + public int run(String[] args) + { + _factory = new Glacier2.SessionFactoryHelper(_initData, new Glacier2.SessionCallback() + { + @Override + public void + connected(Glacier2.SessionHelper session) + throws Glacier2.SessionNotExistException + { + test(false); + } + + @Override + public void + disconnected(Glacier2.SessionHelper session) + { + test(false); + } + + @Override + public void + connectFailed(Glacier2.SessionHelper session, Throwable exception) + { + try + { + throw exception; + } + catch(Glacier2.PermissionDeniedException ex) + { + out.println("ok"); + synchronized(test.Glacier2.sessionHelper.Client.this) + { + test.Glacier2.sessionHelper.Client.wakeUp(); + } + } + catch(Throwable ex) + { + test(false); + } + } + + @Override + public void + createdCommunicator(Glacier2.SessionHelper session) + { + test(session.communicator() != null); + } + }); + + // + // Test to create a session with wrong userid/password + // + synchronized(this) + { + out.print("testing SessionHelper connect with wrong userid/password... "); + out.flush(); + + _session = _factory.connect("userid", "xxx"); + while(true) + { + try + { + wait(); + break; + } + catch(java.lang.InterruptedException ex) + { + } + } + } + + _initData.properties.setProperty("Ice.Default.Router", ""); + _factory = new Glacier2.SessionFactoryHelper(_initData, new Glacier2.SessionCallback() + { + @Override + public void + connected(Glacier2.SessionHelper session) + throws Glacier2.SessionNotExistException + { + out.println("ok"); + synchronized(test.Glacier2.sessionHelper.Client.this) + { + test.Glacier2.sessionHelper.Client.wakeUp(); + } + } + + @Override + public void + disconnected(Glacier2.SessionHelper session) + { + out.println("ok"); + synchronized(test.Glacier2.sessionHelper.Client.this) + { + test.Glacier2.sessionHelper.Client.wakeUp(); + } + } + + @Override + public void + connectFailed(Glacier2.SessionHelper session, Throwable ex) + { + test(false); + } + + @Override + public void + createdCommunicator(Glacier2.SessionHelper session) + { + test(session.communicator() != null); + } + }); + + synchronized(this) + { + out.print("testing SessionHelper connect... "); + out.flush(); + _factory.setRouterHost("127.0.0.1"); + _factory.setPort(12347); + _factory.setSecure(false); + _session = _factory.connect("userid", "abc123"); + while(true) + { + try + { + wait(); + break; + } + catch(java.lang.InterruptedException ex) + { + } + } + + out.print("testing SessionHelper isConnected after connect... "); + out.flush(); + test(_session.isConnected()); + out.println("ok"); + + out.print("testing SessionHelper categoryForClient after connect... "); + out.flush(); + try + { + test(!_session.categoryForClient().equals("")); + } + catch(Glacier2.SessionNotExistException ex) + { + test(false); + } + out.println("ok"); + +// try +// { +// test(_session.session() != null); +// } +// catch(Glacier2.SessionNotExistException ex) +// { +// test(false); +// } + + out.print("testing stringToProxy for server object... "); + out.flush(); + Ice.ObjectPrx base = _session.communicator().stringToProxy("callback:tcp -p 12010"); + out.println("ok"); + + out.print("pinging server after session creation... "); + out.flush(); + base.ice_ping(); + out.println("ok"); + + out.print("testing checked cast for server object... "); + out.flush(); + CallbackPrx twoway = CallbackPrxHelper.checkedCast(base); + test(twoway != null); + out.println("ok"); + + out.print("testing server shutdown... "); + out.flush(); + twoway.shutdown(); + out.println("ok"); + + test(_session.communicator() != null); + out.print("testing SessionHelper destroy... "); + out.flush(); + _session.destroy(); + while(true) + { + try + { + wait(); + break; + } + catch(java.lang.InterruptedException ex) + { + } + } + + out.print("testing SessionHelper isConnected after destroy... "); + out.flush(); + test(_session.isConnected() == false); + out.println("ok"); + + out.print("testing SessionHelper categoryForClient after destroy... "); + out.flush(); + try + { + test(!_session.categoryForClient().equals("")); + test(false); + } + catch(Glacier2.SessionNotExistException ex) + { + } + out.println("ok"); + + out.print("testing SessionHelper session after destroy... "); + try + { + _session.session(); + test(false); + } + catch(Glacier2.SessionNotExistException ex) + { + } + out.println("ok"); + + out.print("testing SessionHelper communicator after destroy... "); + out.flush(); + test(_session.communicator() == null); + out.println("ok"); + + + out.print("uninstalling router with communicator... "); + out.flush(); + communicator().setDefaultRouter(null); + out.println("ok"); + + Ice.ObjectPrx processBase; + { + out.print("testing stringToProxy for process object... "); + processBase = communicator().stringToProxy("Glacier2/admin -f Process:tcp -h 127.0.0.1 -p 12348"); + out.println("ok"); + } + + + Ice.ProcessPrx process; + { + out.print("testing checked cast for admin object... "); + process = Ice.ProcessPrxHelper.checkedCast(processBase); + test(process != null); + out.println("ok"); + } + + out.print("testing Glacier2 shutdown... "); + process.shutdown(); + try + { + process.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + out.println("ok"); + } + } + + _factory = new Glacier2.SessionFactoryHelper(_initData, new Glacier2.SessionCallback() + { + @Override + public void + connected(Glacier2.SessionHelper session) + throws Glacier2.SessionNotExistException + { + test(false); + } + + @Override + public void + disconnected(Glacier2.SessionHelper session) + { + test(false); + } + + @Override + public void + connectFailed(Glacier2.SessionHelper session, Throwable exception) + { + try + { + throw exception; + } + catch(Ice.ConnectFailedException ex) + { + out.println("ok"); + synchronized(test.Glacier2.sessionHelper.Client.this) + { + test.Glacier2.sessionHelper.Client.wakeUp(); + } + } + catch(Throwable ex) + { + test(false); + } + } + + @Override + public void + createdCommunicator(Glacier2.SessionHelper session) + { + test(session.communicator() != null); + } + }); + + // + // Wait a bit to ensure glaci2router has been shutdown. + // + while(true) + { + try + { + Thread.sleep(100); + break; + } + catch(java.lang.InterruptedException ex) + { + } + } + + synchronized(this) + { + out.print("testing SessionHelper connect after router shutdown... "); + out.flush(); + + _factory.setRouterHost("127.0.0.1"); + _factory.setPort(12347); + _factory.setSecure(false); + _session = _factory.connect("userid", "abc123"); + while(true) + { + try + { + wait(); + break; + } + catch(java.lang.InterruptedException ex) + { + } + } + + out.print("testing SessionHelper isConnect after connect failure... "); + out.flush(); + test(_session.isConnected() == false); + out.println("ok"); + + out.print("testing SessionHelper communicator after connect failure... "); + out.flush(); + test(_session.communicator() == null); + out.println("ok"); + + out.print("testing SessionHelper destroy after connect failure... "); + out.flush(); + _session.destroy(); + out.println("ok"); + } + + return 0; + } + + public static void + wakeUp() + { + me.notify(); + } + + public static void + main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } + + private Glacier2.SessionHelper _session; + private Glacier2.SessionFactoryHelper _factory; + private Ice.InitializationData _initData; + static public Client me; + final public PrintWriter out; +} diff --git a/java/test/src/main/java/test/Glacier2/sessionHelper/Server.java b/java/test/src/main/java/test/Glacier2/sessionHelper/Server.java new file mode 100644 index 00000000000..d0cfd717a14 --- /dev/null +++ b/java/test/src/main/java/test/Glacier2/sessionHelper/Server.java @@ -0,0 +1,44 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Glacier2.sessionHelper; + +public class Server extends test.Util.Application +{ + public int + run(String[] args) + { + communicator().getProperties().setProperty("CallbackAdapter.Endpoints", "tcp -p 12010"); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("CallbackAdapter"); + adapter.add(new CallbackI(), communicator().stringToIdentity("callback")); + adapter.activate(); + communicator().waitForShutdown(); + return 0; + } + + + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Glacier2.router"); + + return initData; + } + + public static void + main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Glacier2/sessionHelper/passwords b/java/test/src/main/java/test/Glacier2/sessionHelper/passwords new file mode 100644 index 00000000000..a1527dec2b9 --- /dev/null +++ b/java/test/src/main/java/test/Glacier2/sessionHelper/passwords @@ -0,0 +1 @@ +userid xxMqsnnDcK8tw
\ No newline at end of file diff --git a/java/test/src/main/java/test/Glacier2/sessionHelper/run.py b/java/test/src/main/java/test/Glacier2/sessionHelper/run.py new file mode 100755 index 00000000000..ddb8006f352 --- /dev/null +++ b/java/test/src/main/java/test/Glacier2/sessionHelper/run.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +router = os.path.join(TestUtil.getCppBinDir(), "glacier2router") + +args = ' --Ice.Warn.Dispatch=0' + \ + ' --Ice.Warn.Connections=0' + \ + ' --Glacier2.SessionTimeout="30"' + \ + ' --Glacier2.Client.Endpoints="default -p 12347"' + \ + ' --Glacier2.Server.Endpoints="tcp -h 127.0.0.1"' \ + ' --Ice.Admin.Endpoints="tcp -h 127.0.0.1 -p 12348"' + \ + ' --Ice.Admin.InstanceName=Glacier2' + \ + ' --Glacier2.CryptPasswords="' + os.path.join(os.getcwd(), "passwords") + '"' + +sys.stdout.write("starting router... ") +sys.stdout.flush() +routerConfig = TestUtil.DriverConfig("server") +routerConfig.lang = "cpp" +starterProc = TestUtil.startServer(router, args, count=2, config=routerConfig) +print("ok") + +TestUtil.clientServerTest(additionalClientOptions=" --shutdown") + +starterProc.waitTestSuccess() diff --git a/java/test/src/main/java/test/Ice/acm/AllTests.java b/java/test/src/main/java/test/Ice/acm/AllTests.java new file mode 100644 index 00000000000..a700cdb26b6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/acm/AllTests.java @@ -0,0 +1,625 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.acm; + +import java.io.PrintWriter; + +import test.Ice.acm.Test.RemoteCommunicatorPrx; +import test.Ice.acm.Test.RemoteCommunicatorPrxHelper; +import test.Ice.acm.Test.RemoteObjectAdapterPrx; +import test.Ice.acm.Test.TestIntfPrx; +import test.Ice.acm.Test.TestIntfPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static class LoggerI implements Ice.Logger + { + LoggerI(java.io.PrintWriter out) + { + _out = out; + } + + public void start() + { + synchronized(this) + { + _started = true; + dump(); + } + } + + public void print(String msg) + { + synchronized(this) + { + _messages.add(msg); + if(_started) + { + dump(); + } + } + } + + public void trace(String category, String message) + { + synchronized(this) + { + _messages.add("[" + category + "] " + message); + if(_started) + { + dump(); + } + } + } + + public void warning(String message) + { + synchronized(this) + { + _messages.add("warning: " + message); + if(_started) + { + dump(); + } + } + } + + public void error(String message) + { + synchronized(this) + { + _messages.add("error: " + message); + if(_started) + { + dump(); + } + } + } + + public String getPrefix() + { + return ""; + } + + public Ice.Logger cloneWithPrefix(String prefix) + { + return this; + } + + private void dump() + { + for(String line : _messages) + { + _out.println(line); + } + _messages.clear(); + } + + private boolean _started; + private java.util.List<String> _messages = new java.util.ArrayList<String>(); + private java.io.PrintWriter _out; + }; + + static abstract class TestCase implements Ice.ConnectionCallback + { + public TestCase(String name, RemoteCommunicatorPrx com, java.io.PrintWriter out) + { + _name = name; + _com = com; + _logger = new LoggerI(out); + + _clientACMTimeout = -1; + _clientACMClose = -1; + _clientACMHeartbeat = -1; + + _serverACMTimeout = -1; + _serverACMClose = -1; + _serverACMHeartbeat = -1; + + _heartbeat = 0; + _closed = false; + } + + public void init() + { + _adapter = _com.createObjectAdapter(_serverACMTimeout, _serverACMClose, _serverACMHeartbeat); + + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = _com.ice_getCommunicator().getProperties()._clone(); + initData.logger = _logger; + initData.properties.setProperty("Ice.ACM.Timeout", "1"); + if(_clientACMTimeout >= 0) + { + initData.properties.setProperty("Ice.ACM.Client.Timeout", Integer.toString(_clientACMTimeout)); + } + if(_clientACMClose >= 0) + { + initData.properties.setProperty("Ice.ACM.Client.Close", Integer.toString(_clientACMClose)); + } + if(_clientACMHeartbeat >= 0) + { + initData.properties.setProperty("Ice.ACM.Client.Heartbeat", Integer.toString(_clientACMHeartbeat)); + } + //initData.properties.setProperty("Ice.Trace.Protocol", "2"); + //initData.properties.setProperty("Ice.Trace.Network", "2"); + _communicator = Ice.Util.initialize(initData); + + _thread = new Thread( + new Runnable() + { + public void + run() + { + TestCase.this.run(); + } + }); + } + + public void start() + { + _thread.start(); + } + + public void destroy() + { + _adapter.deactivate(); + _communicator.destroy(); + } + + public void join(PrintWriter out) + { + out.print("testing " + _name + "... "); + out.flush(); + _logger.start(); + try + { + _thread.join(); + } + catch(java.lang.InterruptedException ex) + { + assert(false); + } + if(_msg == null) + { + out.println("ok"); + } + else + { + out.println("failed! " + _msg); + test(false); + } + } + + public void run() + { + TestIntfPrx proxy = TestIntfPrxHelper.uncheckedCast(_communicator.stringToProxy( + _adapter.getTestIntf().toString())); + try + { + proxy.ice_getConnection().setCallback(this); + runTestCase(_adapter, proxy); + } + catch(Exception ex) + { + _msg = "unexpected exception:\n" + ex.toString(); + } + } + + synchronized public void heartbeat(Ice.Connection con) + { + ++_heartbeat; + } + + synchronized public void closed(Ice.Connection con) + { + _closed = true; + } + + public abstract void runTestCase(RemoteObjectAdapterPrx adapter, TestIntfPrx proxy); + + public void setClientACM(int timeout, int close, int heartbeat) + { + _clientACMTimeout = timeout; + _clientACMClose = close; + _clientACMHeartbeat = heartbeat; + } + + public void setServerACM(int timeout, int close, int heartbeat) + { + _serverACMTimeout = timeout; + _serverACMClose = close; + _serverACMHeartbeat = heartbeat; + } + + private String _name; + private RemoteCommunicatorPrx _com; + private String _msg; + private LoggerI _logger; + private Thread _thread; + + private Ice.Communicator _communicator; + private RemoteObjectAdapterPrx _adapter; + + private int _clientACMTimeout; + private int _clientACMClose; + private int _clientACMHeartbeat; + private int _serverACMTimeout; + private int _serverACMClose; + private int _serverACMHeartbeat; + + protected int _heartbeat; + protected boolean _closed; + }; + + static class InvocationHeartbeatTest extends TestCase + { + public InvocationHeartbeatTest(RemoteCommunicatorPrx com, java.io.PrintWriter out) + { + super("invocation heartbeat", com, out); + } + + public void runTestCase(RemoteObjectAdapterPrx adapter, TestIntfPrx proxy) + { + proxy.sleep(2); + test(_heartbeat >= 2); + } + }; + + static class InvocationHeartbeatOnHoldTest extends TestCase + { + public InvocationHeartbeatOnHoldTest(RemoteCommunicatorPrx com, java.io.PrintWriter out) + { + super("invocation with heartbeat on hold", com, out); + // Use default ACM configuration. + } + + public void runTestCase(RemoteObjectAdapterPrx adapter, TestIntfPrx proxy) + { + try + { + // When the OA is put on hold, connections shouldn't + // send heartbeats, the invocation should therefore + // fail. + proxy.sleepAndHold(10); + test(false); + } + catch(Ice.ConnectionTimeoutException ex) + { + adapter.activate(); + proxy.interruptSleep(); + + synchronized(this) + { + test(_closed); + } + } + } + }; + + static class InvocationNoHeartbeatTest extends TestCase + { + public InvocationNoHeartbeatTest(RemoteCommunicatorPrx com, java.io.PrintWriter out) + { + super("invocation with no heartbeat", com, out); + setServerACM(1, 2, 0); // Disable heartbeat on invocations + } + + public void runTestCase(RemoteObjectAdapterPrx adapter, TestIntfPrx proxy) + { + try + { + // Heartbeats are disabled on the server, the + // invocation should fail since heartbeats are + // expected. + proxy.sleep(10); + test(false); + } + catch(Ice.ConnectionTimeoutException ex) + { + proxy.interruptSleep(); + + synchronized(this) + { + test(_heartbeat == 0); + test(_closed); + } + } + } + }; + + static class InvocationHeartbeatCloseOnIdleTest extends TestCase + { + public InvocationHeartbeatCloseOnIdleTest(RemoteCommunicatorPrx com, java.io.PrintWriter out) + { + super("invocation with no heartbeat and close on idle", com, out); + setClientACM(1, 1, 0); // Only close on idle. + setServerACM(1, 2, 0); // Disable heartbeat on invocations + } + + public void runTestCase(RemoteObjectAdapterPrx adapter, TestIntfPrx proxy) + { + // No close on invocation, the call should succeed this + // time. + proxy.sleep(2); + + synchronized(this) + { + test(_heartbeat == 0); + test(!_closed); + } + } + }; + + static class CloseOnIdleTest extends TestCase + { + public CloseOnIdleTest(RemoteCommunicatorPrx com, java.io.PrintWriter out) + { + super("close on idle", com, out); + setClientACM(1, 1, 0); // Only close on idle + } + + public void runTestCase(RemoteObjectAdapterPrx adapter, TestIntfPrx proxy) + { + try + { + Thread.sleep(1500); // Idle for 1.5 second + } + catch(java.lang.InterruptedException ex) + { + } + + synchronized(this) + { + test(_heartbeat == 0); + test(_closed); + } + } + }; + + static class CloseOnInvocationTest extends TestCase + { + public CloseOnInvocationTest(RemoteCommunicatorPrx com, java.io.PrintWriter out) + { + super("close on invocation", com, out); + setClientACM(1, 2, 0); // Only close on invocation + } + + public void runTestCase(RemoteObjectAdapterPrx adapter, TestIntfPrx proxy) + { + try + { + Thread.sleep(1500); // Idle for 1.5 second + } + catch(java.lang.InterruptedException ex) + { + } + + synchronized(this) + { + test(_heartbeat == 0); + test(!_closed); + } + } + }; + + static class CloseOnIdleAndInvocationTest extends TestCase + { + public CloseOnIdleAndInvocationTest(RemoteCommunicatorPrx com, java.io.PrintWriter out) + { + super("close on idle and invocation", com, out); + setClientACM(1, 3, 0); // Only close on idle and invocation + } + + public void runTestCase(RemoteObjectAdapterPrx adapter, TestIntfPrx proxy) + { + // + // Put the adapter on hold. The server will not respond to + // the graceful close. This allows to test whether or not + // the close is graceful or forceful. + // + adapter.hold(); + try + { + Thread.sleep(1500); // Idle for 1.5 second + } + catch(java.lang.InterruptedException ex) + { + } + + synchronized(this) + { + test(_heartbeat == 0); + test(!_closed); // Not closed yet because of graceful close. + } + + adapter.activate(); + try + { + Thread.sleep(500); + } + catch(java.lang.InterruptedException ex) + { + } + + synchronized(this) + { + test(_closed); // Connection should be closed this time. + } + } + }; + + static class ForcefulCloseOnIdleAndInvocationTest extends TestCase + { + public ForcefulCloseOnIdleAndInvocationTest(RemoteCommunicatorPrx com, java.io.PrintWriter out) + { + super("forceful close on idle and invocation", com, out); + setClientACM(1, 4, 0); // Only close on idle and invocation + } + + public void runTestCase(RemoteObjectAdapterPrx adapter, TestIntfPrx proxy) + { + adapter.hold(); + try + { + Thread.sleep(1500); // Idle for 1.5 second + } + catch(java.lang.InterruptedException ex) + { + } + + synchronized(this) + { + test(_heartbeat == 0); + test(_closed); // Connection closed forcefully by ACM + } + } + }; + + static class HeartbeatOnIdleTest extends TestCase + { + public HeartbeatOnIdleTest(RemoteCommunicatorPrx com, java.io.PrintWriter out) + { + super("heartbeat on idle", com, out); + setServerACM(1, -1, 2); // Enable server heartbeats. + } + + public void runTestCase(RemoteObjectAdapterPrx adapter, TestIntfPrx proxy) + { + try + { + Thread.sleep(2000); + } + catch(java.lang.InterruptedException ex) + { + } + + synchronized(this) + { + test(_heartbeat >= 3); + } + } + }; + + static class HeartbeatAlwaysTest extends TestCase + { + public HeartbeatAlwaysTest(RemoteCommunicatorPrx com, java.io.PrintWriter out) + { + super("heartbeat always", com, out); + setServerACM(1, -1, 3); // Enable server heartbeats. + } + + public void runTestCase(RemoteObjectAdapterPrx adapter, TestIntfPrx proxy) + { + for(int i = 0; i < 12; i++) + { + proxy.ice_ping(); + try + { + Thread.sleep(200); + } + catch(java.lang.InterruptedException ex) + { + } + } + + synchronized(this) + { + test(_heartbeat >= 3); + } + } + }; + + static class SetACMTest extends TestCase + { + public SetACMTest(RemoteCommunicatorPrx com, java.io.PrintWriter out) + { + super("setACM/getACM", com, out); + setClientACM(15, 4, 2); + } + + public void runTestCase(RemoteObjectAdapterPrx adapter, TestIntfPrx proxy) + { + Ice.ACM acm = new Ice.ACM(); + acm = proxy.ice_getCachedConnection().getACM(); + test(acm.timeout == 15); + test(acm.close == Ice.ACMClose.CloseOnIdleForceful); + test(acm.heartbeat == Ice.ACMHeartbeat.HeartbeatOnIdle); + + proxy.ice_getCachedConnection().setACM(null, null, null); + acm = proxy.ice_getCachedConnection().getACM(); + test(acm.timeout == 15); + test(acm.close == Ice.ACMClose.CloseOnIdleForceful); + test(acm.heartbeat == Ice.ACMHeartbeat.HeartbeatOnIdle); + + proxy.ice_getCachedConnection().setACM( + new Ice.IntOptional(20), + new Ice.Optional<Ice.ACMClose>(Ice.ACMClose.CloseOnInvocationAndIdle), + new Ice.Optional<Ice.ACMHeartbeat>(Ice.ACMHeartbeat.HeartbeatOnInvocation)); + acm = proxy.ice_getCachedConnection().getACM(); + test(acm.timeout == 20); + test(acm.close == Ice.ACMClose.CloseOnInvocationAndIdle); + test(acm.heartbeat == Ice.ACMHeartbeat.HeartbeatOnInvocation); + } + }; + + public static void + allTests(Ice.Communicator communicator, PrintWriter out) + { + String ref = "communicator:default -p 12010"; + RemoteCommunicatorPrx com = RemoteCommunicatorPrxHelper.uncheckedCast(communicator.stringToProxy(ref)); + + java.util.List<TestCase> tests = new java.util.ArrayList<TestCase>(); + + tests.add(new InvocationHeartbeatTest(com, out)); + tests.add(new InvocationHeartbeatOnHoldTest(com, out)); + tests.add(new InvocationNoHeartbeatTest(com, out)); + tests.add(new InvocationHeartbeatCloseOnIdleTest(com, out)); + + tests.add(new CloseOnIdleTest(com, out)); + tests.add(new CloseOnInvocationTest(com, out)); + tests.add(new CloseOnIdleAndInvocationTest(com, out)); + tests.add(new ForcefulCloseOnIdleAndInvocationTest(com, out)); + + tests.add(new HeartbeatOnIdleTest(com, out)); + tests.add(new HeartbeatAlwaysTest(com, out)); + tests.add(new SetACMTest(com, out)); + + for(TestCase test : tests) + { + test.init(); + } + for(TestCase test : tests) + { + test.start(); + } + for(TestCase test : tests) + { + test.join(out); + } + for(TestCase test : tests) + { + test.destroy(); + } + + out.print("shutting down... "); + out.flush(); + com.shutdown(); + out.println("ok"); + } +} diff --git a/java/test/src/main/java/test/Ice/acm/Client.java b/java/test/src/main/java/test/Ice/acm/Client.java new file mode 100644 index 00000000000..c6045f9a6ca --- /dev/null +++ b/java/test/src/main/java/test/Ice/acm/Client.java @@ -0,0 +1,36 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.acm; + +public class Client extends test.Util.Application +{ + public int run(String[] args) + { + AllTests.allTests(communicator(), getWriter()); + return 0; + } + + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.acm"); + initData.properties.setProperty("Ice.Warn.Connections", "0"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/acm/RemoteCommunicatorI.java b/java/test/src/main/java/test/Ice/acm/RemoteCommunicatorI.java new file mode 100644 index 00000000000..38cb0fc0384 --- /dev/null +++ b/java/test/src/main/java/test/Ice/acm/RemoteCommunicatorI.java @@ -0,0 +1,49 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.acm; + +import test.Ice.acm.Test.RemoteObjectAdapterPrx; +import test.Ice.acm.Test.RemoteObjectAdapterPrxHelper; +import test.Ice.acm.Test._RemoteCommunicatorDisp; + +public class RemoteCommunicatorI extends _RemoteCommunicatorDisp +{ + public RemoteObjectAdapterPrx + createObjectAdapter(int timeout, int close, int heartbeat, Ice.Current current) + { + Ice.Communicator com = current.adapter.getCommunicator(); + Ice.Properties properties = com.getProperties(); + String protocol = properties.getPropertyWithDefault("Ice.Default.Protocol", "tcp"); + + String name = java.util.UUID.randomUUID().toString(); + if(timeout >= 0) + { + properties.setProperty(name + ".ACM.Timeout", Integer.toString(timeout)); + } + if(close >= 0) + { + properties.setProperty(name + ".ACM.Close", Integer.toString(close)); + } + if(heartbeat >= 0) + { + properties.setProperty(name + ".ACM.Heartbeat", Integer.toString(heartbeat)); + } + properties.setProperty(name + ".ThreadPool.Size", "2"); + Ice.ObjectAdapter adapter = com.createObjectAdapterWithEndpoints(name, protocol + " -h 127.0.0.1"); + return RemoteObjectAdapterPrxHelper.uncheckedCast( + current.adapter.addWithUUID(new RemoteObjectAdapterI(adapter))); + } + + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } +}; diff --git a/java/test/src/main/java/test/Ice/acm/RemoteObjectAdapterI.java b/java/test/src/main/java/test/Ice/acm/RemoteObjectAdapterI.java new file mode 100644 index 00000000000..f216f0fee69 --- /dev/null +++ b/java/test/src/main/java/test/Ice/acm/RemoteObjectAdapterI.java @@ -0,0 +1,54 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.acm; + +import test.Ice.acm.Test.TestIntfPrx; +import test.Ice.acm.Test.TestIntfPrxHelper; +import test.Ice.acm.Test._RemoteObjectAdapterDisp; + +public class RemoteObjectAdapterI extends _RemoteObjectAdapterDisp +{ + public RemoteObjectAdapterI(Ice.ObjectAdapter adapter) + { + _adapter = adapter; + _testIntf = TestIntfPrxHelper.uncheckedCast(_adapter.add(new TestI(), + _adapter.getCommunicator().stringToIdentity("test"))); + _adapter.activate(); + } + + public TestIntfPrx getTestIntf(Ice.Current current) + { + return _testIntf; + } + + public void activate(Ice.Current current) + { + _adapter.activate(); + } + + public void hold(Ice.Current current) + { + _adapter.hold(); + } + + public void deactivate(Ice.Current current) + { + try + { + _adapter.destroy(); + } + catch(Ice.ObjectAdapterDeactivatedException ex) + { + } + } + + private Ice.ObjectAdapter _adapter; + private TestIntfPrx _testIntf; +}; diff --git a/java/test/src/main/java/test/Ice/acm/Server.java b/java/test/src/main/java/test/Ice/acm/Server.java new file mode 100644 index 00000000000..e267b9fa498 --- /dev/null +++ b/java/test/src/main/java/test/Ice/acm/Server.java @@ -0,0 +1,48 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.acm; + +public class Server extends test.Util.Application +{ + public int + run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Identity id = communicator.stringToIdentity("communicator"); + adapter.add(new RemoteCommunicatorI(), id); + adapter.activate(); + + // Disable ready print for further adapters. + communicator.getProperties().setProperty("Ice.PrintAdapterReady", "0"); + + return WAIT; + } + + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.acm"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("Ice.Warn.Connections", "0"); + initData.properties.setProperty("Ice.ACM.Timeout", "1"); + return initData; + } + + public static void + main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/acm/Test.ice b/java/test/src/main/java/test/Ice/acm/Test.ice new file mode 100644 index 00000000000..7a2085083e4 --- /dev/null +++ b/java/test/src/main/java/test/Ice/acm/Test.ice @@ -0,0 +1,38 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.acm"]] +module Test +{ + +interface TestIntf +{ + void sleep(int seconds); + void sleepAndHold(int seconds); + void interruptSleep(); +}; + +interface RemoteObjectAdapter +{ + TestIntf* getTestIntf(); + void activate(); + void hold(); + void deactivate(); +}; + +interface RemoteCommunicator +{ + RemoteObjectAdapter* createObjectAdapter(int acmTimeout, int close, int heartbeat); + void shutdown(); +}; + +}; + diff --git a/java/test/src/main/java/test/Ice/acm/TestI.java b/java/test/src/main/java/test/Ice/acm/TestI.java new file mode 100644 index 00000000000..be2e3a4a58e --- /dev/null +++ b/java/test/src/main/java/test/Ice/acm/TestI.java @@ -0,0 +1,51 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.acm; +import test.Ice.acm.Test._TestIntfDisp; + +public class TestI extends _TestIntfDisp +{ + public void sleep(int delay, Ice.Current current) + { + synchronized(this) + { + try + { + wait(delay * 1000); + } + catch(java.lang.InterruptedException ex) + { + } + } + } + + public void sleepAndHold(int delay, Ice.Current current) + { + synchronized(this) + { + try + { + current.adapter.hold(); + wait(delay * 1000); + } + catch(java.lang.InterruptedException ex) + { + } + } + } + + public void interruptSleep(Ice.Current current) + { + synchronized(this) + { + notifyAll(); + } + } +}; diff --git a/java/test/src/main/java/test/Ice/acm/run.py b/java/test/src/main/java/test/Ice/acm/run.py new file mode 100755 index 00000000000..408be7e3127 --- /dev/null +++ b/java/test/src/main/java/test/Ice/acm/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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, getopt + +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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/adapterDeactivation/AllTests.java b/java/test/src/main/java/test/Ice/adapterDeactivation/AllTests.java new file mode 100644 index 00000000000..05cbc8f3d59 --- /dev/null +++ b/java/test/src/main/java/test/Ice/adapterDeactivation/AllTests.java @@ -0,0 +1,103 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.adapterDeactivation; + +import test.Ice.adapterDeactivation.Test.TestIntfPrx; +import test.Ice.adapterDeactivation.Test.TestIntfPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static TestIntfPrx + allTests(Ice.Communicator communicator, java.io.PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + String ref = "test:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + TestIntfPrx obj = TestIntfPrxHelper.checkedCast(base); + test(obj != null); + test(obj.equals(base)); + out.println("ok"); + + { + out.print("creating/destroying/recreating object adapter... "); + out.flush(); + Ice.ObjectAdapter adapter = + communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default"); + try + { + communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default"); + test(false); + } + catch(Ice.AlreadyRegisteredException ex) + { + } + adapter.destroy(); + // + // Use a different port than the first adapter to avoid an "address already in use" error. + // + adapter = communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default"); + adapter.destroy(); + out.println("ok"); + } + + out.print("creating/activating/deactivating object adapter in one operation... "); + out.flush(); + obj._transient(); + out.println("ok"); + + { + out.print("testing connection closure... "); + out.flush(); + for(int i = 0; i < 10; ++i) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + Ice.Communicator comm = Ice.Util.initialize(initData); + comm.stringToProxy("test:default -p 12010").begin_ice_ping(); + comm.destroy(); + } + out.println("ok"); + } + + out.print("deactivating object adapter in the server... "); + out.flush(); + obj.deactivate(); + out.println("ok"); + + out.print("testing whether server is gone... "); + out.flush(); + try + { + obj.ice_ping(); + throw new RuntimeException(); + } + catch(Ice.LocalException ex) + { + out.println("ok"); + } + + return obj; + } +} diff --git a/java/test/src/main/java/test/Ice/adapterDeactivation/Client.java b/java/test/src/main/java/test/Ice/adapterDeactivation/Client.java new file mode 100644 index 00000000000..d5e66de93b6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/adapterDeactivation/Client.java @@ -0,0 +1,38 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.adapterDeactivation; + +public class Client extends test.Util.Application +{ + public int + run(String[] args) + { + AllTests.allTests(communicator(), getWriter()); + return 0; + } + + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.adapterDeactivation"); + return initData; + } + + + public static void + main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/adapterDeactivation/Collocated.java b/java/test/src/main/java/test/Ice/adapterDeactivation/Collocated.java new file mode 100644 index 00000000000..2ddd551b6ac --- /dev/null +++ b/java/test/src/main/java/test/Ice/adapterDeactivation/Collocated.java @@ -0,0 +1,47 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.adapterDeactivation; + +public class Collocated extends test.Util.Application +{ + public int + run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + Ice.ServantLocator locator = new ServantLocatorI(); + adapter.addServantLocator(locator, ""); + + AllTests.allTests(communicator(), getWriter()); + + adapter.waitForDeactivate(); + return 0; + } + + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + if(initData.properties.getPropertyAsInt("Ice.ThreadInterruptSafe") > 0) + { + initData.properties.setProperty("Ice.ThreadPool.Server.Size", "2"); + } + initData.properties.setProperty("Ice.Package.Test", "test.Ice.adapterDeactivation"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + return initData; + } + + public static void + main(String[] args) + { + Collocated app = new Collocated(); + int result = app.main("Collocated", args); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/adapterDeactivation/CookieI.java b/java/test/src/main/java/test/Ice/adapterDeactivation/CookieI.java new file mode 100644 index 00000000000..2d5d990508b --- /dev/null +++ b/java/test/src/main/java/test/Ice/adapterDeactivation/CookieI.java @@ -0,0 +1,21 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.adapterDeactivation; + +import test.Ice.adapterDeactivation.Test.Cookie; + +public final class CookieI extends Cookie +{ + public String + message() + { + return "blahblah"; + } +} diff --git a/java/test/src/main/java/test/Ice/adapterDeactivation/ServantLocatorI.java b/java/test/src/main/java/test/Ice/adapterDeactivation/ServantLocatorI.java new file mode 100644 index 00000000000..1856f6bddcd --- /dev/null +++ b/java/test/src/main/java/test/Ice/adapterDeactivation/ServantLocatorI.java @@ -0,0 +1,78 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.adapterDeactivation; + +import test.Ice.adapterDeactivation.Test.Cookie; + +public final class ServantLocatorI implements Ice.ServantLocator +{ + public + ServantLocatorI() + { + _deactivated = false; + } + + protected synchronized void + finalize() + throws Throwable + { + test(_deactivated); + } + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public Ice.Object + locate(Ice.Current current, Ice.LocalObjectHolder cookie) + { + synchronized(this) + { + test(!_deactivated); + } + + test(current.id.category.length() == 0); + test(current.id.name.equals("test")); + + cookie.value = new CookieI(); + + return new TestI(); + } + + public void + finished(Ice.Current current, Ice.Object servant, java.lang.Object cookie) + { + synchronized(this) + { + test(!_deactivated); + } + + Cookie co = (Cookie)cookie; + test(co.message().equals("blahblah")); + } + + public synchronized void + deactivate(String category) + { + synchronized(this) + { + test(!_deactivated); + + _deactivated = true; + } + } + + private boolean _deactivated; +} diff --git a/java/test/src/main/java/test/Ice/adapterDeactivation/Server.java b/java/test/src/main/java/test/Ice/adapterDeactivation/Server.java new file mode 100644 index 00000000000..56d9ccd5c6b --- /dev/null +++ b/java/test/src/main/java/test/Ice/adapterDeactivation/Server.java @@ -0,0 +1,45 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.adapterDeactivation; + +public class Server extends test.Util.Application +{ + public int + run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + Ice.ServantLocator locator = new ServantLocatorI(); + + adapter.addServantLocator(locator, ""); + adapter.activate(); + serverReady(); + adapter.waitForDeactivate(); + return 0; + } + + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.adapterDeactivation"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + return initData; + } + + public static void + main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/adapterDeactivation/Test.ice b/java/test/src/main/java/test/Ice/adapterDeactivation/Test.ice new file mode 100644 index 00000000000..7b1bd988078 --- /dev/null +++ b/java/test/src/main/java/test/Ice/adapterDeactivation/Test.ice @@ -0,0 +1,28 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.adapterDeactivation"]] +module Test +{ + +interface TestIntf +{ + void transient(); + + void deactivate(); +}; + +local class Cookie +{ + idempotent string message(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/adapterDeactivation/TestI.java b/java/test/src/main/java/test/Ice/adapterDeactivation/TestI.java new file mode 100644 index 00000000000..38ce346f3de --- /dev/null +++ b/java/test/src/main/java/test/Ice/adapterDeactivation/TestI.java @@ -0,0 +1,39 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.adapterDeactivation; + +import test.Ice.adapterDeactivation.Test.*; + +public final class TestI extends _TestIntfDisp +{ + public void + _transient(Ice.Current current) + { + Ice.Communicator communicator = current.adapter.getCommunicator(); + + Ice.ObjectAdapter adapter = + communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default -p 9999"); + adapter.activate(); + adapter.destroy(); + } + + public void + deactivate(Ice.Current current) + { + current.adapter.deactivate(); + try + { + Thread.sleep(100); + } + catch(InterruptedException ex) + { + } + } +} diff --git a/java/test/src/main/java/test/Ice/adapterDeactivation/run.py b/java/test/src/main/java/test/Ice/adapterDeactivation/run.py new file mode 100755 index 00000000000..8bb456187d9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/adapterDeactivation/run.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/admin/AllTests.java b/java/test/src/main/java/test/Ice/admin/AllTests.java new file mode 100644 index 00000000000..abc85ce0b86 --- /dev/null +++ b/java/test/src/main/java/test/Ice/admin/AllTests.java @@ -0,0 +1,553 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.admin; + +import java.io.PrintWriter; +import test.Ice.admin.Test.*; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static void + testFacets(Ice.Communicator com, boolean builtInFacets) + { + if(builtInFacets) + { + test(com.findAdminFacet("Properties") != null); + test(com.findAdminFacet("Process") != null); + test(com.findAdminFacet("Logger") != null); + test(com.findAdminFacet("Metrics") != null); + } + + TestFacet f1 = new TestFacetI(); + TestFacet f2 = new TestFacetI(); + TestFacet f3 = new TestFacetI(); + + com.addAdminFacet(f1, "Facet1"); + com.addAdminFacet(f2, "Facet2"); + com.addAdminFacet(f3, "Facet3"); + + test(com.findAdminFacet("Facet1") == f1); + test(com.findAdminFacet("Facet2") == f2); + test(com.findAdminFacet("Facet3") == f3); + test(com.findAdminFacet("Bogus") == null); + + java.util.Map<String, Ice.Object> facetMap = com.findAllAdminFacets(); + if(builtInFacets) + { + test(facetMap.size() == 7); + test(facetMap.containsKey("Properties")); + test(facetMap.containsKey("Process")); + test(facetMap.containsKey("Logger")); + test(facetMap.containsKey("Metrics")); + } + else + { + test(facetMap.size() >= 3); + } + test(facetMap.containsKey("Facet1")); + test(facetMap.containsKey("Facet2")); + test(facetMap.containsKey("Facet3")); + + try + { + com.addAdminFacet(f1, "Facet1"); + test(false); + } + catch(Ice.AlreadyRegisteredException ex) + { + // Expected + } + + try + { + com.removeAdminFacet("Bogus"); + test(false); + } + catch(Ice.NotRegisteredException ex) + { + // Expected + } + + com.removeAdminFacet("Facet1"); + com.removeAdminFacet("Facet2"); + com.removeAdminFacet("Facet3"); + + try + { + com.removeAdminFacet("Facet1"); + test(false); + } + catch(Ice.NotRegisteredException ex) + { + // Expected + } + } + + public static void + allTests(test.Util.Application app, PrintWriter out) + { + out.print("testing communicator operations... "); + out.flush(); + { + // + // Test: Exercise addAdminFacet, findAdminFacet, removeAdminFacet with a typical configuration. + // + Ice.InitializationData init = new Ice.InitializationData(); + init.properties = Ice.Util.createProperties(); + init.properties.setProperty("Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + init.properties.setProperty("Ice.Admin.InstanceName", "Test"); + Ice.Communicator com = Ice.Util.initialize(init); + testFacets(com, true); + com.destroy(); + } + { + // + // Test: Verify that the operations work correctly in the presence of facet filters. + // + Ice.InitializationData init = new Ice.InitializationData(); + init.properties = Ice.Util.createProperties(); + init.properties.setProperty("Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + init.properties.setProperty("Ice.Admin.InstanceName", "Test"); + init.properties.setProperty("Ice.Admin.Facets", "Properties"); + Ice.Communicator com = Ice.Util.initialize(init); + testFacets(com, false); + com.destroy(); + } + { + // + // Test: Verify that the operations work correctly with the Admin object disabled. + // + Ice.Communicator com = Ice.Util.initialize(); + testFacets(com, false); + com.destroy(); + } + { + // + // Test: Verify that the operations work correctly when Ice.Admin.Enabled is set + // + Ice.InitializationData init = new Ice.InitializationData(); + init.properties = Ice.Util.createProperties(); + init.properties.setProperty("Ice.Admin.Enabled", "1"); + Ice.Communicator com = Ice.Util.initialize(init); + + test(com.getAdmin() == null); + Ice.Identity id = com.stringToIdentity("test-admin"); + try + { + com.createAdmin(null, id); + test(false); + } + catch(Ice.InitializationException ex) + { + } + + Ice.ObjectAdapter adapter = com.createObjectAdapter(""); + test(com.createAdmin(adapter, id) != null); + test(com.getAdmin() != null); + testFacets(com, true); + com.destroy(); + } + { + // + // Test: Verify that the operations work correctly when creation of the Admin object is delayed. + // + Ice.InitializationData init = new Ice.InitializationData(); + init.properties = Ice.Util.createProperties(); + init.properties.setProperty("Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + init.properties.setProperty("Ice.Admin.InstanceName", "Test"); + init.properties.setProperty("Ice.Admin.DelayCreation", "1"); + Ice.Communicator com = Ice.Util.initialize(init); + testFacets(com, true); + com.getAdmin(); + testFacets(com, true); + com.destroy(); + } + out.println("ok"); + + String ref = "factory:default -p 12010 -t 10000"; + RemoteCommunicatorFactoryPrx factory = + RemoteCommunicatorFactoryPrxHelper.uncheckedCast(app.communicator().stringToProxy(ref)); + + out.print("testing process facet... "); + out.flush(); + { + // + // Test: Verify that Process::shutdown() operation shuts down the communicator. + // + java.util.Map<String, String> props = new java.util.HashMap<String, String>(); + props.put("Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + props.put("Ice.Admin.InstanceName", "Test"); + RemoteCommunicatorPrx com = factory.createCommunicator(props); + Ice.ObjectPrx obj = com.getAdmin(); + Ice.ProcessPrx proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process"); + proc.shutdown(); + com.waitForShutdown(); + com.destroy(); + } + out.println("ok"); + + out.print("testing properties facet... "); + out.flush(); + { + java.util.Map<String, String> props = new java.util.HashMap<String, String>(); + props.put("Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + props.put("Ice.Admin.InstanceName", "Test"); + props.put("Prop1", "1"); + props.put("Prop2", "2"); + props.put("Prop3", "3"); + RemoteCommunicatorPrx com = factory.createCommunicator(props); + Ice.ObjectPrx obj = com.getAdmin(); + Ice.PropertiesAdminPrx pa = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties"); + + // + // Test: PropertiesAdmin::getProperty() + // + test(pa.getProperty("Prop2").equals("2")); + test(pa.getProperty("Bogus").equals("")); + + // + // Test: PropertiesAdmin::getProperties() + // + java.util.Map<String, String> pd = pa.getPropertiesForPrefix(""); + test(pd.size() == 5); + test(pd.get("Ice.Admin.Endpoints").equals("tcp -h 127.0.0.1")); + test(pd.get("Ice.Admin.InstanceName").equals("Test")); + test(pd.get("Prop1").equals("1")); + test(pd.get("Prop2").equals("2")); + test(pd.get("Prop3").equals("3")); + + java.util.Map<String, String> changes; + + // + // Test: PropertiesAdmin::setProperties() + // + java.util.Map<String, String> setProps = new java.util.HashMap<String, String>(); + setProps.put("Prop1", "10"); // Changed + setProps.put("Prop2", "20"); // Changed + setProps.put("Prop3", ""); // Removed + setProps.put("Prop4", "4"); // Added + setProps.put("Prop5", "5"); // Added + pa.setProperties(setProps); + test(pa.getProperty("Prop1").equals("10")); + test(pa.getProperty("Prop2").equals("20")); + test(pa.getProperty("Prop3").equals("")); + test(pa.getProperty("Prop4").equals("4")); + test(pa.getProperty("Prop5").equals("5")); + changes = com.getChanges(); + test(changes.size() == 5); + test(changes.get("Prop1").equals("10")); + test(changes.get("Prop2").equals("20")); + test(changes.get("Prop3").equals("")); + test(changes.get("Prop4").equals("4")); + test(changes.get("Prop5").equals("5")); + pa.setProperties(setProps); + changes = com.getChanges(); + test(changes.isEmpty()); + + com.destroy(); + } + out.println("ok"); + + out.print("testing logger facet... "); + out.flush(); + { + java.util.Map<String, String> props = new java.util.HashMap<String, String>(); + props.put("Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + props.put("Ice.Admin.InstanceName", "Test"); + props.put("NullLogger", "1"); + RemoteCommunicatorPrx com = factory.createCommunicator(props); + + com.trace("testCat", "trace"); + com.warning("warning"); + com.error("error"); + com.print("print"); + + Ice.ObjectPrx obj = com.getAdmin(); + Ice.LoggerAdminPrx logger = Ice.LoggerAdminPrxHelper.checkedCast(obj, "Logger"); + test(logger != null); + + Ice.StringHolder prefix = new Ice.StringHolder(); + + // + // Get all + // + Ice.LogMessage[] logMessages = logger.getLog(null, null, -1, prefix); + + test(logMessages.length == 4); + test(prefix.value.equals("NullLogger")); + test(logMessages[0].traceCategory.equals("testCat") && logMessages[0].message.equals("trace")); + test(logMessages[1].message.equals("warning")); + test(logMessages[2].message.equals("error")); + test(logMessages[3].message.equals("print")); + + // + // Get only errors and warnings + // + com.error("error2"); + com.print("print2"); + com.trace("testCat", "trace2"); + com.warning("warning2"); + + Ice.LogMessageType[] messageTypes = {Ice.LogMessageType.ErrorMessage, Ice.LogMessageType.WarningMessage}; + + logMessages = logger.getLog(messageTypes, null, -1, prefix); + test(logMessages.length == 4); + test(prefix.value.equals("NullLogger")); + + for(Ice.LogMessage msg : java.util.Arrays.asList(logMessages)) + { + test(msg.type == Ice.LogMessageType.ErrorMessage || msg.type == Ice.LogMessageType.WarningMessage); + } + + // + // Get only errors and traces with Cat = "testCat" + // + com.trace("testCat2", "A"); + com.trace("testCat", "trace3"); + com.trace("testCat2", "B"); + + messageTypes = new Ice.LogMessageType[]{Ice.LogMessageType.ErrorMessage, Ice.LogMessageType.TraceMessage}; + String[] categories = {"testCat"}; + logMessages = logger.getLog(messageTypes, categories, -1, prefix); + test(logMessages.length == 5); + test(prefix.value.equals("NullLogger")); + + for(Ice.LogMessage msg : java.util.Arrays.asList(logMessages)) + { + test(msg.type == Ice.LogMessageType.ErrorMessage || + (msg.type == Ice.LogMessageType.TraceMessage && msg.traceCategory.equals("testCat"))); + } + + // + // Same, but limited to last 2 messages (trace3 + error3) + // + com.error("error3"); + + logMessages = logger.getLog(messageTypes, categories, 2, prefix); + test(logMessages.length == 2); + test(prefix.value.equals("NullLogger")); + + test(logMessages[0].message.equals("trace3")); + test(logMessages[1].message.equals("error3")); + + // + // Now, test RemoteLogger + // + Ice.ObjectAdapter adapter = + app.communicator().createObjectAdapterWithEndpoints("RemoteLoggerAdapter", "tcp -h localhost"); + + RemoteLoggerI remoteLogger = new RemoteLoggerI(); + + Ice.RemoteLoggerPrx myProxy = Ice.RemoteLoggerPrxHelper.uncheckedCast(adapter.addWithUUID(remoteLogger)); + + adapter.activate(); + + // + // No filtering + // + logMessages = logger.getLog(null, null, -1, prefix); + remoteLogger.checkNextInit(prefix.value, logMessages); + + try + { + logger.attachRemoteLogger(myProxy, null, null, -1); + } + catch(Ice.RemoteLoggerAlreadyAttachedException ex) + { + test(false); + } + + remoteLogger.wait(1); + + remoteLogger.checkNextLog(Ice.LogMessageType.TraceMessage, "rtrace", "testCat"); + remoteLogger.checkNextLog(Ice.LogMessageType.WarningMessage, "rwarning", ""); + remoteLogger.checkNextLog(Ice.LogMessageType.ErrorMessage, "rerror", ""); + remoteLogger.checkNextLog(Ice.LogMessageType.PrintMessage, "rprint", ""); + + com.trace("testCat", "rtrace"); + com.warning("rwarning"); + com.error("rerror"); + com.print("rprint"); + + remoteLogger.wait(4); + + test(logger.detachRemoteLogger(myProxy)); + test(!logger.detachRemoteLogger(myProxy)); + + // + // Use Error + Trace with "traceCat" filter with 4 limit + // + logMessages = logger.getLog(messageTypes, categories, 4, prefix); + test(logMessages.length == 4); + remoteLogger.checkNextInit(prefix.value, logMessages); + + try + { + logger.attachRemoteLogger(myProxy, messageTypes, categories, 4); + } + catch(Ice.RemoteLoggerAlreadyAttachedException ex) + { + test(false); + } + + remoteLogger.wait(1); + + remoteLogger.checkNextLog(Ice.LogMessageType.TraceMessage, "rtrace2", "testCat"); + remoteLogger.checkNextLog(Ice.LogMessageType.ErrorMessage, "rerror2", ""); + + com.warning("rwarning2"); + com.trace("testCat", "rtrace2"); + com.warning("rwarning3"); + com.error("rerror2"); + com.print("rprint2"); + + remoteLogger.wait(2); + + // + // Attempt reconnection with slightly different proxy + // + try + { + logger.attachRemoteLogger(Ice.RemoteLoggerPrxHelper.uncheckedCast(myProxy.ice_oneway()), + messageTypes, categories, 4); + test(false); + } + catch(Ice.RemoteLoggerAlreadyAttachedException ex) + { + // expected + } + + com.destroy(); + } + out.println("ok"); + + out.print("testing custom facet... "); + out.flush(); + { + // + // Test: Verify that the custom facet is present. + // + java.util.Map<String, String> props = new java.util.HashMap<String, String>(); + props.put("Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + props.put("Ice.Admin.InstanceName", "Test"); + RemoteCommunicatorPrx com = factory.createCommunicator(props); + Ice.ObjectPrx obj = com.getAdmin(); + TestFacetPrx tf = TestFacetPrxHelper.checkedCast(obj, "TestFacet"); + tf.op(); + com.destroy(); + } + out.println("ok"); + + out.print("testing facet filtering... "); + out.flush(); + { + // + // Test: Set Ice.Admin.Facets to expose only the Properties facet, + // meaning no other facet is available. + // + java.util.Map<String, String> props = new java.util.HashMap<String, String>(); + props.put("Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + props.put("Ice.Admin.InstanceName", "Test"); + props.put("Ice.Admin.Facets", "Properties"); + RemoteCommunicatorPrx com = factory.createCommunicator(props); + Ice.ObjectPrx obj = com.getAdmin(); + Ice.ProcessPrx proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process"); + test(proc == null); + TestFacetPrx tf = TestFacetPrxHelper.checkedCast(obj, "TestFacet"); + test(tf == null); + com.destroy(); + } + { + // + // Test: Set Ice.Admin.Facets to expose only the Process facet, + // meaning no other facet is available. + // + java.util.Map<String, String> props = new java.util.HashMap<String, String>(); + props.put("Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + props.put("Ice.Admin.InstanceName", "Test"); + props.put("Ice.Admin.Facets", "Process"); + RemoteCommunicatorPrx com = factory.createCommunicator(props); + Ice.ObjectPrx obj = com.getAdmin(); + Ice.PropertiesAdminPrx pa = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties"); + test(pa == null); + TestFacetPrx tf = TestFacetPrxHelper.checkedCast(obj, "TestFacet"); + test(tf == null); + com.destroy(); + } + { + // + // Test: Set Ice.Admin.Facets to expose only the TestFacet facet, + // meaning no other facet is available. + // + java.util.Map<String, String> props = new java.util.HashMap<String, String>(); + props.put("Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + props.put("Ice.Admin.InstanceName", "Test"); + props.put("Ice.Admin.Facets", "TestFacet"); + RemoteCommunicatorPrx com = factory.createCommunicator(props); + Ice.ObjectPrx obj = com.getAdmin(); + Ice.PropertiesAdminPrx pa = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties"); + test(pa == null); + Ice.ProcessPrx proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process"); + test(proc == null); + com.destroy(); + } + { + // + // Test: Set Ice.Admin.Facets to expose two facets. Use whitespace to separate the + // facet names. + // + java.util.Map<String, String> props = new java.util.HashMap<String, String>(); + props.put("Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + props.put("Ice.Admin.InstanceName", "Test"); + props.put("Ice.Admin.Facets", "Properties TestFacet"); + RemoteCommunicatorPrx com = factory.createCommunicator(props); + Ice.ObjectPrx obj = com.getAdmin(); + Ice.PropertiesAdminPrx pa = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties"); + test(pa.getProperty("Ice.Admin.InstanceName").equals("Test")); + TestFacetPrx tf = TestFacetPrxHelper.checkedCast(obj, "TestFacet"); + tf.op(); + Ice.ProcessPrx proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process"); + test(proc == null); + com.destroy(); + } + { + // + // Test: Set Ice.Admin.Facets to expose two facets. Use a comma to separate the + // facet names. + // + java.util.Map<String, String> props = new java.util.HashMap<String, String>(); + props.put("Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + props.put("Ice.Admin.InstanceName", "Test"); + props.put("Ice.Admin.Facets", "TestFacet, Process"); + RemoteCommunicatorPrx com = factory.createCommunicator(props); + Ice.ObjectPrx obj = com.getAdmin(); + Ice.PropertiesAdminPrx pa = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties"); + test(pa == null); + TestFacetPrx tf = TestFacetPrxHelper.checkedCast(obj, "TestFacet"); + tf.op(); + Ice.ProcessPrx proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process"); + proc.shutdown(); + com.waitForShutdown(); + com.destroy(); + } + out.println("ok"); + + factory.shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/admin/Client.java b/java/test/src/main/java/test/Ice/admin/Client.java new file mode 100644 index 00000000000..bdd21e20559 --- /dev/null +++ b/java/test/src/main/java/test/Ice/admin/Client.java @@ -0,0 +1,30 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.admin; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + AllTests.allTests(this, getWriter()); + + return 0; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/admin/RemoteCommunicatorFactoryI.java b/java/test/src/main/java/test/Ice/admin/RemoteCommunicatorFactoryI.java new file mode 100644 index 00000000000..3100081f816 --- /dev/null +++ b/java/test/src/main/java/test/Ice/admin/RemoteCommunicatorFactoryI.java @@ -0,0 +1,93 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.admin; + +import test.Ice.admin.Test.*; + +public class RemoteCommunicatorFactoryI extends _RemoteCommunicatorFactoryDisp +{ + @Override + public RemoteCommunicatorPrx createCommunicator(java.util.Map<String, String> props, Ice.Current current) + { + // + // Prepare the property set using the given properties. + // + Ice.InitializationData init = new Ice.InitializationData(); + init.properties = Ice.Util.createProperties(); + for(java.util.Map.Entry<String, String> e : props.entrySet()) + { + init.properties.setProperty(e.getKey(), e.getValue()); + } + + if(init.properties.getPropertyAsInt("NullLogger") > 0) + { + init.logger = new Ice.Logger() { + @Override public void print(String message) + { + } + + @Override public void trace(String category, String message) + { + } + + @Override public void warning(String message) + { + } + + @Override public void error(String message) + { + } + + @Override public String getPrefix() + { + return "NullLogger"; + } + + @Override public Ice.Logger cloneWithPrefix(String prefix) + { + return this; + } + }; + } + + // + // Initialize a new communicator. + // + Ice.Communicator communicator = Ice.Util.initialize(init); + + // + // Install a custom admin facet. + // + communicator.addAdminFacet(new TestFacetI(), "TestFacet"); + + // + // The RemoteCommunicator servant also implements PropertiesAdminUpdateCallback. + // Set the callback on the admin facet. + // + RemoteCommunicatorI servant = new RemoteCommunicatorI(communicator); + Ice.Object propFacet = communicator.findAdminFacet("Properties"); + + if(propFacet != null) + { + Ice.NativePropertiesAdmin admin = (Ice.NativePropertiesAdmin)propFacet; + assert admin != null; + admin.addUpdateCallback(servant); + } + + Ice.ObjectPrx proxy = current.adapter.addWithUUID(servant); + return RemoteCommunicatorPrxHelper.uncheckedCast(proxy); + } + + @Override + public void shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/admin/RemoteCommunicatorI.java b/java/test/src/main/java/test/Ice/admin/RemoteCommunicatorI.java new file mode 100644 index 00000000000..a4137dd3d9d --- /dev/null +++ b/java/test/src/main/java/test/Ice/admin/RemoteCommunicatorI.java @@ -0,0 +1,111 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.admin; + +import test.Ice.admin.Test.*; + +public class RemoteCommunicatorI extends _RemoteCommunicatorDisp implements Ice.PropertiesAdminUpdateCallback +{ + RemoteCommunicatorI(Ice.Communicator communicator) + { + _communicator = communicator; + _called = false; + } + + @Override + public Ice.ObjectPrx getAdmin(Ice.Current current) + { + return _communicator.getAdmin(); + } + + @Override + public synchronized java.util.Map<String, String> getChanges(Ice.Current current) + { + // + // The client calls PropertiesAdmin::setProperties() and then invokes + // this operation. Since setProperties() is implemented using AMD, the + // client might receive its reply and then call getChanges() before our + // updated() method is called. We block here to ensure that updated() + // gets called before we return the most recent set of changes. + // + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + + return _changes; + } + + @Override + public void print(String message, Ice.Current current) + { + _communicator.getLogger().print(message); + } + + @Override + public void trace(String category, String message, Ice.Current current) + { + _communicator.getLogger().trace(category, message); + } + + @Override + public void warning(String message, Ice.Current current) + { + _communicator.getLogger().warning(message); + } + + @Override + public void error(String message, Ice.Current current) + { + _communicator.getLogger().error(message); + } + + @Override + public void shutdown(Ice.Current current) + { + _communicator.shutdown(); + } + + @Override + public void waitForShutdown(Ice.Current current) + { + // + // Note that we are executing in a thread of the *main* communicator, + // not the one that is being shut down. + // + _communicator.waitForShutdown(); + } + + @Override + public void destroy(Ice.Current current) + { + _communicator.destroy(); + } + + @Override + public synchronized void updated(java.util.Map<String, String> changes) + { + _changes = changes; + _called = true; + notify(); + } + + private Ice.Communicator _communicator; + private java.util.Map<String, String> _changes; + private boolean _called; +} diff --git a/java/test/src/main/java/test/Ice/admin/RemoteLoggerI.java b/java/test/src/main/java/test/Ice/admin/RemoteLoggerI.java new file mode 100644 index 00000000000..8a5a2a8e06e --- /dev/null +++ b/java/test/src/main/java/test/Ice/admin/RemoteLoggerI.java @@ -0,0 +1,77 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.admin; + +class RemoteLoggerI extends Ice._RemoteLoggerDisp +{ + + @Override + public synchronized void init(String prefix, Ice.LogMessage[] logMessages, Ice.Current current) + { + test(prefix.equals(_expectedPrefix)); + test(java.util.Arrays.equals(logMessages, _expectedInitMessages)); + _receivedCalls++; + notifyAll(); + } + + @Override + public synchronized void log(Ice.LogMessage logMessage, Ice.Current current) + { + Ice.LogMessage front = _expectedLogMessages.pollFirst(); + test(front.type == logMessage.type && front.message.equals(logMessage.message) && + front.traceCategory.equals(logMessage.traceCategory)); + + _receivedCalls++; + notifyAll(); + } + + synchronized void checkNextInit(String prefix, Ice.LogMessage[] logMessages) + { + _expectedPrefix = prefix; + _expectedInitMessages = logMessages; + } + + synchronized void checkNextLog(Ice.LogMessageType messageType, String message, String category) + { + Ice.LogMessage logMessage = new Ice.LogMessage(messageType, 0, category, message); + _expectedLogMessages.addLast(logMessage); + } + + synchronized void wait(int calls) + { + _receivedCalls -= calls; + + while(_receivedCalls < 0) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + break; + } + } + } + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private int _receivedCalls; + private String _expectedPrefix; + private Ice.LogMessage[] _expectedInitMessages; + private java.util.Deque<Ice.LogMessage> _expectedLogMessages = new java.util.ArrayDeque<Ice.LogMessage>(); +} diff --git a/java/test/src/main/java/test/Ice/admin/Server.java b/java/test/src/main/java/test/Ice/admin/Server.java new file mode 100644 index 00000000000..a29e6a6d5a2 --- /dev/null +++ b/java/test/src/main/java/test/Ice/admin/Server.java @@ -0,0 +1,42 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.admin; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new RemoteCommunicatorFactoryI(), communicator.stringToIdentity("factory")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.proxy"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/admin/Test.ice b/java/test/src/main/java/test/Ice/admin/Test.ice new file mode 100644 index 00000000000..608e6068a9b --- /dev/null +++ b/java/test/src/main/java/test/Ice/admin/Test.ice @@ -0,0 +1,54 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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 + +#include <Ice/Properties.ice> + +[["java:package:test.Ice.admin"]] +module Test +{ + +interface RemoteCommunicator +{ + Object* getAdmin(); + + Ice::PropertyDict getChanges(); + + // + // Logger operations + // + void print(string message); + void trace(string category, string message); + void warning(string message); + void error(string message); + + void shutdown(); + + void waitForShutdown(); + + void destroy(); +}; + +interface RemoteCommunicatorFactory +{ + RemoteCommunicator* createCommunicator(Ice::PropertyDict props); + + void shutdown(); +}; + +interface TestFacet +{ + void op(); +}; + +}; + +#endif diff --git a/java/test/src/main/java/test/Ice/admin/TestFacetI.java b/java/test/src/main/java/test/Ice/admin/TestFacetI.java new file mode 100644 index 00000000000..a1246dd8ff0 --- /dev/null +++ b/java/test/src/main/java/test/Ice/admin/TestFacetI.java @@ -0,0 +1,20 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.admin; + +import test.Ice.admin.Test.*; + +public class TestFacetI extends _TestFacetDisp +{ + @Override + public void op(Ice.Current current) + { + } +} diff --git a/java/test/src/main/java/test/Ice/admin/run.py b/java/test/src/main/java/test/Ice/admin/run.py new file mode 100755 index 00000000000..d5fe04787c9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/admin/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/ami/AMI.java b/java/test/src/main/java/test/Ice/ami/AMI.java new file mode 100644 index 00000000000..94c9b751401 --- /dev/null +++ b/java/test/src/main/java/test/Ice/ami/AMI.java @@ -0,0 +1,2562 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.ami; + +import java.io.PrintWriter; + +import test.Ice.ami.Test.TestIntfPrx; +import test.Ice.ami.Test.TestIntfPrxHelper; +import test.Ice.ami.Test.TestIntfControllerPrx; +import test.Ice.ami.Test.TestIntfException; +import test.Ice.ami.Test.Callback_TestIntf_op; +import test.Ice.ami.Test.Callback_TestIntf_opWithResult; +import test.Ice.ami.Test.Callback_TestIntf_opWithUE; +import test.Ice.ami.Test.Callback_TestIntf_opWithPayload; +import test.Util.Application; + +public class AMI +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class CallbackBase + { + CallbackBase() + { + _called = false; + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + static class AsyncCallback extends CallbackBase + { + public AsyncCallback() + { + } + + public void + isA(Ice.AsyncResult result) + { + test(result.getProxy().end_ice_isA(result)); + called(); + } + + public void + ping(Ice.AsyncResult result) + { + result.getProxy().end_ice_ping(result); + called(); + } + + public void + id(Ice.AsyncResult result) + { + test(result.getProxy().end_ice_id(result).equals("::Test::TestIntf")); + called(); + } + + public void + ids(Ice.AsyncResult result) + { + test(result.getProxy().end_ice_ids(result).length == 2); + called(); + } + + public void + connection(Ice.AsyncResult result) + { + test(result.getProxy().end_ice_getConnection(result) != null); + called(); + } + + public void + op(Ice.AsyncResult result) + { + TestIntfPrxHelper.uncheckedCast(result.getProxy()).end_op(result); + called(); + } + + public void + opWithResult(Ice.AsyncResult result) + { + test(TestIntfPrxHelper.uncheckedCast(result.getProxy()).end_opWithResult(result) == 15); + called(); + } + + public void + opWithUE(Ice.AsyncResult result) + { + try + { + TestIntfPrxHelper.uncheckedCast(result.getProxy()).end_opWithUE(result); + test(false); + } + catch(TestIntfException ex) + { + called(); + } + catch(Ice.LocalException ex) + { + test(false); + } + } + + public void + isAEx(Ice.AsyncResult result) + { + try + { + result.getProxy().end_ice_isA(result); + test(false); + } + catch(Ice.NoEndpointException ex) + { + called(); + } + catch(Ice.LocalException ex) + { + test(false); + } + } + + public void + pingEx(Ice.AsyncResult result) + { + try + { + result.getProxy().end_ice_ping(result); + test(false); + } + catch(Ice.NoEndpointException ex) + { + called(); + } + catch(Ice.LocalException ex) + { + test(false); + } + } + + public void + idEx(Ice.AsyncResult result) + { + try + { + result.getProxy().end_ice_id(result); + test(false); + } + catch(Ice.NoEndpointException ex) + { + called(); + } + catch(Ice.LocalException ex) + { + test(false); + } + } + + public void + idsEx(Ice.AsyncResult result) + { + try + { + result.getProxy().end_ice_ids(result); + test(false); + } + catch(Ice.NoEndpointException ex) + { + called(); + } + catch(Ice.LocalException ex) + { + test(false); + } + } + + public void + connectionEx(Ice.AsyncResult result) + { + try + { + result.getProxy().end_ice_getConnection(result); + test(false); + } + catch(Ice.NoEndpointException ex) + { + called(); + } + catch(Ice.LocalException ex) + { + test(false); + } + } + + public void + opEx(Ice.AsyncResult result) + { + try + { + TestIntfPrxHelper.uncheckedCast(result.getProxy()).end_op(result); + test(false); + } + catch(Ice.NoEndpointException ex) + { + called(); + } + catch(Ice.LocalException ex) + { + test(false); + } + } + } + + static class ResponseCallback extends CallbackBase + { + ResponseCallback() + { + } + + public void + isA(boolean r) + { + test(r); + called(); + } + + public void + ping() + { + called(); + } + + public void + id(String id) + { + test(id.equals("::Test::TestIntf")); + called(); + } + + public void + ids(String[] ids) + { + test(ids.length == 2); + called(); + } + + public void + connection(Ice.Connection conn) + { + test(conn != null); + called(); + } + + public void + op() + { + called(); + } + + public void + opWithResult(int r) + { + test(r == 15); + called(); + } + + public void + opWithUE(Ice.UserException e) + { + try + { + throw e; + } + catch(TestIntfException ex) + { + called(); + } + catch(Ice.UserException ex) + { + test(false); + } + } + } + + static class ExceptionCallback extends CallbackBase + { + public ExceptionCallback() + { + } + + public void + isA(boolean r) + { + test(false); + } + + public void + ping() + { + test(false); + } + + public void + id(String id) + { + test(false); + } + + public void + ids(String[] ids) + { + test(false); + } + + public void + connection(Ice.Connection conn) + { + test(false); + } + + public void + op() + { + test(false); + } + + public void + ex(Ice.LocalException ex) + { + test(ex instanceof Ice.NoEndpointException); + called(); + } + + public void + noEx(Ice.LocalException ex) + { + test(false); + } + } + + static class SentCallback extends CallbackBase + { + SentCallback() + { + _thread = Thread.currentThread().getId(); + } + + public void + isA(boolean r) + { + } + + public void + ping() + { + } + + public void + id(String s) + { + } + + public void + ids(String[] s) + { + } + + public void + opAsync(Ice.AsyncResult r) + { + } + + public void + op() + { + } + + public void + ex(Ice.LocalException ex) + { + } + + public void + sent(Ice.AsyncResult r) + { + test(r.sentSynchronously() && _thread == Thread.currentThread().getId() || + !r.sentSynchronously() && _thread != Thread.currentThread().getId()); + called(); + } + + public void + sent(boolean ss) + { + test(ss && _thread == Thread.currentThread().getId() || + !ss && _thread != Thread.currentThread().getId()); + called(); + } + + long _thread; + } + + static class FlushCallback extends CallbackBase + { + FlushCallback() + { + _thread = Thread.currentThread().getId(); + } + + public void + completedAsync(Ice.AsyncResult r) + { + test(false); + } + + public void + exception(Ice.LocalException ex) + { + test(false); + } + + public void + sentAsync(Ice.AsyncResult r) + { + test((r.sentSynchronously() && _thread == Thread.currentThread().getId()) || + (!r.sentSynchronously() && _thread != Thread.currentThread().getId())); + called(); + } + + public void + sent(boolean sentSynchronously) + { + test((sentSynchronously && _thread == Thread.currentThread().getId()) || + (!sentSynchronously && _thread != Thread.currentThread().getId())); + called(); + } + + long _thread; + } + + static class FlushExCallback extends CallbackBase + { + FlushExCallback() + { + } + + public void + completedAsync(Ice.AsyncResult r) + { + try + { + if(r.getConnection() != null) + { + r.getConnection().end_flushBatchRequests(r); + } + else + { + r.getProxy().end_ice_flushBatchRequests(r); + } + test(false); + } + catch(Ice.LocalException ex) + { + called(); + } + } + + public void + exception(Ice.LocalException ex) + { + called(); + } + + public void + sentAsync(Ice.AsyncResult r) + { + test(false); + } + + public void + sent(boolean sentSynchronously) + { + test(false); + } + } + + enum ThrowType { LocalException, OtherException }; + + static class Thrower extends CallbackBase + { + public Thrower(ThrowType t) + { + _t = t; + } + + public void + opAsync(Ice.AsyncResult r) + { + called(); + throwEx(); + } + + public void + op() + { + called(); + throwEx(); + } + + public void + noOp() + { + } + + public void + ex(Ice.LocalException ex) + { + called(); + throwEx(); + } + + public void + sent(boolean ss) + { + called(); + throwEx(); + } + + private void + throwEx() + { + switch(_t) + { + case LocalException: + { + throw new Ice.ObjectNotExistException(); + } + case OtherException: + { + throw new RuntimeException(); + } + default: + { + assert(false); + break; + } + } + } + + ThrowType _t; + } + + public static void + run(Application app, Ice.Communicator communicator, boolean collocated, TestIntfPrx p, + TestIntfControllerPrx testController) + { + + PrintWriter out = app.getWriter(); + + out.print("testing begin/end invocation... "); + out.flush(); + { + Ice.AsyncResult result; + java.util.Map<String, String> ctx = new java.util.HashMap<String, String>(); + + result = p.begin_ice_isA("::Test::TestIntf"); + test(p.end_ice_isA(result)); + result = p.begin_ice_isA("::Test::TestIntf", ctx); + test(p.end_ice_isA(result)); + + result = p.begin_ice_ping(); + p.end_ice_ping(result); + result = p.begin_ice_ping(ctx); + p.end_ice_ping(result); + + result = p.begin_ice_id(); + test(p.end_ice_id(result).equals("::Test::TestIntf")); + result = p.begin_ice_id(ctx); + test(p.end_ice_id(result).equals("::Test::TestIntf")); + + result = p.begin_ice_ids(); + test(p.end_ice_ids(result).length == 2); + result = p.begin_ice_ids(ctx); + test(p.end_ice_ids(result).length == 2); + + if(!collocated) + { + result = p.begin_ice_getConnection(); + test(p.end_ice_getConnection(result) != null); + } + + result = p.begin_op(); + p.end_op(result); + result = p.begin_op(ctx); + p.end_op(result); + + result = p.begin_opWithResult(); + test(p.end_opWithResult(result) == 15); + result = p.begin_opWithResult(ctx); + test(p.end_opWithResult(result) == 15); + + result = p.begin_opWithUE(); + try + { + p.end_opWithUE(result); + test(false); + } + catch(TestIntfException ex) + { + } + result = p.begin_opWithUE(ctx); + try + { + p.end_opWithUE(result); + test(false); + } + catch(TestIntfException ex) + { + } + } + out.println("ok"); + + out.print("testing async callback... "); + out.flush(); + { + final AsyncCallback cb = new AsyncCallback(); + java.util.Map<String, String> ctx = new java.util.HashMap<String, String>(); + + p.begin_ice_isA("::Test::TestIntf", new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.isA(r); + } + }); + cb.check(); + + p.begin_ice_isA("::Test::TestIntf", ctx, new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.isA(r); + } + }); + cb.check(); + + p.begin_ice_ping(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.ping(r); + } + }); + cb.check(); + p.begin_ice_ping(ctx, new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.ping(r); + } + }); + cb.check(); + + p.begin_ice_id(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.id(r); + } + }); + cb.check(); + p.begin_ice_id(ctx, new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.id(r); + } + }); + cb.check(); + + p.begin_ice_ids(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.ids(r); + } + }); + cb.check(); + p.begin_ice_ids(ctx, new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.ids(r); + } + }); + cb.check(); + + if(!collocated) + { + p.begin_ice_getConnection(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.connection(r); + } + }); + cb.check(); + } + + p.begin_op(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.op(r); + } + }); + cb.check(); + p.begin_op(ctx, new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.op(r); + } + }); + cb.check(); + + p.begin_opWithResult(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.opWithResult(r); + } + }); + cb.check(); + p.begin_opWithResult(ctx, new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.opWithResult(r); + } + }); + cb.check(); + + p.begin_opWithUE(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.opWithUE(r); + } + }); + cb.check(); + p.begin_opWithUE(ctx, new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.opWithUE(r); + } + }); + cb.check(); + } + out.println("ok"); + + out.print("testing response callback... "); + out.flush(); + { + final ResponseCallback cb = new ResponseCallback(); + java.util.Map<String, String> ctx = new java.util.HashMap<String, String>(); + + p.begin_ice_isA("::Test::TestIntf", new Ice.Callback_Object_ice_isA() + { + @Override + public void + response(boolean r) + { + cb.isA(r); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + p.begin_ice_isA("::Test::TestIntf", ctx, new Ice.Callback_Object_ice_isA() + { + @Override + public void + response(boolean r) + { + cb.isA(r); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + + p.begin_ice_ping(new Ice.Callback_Object_ice_ping() + { + @Override + public void + response() + { + cb.ping(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + p.begin_ice_ping(ctx, new Ice.Callback_Object_ice_ping() + { + @Override + public void + response() + { + cb.ping(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + + p.begin_ice_id(new Ice.Callback_Object_ice_id() + { + @Override + public void + response(String id) + { + cb.id(id); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + p.begin_ice_id(ctx, new Ice.Callback_Object_ice_id() + { + @Override + public void + response(String id) + { + cb.id(id); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + + p.begin_ice_ids(new Ice.Callback_Object_ice_ids() + { + @Override + public void + response(String[] ids) + { + cb.ids(ids); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + p.begin_ice_ids(ctx, new Ice.Callback_Object_ice_ids() + { + @Override + public void + response(String[] ids) + { + cb.ids(ids); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + + if(!collocated) + { + p.begin_ice_getConnection(new Ice.Callback_Object_ice_getConnection() + { + @Override + public void + response(Ice.Connection conn) + { + cb.connection(conn); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + } + + p.begin_op(new Callback_TestIntf_op() + { + @Override + public void + response() + { + cb.op(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + p.begin_op(ctx, new Callback_TestIntf_op() + { + @Override + public void + response() + { + cb.op(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + + p.begin_opWithResult(new Callback_TestIntf_opWithResult() + { + @Override + public void + response(int r) + { + cb.opWithResult(r); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + p.begin_opWithResult(ctx, new Callback_TestIntf_opWithResult() + { + @Override + public void + response(int r) + { + cb.opWithResult(r); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + + p.begin_opWithUE(new Callback_TestIntf_opWithUE() + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.UserException ex) + { + cb.opWithUE(ex); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + p.begin_opWithUE(ctx, new Callback_TestIntf_opWithUE() + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.UserException ex) + { + cb.opWithUE(ex); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + }); + cb.check(); + } + out.println("ok"); + + out.print("testing local exceptions... "); + out.flush(); + { + TestIntfPrx indirect = TestIntfPrxHelper.uncheckedCast(p.ice_adapterId("dummy")); + Ice.AsyncResult r; + + r = indirect.begin_op(); + try + { + indirect.end_op(r); + test(false); + } + catch(Ice.NoEndpointException ex) + { + } + + + try + { + r = ((TestIntfPrx)p.ice_oneway()).begin_opWithResult(); + test(false); + } + catch(java.lang.IllegalArgumentException ex) + { + } + + // + // Check that CommunicatorDestroyedException is raised directly. + // + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + Ice.Communicator ic = app.initialize(initData); + Ice.ObjectPrx o = ic.stringToProxy(p.toString()); + TestIntfPrx p2 = TestIntfPrxHelper.checkedCast(o); + ic.destroy(); + + try + { + p2.begin_op(); + test(false); + } + catch(Ice.CommunicatorDestroyedException ex) + { + // Expected. + } + } + out.println("ok"); + + out.print("testing local exceptions with async callback... "); + out.flush(); + { + TestIntfPrx i = TestIntfPrxHelper.uncheckedCast(p.ice_adapterId("dummy")); + final AsyncCallback cb = new AsyncCallback(); + + i.begin_ice_isA("::Test::TestIntf", new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.isAEx(r); + } + }); + cb.check(); + + i.begin_ice_ping(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.pingEx(r); + } + }); + cb.check(); + + i.begin_ice_id(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.idEx(r); + } + }); + cb.check(); + + i.begin_ice_ids(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.idsEx(r); + } + }); + cb.check(); + + if(!collocated) + { + i.begin_ice_getConnection(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.connectionEx(r); + } + }); + cb.check(); + } + + i.begin_op(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult r) + { + cb.opEx(r); + } + }); + cb.check(); + } + out.println("ok"); + + out.print("testing local exceptions with response callback... "); + out.flush(); + { + TestIntfPrx i = TestIntfPrxHelper.uncheckedCast(p.ice_adapterId("dummy")); + final ExceptionCallback cb = new ExceptionCallback(); + + i.begin_ice_isA("::Test::TestIntf", new Ice.Callback_Object_ice_isA() + { + @Override + public void + response(boolean r) + { + test(false); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.ex(ex); + } + }); + cb.check(); + + i.begin_ice_ping(new Ice.Callback_Object_ice_ping() + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.ex(ex); + } + }); + cb.check(); + + i.begin_ice_id(new Ice.Callback_Object_ice_id() + { + @Override + public void + response(String id) + { + test(false); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.ex(ex); + } + }); + cb.check(); + + i.begin_ice_ids(new Ice.Callback_Object_ice_ids() + { + @Override + public void + response(String[] ids) + { + test(false); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.ex(ex); + } + }); + cb.check(); + + if(!collocated) + { + i.begin_ice_getConnection(new Ice.Callback_Object_ice_getConnection() + { + @Override + public void + response(Ice.Connection conn) + { + test(false); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.ex(ex); + } + }); + cb.check(); + } + + i.begin_op(new Callback_TestIntf_op() + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.ex(ex); + } + }); + cb.check(); + } + out.println("ok"); + + out.print("testing sent callback... "); + out.flush(); + { + final SentCallback cb = new SentCallback(); + + p.begin_ice_isA("", new Ice.Callback_Object_ice_isA() + { + @Override + public void + response(boolean r) + { + cb.isA(r); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.ex(ex); + } + + @Override + public void + sent(boolean ss) + { + cb.sent(ss); + } + }); + cb.check(); + + p.begin_ice_ping(new Ice.Callback_Object_ice_ping() + { + @Override + public void + response() + { + cb.ping(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.ex(ex); + } + + @Override + public void + sent(boolean ss) + { + cb.sent(ss); + } + }); + cb.check(); + + p.begin_ice_id(new Ice.Callback_Object_ice_id() + { + @Override + public void + response(String id) + { + cb.id(id); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.ex(ex); + } + + @Override + public void + sent(boolean ss) + { + cb.sent(ss); + } + }); + cb.check(); + + p.begin_ice_ids(new Ice.Callback_Object_ice_ids() + { + @Override + public void + response(String[] ids) + { + cb.ids(ids); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.ex(ex); + } + + @Override + public void + sent(boolean ss) + { + cb.sent(ss); + } + }); + cb.check(); + + p.begin_op(new Callback_TestIntf_op() + { + @Override + public void + response() + { + cb.op(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.ex(ex); + } + + @Override + public void + sent(boolean ss) + { + cb.sent(ss); + } + }); + cb.check(); + + p.begin_op(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult result) + { + cb.opAsync(result); + } + + @Override + public void + sent(Ice.AsyncResult result) + { + cb.sent(result); + } + }); + cb.check(); + + java.util.List<SentCallback> cbs = new java.util.ArrayList<SentCallback>(); + byte[] seq = new byte[10024]; + new java.util.Random().nextBytes(seq); // Make sure the request doesn't compress too well. + Ice.AsyncResult r; + testController.holdAdapter(); + try + { + do + { + final SentCallback cb2 = new SentCallback(); + r = p.begin_opWithPayload(seq, new Callback_TestIntf_opWithPayload() + { + @Override + public void + response() + { + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb2.ex(ex); + } + + @Override + public void + sent(boolean ss) + { + cb2.sent(ss); + } + }); + cbs.add(cb2); + } + while(r.sentSynchronously()); + } + finally + { + testController.resumeAdapter(); + } + for(SentCallback cb3 : cbs) + { + cb3.check(); + } + } + out.println("ok"); + + out.print("testing illegal arguments... "); + out.flush(); + { + Ice.AsyncResult result; + + result = p.begin_op(); + p.end_op(result); + try + { + p.end_op(result); + test(false); + } + catch(IllegalArgumentException ex) + { + } + + result = p.begin_op(); + try + { + p.end_opWithResult(result); + test(false); + } + catch(IllegalArgumentException ex) + { + } + + try + { + p.end_op(null); + test(false); + } + catch(IllegalArgumentException ex) + { + } + + // try +// { +// p.begin_op((Ice.Callback)null); +// test(false); +// } +// catch(IllegalArgumentException ex) +// { +// } + +// try +// { +// p.begin_op((Callback_TestIntf_op)null); +// test(false); +// } +// catch(IllegalArgumentException ex) +// { +// } + } + out.println("ok"); + + out.print("testing unexpected exceptions from callback... "); + out.flush(); + { + TestIntfPrx q = TestIntfPrxHelper.uncheckedCast(p.ice_adapterId("dummy")); + ThrowType throwEx[] = { ThrowType.LocalException, ThrowType.OtherException }; + + for(int i = 0; i < 2; ++i) + { + final Thrower cb = new Thrower(throwEx[i]); + + p.begin_op(new Ice.Callback() + { + @Override + public void + completed(Ice.AsyncResult result) + { + cb.opAsync(result); + } + }); + cb.check(); + + p.begin_op(new Callback_TestIntf_op() + { + @Override + public void + response() + { + cb.op(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + } + }); + cb.check(); + + q.begin_op(new Callback_TestIntf_op() + { + @Override + public void + response() + { + cb.op(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.ex(ex); + } + }); + cb.check(); + + p.begin_op(new Callback_TestIntf_op() + { + @Override + public void + response() + { + } + + @Override + public void + exception(Ice.LocalException ex) + { + } + + @Override + public void + sent(boolean ss) + { + cb.sent(ss); + } + }); + cb.check(); + } + } + out.println("ok"); + + out.print("testing batch requests with proxy... "); + out.flush(); + { + test(p.ice_batchOneway().begin_ice_flushBatchRequests().sentSynchronously()); + + { + // + // AsyncResult. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.opBatch(); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = b1.begin_ice_flushBatchRequests( + new Ice.Callback() + { + @Override + public void completed(Ice.AsyncResult result) + { + cb.completedAsync(result); + } + + @Override + public void sent(Ice.AsyncResult result) + { + cb.sentAsync(result); + } + }); + cb.check(); + test(r.isSent()); + test(r.isCompleted()); + test(p.waitForBatch(2)); + + final FlushCallback cb2 = new FlushCallback(); + Ice.AsyncResult r2 = b1.begin_ice_flushBatchRequests( + new Ice.Callback() + { + @Override + public void completed(Ice.AsyncResult result) + { + cb2.completedAsync(result); + } + + @Override + public void sent(Ice.AsyncResult result) + { + cb2.sentAsync(result); + } + }); + cb2.check(); + test(r2.isSent()); + test(r2.isCompleted()); + } + + if(p.ice_getConnection() != null) + { + // + // AsyncResult exception. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.ice_getConnection().close(false); + final FlushExCallback cb = new FlushExCallback(); + Ice.AsyncResult r = b1.begin_ice_flushBatchRequests( + new Ice.Callback() + { + @Override + public void completed(Ice.AsyncResult result) + { + cb.completedAsync(result); + } + + @Override + public void sent(Ice.AsyncResult result) + { + cb.sentAsync(result); + } + }); + cb.check(); + test(!r.isSent()); + test(r.isCompleted()); + test(p.opBatchCount() == 0); + } + + { + // + // Type-safe. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.opBatch(); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = b1.begin_ice_flushBatchRequests( + new Ice.Callback_Object_ice_flushBatchRequests() + { + @Override + public void exception(Ice.LocalException ex) + { + cb.exception(ex); + } + + @Override + public void sent(boolean sentSynchronously) + { + cb.sent(sentSynchronously); + } + }); + cb.check(); + test(r.isSent()); + test(r.isCompleted()); + test(p.waitForBatch(2)); + } + + if(p.ice_getConnection() != null) + { + // + // Type-safe exception. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.ice_getConnection().close(false); + final FlushExCallback cb = new FlushExCallback(); + Ice.AsyncResult r = b1.begin_ice_flushBatchRequests( + new Ice.Callback_Object_ice_flushBatchRequests() + { + @Override + public void exception(Ice.LocalException ex) + { + cb.exception(ex); + } + + @Override + public void sent(boolean sentSynchronously) + { + cb.sent(sentSynchronously); + } + }); + cb.check(); + test(!r.isSent()); + test(r.isCompleted()); + test(p.opBatchCount() == 0); + } + } + out.println("ok"); + + if(p.ice_getConnection() != null) + { + out.print("testing batch requests with connection... "); + out.flush(); + { + { + // + // AsyncResult. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.opBatch(); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = b1.ice_getConnection().begin_flushBatchRequests( + new Ice.Callback() + { + @Override + public void completed(Ice.AsyncResult result) + { + cb.completedAsync(result); + } + + @Override + public void sent(Ice.AsyncResult result) + { + cb.sentAsync(result); + } + }); + cb.check(); + test(r.isSent()); + test(r.isCompleted()); + test(p.waitForBatch(2)); + } + + { + // + // AsyncResult exception. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.ice_getConnection().close(false); + final FlushExCallback cb = new FlushExCallback(); + Ice.AsyncResult r = b1.ice_getConnection().begin_flushBatchRequests( + new Ice.Callback() + { + @Override + public void completed(Ice.AsyncResult result) + { + cb.completedAsync(result); + } + + @Override + public void sent(Ice.AsyncResult result) + { + cb.sentAsync(result); + } + }); + cb.check(); + test(!r.isSent()); + test(r.isCompleted()); + test(p.opBatchCount() == 0); + } + + { + // + // Type-safe. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.opBatch(); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = b1.ice_getConnection().begin_flushBatchRequests( + new Ice.Callback_Connection_flushBatchRequests() + { + @Override + public void exception(Ice.LocalException ex) + { + cb.exception(ex); + } + + @Override + public void sent(boolean sentSynchronously) + { + cb.sent(sentSynchronously); + } + }); + cb.check(); + test(r.isSent()); + test(r.isCompleted()); + test(p.waitForBatch(2)); + } + + { + // + // Type-safe exception. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.ice_getConnection().close(false); + final FlushExCallback cb = new FlushExCallback(); + Ice.AsyncResult r = b1.ice_getConnection().begin_flushBatchRequests( + new Ice.Callback_Connection_flushBatchRequests() + { + @Override + public void exception(Ice.LocalException ex) + { + cb.exception(ex); + } + + @Override + public void sent(boolean sentSynchronously) + { + cb.sent(sentSynchronously); + } + }); + cb.check(); + test(!r.isSent()); + test(r.isCompleted()); + test(p.opBatchCount() == 0); + } + } + out.println("ok"); + + out.print("testing batch requests with communicator... "); + out.flush(); + { + { + // + // AsyncResult - 1 connection. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.opBatch(); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + new Ice.Callback() + { + @Override + public void completed(Ice.AsyncResult result) + { + cb.completedAsync(result); + } + + @Override + public void sent(Ice.AsyncResult result) + { + cb.sentAsync(result); + } + }); + cb.check(); + test(r.isSent()); + test(r.isCompleted()); + test(p.waitForBatch(2)); + } + + { + // + // AsyncResult exception - 1 connection. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.ice_getConnection().close(false); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + new Ice.Callback() + { + @Override + public void completed(Ice.AsyncResult result) + { + cb.completedAsync(result); + } + + @Override + public void sent(Ice.AsyncResult result) + { + cb.sentAsync(result); + } + }); + cb.check(); + test(r.isSent()); // Exceptions are ignored! + test(r.isCompleted()); + test(p.opBatchCount() == 0); + } + + { + // + // AsyncResult - 2 connections. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + TestIntfPrx b2 = (TestIntfPrx)p.ice_connectionId("2").ice_batchOneway(); + b2.ice_getConnection(); // Ensure connection is established. + b1.opBatch(); + b1.opBatch(); + b2.opBatch(); + b2.opBatch(); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + new Ice.Callback() + { + @Override + public void completed(Ice.AsyncResult result) + { + cb.completedAsync(result); + } + + @Override + public void sent(Ice.AsyncResult result) + { + cb.sentAsync(result); + } + }); + cb.check(); + test(r.isSent()); + test(r.isCompleted()); + test(p.waitForBatch(4)); + } + + { + // + // AsyncResult exception - 2 connections - 1 failure. + // + // All connections should be flushed even if there are failures on some connections. + // Exceptions should not be reported. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + TestIntfPrx b2 = (TestIntfPrx)p.ice_connectionId("2").ice_batchOneway(); + b2.ice_getConnection(); // Ensure connection is established. + b1.opBatch(); + b2.opBatch(); + b1.ice_getConnection().close(false); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + new Ice.Callback() + { + @Override + public void completed(Ice.AsyncResult result) + { + cb.completedAsync(result); + } + + @Override + public void sent(Ice.AsyncResult result) + { + cb.sentAsync(result); + } + }); + cb.check(); + test(r.isSent()); // Exceptions are ignored! + test(r.isCompleted()); + test(p.waitForBatch(1)); + } + + { + // + // AsyncResult exception - 2 connections - 2 failures. + // + // The sent callback should be invoked even if all connections fail. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + TestIntfPrx b2 = (TestIntfPrx)p.ice_connectionId("2").ice_batchOneway(); + b2.ice_getConnection(); // Ensure connection is established. + b1.opBatch(); + b2.opBatch(); + b1.ice_getConnection().close(false); + b2.ice_getConnection().close(false); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + new Ice.Callback() + { + @Override + public void completed(Ice.AsyncResult result) + { + cb.completedAsync(result); + } + + @Override + public void sent(Ice.AsyncResult result) + { + cb.sentAsync(result); + } + }); + cb.check(); + test(r.isSent()); // Exceptions are ignored! + test(r.isCompleted()); + test(p.opBatchCount() == 0); + } + + { + // + // Type-safe - 1 connection. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.opBatch(); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + new Ice.Callback_Communicator_flushBatchRequests() + { + @Override + public void exception(Ice.LocalException ex) + { + cb.exception(ex); + } + + @Override + public void sent(boolean sentSynchronously) + { + cb.sent(sentSynchronously); + } + }); + cb.check(); + test(r.isSent()); + test(r.isCompleted()); + test(p.waitForBatch(2)); + } + + { + // + // Type-safe exception - 1 connection. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.ice_getConnection().close(false); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + new Ice.Callback_Communicator_flushBatchRequests() + { + @Override + public void exception(Ice.LocalException ex) + { + cb.exception(ex); + } + + @Override + public void sent(boolean sentSynchronously) + { + cb.sent(sentSynchronously); + } + }); + cb.check(); + test(r.isSent()); // Exceptions are ignored! + test(r.isCompleted()); + test(p.opBatchCount() == 0); + } + + { + // + // 2 connections. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + TestIntfPrx b2 = (TestIntfPrx)p.ice_connectionId("2").ice_batchOneway(); + b2.ice_getConnection(); // Ensure connection is established. + b1.opBatch(); + b1.opBatch(); + b2.opBatch(); + b2.opBatch(); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + new Ice.Callback_Communicator_flushBatchRequests() + { + @Override + public void exception(Ice.LocalException ex) + { + cb.exception(ex); + } + + @Override + public void sent(boolean sentSynchronously) + { + cb.sent(sentSynchronously); + } + }); + cb.check(); + test(r.isSent()); + test(r.isCompleted()); + test(p.waitForBatch(4)); + } + + { + // + // Exception - 2 connections - 1 failure. + // + // All connections should be flushed even if there are failures on some connections. + // Exceptions should not be reported. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + TestIntfPrx b2 = (TestIntfPrx)p.ice_connectionId("2").ice_batchOneway(); + b2.ice_getConnection(); // Ensure connection is established. + b1.opBatch(); + b2.opBatch(); + b1.ice_getConnection().close(false); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + new Ice.Callback_Communicator_flushBatchRequests() + { + @Override + public void exception(Ice.LocalException ex) + { + cb.exception(ex); + } + + @Override + public void sent(boolean sentSynchronously) + { + cb.sent(sentSynchronously); + } + }); + cb.check(); + test(r.isSent()); // Exceptions are ignored! + test(r.isCompleted()); + test(p.waitForBatch(1)); + } + + { + // + // Exception - 2 connections - 2 failures. + // + // The sent callback should be invoked even if all connections fail. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + TestIntfPrx b2 = (TestIntfPrx)p.ice_connectionId("2").ice_batchOneway(); + b2.ice_getConnection(); // Ensure connection is established. + b1.opBatch(); + b2.opBatch(); + b1.ice_getConnection().close(false); + b2.ice_getConnection().close(false); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + new Ice.Callback_Communicator_flushBatchRequests() + { + @Override + public void exception(Ice.LocalException ex) + { + cb.exception(ex); + } + + @Override + public void sent(boolean sentSynchronously) + { + cb.sent(sentSynchronously); + } + }); + cb.check(); + test(r.isSent()); // Exceptions are ignored! + test(r.isCompleted()); + test(p.opBatchCount() == 0); + } + } + out.println("ok"); + } + + out.print("testing AsyncResult operations... "); + out.flush(); + { + { + TestIntfPrx indirect = TestIntfPrxHelper.uncheckedCast(p.ice_adapterId("dummy")); + Ice.AsyncResult r = indirect.begin_op(); + try + { + r.waitForCompleted(); + r.throwLocalException(); + test(false); + } + catch(Ice.NoEndpointException ex) + { + } + + testController.holdAdapter(); + Ice.AsyncResult r1; + Ice.AsyncResult r2; + try + { + r1 = p.begin_op(); + byte[] seq = new byte[10024]; + new java.util.Random().nextBytes(seq); // Make sure the request doesn't compress too well. + while((r2 = p.begin_opWithPayload(seq)).sentSynchronously()); + + if(p.ice_getConnection() != null) + { + test(r1.sentSynchronously() && r1.isSent() && !r1.isCompleted() || + !r1.sentSynchronously() && !r1.isCompleted()); + + test(!r2.sentSynchronously() && !r2.isCompleted()); + } + } + finally + { + testController.resumeAdapter(); + } + + r1.waitForSent(); + test(r1.isSent()); + + r2.waitForSent(); + test(r2.isSent()); + + r1.waitForCompleted(); + test(r1.isCompleted()); + + r2.waitForCompleted(); + test(r2.isCompleted()); + + test(r1.getOperation().equals("op")); + test(r2.getOperation().equals("opWithPayload")); + } + + { + Ice.AsyncResult r; + + // + // Twoway + // + r = p.begin_ice_ping(); + test(r.getOperation().equals("ice_ping")); + test(r.getConnection() == null); // Expected + test(r.getCommunicator() == communicator); + test(r.getProxy() == p); + p.end_ice_ping(r); + + TestIntfPrx p2; + + // + // Oneway + // + p2 = (TestIntfPrx)p.ice_oneway(); + r = p2.begin_ice_ping(); + test(r.getOperation().equals("ice_ping")); + test(r.getConnection() == null); // Expected + test(r.getCommunicator() == communicator); + test(r.getProxy() == p2); + + // + // Batch request via proxy + // + p2 = (TestIntfPrx)p.ice_batchOneway(); + p2.ice_ping(); + r = p2.begin_ice_flushBatchRequests(); + test(r.getConnection() == null); // Expected + test(r.getCommunicator() == communicator); + test(r.getProxy() == p2); + p2.end_ice_flushBatchRequests(r); + + if(p.ice_getConnection() != null) + { + // + // Batch request via connection + // + Ice.Connection con = p.ice_getConnection(); + p2 = (TestIntfPrx)p.ice_batchOneway(); + p2.ice_ping(); + r = con.begin_flushBatchRequests(); + test(r.getConnection() == con); + test(r.getCommunicator() == communicator); + test(r.getProxy() == null); // Expected + con.end_flushBatchRequests(r); + + // + // Batch request via communicator + // + p2 = (TestIntfPrx)p.ice_batchOneway(); + p2.ice_ping(); + r = communicator.begin_flushBatchRequests(); + test(r.getConnection() == null); // Expected + test(r.getCommunicator() == communicator); + test(r.getProxy() == null); // Expected + communicator.end_flushBatchRequests(r); + } + } + + if(p.ice_getConnection() != null) + { + Ice.AsyncResult r1 = null; + Ice.AsyncResult r2 = null; + + testController.holdAdapter(); + try + { + Ice.AsyncResult r; + byte[] seq = new byte[10024]; + new java.util.Random().nextBytes(seq); // Make sure the request doesn't compress too well. + while((r = p.begin_opWithPayload(seq)).sentSynchronously()); + + test(!r.isSent()); + + r1 = p.begin_ice_ping(); + r2 = p.begin_ice_id(); + r1.cancel(); + r2.cancel(); + try + { + p.end_ice_ping(r1); + test(false); + } + catch(Ice.InvocationCanceledException ex) + { + } + try + { + p.end_ice_id(r2); + test(false); + } + catch(Ice.InvocationCanceledException ex) + { + } + } + finally + { + testController.resumeAdapter(); + p.ice_ping(); + test(!r1.isSent() && r1.isCompleted()); + test(!r2.isSent() && r2.isCompleted()); + } + + testController.holdAdapter(); + try + { + r1 = p.begin_op(); + r2 = p.begin_ice_id(); + r1.waitForSent(); + r2.waitForSent(); + r1.cancel(); + r2.cancel(); + try + { + p.end_op(r1); + test(false); + } + catch(Ice.InvocationCanceledException ex) + { + } + try + { + p.end_ice_id(r2); + test(false); + } + catch(Ice.InvocationCanceledException ex) + { + } + } + finally + { + testController.resumeAdapter(); + } + } + } + out.println("ok"); + + if(p.ice_getConnection() != null) + { + out.print("testing close connection with sending queue... "); + out.flush(); + { + byte[] seq = new byte[1024 * 10]; + new java.util.Random().nextBytes(seq); // Make sure the request doesn't compress too well. + + // + // Send multiple opWithPayload, followed by a close and followed by multiple opWithPaylod. + // The goal is to make sure that none of the opWithPayload fail even if the server closes + // the connection gracefully in between. + // + int maxQueue = 2; + boolean done = false; + while(!done && maxQueue < 50) + { + done = true; + p.ice_ping(); + java.util.List<Ice.AsyncResult> results = new java.util.ArrayList<Ice.AsyncResult>(); + for(int i = 0; i < maxQueue; ++i) + { + results.add(p.begin_opWithPayload(seq)); + } + if(!p.begin_close(false).isSent()) + { + for(int i = 0; i < maxQueue; i++) + { + Ice.AsyncResult r = p.begin_opWithPayload(seq); + results.add(r); + if(r.isSent()) + { + done = false; + maxQueue *= 2; + break; + } + } + } + else + { + maxQueue *= 2; + done = false; + } + for(Ice.AsyncResult q : results) + { + q.waitForCompleted(); + try + { + q.throwLocalException(); + } + catch(Ice.LocalException ex) + { + test(false); + } + } + } + } + out.println("ok"); + } + } +} diff --git a/java/test/src/main/java/test/Ice/ami/AllTests.java b/java/test/src/main/java/test/Ice/ami/AllTests.java new file mode 100644 index 00000000000..cfb6be791c3 --- /dev/null +++ b/java/test/src/main/java/test/Ice/ami/AllTests.java @@ -0,0 +1,83 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.ami; + +import java.io.PrintWriter; + +import test.Ice.ami.Test.TestIntfPrx; +import test.Ice.ami.Test.TestIntfPrxHelper; +import test.Ice.ami.Test.TestIntfControllerPrx; +import test.Ice.ami.Test.TestIntfControllerPrxHelper; +import test.Util.Application; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + allTests(Application app, boolean collocated) + { + Ice.Communicator communicator = app.communicator(); + PrintWriter out = app.getWriter(); + + String sref = "test:default -p 12010"; + Ice.ObjectPrx obj = communicator.stringToProxy(sref); + test(obj != null); + + TestIntfPrx p = TestIntfPrxHelper.uncheckedCast(obj); + + sref = "testController:default -p 12011"; + obj = communicator.stringToProxy(sref); + test(obj != null); + + TestIntfControllerPrx testController = TestIntfControllerPrxHelper.uncheckedCast(obj); + + out.println("testing with new AMI mapping... "); + test.Ice.ami.AMI.run(app, communicator, collocated, p, testController); + + // + // Use reflection to load TwowaysLambdaAMI as that is only supported with Java >= 1.8 + // + try + { + Class<?> cls = IceInternal.Util.findClass("test.Ice.ami.lambda.AMI", null); + if(cls != null) + { + java.lang.reflect.Method run = cls.getDeclaredMethod("run", + new Class<?>[]{test.Util.Application.class, Ice.Communicator.class, boolean.class, TestIntfPrx.class, + TestIntfControllerPrx.class}); + out.println("testing with lambda AMI mapping... "); + out.flush(); + run.invoke(null, app, communicator, collocated, p, testController); + } + } + catch(java.lang.NoSuchMethodException ex) + { + throw new RuntimeException(ex); + } + catch(java.lang.IllegalAccessException ex) + { + throw new RuntimeException(ex); + } + catch(java.lang.reflect.InvocationTargetException ex) + { + throw new RuntimeException(ex); + } + + p.shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/ami/Client.java b/java/test/src/main/java/test/Ice/ami/Client.java new file mode 100644 index 00000000000..3e547a17ec0 --- /dev/null +++ b/java/test/src/main/java/test/Ice/ami/Client.java @@ -0,0 +1,38 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.ami; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + AllTests.allTests(this, false); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.ami"); + initData.properties.setProperty("Ice.Warn.AMICallback", "0"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/ami/Collocated.java b/java/test/src/main/java/test/Ice/ami/Collocated.java new file mode 100644 index 00000000000..2c77bbd3833 --- /dev/null +++ b/java/test/src/main/java/test/Ice/ami/Collocated.java @@ -0,0 +1,49 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.ami; + +public class Collocated extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + Ice.ObjectAdapter adapter2 = communicator().createObjectAdapter("ControllerAdapter"); + + adapter.add(new TestI(), communicator().stringToIdentity("test")); + adapter.activate(); + adapter2.add(new TestControllerI(adapter), communicator().stringToIdentity("testController")); + adapter2.activate(); + + AllTests.allTests(this, true); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.ami"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("ControllerAdapter.Endpoints", "default -p 12011"); + initData.properties.setProperty("ControllerAdapter.ThreadPool.Size", "1"); + initData.properties.setProperty("Ice.Warn.AMICallback", "0"); + return initData; + } + + public static void main(String[] args) + { + Collocated app = new Collocated(); + int result = app.main("Collocated", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/ami/Server.java b/java/test/src/main/java/test/Ice/ami/Server.java new file mode 100644 index 00000000000..b22e052fa06 --- /dev/null +++ b/java/test/src/main/java/test/Ice/ami/Server.java @@ -0,0 +1,49 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.ami; + +public class Server extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + Ice.ObjectAdapter adapter2 = communicator().createObjectAdapter("ControllerAdapter"); + + adapter.add(new TestI(), communicator().stringToIdentity("test")); + adapter.activate(); + adapter2.add(new TestControllerI(adapter), communicator().stringToIdentity("testController")); + adapter2.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.ami"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("ControllerAdapter.Endpoints", "default -p 12011"); + initData.properties.setProperty("ControllerAdapter.ThreadPool.Size", "1"); + return initData; + } + + public static void + main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/ami/Test.ice b/java/test/src/main/java/test/Ice/ami/Test.ice new file mode 100644 index 00000000000..7d1ddc7f374 --- /dev/null +++ b/java/test/src/main/java/test/Ice/ami/Test.ice @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/BuiltinSequences.ice> +#include <Ice/Endpoint.ice> + +[["java:package:test.Ice.ami"]] +module Test +{ + +exception TestIntfException +{ +}; + +interface TestIntf +{ + void op(); + void opWithPayload(Ice::ByteSeq seq); + int opWithResult(); + void opWithUE() + throws TestIntfException; + void opBatch(); + int opBatchCount(); + bool waitForBatch(int count); + void close(bool force); + void shutdown(); +}; + +interface TestIntfController +{ + void holdAdapter(); + void resumeAdapter(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/ami/TestControllerI.java b/java/test/src/main/java/test/Ice/ami/TestControllerI.java new file mode 100644 index 00000000000..9eebceb7214 --- /dev/null +++ b/java/test/src/main/java/test/Ice/ami/TestControllerI.java @@ -0,0 +1,36 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.ami; + +import test.Ice.ami.Test._TestIntfControllerDisp; + +class TestControllerI extends _TestIntfControllerDisp +{ + @Override + public void + holdAdapter(Ice.Current current) + { + _adapter.hold(); + } + + @Override + public void + resumeAdapter(Ice.Current current) + { + _adapter.activate(); + } + + public + TestControllerI(Ice.ObjectAdapter adapter) + { + _adapter = adapter; + } + + final private Ice.ObjectAdapter _adapter; +} diff --git a/java/test/src/main/java/test/Ice/ami/TestI.java b/java/test/src/main/java/test/Ice/ami/TestI.java new file mode 100644 index 00000000000..cc4f2a2040d --- /dev/null +++ b/java/test/src/main/java/test/Ice/ami/TestI.java @@ -0,0 +1,97 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.ami; + +import test.Ice.ami.Test._TestIntfDisp; +import test.Ice.ami.Test.TestIntfException; + +public class TestI extends _TestIntfDisp +{ + TestI() + { + } + + @Override + public void + op(Ice.Current current) + { + } + + @Override + public int + opWithResult(Ice.Current current) + { + return 15; + } + + @Override + public void + opWithUE(Ice.Current current) + throws TestIntfException + { + throw new TestIntfException(); + } + + @Override + public void + opWithPayload(byte[] seq, Ice.Current current) + { + } + + @Override + public synchronized void + opBatch(Ice.Current current) + { + ++_batchCount; + notify(); + } + + @Override + public synchronized int + opBatchCount(Ice.Current current) + { + return _batchCount; + } + + @Override + public synchronized boolean + waitForBatch(int count, Ice.Current current) + { + while(_batchCount < count) + { + try + { + wait(5000); + } + catch(InterruptedException ex) + { + } + } + boolean result = count == _batchCount; + _batchCount = 0; + return result; + } + + @Override + public void + close(boolean force, Ice.Current current) + { + current.con.close(force); + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + private int _batchCount; +} diff --git a/java/test/src/main/java/test/Ice/ami/lambda/AMI.java b/java/test/src/main/java/test/Ice/ami/lambda/AMI.java new file mode 100644 index 00000000000..65bd185a849 --- /dev/null +++ b/java/test/src/main/java/test/Ice/ami/lambda/AMI.java @@ -0,0 +1,1138 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.ami.lambda; + +import java.io.PrintWriter; + +import test.Ice.ami.Test.TestIntfPrx; +import test.Ice.ami.Test.TestIntfPrxHelper; +import test.Ice.ami.Test.TestIntfControllerPrx; +import test.Ice.ami.Test.TestIntfControllerPrxHelper; +import test.Ice.ami.Test.TestIntfException; +import test.Ice.ami.Test.Callback_TestIntf_op; +import test.Ice.ami.Test.Callback_TestIntf_opWithResult; +import test.Ice.ami.Test.Callback_TestIntf_opWithUE; +import test.Ice.ami.Test.Callback_TestIntf_opWithPayload; +import test.Util.Application; + +public class AMI +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class CallbackBase + { + CallbackBase() + { + _called = false; + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + static class AsyncCallback extends CallbackBase + { + public AsyncCallback() + { + } + + public void + isA(Ice.AsyncResult result) + { + test(result.getProxy().end_ice_isA(result)); + called(); + } + + public void + ping(Ice.AsyncResult result) + { + result.getProxy().end_ice_ping(result); + called(); + } + + public void + id(Ice.AsyncResult result) + { + test(result.getProxy().end_ice_id(result).equals("::Test::TestIntf")); + called(); + } + + public void + ids(Ice.AsyncResult result) + { + test(result.getProxy().end_ice_ids(result).length == 2); + called(); + } + + public void + connection(Ice.AsyncResult result) + { + test(result.getProxy().end_ice_getConnection(result) != null); + called(); + } + + public void + op(Ice.AsyncResult result) + { + TestIntfPrxHelper.uncheckedCast(result.getProxy()).end_op(result); + called(); + } + + public void + opWithResult(Ice.AsyncResult result) + { + test(TestIntfPrxHelper.uncheckedCast(result.getProxy()).end_opWithResult(result) == 15); + called(); + } + + public void + opWithUE(Ice.AsyncResult result) + { + try + { + TestIntfPrxHelper.uncheckedCast(result.getProxy()).end_opWithUE(result); + test(false); + } + catch(TestIntfException ex) + { + called(); + } + catch(Ice.Exception ex) + { + test(false); + } + } + + public void + isAEx(Ice.AsyncResult result) + { + try + { + result.getProxy().end_ice_isA(result); + test(false); + } + catch(Ice.NoEndpointException ex) + { + called(); + } + catch(Ice.Exception ex) + { + test(false); + } + } + + public void + pingEx(Ice.AsyncResult result) + { + try + { + result.getProxy().end_ice_ping(result); + test(false); + } + catch(Ice.NoEndpointException ex) + { + called(); + } + catch(Ice.Exception ex) + { + test(false); + } + } + + public void + idEx(Ice.AsyncResult result) + { + try + { + result.getProxy().end_ice_id(result); + test(false); + } + catch(Ice.NoEndpointException ex) + { + called(); + } + catch(Ice.Exception ex) + { + test(false); + } + } + + public void + idsEx(Ice.AsyncResult result) + { + try + { + result.getProxy().end_ice_ids(result); + test(false); + } + catch(Ice.NoEndpointException ex) + { + called(); + } + catch(Ice.Exception ex) + { + test(false); + } + } + + public void + connectionEx(Ice.AsyncResult result) + { + try + { + result.getProxy().end_ice_getConnection(result); + test(false); + } + catch(Ice.NoEndpointException ex) + { + called(); + } + catch(Ice.Exception ex) + { + test(false); + } + } + + public void + opEx(Ice.AsyncResult result) + { + try + { + TestIntfPrxHelper.uncheckedCast(result.getProxy()).end_op(result); + test(false); + } + catch(Ice.NoEndpointException ex) + { + called(); + } + catch(Ice.Exception ex) + { + test(false); + } + } + } + + static class ResponseCallback extends CallbackBase + { + ResponseCallback() + { + } + + public void + isA(boolean r) + { + test(r); + called(); + } + + public void + ping() + { + called(); + } + + public void + id(String id) + { + test(id.equals("::Test::TestIntf")); + called(); + } + + public void + ids(String[] ids) + { + test(ids.length == 2); + called(); + } + + public void + connection(Ice.Connection conn) + { + test(conn != null); + called(); + } + + public void + op() + { + called(); + } + + public void + opWithResult(int r) + { + test(r == 15); + called(); + } + + public void + opWithUE(Ice.UserException e) + { + try + { + throw e; + } + catch(TestIntfException ex) + { + called(); + } + catch(Ice.UserException ex) + { + test(false); + } + } + } + + static class ExceptionCallback extends CallbackBase + { + public ExceptionCallback() + { + } + + public void + isA(boolean r) + { + test(false); + } + + public void + ping() + { + test(false); + } + + public void + id(String id) + { + test(false); + } + + public void + ids(String[] ids) + { + test(false); + } + + public void + connection(Ice.Connection conn) + { + test(false); + } + + public void + op() + { + test(false); + } + + public void + ex(Ice.Exception ex) + { + test(ex instanceof Ice.NoEndpointException); + called(); + } + + public void + noEx(Ice.Exception ex) + { + test(false); + } + } + + static class SentCallback extends CallbackBase + { + SentCallback() + { + _thread = Thread.currentThread().getId(); + } + + public void + isA(boolean r) + { + } + + public void + ping() + { + } + + public void + id(String s) + { + } + + public void + ids(String[] s) + { + } + + public void + opAsync(Ice.AsyncResult r) + { + } + + public void + op() + { + } + + public void + ex(Ice.Exception ex) + { + } + + public void + sent(Ice.AsyncResult r) + { + test(r.sentSynchronously() && _thread == Thread.currentThread().getId() || + !r.sentSynchronously() && _thread != Thread.currentThread().getId()); + called(); + } + + public void + sent(boolean ss) + { + test(ss && _thread == Thread.currentThread().getId() || + !ss && _thread != Thread.currentThread().getId()); + called(); + } + + long _thread; + } + + static class FlushCallback extends CallbackBase + { + FlushCallback() + { + _thread = Thread.currentThread().getId(); + } + + public void + completedAsync(Ice.AsyncResult r) + { + test(false); + } + + public void + exception(Ice.Exception ex) + { + test(false); + } + + public void + sentAsync(Ice.AsyncResult r) + { + test((r.sentSynchronously() && _thread == Thread.currentThread().getId()) || + (!r.sentSynchronously() && _thread != Thread.currentThread().getId())); + called(); + } + + public void + sent(boolean sentSynchronously) + { + test((sentSynchronously && _thread == Thread.currentThread().getId()) || + (!sentSynchronously && _thread != Thread.currentThread().getId())); + called(); + } + + long _thread; + } + + static class FlushExCallback extends CallbackBase + { + FlushExCallback() + { + } + + public void + completedAsync(Ice.AsyncResult r) + { + try + { + if(r.getConnection() != null) + { + r.getConnection().end_flushBatchRequests(r); + } + else + { + r.getProxy().end_ice_flushBatchRequests(r); + } + test(false); + } + catch(Ice.Exception ex) + { + called(); + } + } + + public void + exception(Ice.Exception ex) + { + called(); + } + + public void + sentAsync(Ice.AsyncResult r) + { + test(false); + } + + public void + sent(boolean sentSynchronously) + { + test(false); + } + } + + enum ThrowType { LocalException, OtherException }; + + static class Thrower extends CallbackBase + { + public Thrower(ThrowType t) + { + _t = t; + } + + public void + opAsync(Ice.AsyncResult r) + { + called(); + throwEx(); + } + + public void + op() + { + called(); + throwEx(); + } + + public void + noOp() + { + } + + public void + ex(Ice.Exception ex) + { + called(); + throwEx(); + } + + public void + sent(boolean ss) + { + called(); + throwEx(); + } + + private void + throwEx() + { + switch(_t) + { + case LocalException: + { + throw new Ice.ObjectNotExistException(); + } + case OtherException: + { + throw new RuntimeException(); + } + default: + { + assert(false); + break; + } + } + } + + ThrowType _t; + } + + public static void + run(Application app, Ice.Communicator communicator, boolean collocated, TestIntfPrx p, + TestIntfControllerPrx testController) + { + + PrintWriter out = app.getWriter(); + + out.print("testing response callback... "); + out.flush(); + { + final ResponseCallback cb = new ResponseCallback(); + java.util.Map<String, String> ctx = new java.util.HashMap<String, String>(); + + p.begin_ice_isA("::Test::TestIntf", + (boolean r) -> cb.isA(r), + (Ice.Exception ex) -> test(false)); + cb.check(); + + p.begin_ice_isA("::Test::TestIntf", + (boolean r) -> cb.isA(r), + (Ice.Exception ex) -> test(false)); + cb.check(); + + p.begin_ice_ping( + () -> cb.ping(), + (Ice.Exception ex) -> test(false)); + cb.check(); + + p.begin_ice_ping(ctx, + () -> cb.ping(), + (Ice.Exception ex) -> test(false)); + cb.check(); + + p.begin_ice_id( + (String id) -> cb.id(id), + (Ice.Exception ex) -> test(false)); + cb.check(); + + p.begin_ice_id(ctx, + (String id) -> cb.id(id), + (Ice.Exception ex) -> test(false)); + cb.check(); + + p.begin_ice_ids( + (String[] ids) -> cb.ids(ids), + (Ice.Exception ex) -> test(false)); + cb.check(); + + p.begin_ice_ids(ctx, + (String[] ids) -> cb.ids(ids), + (Ice.Exception ex) -> test(false)); + cb.check(); + + if(!collocated) + { + p.begin_ice_getConnection( + (Ice.Connection conn) -> cb.connection(conn), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + p.begin_op( + () -> cb.op(), + (Ice.Exception ex) -> test(false)); + cb.check(); + + p.begin_op(ctx, + () -> cb.op(), + (Ice.Exception ex) -> test(false)); + cb.check(); + + p.begin_opWithResult( + (int r) -> cb.opWithResult(r), + (Ice.Exception ex) -> test(false)); + cb.check(); + + p.begin_opWithResult(ctx, + (int r) -> cb.opWithResult(r), + (Ice.Exception ex) -> test(false)); + cb.check(); + + p.begin_opWithUE( + () -> test(false), + (Ice.UserException ex) -> cb.opWithUE(ex), + (Ice.Exception ex) -> test(false)); + cb.check(); + + p.begin_opWithUE(ctx, + () -> test(false), + (Ice.UserException ex) -> cb.opWithUE(ex), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + out.println("ok"); + + out.print("testing local exceptions with response callback... "); + out.flush(); + { + TestIntfPrx i = TestIntfPrxHelper.uncheckedCast(p.ice_adapterId("dummy")); + final ExceptionCallback cb = new ExceptionCallback(); + + i.begin_ice_isA("::Test::TestIntf", + (boolean r) -> test(false), + (Ice.Exception ex) -> cb.ex(ex)); + cb.check(); + + i.begin_ice_ping( + () -> test(false), + (Ice.Exception ex) -> cb.ex(ex)); + cb.check(); + + i.begin_ice_id( + (String id) -> test(false), + (Ice.Exception ex) -> cb.ex(ex)); + cb.check(); + + i.begin_ice_ids( + (String[] ids) -> test(false), + (Ice.Exception ex) -> cb.ex(ex)); + cb.check(); + + if(!collocated) + { + i.begin_ice_getConnection( + (Ice.Connection conn) -> test(false), + (Ice.Exception ex) -> cb.ex(ex)); + cb.check(); + } + + i.begin_op( + () -> test(false), + (Ice.Exception ex) -> cb.ex(ex)); + cb.check(); + } + out.println("ok"); + + out.print("testing sent callback... "); + out.flush(); + { + final SentCallback cb = new SentCallback(); + + p.begin_ice_isA("", + (boolean r) -> cb.isA(r), + (Ice.Exception ex) -> cb.ex(ex), + (boolean ss) -> cb.sent(ss)); + cb.check(); + + p.begin_ice_ping( + () -> cb.ping(), + (Ice.Exception ex) -> cb.ex(ex), + (boolean ss) -> cb.sent(ss)); + cb.check(); + + p.begin_ice_id( + (String id) -> cb.id(id), + (Ice.Exception ex) -> cb.ex(ex), + (boolean ss) -> cb.sent(ss)); + cb.check(); + + p.begin_ice_ids( + (String[] ids) -> cb.ids(ids), + (Ice.Exception ex) -> cb.ex(ex), + (boolean ss) -> cb.sent(ss)); + cb.check(); + + p.begin_op( + () -> cb.op(), + (Ice.Exception ex) -> cb.ex(ex), + (boolean ss) -> cb.sent(ss)); + cb.check(); + + java.util.List<SentCallback> cbs = new java.util.ArrayList<SentCallback>(); + byte[] seq = new byte[10024]; + new java.util.Random().nextBytes(seq); // Make sure the request doesn't compress too well. + Ice.AsyncResult r; + testController.holdAdapter(); + try + { + do + { + final SentCallback cb2 = new SentCallback(); + r = p.begin_opWithPayload(seq, + () -> {}, + (Ice.Exception ex) -> cb2.ex(ex), + (boolean ss) -> cb2.sent(ss)); + cbs.add(cb2); + } + while(r.sentSynchronously()); + } + finally + { + testController.resumeAdapter(); + } + for(SentCallback cb3 : cbs) + { + cb3.check(); + } + } + out.println("ok"); + + out.print("testing unexpected exceptions from callback... "); + out.flush(); + { + TestIntfPrx q = TestIntfPrxHelper.uncheckedCast(p.ice_adapterId("dummy")); + ThrowType throwEx[] = { ThrowType.LocalException, ThrowType.OtherException }; + + for(int i = 0; i < 2; ++i) + { + final Thrower cb = new Thrower(throwEx[i]); + + p.begin_op( + () -> cb.op(), + null); + cb.check(); + + q.begin_op( + () -> cb.op(), + (Ice.Exception ex) -> cb.ex(ex)); + cb.check(); + + p.begin_op( + () -> {}, + (Ice.Exception ex) -> {}, + (boolean ss) -> cb.sent(ss)); + cb.check(); + } + } + out.println("ok"); + + out.print("testing batch requests with proxy... "); + out.flush(); + { + { + // + // Type-safe. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.opBatch(); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = b1.begin_ice_flushBatchRequests( + null, + (Ice.Exception ex) -> cb.exception(ex), + (boolean sentSynchronously) -> cb.sent(sentSynchronously)); + cb.check(); + test(r.isSent()); + test(r.isCompleted()); + test(p.waitForBatch(2)); + } + + if(p.ice_getConnection() != null) + { + // + // Type-safe exception. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.ice_getConnection().close(false); + final FlushExCallback cb = new FlushExCallback(); + Ice.AsyncResult r = b1.begin_ice_flushBatchRequests( + null, + (Ice.Exception ex) -> cb.exception(ex), + (boolean sentSynchronously) -> cb.sent(sentSynchronously)); + cb.check(); + test(!r.isSent()); + test(r.isCompleted()); + test(p.opBatchCount() == 0); + } + } + out.println("ok"); + + if(p.ice_getConnection() != null) + { + out.print("testing batch requests with connection... "); + out.flush(); + { + { + // + // Type-safe. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.opBatch(); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = b1.ice_getConnection().begin_flushBatchRequests( + null, + (Ice.Exception ex) -> cb.exception(ex), + (boolean sentSynchronously) -> cb.sent(sentSynchronously)); + cb.check(); + test(r.isSent()); + test(r.isCompleted()); + test(p.waitForBatch(2)); + + final FlushCallback cb2 = new FlushCallback(); + Ice.AsyncResult r2 = b1.ice_getConnection().begin_flushBatchRequests( + null, + (Ice.Exception ex) -> cb2.exception(ex), + (boolean sentSynchronously) -> cb2.sent(sentSynchronously)); + cb2.check(); + test(r2.isSent()); + test(r2.isCompleted()); + } + + { + // + // Type-safe exception. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.ice_getConnection().close(false); + final FlushExCallback cb = new FlushExCallback(); + Ice.AsyncResult r = b1.ice_getConnection().begin_flushBatchRequests( + null, + (Ice.Exception ex) -> cb.exception(ex), + (boolean sentSynchronously) -> cb.sent(sentSynchronously)); + cb.check(); + test(!r.isSent()); + test(r.isCompleted()); + test(p.opBatchCount() == 0); + } + } + out.println("ok"); + + out.print("testing batch requests with communicator... "); + out.flush(); + { + { + // + // Type-safe - 1 connection. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.opBatch(); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + null, + (Ice.Exception ex) -> cb.exception(ex), + (boolean sentSynchronously) -> cb.sent(sentSynchronously)); + cb.check(); + test(r.isSent()); + test(r.isCompleted()); + test(p.waitForBatch(2)); + } + + { + // + // Type-safe exception - 1 connection. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + b1.opBatch(); + b1.ice_getConnection().close(false); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + null, + (Ice.Exception ex) -> cb.exception(ex), + (boolean sentSynchronously) -> cb.sent(sentSynchronously)); + cb.check(); + test(r.isSent()); // Exceptions are ignored! + test(r.isCompleted()); + test(p.opBatchCount() == 0); + } + + { + // + // 2 connections. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + TestIntfPrx b2 = (TestIntfPrx)p.ice_connectionId("2").ice_batchOneway(); + b2.ice_getConnection(); // Ensure connection is established. + b1.opBatch(); + b1.opBatch(); + b2.opBatch(); + b2.opBatch(); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + null, + (Ice.Exception ex) -> cb.exception(ex), + (boolean sentSynchronously) -> cb.sent(sentSynchronously)); + cb.check(); + test(r.isSent()); + test(r.isCompleted()); + test(p.waitForBatch(4)); + } + + { + // + // Exception - 2 connections - 1 failure. + // + // All connections should be flushed even if there are failures on some connections. + // Exceptions should not be reported. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + TestIntfPrx b2 = (TestIntfPrx)p.ice_connectionId("2").ice_batchOneway(); + b2.ice_getConnection(); // Ensure connection is established. + b1.opBatch(); + b2.opBatch(); + b1.ice_getConnection().close(false); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + null, + (Ice.Exception ex) -> cb.exception(ex), + (boolean sentSynchronously) -> cb.sent(sentSynchronously)); + cb.check(); + test(r.isSent()); // Exceptions are ignored! + test(r.isCompleted()); + test(p.waitForBatch(1)); + } + + { + // + // Exception - 2 connections - 2 failures. + // + // The sent callback should be invoked even if all connections fail. + // + test(p.opBatchCount() == 0); + TestIntfPrx b1 = (TestIntfPrx)p.ice_batchOneway(); + TestIntfPrx b2 = (TestIntfPrx)p.ice_connectionId("2").ice_batchOneway(); + b2.ice_getConnection(); // Ensure connection is established. + b1.opBatch(); + b2.opBatch(); + b1.ice_getConnection().close(false); + b2.ice_getConnection().close(false); + final FlushCallback cb = new FlushCallback(); + Ice.AsyncResult r = communicator.begin_flushBatchRequests( + null, + (Ice.Exception ex) -> cb.exception(ex), + (boolean sentSynchronously) -> cb.sent(sentSynchronously)); + cb.check(); + test(r.isSent()); // Exceptions are ignored! + test(r.isCompleted()); + test(p.opBatchCount() == 0); + } + } + out.println("ok"); + } + + out.print("testing null callbacks..."); + try + { + IceInternal.Functional_VoidCallback response = null; + IceInternal.Functional_GenericCallback1<Ice.Exception> exception = null; + p.begin_ice_ping(response, exception); + test(false); + } + catch(IllegalArgumentException ex) + { + // Excepted when response and exception callback are both null. + } + + try + { + p.begin_ice_ping(() -> {}, null); + + } + catch(IllegalArgumentException ex) + { + test(false); + } + + try + { + p.begin_ice_ping(null, (Ice.Exception ex) -> {}); + + } + catch(IllegalArgumentException ex) + { + test(false); + } + + try + { + IceInternal.Functional_BoolCallback response = null; + IceInternal.Functional_GenericCallback1<Ice.Exception> exception = null; + p.begin_ice_isA("::Test::TestIntf", response, exception); + test(false); + } + catch(IllegalArgumentException ex) + { + // Excepted when response and exception callback are both null. + } + + try + { + p.begin_ice_isA("::Test::TestIntf", (boolean v) -> {}, null); + + } + catch(IllegalArgumentException ex) + { + test(false); + } + + try + { + p.begin_ice_isA("::Test::TestIntf", null, (Ice.Exception ex) -> {}); + + } + catch(IllegalArgumentException ex) + { + test(false); + } + + try + { + IceInternal.Functional_VoidCallback response = null; + p.begin_opWithUE(response, null, (Ice.Exception ex) -> {}); + test(false); + } + catch(IllegalArgumentException ex) + { + // Excepted when response and exception callback are both null, for + // an operation that throws user exceptions both user exception callback + // an local exception callback must be present. + } + + try + { + IceInternal.Functional_VoidCallback response = null; + p.begin_opWithUE(response, (Ice.UserException ex) -> {}, null); + test(false); + } + catch(IllegalArgumentException ex) + { + // Excepted when response and exception callback are both null, for + // an operation that throws user exceptions both user exception callback + // an local exception callback must be present. + } + + try + { + IceInternal.Functional_VoidCallback response = null; + IceInternal.Functional_GenericCallback1<Ice.UserException> userException = null; + IceInternal.Functional_GenericCallback1<Ice.Exception> exception = null; + p.begin_opWithUE(response, userException, exception); + test(false); + } + catch(IllegalArgumentException ex) + { + // Excepted when response and exception callback are both null. + } + out.println("ok"); + } +} diff --git a/java/test/src/main/java/test/Ice/ami/run.py b/java/test/src/main/java/test/Ice/ami/run.py new file mode 100755 index 00000000000..6444a527f9a --- /dev/null +++ b/java/test/src/main/java/test/Ice/ami/run.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("tests with regular server.") +TestUtil.clientServerTest() +print("tests with collocated server.") +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/background/Acceptor.java b/java/test/src/main/java/test/Ice/background/Acceptor.java new file mode 100644 index 00000000000..598ff348fb2 --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/Acceptor.java @@ -0,0 +1,80 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.background; + +class Acceptor implements IceInternal.Acceptor +{ + @Override + public java.nio.channels.ServerSocketChannel + fd() + { + return _acceptor.fd(); + } + + @Override + public void + close() + { + _acceptor.close(); + } + + @Override + public IceInternal.EndpointI + listen() + { + _endpoint = _endpoint.endpoint(_acceptor.listen()); + return _endpoint; + } + + @Override + public IceInternal.Transceiver + accept() + { + return new Transceiver(_configuration, _acceptor.accept()); + } + + @Override + public String + protocol() + { + return _acceptor.protocol(); + } + + @Override + public String + toString() + { + return _acceptor.toString(); + } + + @Override + public String + toDetailedString() + { + return _acceptor.toDetailedString(); + } + + public IceInternal.Acceptor + delegate() + { + return _acceptor; + } + + Acceptor(EndpointI endpoint, Configuration configuration, IceInternal.Acceptor acceptor) + { + _endpoint = endpoint; + _configuration = configuration; + _acceptor = acceptor; + } + + private EndpointI _endpoint; + final private IceInternal.Acceptor _acceptor; + private Configuration _configuration; +} diff --git a/java/test/src/main/java/test/Ice/background/AllTests.java b/java/test/src/main/java/test/Ice/background/AllTests.java new file mode 100644 index 00000000000..ba04e6421b7 --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/AllTests.java @@ -0,0 +1,1394 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.background; + +import java.io.PrintWriter; + +import test.Ice.background.Test.BackgroundControllerPrx; +import test.Ice.background.Test.BackgroundControllerPrxHelper; +import test.Ice.background.Test.BackgroundPrx; +import test.Ice.background.Test.BackgroundPrxHelper; +import test.Ice.background.Test.Callback_Background_op; +import test.Ice.background.Test.Callback_Background_opWithPayload; + +public class AllTests +{ + private static void test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + _called = false; + } + + public synchronized void called() + { + assert(!_called); + _called = true; + notify(); + } + + public synchronized boolean isCalled() + { + return _called; + } + + private boolean _called; + } + + private static class OpAMICallback extends Callback_Background_op + { + @Override + public void response() + { + _response.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + + @Override + public void sent(boolean ss) + { + _sent.called(); + } + + public boolean response(boolean wait) + { + if(wait) + { + _response.check(); + return true; + } + else + { + return _response.isCalled(); + } + } + + public void responseAndSent() + { + _sent.check(); + _response.check(); + } + + private Callback _response = new Callback(); + private Callback _sent = new Callback(); + } + + private static class OpAMICallbackEx extends Callback_Background_op + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException ex) + { + _response.called(); + } + + @Override + public void sent(boolean ss) + { + _sent.called(); + } + + public boolean exception(boolean wait) + { + if(wait) + { + _response.check(); + return true; + } + else + { + return _response.isCalled(); + } + } + + private Callback _response = new Callback(); + private Callback _sent = new Callback(); + } + + private static class OpAMICallbackNoOp extends Callback_Background_op + { + @Override + public void response() + { + } + + @Override + public void exception(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + + @Override + public void sent(boolean ss) + { + } + } + + private static class NoResponse extends Callback_Background_opWithPayload + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + } + + /* + private static class OpWithPayloadOnewayAMICallback extends AMI_Background_opWithPayload + { + public void + ice_response() + { + test(false); + } + + public void + ice_exception(Ice.LocalException ex) + { + test(false); + } + } + + private static class FlushBatchRequestsCallback extends Ice.AMI_Object_ice_flushBatchRequests + { + public void + ice_exception(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + } + */ + + static class OpThread extends Thread + { + OpThread(BackgroundPrx background) + { + _destroyed = false; + _background = BackgroundPrxHelper.uncheckedCast(background.ice_oneway()); + start(); + } + + @Override + public void + run() + { + int count = 0; + while(true) + { + synchronized(this) + { + if(_destroyed) + { + return; + } + } + + try + { + if(++count == 10) // Don't blast the connection with only oneway's + { + count = 0; + _background.ice_twoway().ice_ping(); + } + _background.op(); + try + { + Thread.sleep(1); + } + catch(java.lang.InterruptedException ex) + { + } + } + catch(Ice.LocalException ex) + { + } + } + } + + public synchronized void + _destroy() // Thread.destroy is deprecated + { + _destroyed = true; + } + + private boolean _destroyed; + private BackgroundPrx _background = null; + } + + public static BackgroundPrx + allTests(Configuration configuration, Ice.Communicator communicator, PrintWriter out) + { + String sref = "background:default -p 12010"; + Ice.ObjectPrx obj = communicator.stringToProxy(sref); + test(obj != null); + + BackgroundPrx background = BackgroundPrxHelper.uncheckedCast(obj); + + sref = "backgroundController:tcp -p 12011"; + obj = communicator.stringToProxy(sref); + test(obj != null); + + BackgroundControllerPrx backgroundController = BackgroundControllerPrxHelper.uncheckedCast(obj); + + out.print("testing connect... "); + out.flush(); + { + connectTests(configuration, background); + } + out.println("ok"); + + out.print("testing initialization... "); + out.flush(); + { + initializeTests(configuration, background, backgroundController); + } + out.println("ok"); + + out.print("testing connection validation... "); + out.flush(); + { + validationTests(configuration, background, backgroundController); + } + out.println("ok"); + + out.print("testing read/write... "); + out.flush(); + { + readWriteTests(configuration, background, backgroundController); + } + out.println("ok"); + + out.print("testing locator... "); + out.flush(); + { + Ice.LocatorPrx locator; + obj = communicator.stringToProxy("locator:default -p 12010").ice_invocationTimeout(250); + locator = Ice.LocatorPrxHelper.uncheckedCast(obj); + obj = communicator.stringToProxy("background@Test").ice_locator(locator).ice_oneway(); + + backgroundController.pauseCall("findAdapterById"); + try + { + obj.ice_ping(); + test(false); + } + catch(Ice.TimeoutException ex) + { + } + backgroundController.resumeCall("findAdapterById"); + + obj = communicator.stringToProxy("locator:default -p 12010"); + locator = Ice.LocatorPrxHelper.uncheckedCast(obj); + obj = obj.ice_locator(locator); + obj.ice_ping(); + + obj = communicator.stringToProxy("background@Test").ice_locator(locator); + BackgroundPrx bg = BackgroundPrxHelper.uncheckedCast(obj); + + backgroundController.pauseCall("findAdapterById"); + Ice.AsyncResult r1 = bg.begin_op(); + Ice.AsyncResult r2 = bg.begin_op(); + test(!r1.isCompleted()); + test(!r2.isCompleted()); + backgroundController.resumeCall("findAdapterById"); + bg.end_op(r1); + bg.end_op(r2); + test(r1.isCompleted()); + test(r2.isCompleted()); + } + out.println("ok"); + + out.print("testing router... "); + out.flush(); + { + Ice.RouterPrx router; + + obj = communicator.stringToProxy("router:default -p 12010").ice_invocationTimeout(250); + router = Ice.RouterPrxHelper.uncheckedCast(obj); + obj = communicator.stringToProxy("background@Test").ice_router(router).ice_oneway(); + + backgroundController.pauseCall("getClientProxy"); + try + { + obj.ice_ping(); + test(false); + } + catch(Ice.TimeoutException ex) + { + } + backgroundController.resumeCall("getClientProxy"); + + obj = communicator.stringToProxy("router:default -p 12010"); + router = Ice.RouterPrxHelper.uncheckedCast(obj); + obj = communicator.stringToProxy("background@Test").ice_router(router); + BackgroundPrx bg = BackgroundPrxHelper.uncheckedCast(obj); + test(bg.ice_getRouter() != null); + + backgroundController.pauseCall("getClientProxy"); + Ice.AsyncResult r1 = bg.begin_op(); + Ice.AsyncResult r2 = bg.begin_op(); + test(!r1.isCompleted()); + test(!r2.isCompleted()); + backgroundController.resumeCall("getClientProxy"); + bg.end_op(r1); + bg.end_op(r2); + test(r1.isCompleted()); + test(r2.isCompleted()); + } + out.println("ok"); + + final boolean ws = communicator.getProperties().getProperty("Ice.Default.Protocol").equals("test-ws"); + final boolean wss = communicator.getProperties().getProperty("Ice.Default.Protocol").equals("test-wss"); + if(!ws && !wss) + { + out.print("testing buffered transport... "); + out.flush(); + + configuration.buffered(true); + backgroundController.buffered(true); + background.begin_op(); + background.ice_getCachedConnection().close(true); + background.begin_op(); + + Ice.AsyncResult r = null; + OpAMICallbackNoOp cb = new OpAMICallbackNoOp(); + + for(int i = 0; i < 10000; ++i) + { + r = background.begin_op(cb); + if(i % 50 == 0) + { + backgroundController.holdAdapter(); + backgroundController.resumeAdapter(); + } + if(i % 100 == 0) + { + r.waitForCompleted(); + } + } + r.waitForCompleted(); + + out.println("ok"); + } + + return background; + } + + private static void + connectTests(Configuration configuration, BackgroundPrx background) + { + try + { + background.op(); + } + catch(Ice.LocalException ex) + { + test(false); + } + background.ice_getConnection().close(false); + + for(int i = 0; i < 4; ++i) + { + if(i == 0 || i == 2) + { + configuration.connectorsException(new Ice.DNSException()); + } + else + { + configuration.connectException(new Ice.SocketException()); + } + BackgroundPrx prx = (i == 1 || i == 3) ? background : (BackgroundPrx)background.ice_oneway(); + + try + { + prx.op(); + test(false); + } + catch(Ice.LocalException ex) + { + } + + Ice.AsyncResult r = prx.begin_op(); + test(!r.sentSynchronously()); + try + { + prx.end_op(r); + test(false); + } + catch(Ice.LocalException ex) + { + } + test(r.isCompleted()); + + OpAMICallbackEx cbEx = new OpAMICallbackEx(); + r = prx.begin_op(cbEx); + test(!r.sentSynchronously()); + cbEx.exception(true); + test(r.isCompleted()); + + if(i == 0 || i == 2) + { + configuration.connectorsException(null); + } + else + { + configuration.connectException(null); + } + } + + OpThread thread1 = new OpThread(background); + OpThread thread2 = new OpThread(background); + + for(int i = 0; i < 5; i++) + { + try + { + background.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + + configuration.connectException(new Ice.SocketException()); + background.ice_getCachedConnection().close(true); + try + { + Thread.sleep(10); + } + catch(java.lang.InterruptedException ex) + { + } + configuration.connectException(null); + try + { + background.ice_ping(); + } + catch(Ice.LocalException ex) + { + } + } + + thread1._destroy(); + thread2._destroy(); + + try + { + thread1.join(); + thread2.join(); + } + catch(InterruptedException e) + { + } + } + + private static void + initializeTests(Configuration configuration, BackgroundPrx background, BackgroundControllerPrx ctl) + { + try + { + background.op(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + background.ice_getConnection().close(false); + + for(int i = 0; i < 4; i++) + { + if(i == 0 || i == 2) + { + configuration.initializeException(new Ice.SocketException()); + } + else + { + configuration.initializeSocketStatus(IceInternal.SocketOperation.Write); + configuration.initializeException(new Ice.SocketException()); + } + BackgroundPrx prx = (i == 1 || i == 3) ? background : (BackgroundPrx)background.ice_oneway(); + + try + { + prx.op(); + test(false); + } + catch(Ice.SocketException ex) + { + } + + Ice.AsyncResult r = prx.begin_op(); + test(!r.sentSynchronously()); + try + { + prx.end_op(r); + test(false); + } + catch(Ice.LocalException ex) + { + } + test(r.isCompleted()); + + OpAMICallbackEx cbEx = new OpAMICallbackEx(); + r = prx.begin_op(cbEx); + test(!r.sentSynchronously()); + cbEx.exception(true); + test(r.isCompleted()); + + if(i == 0 || i == 2) + { + configuration.initializeException(null); + } + else + { + configuration.initializeSocketStatus(IceInternal.SocketOperation.None); + configuration.initializeException(null); + } + } + + try + { + configuration.initializeSocketStatus(IceInternal.SocketOperation.Connect); + background.op(); + configuration.initializeSocketStatus(IceInternal.SocketOperation.None); + } + catch(Ice.LocalException ex) + { + test(false); + } + background.ice_getConnection().close(false); + + try + { + configuration.initializeSocketStatus(IceInternal.SocketOperation.Write); + background.op(); + configuration.initializeSocketStatus(IceInternal.SocketOperation.None); + } + catch(Ice.LocalException ex) + { + test(false); + } + background.ice_getConnection().close(false); + + try + { + configuration.initializeSocketStatus(IceInternal.SocketOperation.Write); + configuration.initializeException(new Ice.SocketException()); + background.op(); + test(false); + } + catch(Ice.SocketException ex) + { + configuration.initializeException(null); + configuration.initializeSocketStatus(IceInternal.SocketOperation.None); + } + + // + // Now run the same tests with the server side. + // + + try + { + ctl.initializeException(true); + background.op(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + ctl.initializeException(false); + } + catch(Ice.SecurityException ex) + { + ctl.initializeException(false); + } + + try + { + ctl.initializeSocketStatus(IceInternal.SocketOperation.Write); + background.op(); + ctl.initializeSocketStatus(IceInternal.SocketOperation.None); + } + catch(Ice.LocalException ex) + { + test(false); + } + background.ice_getConnection().close(false); + + try + { + ctl.initializeSocketStatus(IceInternal.SocketOperation.Write); + ctl.initializeException(true); + background.op(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + ctl.initializeException(false); + ctl.initializeSocketStatus(IceInternal.SocketOperation.None); + } + catch(Ice.SecurityException ex) + { + ctl.initializeException(false); + ctl.initializeSocketStatus(IceInternal.SocketOperation.None); + } + + OpThread thread1 = new OpThread(background); + OpThread thread2 = new OpThread(background); + + for(int i = 0; i < 5; i++) + { + try + { + background.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + + configuration.initializeException(new Ice.SocketException()); + background.ice_getCachedConnection().close(true); + try + { + Thread.sleep(10); + } + catch(java.lang.InterruptedException ex) + { + } + configuration.initializeException(null); + try + { + background.ice_ping(); + } + catch(Ice.LocalException ex) + { + } + try + { + background.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + + configuration.initializeSocketStatus(IceInternal.SocketOperation.Write); + background.ice_getCachedConnection().close(true); + background.ice_ping(); + configuration.initializeSocketStatus(IceInternal.SocketOperation.None); + + ctl.initializeException(true); + background.ice_getCachedConnection().close(true); + try + { + Thread.sleep(10); + } + catch(java.lang.InterruptedException ex) + { + } + ctl.initializeException(false); + try + { + background.ice_ping(); + } + catch(Ice.LocalException ex) + { + } + try + { + background.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + + try + { + ctl.initializeSocketStatus(IceInternal.SocketOperation.Write); + background.ice_getCachedConnection().close(true); + background.op(); + ctl.initializeSocketStatus(IceInternal.SocketOperation.None); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + } + + thread1._destroy(); + thread2._destroy(); + + try + { + thread1.join(); + thread2.join(); + } + catch(InterruptedException e) + { + } + } + + private static void + validationTests(Configuration configuration, BackgroundPrx background, BackgroundControllerPrx ctl) + { + try + { + background.op(); + } + catch(Ice.LocalException ex) + { + test(false); + } + background.ice_getConnection().close(false); + + try + { + // Get the read() of connection validation to throw right away. + configuration.readException(new Ice.SocketException()); + background.op(); + test(false); + } + catch(Ice.SocketException ex) + { + configuration.readException(null); + } + + for(int i = 0; i < 2; i++) + { + configuration.readException(new Ice.SocketException()); + BackgroundPrx prx = i == 0 ? background : (BackgroundPrx)background.ice_oneway(); + Ice.AsyncResult r = prx.begin_op(); + test(!r.sentSynchronously()); + try + { + prx.end_op(r); + test(false); + } + catch(Ice.SocketException ex) + { + } + test(r.isCompleted()); + configuration.readException(null); + } + + if(!background.ice_getCommunicator().getProperties().getProperty("Ice.Default.Protocol").equals("test-ssl")) + { + try + { + // Get the read() of the connection validation to return "would block" + configuration.readReady(false); + background.op(); + configuration.readReady(true); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + background.ice_getConnection().close(false); + + try + { + // Get the read() of the connection validation to return "would block" and then throw. + configuration.readReady(false); + configuration.readException(new Ice.SocketException()); + background.op(); + test(false); + } + catch(Ice.SocketException ex) + { + configuration.readException(null); + configuration.readReady(true); + } + + for(int i = 0; i < 2; i++) + { + configuration.readReady(false); + configuration.readException(new Ice.SocketException()); + Ice.AsyncResult r = background.begin_op(); + test(!r.sentSynchronously()); + try + { + background.end_op(r); + test(false); + } + catch(Ice.SocketException ex) + { + } + test(r.isCompleted()); + configuration.readException(null); + configuration.readReady(true); + } + } + + ctl.holdAdapter(); // Hold to block in connection validation + Ice.AsyncResult r = background.begin_op(); + Ice.AsyncResult r2 = background.begin_op(); + test(!r.sentSynchronously() && !r2.sentSynchronously()); + test(!r.isCompleted() && !r2.isCompleted()); + ctl.resumeAdapter(); + background.end_op(r); + background.end_op(r2); + test(r.isCompleted() && r2.isCompleted()); + + try + { + // Get the write() of connection validation to throw right away. + ctl.writeException(true); + background.op(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + ctl.writeException(false); + } + + try + { + // Get the write() of the connection validation to return "would block" + ctl.writeReady(false); + background.op(); + ctl.writeReady(true); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + background.ice_getConnection().close(false); + + try + { + // Get the write() of the connection validation to return "would block" and then throw. + ctl.writeReady(false); + ctl.writeException(true); + background.op(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + ctl.writeException(false); + ctl.writeReady(true); + } + + byte[] seq = new byte[512 * 1024]; + + BackgroundPrx backgroundBatchOneway = BackgroundPrxHelper.uncheckedCast(background.ice_batchOneway()); + + // + // First send small requests to test without auto-flushing. + // + backgroundBatchOneway.ice_ping(); + backgroundBatchOneway.ice_getConnection().close(false); + try + { + backgroundBatchOneway.ice_ping(); + test(false); + } + catch(Ice.CloseConnectionException ex) + { + } + ctl.holdAdapter(); + backgroundBatchOneway.op(); + backgroundBatchOneway.op(); + backgroundBatchOneway.op(); + backgroundBatchOneway.op(); + ctl.resumeAdapter(); + backgroundBatchOneway.ice_flushBatchRequests(); + + // + // Send bigger requests to test with auto-flushing. + // + backgroundBatchOneway.ice_ping(); + backgroundBatchOneway.ice_getConnection().close(false); + try + { + backgroundBatchOneway.ice_ping(); + test(false); + } + catch(Ice.CloseConnectionException ex) + { + } + ctl.holdAdapter(); + backgroundBatchOneway.opWithPayload(seq); + backgroundBatchOneway.opWithPayload(seq); + backgroundBatchOneway.opWithPayload(seq); + backgroundBatchOneway.opWithPayload(seq); + ctl.resumeAdapter(); + backgroundBatchOneway.ice_flushBatchRequests(); + + // + // Then try the same thing with async flush. + // + + backgroundBatchOneway.ice_ping(); + backgroundBatchOneway.ice_getConnection().close(false); + try + { + backgroundBatchOneway.ice_ping(); + test(false); + } + catch(Ice.CloseConnectionException ex) + { + } + ctl.holdAdapter(); + backgroundBatchOneway.op(); + backgroundBatchOneway.op(); + backgroundBatchOneway.op(); + backgroundBatchOneway.op(); + ctl.resumeAdapter(); + backgroundBatchOneway.begin_ice_flushBatchRequests(); + backgroundBatchOneway.ice_getConnection().close(false); + + backgroundBatchOneway.ice_ping(); + backgroundBatchOneway.ice_getConnection().close(false); + try + { + backgroundBatchOneway.ice_ping(); + test(false); + } + catch(Ice.CloseConnectionException ex) + { + } + ctl.holdAdapter(); + backgroundBatchOneway.opWithPayload(seq); + backgroundBatchOneway.opWithPayload(seq); + backgroundBatchOneway.opWithPayload(seq); + backgroundBatchOneway.opWithPayload(seq); + ctl.resumeAdapter(); + r = backgroundBatchOneway.begin_ice_flushBatchRequests(); + // + // We can't close the connection before ensuring all the batches + // have been sent since with auto-flushing the close connection + // message might be sent once the first call opWithPayload is sent + // and before the flushBatchRequests (this would therefore result + // in the flush to report a CloseConnectionException). Instead we + // wait for the first flush to complete. + // + //backgroundBatchOneway.ice_getConnection().close(false); + backgroundBatchOneway.end_ice_flushBatchRequests(r); + backgroundBatchOneway.ice_getConnection().close(false); + } + + private static void + readWriteTests(Configuration configuration, BackgroundPrx background, BackgroundControllerPrx ctl) + { + try + { + background.op(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + + for(int i = 0; i < 2; i++) + { + BackgroundPrx prx = i == 0 ? background : (BackgroundPrx)background.ice_oneway(); + + try + { + background.ice_ping(); + configuration.writeException(new Ice.SocketException()); + prx.op(); + test(false); + } + catch(Ice.SocketException ex) + { + configuration.writeException(null); + } + + background.ice_ping(); + configuration.writeException(new Ice.SocketException()); + Ice.AsyncResult r = prx.begin_op(); + test(!r.sentSynchronously()); + try + { + prx.end_op(r); + test(false); + } + catch(Ice.SocketException ex) + { + } + test(r.isCompleted()); + configuration.writeException(null); + } + + try + { + background.ice_ping(); + configuration.readException(new Ice.SocketException()); + background.op(); + test(false); + } + catch(Ice.SocketException ex) + { + configuration.readException(null); + } + + background.ice_ping(); + configuration.readReady(false); // Required in C# to make sure beginRead() doesn't throw too soon. + configuration.readException(new Ice.SocketException()); + Ice.AsyncResult r = background.begin_op(); + if(!r.sentSynchronously()) + { + // The read exception might propagate before the message send is seen as completed on IOCP. + test(r.isCompleted()); + } + try + { + background.end_op(r); + test(false); + } + catch(Ice.SocketException ex) + { + } + test(r.isCompleted()); + configuration.readException(null); + configuration.readReady(true); + + try + { + background.ice_ping(); + configuration.writeReady(false); + background.op(); + configuration.writeReady(true); + } + catch(Ice.LocalException ex) + { + test(false); + } + + try + { + background.ice_ping(); + configuration.readReady(false); + background.op(); + configuration.readReady(true); + } + catch(Ice.LocalException ex) + { + test(false); + } + + try + { + background.ice_ping(); + configuration.writeReady(false); + configuration.writeException(new Ice.SocketException()); + background.op(); + test(false); + } + catch(Ice.SocketException ex) + { + configuration.writeReady(true); + configuration.writeException(null); + } + + for(int i = 0; i < 2; ++i) + { + BackgroundPrx prx = i == 0 ? background : (BackgroundPrx)background.ice_oneway(); + + background.ice_ping(); + configuration.writeReady(false); + configuration.writeException(new Ice.SocketException()); + r = prx.begin_op(); + test(!r.sentSynchronously()); + try + { + prx.end_op(r); + test(false); + } + catch(Ice.SocketException ex) + { + } + test(r.isCompleted()); + configuration.writeReady(true); + configuration.writeException(null); + } + + try + { + background.ice_ping(); + configuration.readReady(false); + configuration.readException(new Ice.SocketException()); + background.op(); + test(false); + } + catch(Ice.SocketException ex) + { + configuration.readException(null); + configuration.readReady(true); + } + + { + background.ice_ping(); + configuration.readReady(false); + configuration.readException(new Ice.SocketException()); + r = background.begin_op(); + if(!r.sentSynchronously()) + { + // The read exception might propagate before the message send is seen as completed on IOCP. + test(r.isCompleted()); + } + try + { + background.end_op(r); + test(false); + } + catch(Ice.SocketException ex) + { + } + test(r.isCompleted()); + configuration.readReady(true); + configuration.readException(null); + } + + { + background.ice_ping(); + configuration.readReady(false); + configuration.writeReady(false); + configuration.readException(new Ice.SocketException()); + r = background.begin_op(); + // The read exception might propagate before the message send is seen as completed on IOCP. + r.waitForSent(); + try + { + background.end_op(r); + test(false); + } + catch(Ice.SocketException ex) + { + } + test(r.isCompleted()); + configuration.writeReady(true); + configuration.readReady(true); + configuration.readException(null); + } + + background.ice_ping(); // Establish the connection + + BackgroundPrx backgroundOneway = BackgroundPrxHelper.uncheckedCast(background.ice_oneway()); + test(backgroundOneway.ice_getConnection() == background.ice_getConnection()); + + ctl.holdAdapter(); // Hold to block in request send. + + byte[] seq = new byte[1024 * 1024]; + new java.util.Random().nextBytes(seq); // Make sure the request doesn't compress too well. + NoResponse noResponse = new NoResponse(); + while(backgroundOneway.begin_opWithPayload(seq, noResponse).sentSynchronously()) + { + } + + OpAMICallback cb = new OpAMICallback(); + Ice.AsyncResult r1 = background.begin_op(cb); + test(!r1.sentSynchronously() && !r1.isSent()); + + OpAMICallback cb2 = new OpAMICallback(); + Ice.AsyncResult r2 = background.begin_op(cb2); + test(!r2.sentSynchronously() && !r2.isSent()); + + test(!backgroundOneway.begin_opWithPayload(seq, noResponse).sentSynchronously()); + test(!backgroundOneway.begin_opWithPayload(seq, noResponse).sentSynchronously()); + + test(!cb.response(false)); + test(!cb2.response(false)); + ctl.resumeAdapter(); + cb.responseAndSent(); + cb2.responseAndSent(); + test(r1.isSent() && r1.isCompleted()); + test(r2.isSent() && r2.isCompleted()); + + try + { + background.ice_ping(); + ctl.writeException(true); + background.op(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + ctl.writeException(false); + } + + try + { + background.ice_ping(); + ctl.readException(true); + background.op(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + ctl.readException(false); + } + + try + { + background.ice_ping(); + ctl.writeReady(false); + background.op(); + ctl.writeReady(true); + } + catch(Ice.LocalException ex) + { + test(false); + } + + try + { + background.ice_ping(); + ctl.readReady(false); + background.op(); + ctl.readReady(true); + } + catch(Ice.LocalException ex) + { + test(false); + } + + try + { + background.ice_ping(); + ctl.writeReady(false); + ctl.writeException(true); + background.op(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + ctl.writeException(false); + ctl.writeReady(true); + } + + try + { + background.ice_ping(); + ctl.readReady(false); + ctl.readException(true); + background.op(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + ctl.readException(false); + ctl.readReady(true); + } + + OpThread thread1 = new OpThread(background); + OpThread thread2 = new OpThread(background); + + for(int i = 0; i < 5; i++) + { + try + { + background.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + + try + { + Thread.sleep(10); + } + catch(java.lang.InterruptedException ex) + { + } + configuration.writeException(new Ice.SocketException()); + try + { + background.op(); + } + catch(Ice.LocalException ex) + { + } + configuration.writeException(null); + + try + { + Thread.sleep(10); + } + catch(java.lang.InterruptedException ex) + { + } + + background.ice_ping(); + background.ice_getCachedConnection().close(true); + try + { + Thread.sleep(10); + } + catch(java.lang.InterruptedException ex) + { + } + + background.ice_getCachedConnection().close(true); + } + + thread1._destroy(); + thread2._destroy(); + + try + { + thread1.join(); + thread2.join(); + } + catch(InterruptedException e) + { + } + } +} diff --git a/java/test/src/main/java/test/Ice/background/BackgroundControllerI.java b/java/test/src/main/java/test/Ice/background/BackgroundControllerI.java new file mode 100644 index 00000000000..fb1a591e193 --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/BackgroundControllerI.java @@ -0,0 +1,119 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.background; + +import test.Ice.background.Test._BackgroundControllerDisp; + +class BackgroundControllerI extends _BackgroundControllerDisp +{ + @Override + synchronized public void + pauseCall(String opName, Ice.Current current) + { + _pausedCalls.add(opName); + } + + @Override + synchronized public void + resumeCall(String opName, Ice.Current current) + { + _pausedCalls.remove(opName); + notifyAll(); + } + + synchronized public void + checkCallPause(Ice.Current current) + { + while(_pausedCalls.contains(current.operation)) + { + try + { + wait(); + break; + } + catch(java.lang.InterruptedException ex) + { + } + } + } + + @Override + public void + holdAdapter(Ice.Current current) + { + _adapter.hold(); + } + + @Override + public void + resumeAdapter(Ice.Current current) + { + _adapter.activate(); + } + + @Override + public void + initializeSocketStatus(int status, Ice.Current current) + { + _configuration.initializeSocketStatus(status); + } + + @Override + public void + initializeException(boolean enable, Ice.Current current) + { + _configuration.initializeException(enable ? new Ice.SocketException() : null); + } + + @Override + public void + readReady(boolean enable, Ice.Current current) + { + _configuration.readReady(enable); + } + + @Override + public void + readException(boolean enable, Ice.Current current) + { + _configuration.readException(enable ? new Ice.SocketException() : null); + } + + @Override + public void + writeReady(boolean enable, Ice.Current current) + { + _configuration.writeReady(enable); + } + + @Override + public void + writeException(boolean enable, Ice.Current current) + { + _configuration.writeException(enable ? new Ice.SocketException() : null); + } + + @Override + public void + buffered(boolean enable, Ice.Current current) + { + _configuration.buffered(enable); + } + + public + BackgroundControllerI(Configuration configuration, Ice.ObjectAdapter adapter) + { + _adapter = adapter; + _configuration = configuration; + } + + final private Ice.ObjectAdapter _adapter; + final private java.util.Set<String> _pausedCalls = new java.util.HashSet<String>(); + final private Configuration _configuration; +} diff --git a/java/test/src/main/java/test/Ice/background/BackgroundI.java b/java/test/src/main/java/test/Ice/background/BackgroundI.java new file mode 100644 index 00000000000..57adf958ca5 --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/BackgroundI.java @@ -0,0 +1,42 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.background; + +import test.Ice.background.Test._BackgroundDisp; + +class BackgroundI extends _BackgroundDisp +{ + @Override + public void + op(Ice.Current current) + { + _controller.checkCallPause(current); + } + + @Override + public void + opWithPayload(byte[] seq, Ice.Current current) + { + _controller.checkCallPause(current); + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + BackgroundI(BackgroundControllerI controller) + { + _controller = controller; + } + + private final BackgroundControllerI _controller; +} diff --git a/java/test/src/main/java/test/Ice/background/Client.java b/java/test/src/main/java/test/Ice/background/Client.java new file mode 100644 index 00000000000..1955472ebab --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/Client.java @@ -0,0 +1,70 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.background; + +import test.Ice.background.PluginFactory.PluginI; +import test.Ice.background.Test.BackgroundPrx; + +public class Client extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + Configuration configuration = new Configuration(); + PluginI plugin = (PluginI)communicator().getPluginManager().getPlugin("Test"); + plugin.setConfiguration(configuration); + communicator().getPluginManager().initializePlugins(); + + BackgroundPrx background = AllTests.allTests(configuration, communicator(), getWriter()); + background.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + + // For this test, we want to disable retries. + // + initData.properties.setProperty("Ice.RetryIntervals", "-1"); + + // + // This test kills connections, so we don't want warnings. + // + initData.properties.setProperty("Ice.Warn.Connections", "0"); + + initData.properties.setProperty("Ice.MessageSizeMax", "50000"); + + // + // Setup the test transport plug-in. + // + initData.properties.setProperty("Ice.Plugin.Test", "test.Ice.background.PluginFactory"); + String defaultProtocol = initData.properties.getPropertyWithDefault("Ice.Default.Protocol", "tcp"); + initData.properties.setProperty("Ice.Default.Protocol", "test-" + defaultProtocol); + + initData.properties.setProperty("Ice.Package.Test", "test.Ice.background"); + + // Don't initialize the plugin until I've set the configuration. + initData.properties.setProperty("Ice.InitPlugins", "0"); + + return initData; + } + + public static void + main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/background/Collocated.java b/java/test/src/main/java/test/Ice/background/Collocated.java new file mode 100644 index 00000000000..ac3e4622f17 --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/Collocated.java @@ -0,0 +1,85 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.background; + +public class Collocated +{ + static Thread _clientThread; + static int result; + + public static void + main(String[] args) + { + final Client client = new Client(); + final Server server = new Server(); + Thread t = new Thread(new Runnable() + { + @Override + public void run() + { + String[] args = + { + "--Ice.NullHandleAbort=1", + "--Ice.Warn.Connections=1", + "--Ice.ThreadPool.Server.Size=1", + "--Ice.ThreadPool.Server.SizeMax=3", + "--Ice.ThreadPool.Server.SizeWarn=0", + "--Ice.PrintAdapterReady=1", + "--Ice.ServerIdleTime=30", + "--Ice.Default.Host=127.0.0.1" + }; + server.setServerReadyListener(new test.Util.Application.ServerReadyListener() + { + @Override + public void serverReady() + { + _clientThread = new Thread(new Runnable() + { + @Override + public void run() + { + String[] args = + { + "--Ice.NullHandleAbort=1", "--Ice.Warn.Connections=1", "--Ice.Default.Host=127.0.0.1" + }; + client.main("Client", args); + } + }); + _clientThread.start(); + } + }); + + result = server.main("Server", args); + if(_clientThread != null) + { + while(_clientThread.isAlive()) + { + try + { + _clientThread.join(); + } + catch(InterruptedException e1) + { + } + } + } + } + }); + t.start(); + try + { + t.join(); + } + catch(InterruptedException ex) + { + } + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/background/Configuration.java b/java/test/src/main/java/test/Ice/background/Configuration.java new file mode 100644 index 00000000000..befe01738fc --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/Configuration.java @@ -0,0 +1,168 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.background; + +public final class Configuration +{ + public synchronized void + connectorsException(Ice.LocalException ex) + { + _connectorsException = ex; + } + + public synchronized void + checkConnectorsException() + { + if(_connectorsException != null) + { + throw _connectorsException; + } + } + + public synchronized void + connectException(Ice.LocalException ex) + { + _connectException = ex; + } + + public synchronized void + checkConnectException() + { + if(_connectException != null) + { + throw _connectException; + } + } + + public synchronized void + initializeSocketStatus(int status) + { + if(status == IceInternal.SocketOperation.None) + { + _initializeResetCount = 0; + return; + } + _initializeResetCount = 10; + _initializeSocketStatus = status; + } + + public synchronized void + initializeException(Ice.LocalException ex) + { + _initializeException = ex; + } + + public synchronized int + initializeSocketStatus() + { + if(_initializeResetCount == 0) + { + return IceInternal.SocketOperation.None; + } + --_initializeResetCount; + return _initializeSocketStatus; + } + + public synchronized void + checkInitializeException() + { + if(_initializeException != null) + { + throw _initializeException; + } + } + + public synchronized void + readReady(boolean ready) + { + _readReadyCount = ready ? 0 : 10; + } + + public synchronized void + readException(Ice.LocalException ex) + { + _readException = ex; + } + + public synchronized boolean + readReady() + { + if(_readReadyCount == 0) + { + return true; + } + --_readReadyCount; + return false; + } + + public synchronized void + checkReadException() + { + if(_readException != null) + { + throw _readException; + } + } + + public synchronized void + writeReady(boolean ready) + { + _writeReadyCount = ready ? 0 : 10; + } + + public synchronized void + writeException(Ice.LocalException ex) + { + _writeException = ex; + } + + public synchronized boolean + writeReady() + { + if(_writeReadyCount == 0) + { + return true; + } + --_writeReadyCount; + return false; + } + + public synchronized void + checkWriteException() + { + if(_writeException != null) + { + throw _writeException; + } + } + + public synchronized void + buffered(boolean b) + { + _buffered = b; + } + + public synchronized boolean + buffered() + { + return _buffered; + } + + private Ice.LocalException _connectorsException; + private Ice.LocalException _connectException; + private int _initializeSocketStatus; + private int _initializeResetCount; + private Ice.LocalException _initializeException; + private int _readReadyCount; + private Ice.LocalException _readException; + private int _writeReadyCount; + private Ice.LocalException _writeException; + private boolean _buffered; +} diff --git a/java/test/src/main/java/test/Ice/background/Connector.java b/java/test/src/main/java/test/Ice/background/Connector.java new file mode 100644 index 00000000000..afc3db49abe --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/Connector.java @@ -0,0 +1,76 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.background; + +final class Connector implements IceInternal.Connector +{ + @Override + public IceInternal.Transceiver + connect() + { + _configuration.checkConnectException(); + return new Transceiver(_configuration, _connector.connect()); + } + + @Override + public short + type() + { + return (short)(EndpointI.TYPE_BASE + _connector.type()); + } + + @Override + public String + toString() + { + return _connector.toString(); + } + + @Override + public int + hashCode() + { + return _connector.hashCode(); + } + + // + // Only for use by Endpoint + // + Connector(Configuration configuration, IceInternal.Connector connector) + { + _configuration = configuration; + _connector = connector; + } + + @Override + public boolean + equals(java.lang.Object obj) + { + Connector p = null; + + try + { + p = (Connector)obj; + } + catch(ClassCastException ex) + { + return false; + } + + if(this == p) + { + return true; + } + + return _connector.equals(p._connector); + } + + final private IceInternal.Connector _connector; + final private Configuration _configuration; +} diff --git a/java/test/src/main/java/test/Ice/background/EndpointFactory.java b/java/test/src/main/java/test/Ice/background/EndpointFactory.java new file mode 100644 index 00000000000..09a8f35290b --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/EndpointFactory.java @@ -0,0 +1,68 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.background; + +final class EndpointFactory implements IceInternal.EndpointFactory +{ + EndpointFactory(Configuration configuration, IceInternal.EndpointFactory factory) + { + _configuration = configuration; + _factory = factory; + } + + @Override + public short + type() + { + return (short)(EndpointI.TYPE_BASE + _factory.type()); + } + + @Override + public String + protocol() + { + return "test-" + _factory.protocol(); + } + + @Override + public IceInternal.EndpointI + create(java.util.ArrayList<String> args, boolean server) + { + return new EndpointI(_configuration, _factory.create(args, server)); + } + + @Override + public IceInternal.EndpointI + read(IceInternal.BasicStream s) + { + short type = s.readShort(); + assert(type == _factory.type()); + + s.startReadEncaps(); + IceInternal.EndpointI endpoint = new EndpointI(_configuration, _factory.read(s)); + s.endReadEncaps(); + return endpoint; + } + + @Override + public void + destroy() + { + } + + @Override + public IceInternal.EndpointFactory + clone(IceInternal.ProtocolInstance instance) + { + return this; + } + + private Configuration _configuration; + private IceInternal.EndpointFactory _factory; +} diff --git a/java/test/src/main/java/test/Ice/background/EndpointI.java b/java/test/src/main/java/test/Ice/background/EndpointI.java new file mode 100644 index 00000000000..bed906911d6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/EndpointI.java @@ -0,0 +1,309 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.background; + +final class EndpointI extends IceInternal.EndpointI +{ + final static short TYPE_BASE = 100; + + public + EndpointI(Configuration configuration, IceInternal.EndpointI endpoint) + { + _endpoint = endpoint; + _configuration = configuration; + } + + @Override + public String + _toString() + { + return "test-" + _endpoint.toString(); + } + + @Override + public Ice.EndpointInfo + getInfo() + { + return _endpoint.getInfo(); + } + + @Override + public void + streamWrite(IceInternal.BasicStream s) + { + s.startWriteEncaps(); + s.writeShort(_endpoint.type()); + _endpoint.streamWrite(s); + s.endWriteEncaps(); + } + + @Override + public short + type() + { + return (short)(TYPE_BASE + _endpoint.type()); + } + + @Override + public String + protocol() + { + return _endpoint.protocol(); + } + + @Override + public int + timeout() + { + return _endpoint.timeout(); + } + + @Override + public IceInternal.EndpointI + timeout(int timeout) + { + IceInternal.EndpointI endpoint = _endpoint.timeout(timeout); + if(endpoint == _endpoint) + { + return this; + } + else + { + return new EndpointI(_configuration, endpoint); + } + } + + @Override + public String + connectionId() + { + return _endpoint.connectionId(); + } + + @Override + public IceInternal.EndpointI + connectionId(String connectionId) + { + IceInternal.EndpointI endpoint = _endpoint.connectionId(connectionId); + if(endpoint == _endpoint) + { + return this; + } + else + { + return new EndpointI(_configuration, endpoint); + } + } + + @Override + public boolean + compress() + { + return _endpoint.compress(); + } + + @Override + public IceInternal.EndpointI + compress(boolean compress) + { + IceInternal.EndpointI endpoint = _endpoint.compress(compress); + if(endpoint == _endpoint) + { + return this; + } + else + { + return new EndpointI(_configuration, endpoint); + } + } + + @Override + public boolean + datagram() + { + return _endpoint.datagram(); + } + + @Override + public boolean + secure() + { + return _endpoint.secure(); + } + + @Override + public IceInternal.Transceiver + transceiver() + { + IceInternal.Transceiver transceiver = _endpoint.transceiver(); + if(transceiver != null) + { + return new Transceiver(_configuration, transceiver); + } + else + { + return null; + } + } + + @Override + public java.util.List<IceInternal.Connector> + connectors(Ice.EndpointSelectionType selType) + { + _configuration.checkConnectorsException(); + java.util.List<IceInternal.Connector> connectors = new java.util.ArrayList<IceInternal.Connector>(); + for(IceInternal.Connector p : _endpoint.connectors(selType)) + { + connectors.add(new Connector(_configuration, p)); + } + return connectors; + } + + @Override + public void + connectors_async(Ice.EndpointSelectionType selType, final IceInternal.EndpointI_connectors cb) + { + class Callback implements IceInternal.EndpointI_connectors + { + @Override + public void + connectors(java.util.List<IceInternal.Connector> cons) + { + java.util.List<IceInternal.Connector> connectors = new java.util.ArrayList<IceInternal.Connector>(); + for(IceInternal.Connector p : cons) + { + connectors.add(new Connector(_configuration, p)); + } + cb.connectors(connectors); + } + + @Override + public void + exception(Ice.LocalException exception) + { + cb.exception(exception); + } + } + + try + { + _configuration.checkConnectorsException(); + _endpoint.connectors_async(selType, new Callback()); + } + catch(Ice.LocalException ex) + { + cb.exception(ex); + } + } + + @Override + public IceInternal.Acceptor + acceptor(String adapterName) + { + return new Acceptor(this, _configuration, _endpoint.acceptor(adapterName)); + } + + public EndpointI + endpoint(IceInternal.EndpointI delEndp) + { + return new EndpointI(_configuration, delEndp); + } + + @Override + public java.util.List<IceInternal.EndpointI> + expand() + { + java.util.List<IceInternal.EndpointI> endps = new java.util.ArrayList<IceInternal.EndpointI>(); + for(IceInternal.EndpointI endpt : _endpoint.expand()) + { + endps.add(endpt == _endpoint ? this : new EndpointI(_configuration, endpt)); + } + return endps; + } + + @Override + public boolean + equivalent(IceInternal.EndpointI endpoint) + { + EndpointI testEndpoint = null; + try + { + testEndpoint = (EndpointI)endpoint; + } + catch(ClassCastException ex) + { + return false; + } + return testEndpoint._endpoint.equivalent(_endpoint); + } + + @Override + public String + options() + { + return _endpoint.options(); + } + + @Override + public int + hashCode() + { + return _endpoint.hashCode(); + } + + // + // Compare endpoints for sorting purposes + // + @Override + public boolean + equals(java.lang.Object obj) + { + try + { + return compareTo((IceInternal.EndpointI)obj) == 0; + } + catch(ClassCastException ee) + { + assert(false); + return false; + } + } + + @Override + public int + compareTo(IceInternal.EndpointI obj) // From java.lang.Comparable + { + EndpointI p = null; + + try + { + p = (EndpointI)obj; + } + catch(ClassCastException ex) + { + return type() < obj.type() ? -1 : 1; + } + + if(this == p) + { + return 0; + } + + return _endpoint.compareTo(p._endpoint); + } + + public IceInternal.EndpointI + delegate() + { + return _endpoint; + } + + private IceInternal.EndpointI _endpoint; + private Configuration _configuration; +} diff --git a/java/test/src/main/java/test/Ice/background/PluginFactory.java b/java/test/src/main/java/test/Ice/background/PluginFactory.java new file mode 100644 index 00000000000..9edd6c8fa38 --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/PluginFactory.java @@ -0,0 +1,60 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.background; + +public class PluginFactory implements Ice.PluginFactory +{ + static public class PluginI implements Ice.Plugin + { + public + PluginI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + @Override + public void + initialize() + { + assert _configuration != null; + IceInternal.ProtocolPluginFacade facade = IceInternal.Util.getProtocolPluginFacade(_communicator); + for(short s = 0; s < 100; ++s) + { + IceInternal.EndpointFactory factory = facade.getEndpointFactory(s); + if(factory != null) + { + facade.addEndpointFactory(new EndpointFactory(_configuration, factory)); + } + } + } + + @Override + public void + destroy() + { + } + + public void + setConfiguration(Configuration configuration) + { + _configuration = configuration; + } + + private final Ice.Communicator _communicator; + private Configuration _configuration; + } + + @Override + public Ice.Plugin + create(Ice.Communicator communicator, String name, String[] args) + { + return new PluginI(communicator); + } +} diff --git a/java/test/src/main/java/test/Ice/background/Server.java b/java/test/src/main/java/test/Ice/background/Server.java new file mode 100644 index 00000000000..52aaf1f1f49 --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/Server.java @@ -0,0 +1,159 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.background; + +import test.Ice.background.PluginFactory.PluginI; + +public class Server extends test.Util.Application +{ + static public class LocatorI extends Ice._LocatorDisp + { + @Override + public void + findAdapterById_async(Ice.AMD_Locator_findAdapterById response, String adapter, Ice.Current current) + throws Ice.AdapterNotFoundException + { + _controller.checkCallPause(current); + Ice.Communicator communicator = current.adapter.getCommunicator(); + response.ice_response(current.adapter.createDirectProxy(communicator.stringToIdentity("dummy"))); + } + + @Override + public void + findObjectById_async(Ice.AMD_Locator_findObjectById response, Ice.Identity id, Ice.Current current) + throws Ice.ObjectNotFoundException + { + _controller.checkCallPause(current); + response.ice_response(current.adapter.createDirectProxy(id)); + } + + @Override + public Ice.LocatorRegistryPrx + getRegistry(Ice.Current current) + { + return null; + } + + LocatorI(BackgroundControllerI controller) + { + _controller = controller; + } + + final private BackgroundControllerI _controller; + } + + static public class RouterI extends Ice._RouterDisp + { + @Override + public Ice.ObjectPrx + getClientProxy(Ice.Current current) + { + _controller.checkCallPause(current); + return null; + } + + @Override + public Ice.ObjectPrx + getServerProxy(Ice.Current current) + { + _controller.checkCallPause(current); + return null; + } + + /** + * @deprecated addProxy() is deprecated, use addProxies() instead. + **/ + @Deprecated + @Override + public void + addProxy(Ice.ObjectPrx proxy, Ice.Current current) + { + } + + @Override + public Ice.ObjectPrx[] + addProxies(Ice.ObjectPrx[] proxies, Ice.Current current) + { + return new Ice.ObjectPrx[0]; + } + + RouterI(BackgroundControllerI controller) + { + _controller = controller; + } + + final private BackgroundControllerI _controller; + } + + @Override + public int + run(String[] args) + { + Configuration configuration = new Configuration(); + PluginI plugin = (PluginI)communicator().getPluginManager().getPlugin("Test"); + plugin.setConfiguration(configuration); + communicator().getPluginManager().initializePlugins(); + + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + Ice.ObjectAdapter adapter2 = communicator().createObjectAdapter("ControllerAdapter"); + + BackgroundControllerI backgroundController = new BackgroundControllerI(configuration, adapter); + + adapter.add(new BackgroundI(backgroundController), communicator().stringToIdentity("background")); + adapter.add(new LocatorI(backgroundController), communicator().stringToIdentity("locator")); + adapter.add(new RouterI(backgroundController), communicator().stringToIdentity("router")); + adapter.activate(); + + adapter2.add(backgroundController, communicator().stringToIdentity("backgroundController")); + adapter2.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + + // + // This test kills connections, so we don't want warnings. + // + initData.properties.setProperty("Ice.Warn.Connections", "0"); + + initData.properties.setProperty("Ice.MessageSizeMax", "50000"); + + // + // Setup the test transport plug-in. + // + initData.properties.setProperty("Ice.Plugin.Test", "test.Ice.background.PluginFactory"); + String defaultProtocol = initData.properties.getPropertyWithDefault("Ice.Default.Protocol", "tcp"); + initData.properties.setProperty("Ice.Default.Protocol", "test-" + defaultProtocol); + + initData.properties.setProperty("Ice.Package.Test", "test.Ice.background"); + + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("ControllerAdapter.Endpoints", "tcp -p 12011"); + initData.properties.setProperty("ControllerAdapter.ThreadPool.Size", "1"); + + // Don't initialize the plugin until I've set the configuration. + initData.properties.setProperty("Ice.InitPlugins", "0"); + + return initData; + } + + public static void + main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/background/Test.ice b/java/test/src/main/java/test/Ice/background/Test.ice new file mode 100644 index 00000000000..b612eb4d280 --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/Test.ice @@ -0,0 +1,47 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/BuiltinSequences.ice> +#include <Ice/Endpoint.ice> + +[["java:package:test.Ice.background"]] +module Test +{ + +interface Background +{ + void op(); + void opWithPayload(Ice::ByteSeq seq); + + void shutdown(); +}; + +interface BackgroundController +{ + void pauseCall(string call); + void resumeCall(string call); + + void holdAdapter(); + void resumeAdapter(); + + void initializeSocketStatus(int status); + void initializeException(bool enable); + + void readReady(bool enable); + void readException(bool enable); + + void writeReady(bool enable); + void writeException(bool enable); + + void buffered(bool enable); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/background/Transceiver.java b/java/test/src/main/java/test/Ice/background/Transceiver.java new file mode 100644 index 00000000000..738c7ef1f10 --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/Transceiver.java @@ -0,0 +1,208 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.background; + +final class Transceiver implements IceInternal.Transceiver +{ + @Override + public java.nio.channels.SelectableChannel + fd() + { + return _transceiver.fd(); + } + + @Override + public int + initialize(IceInternal.Buffer readBuffer, IceInternal.Buffer writeBuffer, Ice.Holder<Boolean> moreData) + { + int status = _configuration.initializeSocketStatus(); + if(status == IceInternal.SocketOperation.Connect) + { + return status; + } + else if(status == IceInternal.SocketOperation.Write) + { + if(!_initialized) + { + status = _transceiver.initialize(readBuffer, writeBuffer, moreData); + if(status != IceInternal.SocketOperation.None) + { + return status; + } + _initialized = true; + } + return IceInternal.SocketOperation.Write; + } + else if(status == IceInternal.SocketOperation.Read) + { + return status; + } + + _configuration.checkInitializeException(); + if(!_initialized) + { + status = _transceiver.initialize(readBuffer, writeBuffer, moreData); + if(status != IceInternal.SocketOperation.None) + { + return status; + } + _initialized = true; + } + return IceInternal.SocketOperation.None; + } + + @Override + public int + closing(boolean initiator, Ice.LocalException ex) + { + return _transceiver.closing(initiator, ex); + } + + @Override + public void + close() + { + _transceiver.close(); + } + + @Override + public IceInternal.EndpointI + bind() + { + return _transceiver.bind(); + } + + @Override + public int + write(IceInternal.Buffer buf) + { + if(!_configuration.writeReady() && buf.b.hasRemaining()) + { + return IceInternal.SocketOperation.Write; + } + + _configuration.checkWriteException(); + return _transceiver.write(buf); + } + + @Override + public int + read(IceInternal.Buffer buf, Ice.Holder<Boolean> moreData) + { + if(!_configuration.readReady() && buf.b.hasRemaining()) + { + return IceInternal.SocketOperation.Read; + } + + _configuration.checkReadException(); + + if(_buffered) + { + while(buf.b.hasRemaining()) + { + if(_readBufferPos == _readBuffer.b.position()) + { + _readBufferPos = 0; + _readBuffer.b.position(0); + _transceiver.read(_readBuffer, moreData); + if(_readBufferPos == _readBuffer.b.position()) + { + moreData.value = false; + return IceInternal.SocketOperation.Read; + } + } + final int pos = _readBuffer.b.position(); + assert(pos > _readBufferPos); + final int requested = buf.b.remaining(); + int available = pos - _readBufferPos; + assert(available > 0); + if(available >= requested) + { + available = requested; + } + + byte[] arr = new byte[available]; + _readBuffer.b.position(_readBufferPos); + _readBuffer.b.get(arr); + buf.b.put(arr); + _readBufferPos += available; + _readBuffer.b.position(pos); + } + moreData.value = _readBufferPos < _readBuffer.b.position(); + return IceInternal.SocketOperation.None; + } + else + { + return _transceiver.read(buf, moreData); + } + } + + @Override + public String + protocol() + { + return "test-" + _transceiver.protocol(); + } + + @Override + public String + toString() + { + return _transceiver.toString(); + } + + @Override + public String + toDetailedString() + { + return _transceiver.toDetailedString(); + } + + @Override + public Ice.ConnectionInfo + getInfo() + { + return _transceiver.getInfo(); + } + + @Override + public void + checkSendSize(IceInternal.Buffer buf, int messageSizeMax) + { + _transceiver.checkSendSize(buf, messageSizeMax); + } + + public IceInternal.Transceiver + delegate() + { + return _transceiver; + } + + // + // Only for use by Connector, Acceptor + // + Transceiver(Configuration configuration, IceInternal.Transceiver transceiver) + { + _transceiver = transceiver; + _configuration = configuration; + _initialized = false; + _buffered = _configuration.buffered(); + _readBuffer = new IceInternal.Buffer(100 * 1024, false); + _readBuffer.resize(1024 * 8, true); // 8KB buffer + _readBufferPos = 0; + } + + private final IceInternal.Transceiver _transceiver; + private final Configuration _configuration; + private boolean _initialized; + private final boolean _buffered; + private IceInternal.Buffer _readBuffer; + private int _readBufferPos; +} diff --git a/java/test/src/main/java/test/Ice/background/run.py b/java/test/src/main/java/test/Ice/background/run.py new file mode 100755 index 00000000000..d5fe04787c9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/background/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/binding/AllTests.java b/java/test/src/main/java/test/Ice/binding/AllTests.java new file mode 100644 index 00000000000..88aa196b157 --- /dev/null +++ b/java/test/src/main/java/test/Ice/binding/AllTests.java @@ -0,0 +1,977 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.binding; + +import java.io.PrintWriter; + +import test.Ice.binding.Test.RemoteCommunicatorPrx; +import test.Ice.binding.Test.RemoteCommunicatorPrxHelper; +import test.Ice.binding.Test.RemoteObjectAdapterPrx; +import test.Ice.binding.Test.TestIntfPrx; +import test.Ice.binding.Test.TestIntfPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static class GetAdapterNameCB extends Ice.Callback + { + @Override + synchronized public void + completed(Ice.AsyncResult result) + { + try + { + _name = TestIntfPrxHelper.uncheckedCast(result.getProxy()).end_getAdapterName(result); + notify(); + } + catch(Ice.LocalException ex) + { + test(false); + } + } + + synchronized public String + getResult() + { + while(_name == null) + { + try + { + wait(); + } + catch(java.lang.InterruptedException ex) + { + } + } + return _name; + } + + private String _name = null; + } + + private static String + getAdapterNameWithAMI(TestIntfPrx test) + { + GetAdapterNameCB cb = new GetAdapterNameCB(); + test.begin_getAdapterName(cb); + return cb.getResult(); + } + + private static TestIntfPrx + createTestIntfPrx(java.util.List<RemoteObjectAdapterPrx> adapters) + { + java.util.List<Ice.Endpoint> endpoints = new java.util.ArrayList<Ice.Endpoint>(); + TestIntfPrx test = null; + for(RemoteObjectAdapterPrx p : adapters) + { + test = p.getTestIntf(); + Ice.Endpoint[] edpts = test.ice_getEndpoints(); + endpoints.addAll(java.util.Arrays.asList(edpts)); + } + return TestIntfPrxHelper.uncheckedCast( + test.ice_endpoints(endpoints.toArray(new Ice.Endpoint[endpoints.size()]))); + } + + private static void + deactivate(RemoteCommunicatorPrx communicator, java.util.List<RemoteObjectAdapterPrx> adapters) + { + for(RemoteObjectAdapterPrx p : adapters) + { + communicator.deactivateObjectAdapter(p); + } + } + + public static void + allTests(Ice.Communicator communicator, PrintWriter out) + { + String ref = "communicator:default -p 12010"; + RemoteCommunicatorPrx com = RemoteCommunicatorPrxHelper.uncheckedCast(communicator.stringToProxy(ref)); + + out.print("testing binding with single endpoint... "); + out.flush(); + { + RemoteObjectAdapterPrx adapter = com.createObjectAdapter("Adapter", "default"); + + TestIntfPrx test1 = adapter.getTestIntf(); + TestIntfPrx test2 = adapter.getTestIntf(); + test(test1.ice_getConnection() == test2.ice_getConnection()); + + test1.ice_ping(); + test2.ice_ping(); + + com.deactivateObjectAdapter(adapter); + + TestIntfPrx test3 = TestIntfPrxHelper.uncheckedCast(test1); + test(test3.ice_getConnection() == test1.ice_getConnection()); + test(test3.ice_getConnection() == test2.ice_getConnection()); + + try + { + test3.ice_ping(); + test(false); + } + catch(Ice.ConnectFailedException ex) + { + // + // Usually the actual type of this exception is ConnectionRefusedException, + // but not always. See bug 3179. + // + } + } + out.println("ok"); + + out.print("testing binding with multiple endpoints... "); + out.flush(); + { + java.util.List<RemoteObjectAdapterPrx> adapters = new java.util.ArrayList<RemoteObjectAdapterPrx>(); + adapters.add(com.createObjectAdapter("Adapter11", "default")); + adapters.add(com.createObjectAdapter("Adapter12", "default")); + adapters.add(com.createObjectAdapter("Adapter13", "default")); + + // + // Ensure that when a connection is opened it's reused for new + // proxies and that all endpoints are eventually tried. + // + java.util.Set<String> names = new java.util.HashSet<String>(); + names.add("Adapter11"); + names.add("Adapter12"); + names.add("Adapter13"); + while(!names.isEmpty()) + { + java.util.List<RemoteObjectAdapterPrx> adpts = + new java.util.ArrayList<RemoteObjectAdapterPrx>(adapters); + + TestIntfPrx test1 = createTestIntfPrx(adpts); + java.util.Collections.shuffle(adpts); + TestIntfPrx test2 = createTestIntfPrx(adpts); + java.util.Collections.shuffle(adpts); + TestIntfPrx test3 = createTestIntfPrx(adpts); + + test(test1.ice_getConnection() == test2.ice_getConnection()); + test(test2.ice_getConnection() == test3.ice_getConnection()); + + names.remove(test1.getAdapterName()); + test1.ice_getConnection().close(false); + } + + // + // Ensure that the proxy correctly caches the connection (we + // always send the request over the same connection.) + // + { + for(RemoteObjectAdapterPrx p : adapters) + { + p.getTestIntf().ice_ping(); + } + + TestIntfPrx test = createTestIntfPrx(adapters); + String name = test.getAdapterName(); + final int nRetry = 10; + int i; + for(i = 0; i < nRetry && test.getAdapterName().equals(name); i++); + test(i == nRetry); + + for(RemoteObjectAdapterPrx p : adapters) + { + p.getTestIntf().ice_getConnection().close(false); + } + } + + // + // Deactivate an adapter and ensure that we can still + // establish the connection to the remaining adapters. + // + com.deactivateObjectAdapter(adapters.get(0)); + names.add("Adapter12"); + names.add("Adapter13"); + while(!names.isEmpty()) + { + java.util.List<RemoteObjectAdapterPrx> adpts = + new java.util.ArrayList<RemoteObjectAdapterPrx>(adapters); + + TestIntfPrx test1 = createTestIntfPrx(adpts); + java.util.Collections.shuffle(adpts); + TestIntfPrx test2 = createTestIntfPrx(adpts); + java.util.Collections.shuffle(adpts); + TestIntfPrx test3 = createTestIntfPrx(adpts); + + test(test1.ice_getConnection() == test2.ice_getConnection()); + test(test2.ice_getConnection() == test3.ice_getConnection()); + + names.remove(test1.getAdapterName()); + test1.ice_getConnection().close(false); + } + + // + // Deactivate an adapter and ensure that we can still + // establish the connection to the remaining adapter. + // + com.deactivateObjectAdapter(adapters.get(2)); + TestIntfPrx test = createTestIntfPrx(adapters); + test(test.getAdapterName().equals("Adapter12")); + + deactivate(com, adapters); + } + out.println("ok"); + + out.print("testing binding with multiple random endpoints... "); + 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"); + + boolean shortenTest = + System.getProperty("os.name").startsWith("Windows") || + System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0; + + int count; + if(shortenTest) + { + count = 60; + } + else + { + count = 20; + } + + int adapterCount = adapters.length; + while(--count > 0) + { + TestIntfPrx[] proxies; + if(shortenTest) + { + 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(TestIntfPrx p : proxies) + { + p.begin_getAdapterName(); + } + for(TestIntfPrx p : proxies) + { + try + { + p.ice_ping(); + } + catch(Ice.LocalException ex) + { + } + } + + java.util.Set<Ice.Connection> connections = new java.util.HashSet<Ice.Connection>(); + for(TestIntfPrx p : proxies) + { + if(p.ice_getCachedConnection() != null) + { + connections.add(p.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. + } + } + } + } + out.println("ok"); + + out.print("testing binding with multiple endpoints and AMI... "); + out.flush(); + { + java.util.List<RemoteObjectAdapterPrx> adapters = new java.util.ArrayList<RemoteObjectAdapterPrx>(); + adapters.add(com.createObjectAdapter("AdapterAMI11", "default")); + adapters.add(com.createObjectAdapter("AdapterAMI12", "default")); + adapters.add(com.createObjectAdapter("AdapterAMI13", "default")); + + // + // Ensure that when a connection is opened it's reused for new + // proxies and that all endpoints are eventually tried. + // + java.util.Set<String> names = new java.util.HashSet<String>(); + names.add("AdapterAMI11"); + names.add("AdapterAMI12"); + names.add("AdapterAMI13"); + while(!names.isEmpty()) + { + java.util.List<RemoteObjectAdapterPrx> adpts = + new java.util.ArrayList<RemoteObjectAdapterPrx>(adapters); + + TestIntfPrx test1 = createTestIntfPrx(adpts); + java.util.Collections.shuffle(adpts); + TestIntfPrx test2 = createTestIntfPrx(adpts); + java.util.Collections.shuffle(adpts); + TestIntfPrx test3 = createTestIntfPrx(adpts); + + test(test1.ice_getConnection() == test2.ice_getConnection()); + test(test2.ice_getConnection() == test3.ice_getConnection()); + + names.remove(getAdapterNameWithAMI(test1)); + test1.ice_getConnection().close(false); + } + + // + // Ensure that the proxy correctly caches the connection (we + // always send the request over the same connection.) + // + { + for(RemoteObjectAdapterPrx p : adapters) + { + p.getTestIntf().ice_ping(); + } + + TestIntfPrx test = createTestIntfPrx(adapters); + String name = getAdapterNameWithAMI(test); + final int nRetry = 10; + int i; + for(i = 0; i < nRetry && getAdapterNameWithAMI(test).equals(name); i++); + test(i == nRetry); + + for(RemoteObjectAdapterPrx p : adapters) + { + p.getTestIntf().ice_getConnection().close(false); + } + } + + // + // Deactivate an adapter and ensure that we can still + // establish the connection to the remaining adapters. + // + com.deactivateObjectAdapter(adapters.get(0)); + names.add("AdapterAMI12"); + names.add("AdapterAMI13"); + while(!names.isEmpty()) + { + java.util.List<RemoteObjectAdapterPrx> adpts = + new java.util.ArrayList<RemoteObjectAdapterPrx>(adapters); + + TestIntfPrx test1 = createTestIntfPrx(adpts); + java.util.Collections.shuffle(adpts); + TestIntfPrx test2 = createTestIntfPrx(adpts); + java.util.Collections.shuffle(adpts); + TestIntfPrx test3 = createTestIntfPrx(adpts); + + test(test1.ice_getConnection() == test2.ice_getConnection()); + test(test2.ice_getConnection() == test3.ice_getConnection()); + + names.remove(getAdapterNameWithAMI(test1)); + test1.ice_getConnection().close(false); + } + + // + // Deactivate an adapter and ensure that we can still + // establish the connection to the remaining adapter. + // + com.deactivateObjectAdapter(adapters.get(2)); + TestIntfPrx test = createTestIntfPrx(adapters); + test(getAdapterNameWithAMI(test).equals("AdapterAMI12")); + + deactivate(com, adapters); + } + out.println("ok"); + + out.print("testing random endpoint selection... "); + out.flush(); + { + java.util.List<RemoteObjectAdapterPrx> adapters = new java.util.ArrayList<RemoteObjectAdapterPrx>(); + adapters.add(com.createObjectAdapter("Adapter21", "default")); + adapters.add(com.createObjectAdapter("Adapter22", "default")); + adapters.add(com.createObjectAdapter("Adapter23", "default")); + + TestIntfPrx test = createTestIntfPrx(adapters); + test(test.ice_getEndpointSelection() == Ice.EndpointSelectionType.Random); + + java.util.Set<String> names = new java.util.HashSet<String>(); + names.add("Adapter21"); + names.add("Adapter22"); + names.add("Adapter23"); + while(!names.isEmpty()) + { + names.remove(test.getAdapterName()); + test.ice_getConnection().close(false); + } + + test = TestIntfPrxHelper.uncheckedCast(test.ice_endpointSelection(Ice.EndpointSelectionType.Random)); + test(test.ice_getEndpointSelection() == Ice.EndpointSelectionType.Random); + + names.add("Adapter21"); + names.add("Adapter22"); + names.add("Adapter23"); + while(!names.isEmpty()) + { + names.remove(test.getAdapterName()); + test.ice_getConnection().close(false); + } + + deactivate(com, adapters); + } + out.println("ok"); + + out.print("testing ordered endpoint selection... "); + out.flush(); + { + java.util.List<RemoteObjectAdapterPrx> adapters = new java.util.ArrayList<RemoteObjectAdapterPrx>(); + adapters.add(com.createObjectAdapter("Adapter31", "default")); + adapters.add(com.createObjectAdapter("Adapter32", "default")); + adapters.add(com.createObjectAdapter("Adapter33", "default")); + + TestIntfPrx test = createTestIntfPrx(adapters); + test = TestIntfPrxHelper.uncheckedCast(test.ice_endpointSelection(Ice.EndpointSelectionType.Ordered)); + test(test.ice_getEndpointSelection() == Ice.EndpointSelectionType.Ordered); + int nRetry = 5; + int i; + + // + // Ensure that endpoints are tried in order by deactiving the adapters + // one after the other. + // + for(i = 0; i < nRetry && test.getAdapterName().equals("Adapter31"); i++); + test(i == nRetry); + com.deactivateObjectAdapter(adapters.get(0)); + for(i = 0; i < nRetry && test.getAdapterName().equals("Adapter32"); i++); + test(i == nRetry); + com.deactivateObjectAdapter(adapters.get(1)); + for(i = 0; i < nRetry && test.getAdapterName().equals("Adapter33"); i++); + test(i == nRetry); + com.deactivateObjectAdapter(adapters.get(2)); + + try + { + test.getAdapterName(); + } + catch(Ice.ConnectFailedException ex) + { + // + // Usually the actual type of this exception is ConnectionRefusedException, + // but not always. See bug 3179. + // + } + + Ice.Endpoint[] endpoints = test.ice_getEndpoints(); + + adapters.clear(); + + // + // Now, re-activate the adapters with the same endpoints in the opposite + // order. + // + adapters.add(com.createObjectAdapter("Adapter36", endpoints[2].toString())); + for(i = 0; i < nRetry && test.getAdapterName().equals("Adapter36"); i++); + test(i == nRetry); + test.ice_getConnection().close(false); + adapters.add(com.createObjectAdapter("Adapter35", endpoints[1].toString())); + for(i = 0; i < nRetry && test.getAdapterName().equals("Adapter35"); i++); + test(i == nRetry); + test.ice_getConnection().close(false); + adapters.add(com.createObjectAdapter("Adapter34", endpoints[0].toString())); + for(i = 0; i < nRetry && test.getAdapterName().equals("Adapter34"); i++); + test(i == nRetry); + + deactivate(com, adapters); + } + out.println("ok"); + + out.print("testing per request binding with single endpoint... "); + out.flush(); + { + RemoteObjectAdapterPrx adapter = com.createObjectAdapter("Adapter41", "default"); + + TestIntfPrx test1 = TestIntfPrxHelper.uncheckedCast(adapter.getTestIntf().ice_connectionCached(false)); + TestIntfPrx test2 = TestIntfPrxHelper.uncheckedCast(adapter.getTestIntf().ice_connectionCached(false)); + test(!test1.ice_isConnectionCached()); + test(!test2.ice_isConnectionCached()); + test(test1.ice_getConnection() == test2.ice_getConnection()); + + test1.ice_ping(); + + com.deactivateObjectAdapter(adapter); + + TestIntfPrx test3 = TestIntfPrxHelper.uncheckedCast(test1); + try + { + test(test3.ice_getConnection() == test1.ice_getConnection()); + test(false); + } + catch(Ice.ConnectFailedException ex) + { + // + // Usually the actual type of this exception is ConnectionRefusedException, + // but not always. See bug 3179. + // + } + } + out.println("ok"); + + out.print("testing per request binding with multiple endpoints... "); + out.flush(); + { + java.util.List<RemoteObjectAdapterPrx> adapters = new java.util.ArrayList<RemoteObjectAdapterPrx>(); + adapters.add(com.createObjectAdapter("Adapter51", "default")); + adapters.add(com.createObjectAdapter("Adapter52", "default")); + adapters.add(com.createObjectAdapter("Adapter53", "default")); + + TestIntfPrx test = TestIntfPrxHelper.uncheckedCast(createTestIntfPrx(adapters).ice_connectionCached(false)); + test(!test.ice_isConnectionCached()); + + java.util.Set<String> names = new java.util.HashSet<String>(); + names.add("Adapter51"); + names.add("Adapter52"); + names.add("Adapter53"); + while(!names.isEmpty()) + { + names.remove(test.getAdapterName()); + } + + com.deactivateObjectAdapter(adapters.get(0)); + + names.add("Adapter52"); + names.add("Adapter53"); + while(!names.isEmpty()) + { + names.remove(test.getAdapterName()); + } + + com.deactivateObjectAdapter(adapters.get(2)); + + test(test.getAdapterName().equals("Adapter52")); + + deactivate(com, adapters); + } + out.println("ok"); + + out.print("testing per request binding with multiple endpoints and AMI... "); + out.flush(); + { + java.util.List<RemoteObjectAdapterPrx> adapters = new java.util.ArrayList<RemoteObjectAdapterPrx>(); + adapters.add(com.createObjectAdapter("AdapterAMI51", "default")); + adapters.add(com.createObjectAdapter("AdapterAMI52", "default")); + adapters.add(com.createObjectAdapter("AdapterAMI53", "default")); + + TestIntfPrx test = TestIntfPrxHelper.uncheckedCast(createTestIntfPrx(adapters).ice_connectionCached(false)); + test(!test.ice_isConnectionCached()); + + java.util.Set<String> names = new java.util.HashSet<String>(); + names.add("AdapterAMI51"); + names.add("AdapterAMI52"); + names.add("AdapterAMI53"); + while(!names.isEmpty()) + { + names.remove(getAdapterNameWithAMI(test)); + } + + com.deactivateObjectAdapter(adapters.get(0)); + + names.add("AdapterAMI52"); + names.add("AdapterAMI53"); + while(!names.isEmpty()) + { + names.remove(getAdapterNameWithAMI(test)); + } + + com.deactivateObjectAdapter(adapters.get(2)); + + test(getAdapterNameWithAMI(test).equals("AdapterAMI52")); + + deactivate(com, adapters); + } + out.println("ok"); + + out.print("testing per request binding and ordered endpoint selection... "); + out.flush(); + { + java.util.List<RemoteObjectAdapterPrx> adapters = new java.util.ArrayList<RemoteObjectAdapterPrx>(); + adapters.add(com.createObjectAdapter("Adapter61", "default")); + adapters.add(com.createObjectAdapter("Adapter62", "default")); + adapters.add(com.createObjectAdapter("Adapter63", "default")); + + TestIntfPrx test = createTestIntfPrx(adapters); + test = TestIntfPrxHelper.uncheckedCast(test.ice_endpointSelection(Ice.EndpointSelectionType.Ordered)); + test(test.ice_getEndpointSelection() == Ice.EndpointSelectionType.Ordered); + test = TestIntfPrxHelper.uncheckedCast(test.ice_connectionCached(false)); + test(!test.ice_isConnectionCached()); + int nRetry = 5; + int i; + + // + // Ensure that endpoints are tried in order by deactiving the adapters + // one after the other. + // + for(i = 0; i < nRetry && test.getAdapterName().equals("Adapter61"); i++); + test(i == nRetry); + com.deactivateObjectAdapter(adapters.get(0)); + for(i = 0; i < nRetry && test.getAdapterName().equals("Adapter62"); i++); + test(i == nRetry); + com.deactivateObjectAdapter(adapters.get(1)); + for(i = 0; i < nRetry && test.getAdapterName().equals("Adapter63"); i++); + test(i == nRetry); + com.deactivateObjectAdapter(adapters.get(2)); + + try + { + test.getAdapterName(); + } + catch(Ice.ConnectFailedException ex) + { + // + // Usually the actual type of this exception is ConnectionRefusedException, + // but not always. See bug 3179. + // + } + + Ice.Endpoint[] endpoints = test.ice_getEndpoints(); + + adapters.clear(); + + // + // Now, re-activate the adapters with the same endpoints in the opposite + // order. + // + adapters.add(com.createObjectAdapter("Adapter66", endpoints[2].toString())); + for(i = 0; i < nRetry && test.getAdapterName().equals("Adapter66"); i++); + test(i == nRetry); + adapters.add(com.createObjectAdapter("Adapter65", endpoints[1].toString())); + for(i = 0; i < nRetry && test.getAdapterName().equals("Adapter65"); i++); + test(i == nRetry); + adapters.add(com.createObjectAdapter("Adapter64", endpoints[0].toString())); + for(i = 0; i < nRetry && test.getAdapterName().equals("Adapter64"); i++); + test(i == nRetry); + + deactivate(com, adapters); + } + out.println("ok"); + + out.print("testing per request binding and ordered endpoint selection and AMI... "); + out.flush(); + { + java.util.List<RemoteObjectAdapterPrx> adapters = new java.util.ArrayList<RemoteObjectAdapterPrx>(); + adapters.add(com.createObjectAdapter("AdapterAMI61", "default")); + adapters.add(com.createObjectAdapter("AdapterAMI62", "default")); + adapters.add(com.createObjectAdapter("AdapterAMI63", "default")); + + TestIntfPrx test = createTestIntfPrx(adapters); + test = TestIntfPrxHelper.uncheckedCast(test.ice_endpointSelection(Ice.EndpointSelectionType.Ordered)); + test(test.ice_getEndpointSelection() == Ice.EndpointSelectionType.Ordered); + test = TestIntfPrxHelper.uncheckedCast(test.ice_connectionCached(false)); + test(!test.ice_isConnectionCached()); + int nRetry = 5; + int i; + + // + // Ensure that endpoints are tried in order by deactiving the adapters + // one after the other. + // + for(i = 0; i < nRetry && getAdapterNameWithAMI(test).equals("AdapterAMI61"); i++); + test(i == nRetry); + com.deactivateObjectAdapter(adapters.get(0)); + for(i = 0; i < nRetry && getAdapterNameWithAMI(test).equals("AdapterAMI62"); i++); + test(i == nRetry); + com.deactivateObjectAdapter(adapters.get(1)); + for(i = 0; i < nRetry && getAdapterNameWithAMI(test).equals("AdapterAMI63"); i++); + test(i == nRetry); + com.deactivateObjectAdapter(adapters.get(2)); + + try + { + test.getAdapterName(); + } + catch(Ice.ConnectFailedException ex) + { + // + // Usually the actual type of this exception is ConnectionRefusedException, + // but not always. See bug 3179. + // + } + + Ice.Endpoint[] endpoints = test.ice_getEndpoints(); + + adapters.clear(); + + // + // Now, re-activate the adapters with the same endpoints in the opposite + // order. + // + adapters.add(com.createObjectAdapter("AdapterAMI66", endpoints[2].toString())); + for(i = 0; i < nRetry && getAdapterNameWithAMI(test).equals("AdapterAMI66"); i++); + test(i == nRetry); + adapters.add(com.createObjectAdapter("AdapterAMI65", endpoints[1].toString())); + for(i = 0; i < nRetry && getAdapterNameWithAMI(test).equals("AdapterAMI65"); i++); + test(i == nRetry); + adapters.add(com.createObjectAdapter("AdapterAMI64", endpoints[0].toString())); + for(i = 0; i < nRetry && getAdapterNameWithAMI(test).equals("AdapterAMI64"); i++); + test(i == nRetry); + + deactivate(com, adapters); + } + out.println("ok"); + + out.print("testing endpoint mode filtering... "); + out.flush(); + { + java.util.List<RemoteObjectAdapterPrx> adapters = new java.util.ArrayList<RemoteObjectAdapterPrx>(); + adapters.add(com.createObjectAdapter("Adapter71", "default")); + adapters.add(com.createObjectAdapter("Adapter72", "udp")); + + TestIntfPrx test = createTestIntfPrx(adapters); + test(test.getAdapterName().equals("Adapter71")); + + TestIntfPrx testUDP = TestIntfPrxHelper.uncheckedCast(test.ice_datagram()); + test(test.ice_getConnection() != testUDP.ice_getConnection()); + try + { + testUDP.getAdapterName(); + } + catch(Ice.TwowayOnlyException ex) + { + } + } + out.println("ok"); + + if(communicator.getProperties().getProperty("Ice.Plugin.IceSSL").length() > 0) + { + out.print("testing unsecure vs. secure endpoints... "); + out.flush(); + { + java.util.List<RemoteObjectAdapterPrx> adapters = new java.util.ArrayList<RemoteObjectAdapterPrx>(); + adapters.add(com.createObjectAdapter("Adapter81", "ssl")); + adapters.add(com.createObjectAdapter("Adapter82", "tcp")); + + TestIntfPrx test = createTestIntfPrx(adapters); + int i; + for(i = 0; i < 5; i++) + { + test(test.getAdapterName().equals("Adapter82")); + test.ice_getConnection().close(false); + } + + TestIntfPrx testSecure = TestIntfPrxHelper.uncheckedCast(test.ice_secure(true)); + test(testSecure.ice_isSecure()); + testSecure = TestIntfPrxHelper.uncheckedCast(test.ice_secure(false)); + test(!testSecure.ice_isSecure()); + testSecure = TestIntfPrxHelper.uncheckedCast(test.ice_secure(true)); + test(testSecure.ice_isSecure()); + test(test.ice_getConnection() != testSecure.ice_getConnection()); + + com.deactivateObjectAdapter(adapters.get(1)); + + for(i = 0; i < 5; i++) + { + test(test.getAdapterName().equals("Adapter81")); + test.ice_getConnection().close(false); + } + + com.createObjectAdapter("Adapter83", (test.ice_getEndpoints()[1]).toString()); // Reactive tcp OA. + + for(i = 0; i < 5; i++) + { + test(test.getAdapterName().equals("Adapter83")); + test.ice_getConnection().close(false); + } + + com.deactivateObjectAdapter(adapters.get(0)); + try + { + testSecure.ice_ping(); + test(false); + } + catch(Ice.ConnectFailedException ex) + { + // + // Usually the actual type of this exception is ConnectionRefusedException, + // but not always. See bug 3179. + // + } + + deactivate(com, adapters); + } + out.println("ok"); + } + + { + out.print("testing ipv4 & ipv6 connections... "); + out.flush(); + + Ice.Properties ipv4 = Ice.Util.createProperties(); + ipv4.setProperty("Ice.IPv4", "1"); + ipv4.setProperty("Ice.IPv6", "0"); + ipv4.setProperty("Adapter.Endpoints", "tcp -h localhost"); + + Ice.Properties ipv6 = Ice.Util.createProperties(); + ipv6.setProperty("Ice.IPv4", "0"); + ipv6.setProperty("Ice.IPv6", "1"); + ipv6.setProperty("Adapter.Endpoints", "tcp -h localhost"); + + Ice.Properties bothPreferIPv4 = Ice.Util.createProperties(); + bothPreferIPv4.setProperty("Ice.IPv4", "1"); + bothPreferIPv4.setProperty("Ice.IPv6", "1"); + bothPreferIPv4.setProperty("Ice.PreferIPv6Address", "0"); + bothPreferIPv4.setProperty("Adapter.Endpoints", "tcp -h localhost"); + + Ice.Properties bothPreferIPv6 = Ice.Util.createProperties(); + bothPreferIPv6.setProperty("Ice.IPv4", "1"); + bothPreferIPv6.setProperty("Ice.IPv6", "1"); + bothPreferIPv6.setProperty("Ice.PreferIPv6Address", "1"); + bothPreferIPv6.setProperty("Adapter.Endpoints", "tcp -h localhost"); + + java.util.List<Ice.Properties> clientProps = new java.util.ArrayList<Ice.Properties>(); + clientProps.add(ipv4); + clientProps.add(ipv6); + clientProps.add(bothPreferIPv4); + clientProps.add(bothPreferIPv6); + + Ice.Properties anyipv4 = ipv4._clone(); + anyipv4.setProperty("Adapter.Endpoints", "tcp -p 12012"); + anyipv4.setProperty("Adapter.PublishedEndpoints", "tcp -h 127.0.0.1 -p 12012"); + + Ice.Properties anyipv6 = ipv6._clone(); + anyipv6.setProperty("Adapter.Endpoints", "tcp -p 12012"); + anyipv6.setProperty("Adapter.PublishedEndpoints", "tcp -h \".1\" -p 12012"); + + Ice.Properties anyboth = Ice.Util.createProperties(); + anyboth.setProperty("Ice.IPv4", "1"); + anyboth.setProperty("Ice.IPv6", "1"); + anyboth.setProperty("Adapter.Endpoints", "tcp -p 12012"); + anyboth.setProperty("Adapter.PublishedEndpoints", "tcp -h \"::1\" -p 12012:tcp -h 127.0.0.1 -p 12012"); + + Ice.Properties localipv4 = ipv4._clone(); + localipv4.setProperty("Adapter.Endpoints", "tcp -h 127.0.0.1"); + + Ice.Properties localipv6 = ipv6._clone(); + localipv6.setProperty("Adapter.Endpoints", "tcp -h \"::1\""); + + java.util.List<Ice.Properties> serverProps = new java.util.ArrayList<Ice.Properties>(clientProps); + serverProps.add(anyipv4); + serverProps.add(anyipv6); + serverProps.add(anyboth); + serverProps.add(localipv4); + serverProps.add(localipv6); + + boolean ipv6NotSupported = false; + for(Ice.Properties p : serverProps) + { + Ice.InitializationData serverInitData = new Ice.InitializationData(); + serverInitData.properties = p; + Ice.Communicator serverCommunicator = Ice.Util.initialize(serverInitData); + Ice.ObjectAdapter oa; + try + { + oa = serverCommunicator.createObjectAdapter("Adapter"); + oa.activate(); + } + catch(Ice.DNSException ex) + { + serverCommunicator.destroy(); + continue; // IP version not supported. + } + catch(Ice.SocketException ex) + { + if(p == ipv6) + { + ipv6NotSupported = true; + } + serverCommunicator.destroy(); + continue; // IP version not supported. + } + + String strPrx = oa.createProxy(serverCommunicator.stringToIdentity("dummy")).toString(); + for(Ice.Properties q : clientProps) + { + Ice.InitializationData clientInitData = new Ice.InitializationData(); + clientInitData.properties = q; + Ice.Communicator clientCommunicator = Ice.Util.initialize(clientInitData); + Ice.ObjectPrx prx = clientCommunicator.stringToProxy(strPrx); + try + { + prx.ice_ping(); + test(false); + } + catch(Ice.ObjectNotExistException ex) + { + // Expected, no object registered. + } + catch(Ice.DNSException ex) + { + // Expected if no IPv4 or IPv6 address is + // associated to localhost or if trying to connect + // to an any endpoint with the wrong IP version, + // e.g.: resolving an IPv4 address when only IPv6 + // is enabled fails with a DNS exception. + } + catch(Ice.SocketException ex) + { + test((p == ipv4 && q == ipv6) || (p == ipv6 && q == ipv4) || + (p == bothPreferIPv4 && q == ipv6) || (p == bothPreferIPv6 && q == ipv4) || + (p == bothPreferIPv6 && q == ipv6 && ipv6NotSupported) || + (p == anyipv4 && q == ipv6) || (p == anyipv6 && q == ipv4) || + (p == localipv4 && q == ipv6) || (p == localipv6 && q == ipv4) || + (p == ipv6 && q == bothPreferIPv4) || (p == bothPreferIPv6 && q == ipv6) || + (p == ipv6 && q == bothPreferIPv4) || (p == ipv6 && q == bothPreferIPv6) || + (p == bothPreferIPv6 && q == ipv6)); + } + clientCommunicator.destroy(); + } + serverCommunicator.destroy(); + } + + out.println("ok"); + } + + com.shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/binding/Client.java b/java/test/src/main/java/test/Ice/binding/Client.java new file mode 100644 index 00000000000..30d087baac3 --- /dev/null +++ b/java/test/src/main/java/test/Ice/binding/Client.java @@ -0,0 +1,37 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.binding; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + AllTests.allTests(communicator(), getWriter()); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.binding"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/binding/RemoteCommunicatorI.java b/java/test/src/main/java/test/Ice/binding/RemoteCommunicatorI.java new file mode 100644 index 00000000000..fbebb72cd59 --- /dev/null +++ b/java/test/src/main/java/test/Ice/binding/RemoteCommunicatorI.java @@ -0,0 +1,49 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.binding; +import test.Ice.binding.Test.RemoteObjectAdapterPrx; +import test.Ice.binding.Test.RemoteObjectAdapterPrxHelper; +import test.Ice.binding.Test._RemoteCommunicatorDisp; + +public class RemoteCommunicatorI extends _RemoteCommunicatorDisp +{ + @Override + public RemoteObjectAdapterPrx + createObjectAdapter(String name, String endpts, Ice.Current current) + { + String endpoints = endpts; + if(endpoints.indexOf("-p") < 0) + { + // Use a fixed port if none is specified (bug 2896) + endpoints = endpoints + " -h 127.0.0.1 -p " + _nextPort++; + } + + Ice.Communicator com = current.adapter.getCommunicator(); + com.getProperties().setProperty(name + ".ThreadPool.Size", "1"); + Ice.ObjectAdapter adapter = com.createObjectAdapterWithEndpoints(name, endpoints); + return RemoteObjectAdapterPrxHelper.uncheckedCast( + current.adapter.addWithUUID(new RemoteObjectAdapterI(adapter))); + } + + @Override + public void + deactivateObjectAdapter(RemoteObjectAdapterPrx adapter, Ice.Current current) + { + adapter.deactivate(); // Collocated call. + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + private int _nextPort = 10001; +} diff --git a/java/test/src/main/java/test/Ice/binding/RemoteObjectAdapterI.java b/java/test/src/main/java/test/Ice/binding/RemoteObjectAdapterI.java new file mode 100644 index 00000000000..a8b22ec5197 --- /dev/null +++ b/java/test/src/main/java/test/Ice/binding/RemoteObjectAdapterI.java @@ -0,0 +1,49 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.binding; + +import test.Ice.binding.Test.TestIntfPrx; +import test.Ice.binding.Test.TestIntfPrxHelper; +import test.Ice.binding.Test._RemoteObjectAdapterDisp; + +public class RemoteObjectAdapterI extends _RemoteObjectAdapterDisp +{ + public + RemoteObjectAdapterI(Ice.ObjectAdapter adapter) + { + _adapter = adapter; + _testIntf = TestIntfPrxHelper.uncheckedCast(_adapter.add(new TestI(), + _adapter.getCommunicator().stringToIdentity("test"))); + _adapter.activate(); + } + + @Override + public TestIntfPrx + getTestIntf(Ice.Current current) + { + return _testIntf; + } + + @Override + public void + deactivate(Ice.Current current) + { + try + { + _adapter.destroy(); + } + catch(Ice.ObjectAdapterDeactivatedException ex) + { + } + } + + final Ice.ObjectAdapter _adapter; + final TestIntfPrx _testIntf; +}; diff --git a/java/test/src/main/java/test/Ice/binding/Server.java b/java/test/src/main/java/test/Ice/binding/Server.java new file mode 100644 index 00000000000..9c2926cdc3b --- /dev/null +++ b/java/test/src/main/java/test/Ice/binding/Server.java @@ -0,0 +1,45 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.binding; + +public class Server extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Identity id = communicator.stringToIdentity("communicator"); + adapter.add(new RemoteCommunicatorI(), id); + adapter.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.binding"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + return initData; + } + + public static void + main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/binding/Test.ice b/java/test/src/main/java/test/Ice/binding/Test.ice new file mode 100644 index 00000000000..9b951c9b6fb --- /dev/null +++ b/java/test/src/main/java/test/Ice/binding/Test.ice @@ -0,0 +1,37 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.binding"]] +module Test +{ + +interface TestIntf +{ + string getAdapterName(); +}; + +interface RemoteObjectAdapter +{ + TestIntf* getTestIntf(); + + void deactivate(); +}; + +interface RemoteCommunicator +{ + RemoteObjectAdapter* createObjectAdapter(string name, string endpoints); + + void deactivateObjectAdapter(RemoteObjectAdapter* adapter); + + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/binding/TestI.java b/java/test/src/main/java/test/Ice/binding/TestI.java new file mode 100644 index 00000000000..23a13b96ff8 --- /dev/null +++ b/java/test/src/main/java/test/Ice/binding/TestI.java @@ -0,0 +1,25 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.binding; +import test.Ice.binding.Test._TestIntfDisp; + +public class TestI extends _TestIntfDisp +{ + TestI() + { + } + + @Override + public String + getAdapterName(Ice.Current current) + { + return current.adapter.getName(); + } +} diff --git a/java/test/src/main/java/test/Ice/binding/run.py b/java/test/src/main/java/test/Ice/binding/run.py new file mode 100755 index 00000000000..d5fe04787c9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/binding/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/checksum/AllTests.java b/java/test/src/main/java/test/Ice/checksum/AllTests.java new file mode 100644 index 00000000000..3fb2c711746 --- /dev/null +++ b/java/test/src/main/java/test/Ice/checksum/AllTests.java @@ -0,0 +1,92 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.checksum; + +import java.io.PrintWriter; +import test.Ice.checksum.Test.*; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static ChecksumPrx + allTests(Ice.Communicator communicator, boolean collocated, PrintWriter out) + { + String ref = "test:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + + ChecksumPrx checksum = ChecksumPrxHelper.checkedCast(base); + test(checksum != null); + + // + // Verify that no checksums are present for local types. + // + out.print("testing checksums... "); + out.flush(); + for(java.util.Map.Entry<String, String> p : SliceChecksums.checksums.entrySet()) + { + String key = p.getKey(); + int pos = key.indexOf("Local"); + test(pos == -1); + } + + // + // Get server's Slice checksums. + // + java.util.Map<String, String> d = checksum.getSliceChecksums(); + + // + // Compare the checksums. For a type FooN whose name ends in an integer N, + // we assume that the server's type does not change for N = 1, and does + // change for N > 1. + // + java.util.regex.Pattern patt = java.util.regex.Pattern.compile("\\d+"); + for(java.util.Map.Entry<String, String> p : d.entrySet()) + { + int n = 0; + String key = p.getKey(); + java.util.regex.Matcher m = patt.matcher(key); + if(m.find()) + { + try + { + n = Integer.parseInt(key.substring(m.start(), m.end())); + } + catch(NumberFormatException ex) + { + test(false); + } + } + + String value = SliceChecksums.checksums.get(key); + test(value != null); + + if(n <= 1) + { + test(value.equals(p.getValue())); + } + else + { + test(!value.equals(p.getValue())); + } + } + out.println("ok"); + + return checksum; + } +} diff --git a/java/test/src/main/java/test/Ice/checksum/ChecksumI.java b/java/test/src/main/java/test/Ice/checksum/ChecksumI.java new file mode 100644 index 00000000000..a85707f400e --- /dev/null +++ b/java/test/src/main/java/test/Ice/checksum/ChecksumI.java @@ -0,0 +1,34 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.checksum; + +import test.Ice.checksum.server.Test.*; + +public final class ChecksumI extends _ChecksumDisp +{ + public + ChecksumI() + { + } + + @Override + public java.util.Map<String, String> + getSliceChecksums(Ice.Current current) + { + return SliceChecksums.checksums; + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/checksum/Client.java b/java/test/src/main/java/test/Ice/checksum/Client.java new file mode 100644 index 00000000000..34d4f3ab1b8 --- /dev/null +++ b/java/test/src/main/java/test/Ice/checksum/Client.java @@ -0,0 +1,45 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.checksum; + +import test.Ice.checksum.Test.ChecksumPrx; + +public class Client extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + Ice.Communicator communicator = communicator(); + ChecksumPrx checksum = AllTests.allTests(communicator, false, getWriter()); + checksum.shutdown(); + return 0; + } + + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.checksum"); + return initData; + } + + public static void + main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/checksum/Server.java b/java/test/src/main/java/test/Ice/checksum/Server.java new file mode 100644 index 00000000000..c64042283e4 --- /dev/null +++ b/java/test/src/main/java/test/Ice/checksum/Server.java @@ -0,0 +1,45 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.checksum; + +public class Server extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + Ice.Communicator communicator = communicator(); + communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object object = new ChecksumI(); + adapter.add(object, communicator.stringToIdentity("test")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.checksum.server"); + return initData; + } + + public static void + main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/checksum/Test.ice b/java/test/src/main/java/test/Ice/checksum/Test.ice new file mode 100644 index 00000000000..060d9078201 --- /dev/null +++ b/java/test/src/main/java/test/Ice/checksum/Test.ice @@ -0,0 +1,25 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/SliceChecksumDict.ice> + +[["java:package:test.Ice.checksum"]] +module Test +{ + +interface Checksum +{ + idempotent Ice::SliceChecksumDict getSliceChecksums(); + + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/checksum/TestServer.ice b/java/test/src/main/java/test/Ice/checksum/TestServer.ice new file mode 100644 index 00000000000..0fef43faabf --- /dev/null +++ b/java/test/src/main/java/test/Ice/checksum/TestServer.ice @@ -0,0 +1,25 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/SliceChecksumDict.ice> + +[["java:package:test.Ice.checksum.server"]] +module Test +{ + +interface Checksum +{ + idempotent Ice::SliceChecksumDict getSliceChecksums(); + + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/checksum/Types.ice b/java/test/src/main/java/test/Ice/checksum/Types.ice new file mode 100644 index 00000000000..8da301c229a --- /dev/null +++ b/java/test/src/main/java/test/Ice/checksum/Types.ice @@ -0,0 +1,635 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.checksum"]] +module Test +{ + +// +// TEST: Same +// +const int IntConst1 = 100; + +// +// TEST: Value changed +// +const int IntConst2 = 100; + +// +// TEST: Type changed +// +const int IntConst3 = 100; + +// +// TEST: Same +// +enum Enum1 { Enum11, Enum12, Enum13 }; + +// +// TEST: Add enumerator +// +enum Enum2 { Enum21, Enum22, Enum23 }; + +// +// TEST: Remove enumerator +// +enum Enum3 { Enum31, Enum32, Enum33 }; + +// +// TEST: Change to a different type +// +enum Enum4 { Enum41, Enum42, Enum43 }; + +// +// TEST: Enum with explicit values. +// +enum EnumExplicit0 { EnumExplicit01 = 1, EnumExplicit02 = 2, EnumExplicit03 = 3 }; + +// +// TEST: Enum with same explicit values, different order. +// +enum EnumExplicit1 { EnumExplicit11 = 1, EnumExplicit12 = 2, EnumExplicit13 = 3 }; + +// +// TEST: Enum with different explicit values. +// +enum EnumExplicit2 { EnumExplicit21 = 1, EnumExplicit22 = 2, EnumExplicit23 = 3}; + +// +// TEST: Enum with explicit values, removed enumerator. +// +enum EnumExplicit3 { EnumExplicit31 = 1, EnumExplicit32 = 2, EnumExplicit33 = 3}; + +// +// TEST: Same +// +sequence<int> Sequence1; + +// +// TEST: Change sequence type +// +sequence<int> Sequence2; + +// +// TEST: Change to a different type +// +sequence<int> Sequence3; + +// +// TEST: Same +// +dictionary<string, int> Dictionary1; + +// +// TEST: Change key type +// +dictionary<string, int> Dictionary2; + +// +// TEST: Change value type +// +dictionary<string, int> Dictionary3; + +// +// TEST: Change to a different type +// +dictionary<string, int> Dictionary4; + +// +// TEST: Same +// +struct Struct1 +{ + string str; + bool b; +}; + +// +// TEST: Add member +// +struct Struct2 +{ + string str; + bool b; +}; + +// +// TEST: Change member type +// +struct Struct3 +{ + string str; + bool b; +}; + +// +// TEST: Remove member +// +struct Struct4 +{ + string str; + bool b; +}; + +// +// TEST: Change to a different type +// +struct Struct5 +{ + string str; + bool b; +}; + +// +// TEST: Same +// +interface Interface1 +{ +}; + +// +// TEST: Change interface to class +// +interface Interface2 +{ +}; + +// +// TEST: Add base interface +// +interface Interface3 +{ +}; + +// +// TEST: Add operation +// +interface Interface4 +{ +}; + +// +// TEST: Same +// +class EmptyClass1 +{ +}; + +// +// TEST: Add data member +// +class EmptyClass2 +{ +}; + +// +// TEST: Add operation +// +class EmptyClass3 +{ +}; + +// +// TEST: Add base class +// +class EmptyClass4 +{ +}; + +// +// TEST: Add interface +// +class EmptyClass5 +{ +}; + +// +// TEST: Same +// +class SimpleClass1 +{ + string str; + float f; +}; + +// +// TEST: Add operation +// +class SimpleClass2 +{ + string str; + float f; +}; + +// +// TEST: Rename member +// +class SimpleClass3 +{ + string str; + float f; +}; + +// +// TEST: Add member +// +class SimpleClass4 +{ + string str; + float f; +}; + +// +// TEST: Remove member +// +class SimpleClass5 +{ + string str; + float f; +}; + +// +// TEST: Reorder members +// +class SimpleClass6 +{ + string str; + float f; +}; + +// +// TEST: Change member type +// +class SimpleClass7 +{ + string str; + float f; +}; + +// +// TEST: Same +// +exception Exception1 +{ + string str; + bool b; +}; + +// +// TEST: Add member +// +exception Exception2 +{ + string str; + bool b; +}; + +// +// TEST: Change member type +// +exception Exception3 +{ + string str; + bool b; +}; + +// +// TEST: Remove member +// +exception Exception4 +{ + string str; + bool b; +}; + +// +// TEST: Add base exception +// +exception Exception5 +{ +}; + +// +// TEST: Change to a different type +// +exception Exception6 +{ + string str; + bool b; +}; + +// +// TEST: Exception with optional members. +// +exception OptionalEx0 +{ + string firstName; + optional(1) string secondName; + optional(2) string emailAddress; +}; + +// +// TEST: Exception with optional members, different order, same tags. +// +exception OptionalEx1 +{ + string firstName; + optional(1) string secondName; + optional(2) string emailAddress; +}; + +// +// TEST: Exception with different optional members. +// +exception OptionalEx2 +{ + string firstName; + string secondName; + optional(1) string emailAddress; +}; + +// +// TEST: Exception with different optional members. +// +exception OptionalEx3 +{ + string firstName; + optional(1) string secondName; + optional(2) string emailAddress; +}; + +// +// TEST: Exception with optional members using different tags. +// +exception OptionalEx4 +{ + string firstName; + optional(1) string secondName; + optional(2) string emailAddress; +}; + +// +// TEST: Same +// +class BaseClass1 +{ + void baseOp1(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Change return type +// +class BaseClass2 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Add parameter +// +class BaseClass3 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Add exception +// +class BaseClass4 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Change out parameter to in parameter +// +class BaseClass5 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Remove parameter +// +class BaseClass6 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Remove exception +// +class BaseClass7 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Remove operation +// +class BaseClass8 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Add base class +// +class BaseClass9 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Add interface +// +class BaseClass10 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Add base class and interface +// +class BaseClass11 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Class with compact id +// +class Compact1(1) +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Derived from class with compact id +// +class Derived1 extends Compact1 +{ +}; + +// +// TEST: Same class names but different compact id +// +class Compact2(2) +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Class with optional members. +// +class Optional0 +{ + string firstName; + optional(1) string secondName; + optional(2) string emailAddress; +}; + +// +// TEST: Class with optional members, different order, same tags. +// +class Optional1 +{ + string firstName; + optional(1) string secondName; + optional(2) string emailAddress; +}; + +// +// TEST: Class with different optional members. +// +class Optional2 +{ + string firstName; + string secondName; + optional(1) string emailAddress; +}; + +// +// TEST: Class with different optional members. +// +class Optional3 +{ + string firstName; + optional(1) string secondName; + optional(2) string emailAddress; +}; + +// +// TEST: Class with optional members using different tags. +// +class Optional4 +{ + string firstName; + optional(1) string secondName; + optional(2) string emailAddress; +}; + +// +// TEST: Class with optional parameters. +// +class OptionalParameters0 +{ + void op1(string firstName, optional(1) string secondName, + optional(2) string emailAddress); +}; + +// +// TEST: Class with optional parameters, different order. +// +class OptionalParameters1 +{ + void op1(string firstName, optional(1) string secondName, + optional(2) string emailAddress); +}; + +// +// TEST: Class with optional parameters, different tags. +// +class OptionalParameters2 +{ + void op1(string firstName, optional(1) string emailAddress, + optional(2) string secondName); +}; + +// +// TEST: Class with different optional parameters. +// +class OptionalParameters3 +{ + void op1(string firstName, optional(1) string emailAddress, + string secondName); +}; + +// +// TEST: Class with optional return type. +// +class OptionalReturn0 +{ + optional(1) int op(); +}; + +// +// TEST: Class that changes optional return type. +// +class OptionalReturn2 +{ + optional(1) int op(); +}; + +// +// TEST: Local +// +local enum LocalEnum { LocalEnum1, LocalEnum2, LocalEnum3 }; + +// +// TEST: Local +// +local sequence<string> LocalSequence; + +// +// TEST: Local +// +local dictionary<string, string> LocalDictionary; + +// +// TEST: Local +// +local struct LocalStruct +{ + string str; +}; + +// +// TEST: Local +// +local class LocalClass +{ +}; + +}; diff --git a/java/test/src/main/java/test/Ice/checksum/TypesServer.ice b/java/test/src/main/java/test/Ice/checksum/TypesServer.ice new file mode 100644 index 00000000000..0fd16b143bc --- /dev/null +++ b/java/test/src/main/java/test/Ice/checksum/TypesServer.ice @@ -0,0 +1,632 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.checksum.server"]] +module Test +{ + +// +// TEST: Same +// +const int IntConst1 = 100; + +// +// TEST: Value changed +// +const int IntConst2 = 1000; + +// +// TEST: Type changed +// +const short IntConst3 = 100; + +// +// TEST: Same +// +enum Enum1 { Enum11, Enum12, Enum13 }; + +// +// TEST: Add enumerator +// +enum Enum2 { Enum21, Enum22, Enum23, Enum24 }; + +// +// TEST: Remove enumerator +// +enum Enum3 { Enum32, Enum33 }; + +// +// TEST: Enum with explicit values. +// +enum EnumExplicit0 { EnumExplicit01 = 1, EnumExplicit02 = 2, EnumExplicit03 = 3 }; + +// +// TEST: Enum with same explicit values, different order. +// +enum EnumExplicit1 { EnumExplicit11 = 1, EnumExplicit13 = 3, EnumExplicit12 = 2 }; + +// +// TEST: Enum with different explicit values. +// +enum EnumExplicit2 { EnumExplicit21 = 1, EnumExplicit22 = 3, EnumExplicit23 }; + +// +// TEST: Enum with explicit values, removed enumerator. +// +enum EnumExplicit3 { EnumExplicit31 = 1, EnumExplicit32 = 2}; + +// +// TEST: Change to a different type +// +class Enum4 {}; + +// +// TEST: Same +// +sequence<int> Sequence1; + +// +// TEST: Change sequence type +// +sequence<short> Sequence2; + +// +// TEST: Change to a different type +// +class Sequence3 {}; + +// +// TEST: Same +// +dictionary<string, int> Dictionary1; + +// +// TEST: Change key type +// +dictionary<long, int> Dictionary2; + +// +// TEST: Change value type +// +dictionary<string, bool> Dictionary3; + +// +// TEST: Change to a different type +// +class Dictionary4 {}; + +// +// TEST: Same +// +struct Struct1 +{ + string str; + bool b; +}; + +// +// TEST: Add member +// +struct Struct2 +{ + string str; + bool b; + float f; +}; + +// +// TEST: Change member type +// +struct Struct3 +{ + string str; + double b; +}; + +// +// TEST: Remove member +// +struct Struct4 +{ + bool b; +}; + +// +// TEST: Change to a different type +// +class Struct5 {}; + +// +// TEST: Same +// +interface Interface1 +{ +}; + +// +// TEST: Change interface to class +// +class Interface2 +{ +}; + +// +// TEST: Add base interface +// +interface Interface3 extends Interface1 +{ +}; + +// +// TEST: Add operation +// +interface Interface4 +{ + void opInterface4(); +}; + +// +// TEST: Same +// +class EmptyClass1 +{ +}; + +// +// TEST: Add data member +// +class EmptyClass2 +{ + double d; +}; + +// +// TEST: Add operation +// +class EmptyClass3 +{ + void newOp(); +}; + +// +// TEST: Add base class +// +class EmptyClass4 extends EmptyClass1 +{ +}; + +// +// TEST: Add interface +// +class EmptyClass5 implements Interface1 +{ +}; + +// +// TEST: Same +// +class SimpleClass1 +{ + string str; + float f; +}; + +// +// TEST: Add operation +// +class SimpleClass2 +{ + string str; + float f; + void newOp(); +}; + +// +// TEST: Rename member +// +class SimpleClass3 +{ + string str; + float g; +}; + +// +// TEST: Add member +// +class SimpleClass4 +{ + string str; + float f; + bool b; +}; + +// +// TEST: Remove member +// +class SimpleClass5 +{ + string str; +}; + +// +// TEST: Reorder members +// +class SimpleClass6 +{ + float f; + string str; +}; + +// +// TEST: Change member type +// +class SimpleClass7 +{ + string str; + double f; +}; + +// +// TEST: Same +// +exception Exception1 +{ + string str; + bool b; +}; + +// +// TEST: Add member +// +exception Exception2 +{ + string str; + bool b; + float f; +}; + +// +// TEST: Change member type +// +exception Exception3 +{ + string str; + double b; +}; + +// +// TEST: Remove member +// +exception Exception4 +{ + bool b; +}; + +// +// TEST: Add base exception +// +exception Exception5 extends Exception1 +{ +}; + +// +// TEST: Change to a different type +// +class Exception6 {}; + +// +// TEST: Exception with optional members. +// +exception OptionalEx0 +{ + string firstName; + optional(1) string secondName; + optional(2) string emailAddress; +}; + +// +// TEST: Exception with optional members, different order, same tags. +// +exception OptionalEx1 +{ + string firstName; + optional(2) string emailAddress; + optional(1) string secondName; +}; + +// +// TEST: Exception with different optional members. +// +exception OptionalEx2 +{ + string firstName; + optional(1) string secondName; + string emailAddress; +}; + +// +// TEST: Exception with different optional members. +// +exception OptionalEx3 +{ + string firstName; + optional(1) string secondName; + optional(2) string emailAddress; + optional(3) string phoneNumber; +}; + +// +// TEST: Exception with optional members using different tags. +// +exception OptionalEx4 +{ + string firstName; + optional(2) string secondName; + optional(1) string emailAddress; +}; + +// +// TEST: Same +// +class BaseClass1 +{ + void baseOp1(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Change return type +// +class BaseClass2 +{ + int baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Add parameter +// +class BaseClass3 +{ + void baseOp(Object o); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Add exception +// +class BaseClass4 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1, Exception2; +}; + +// +// TEST: Change out parameter to in parameter +// +class BaseClass5 +{ + void baseOp(); + void baseOp2(int i, string s) throws Exception1; +}; + +// +// TEST: Remove parameter +// +class BaseClass6 +{ + void baseOp(); + void baseOp2(out string s) throws Exception1; +}; + +// +// TEST: Remove exception +// +class BaseClass7 +{ + void baseOp(); + void baseOp2(int i, out string s); +}; + +// +// TEST: Remove operation +// +class BaseClass8 +{ + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Add base class +// +class BaseClass9 extends EmptyClass1 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Add interface +// +class BaseClass10 implements Interface1 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Add base class and interface +// +class BaseClass11 extends EmptyClass1 implements Interface1 +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Class with compact id +// +class Compact1(1) +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Derived from class with compact id +// +class Derived1 extends Compact1 +{ +}; + +// +// TEST: Same class names but different compact id +// +class Compact2(3) +{ + void baseOp(); + void baseOp2(int i, out string s) throws Exception1; +}; + +// +// TEST: Class with optional members. +// +class Optional0 +{ + string firstName; + optional(1) string secondName; + optional(2) string emailAddress; +}; + +// +// TEST: Class with optional members, different order, same tags. +// +class Optional1 +{ + string firstName; + optional(2) string emailAddress; + optional(1) string secondName; +}; + +// +// TEST: Class with different optional members. +// +class Optional2 +{ + string firstName; + optional(1) string secondName; + string emailAddress; +}; + +// +// TEST: Class with different optional members. +// +class Optional3 +{ + string firstName; + optional(1) string secondName; + optional(2) string emailAddress; + optional(3) string phoneNumber; +}; + +// +// TEST: Class with optional members using different tags. +// +class Optional4 +{ + string firstName; + optional(2) string secondName; + optional(1) string emailAddress; +}; + +// +// TEST: Class with optional parameters. +// +class OptionalParameters0 +{ + void op1(string firstName, optional(1) string secondName, + optional(2) string emailAddress); +}; + +// +// TEST: Class with optional parameters, different order. +// +class OptionalParameters1 +{ + void op1(string firstName, optional(2) string emailAddress, + optional(1) string secondName); +}; + +// +// TEST: Class with optional parameters, different tags. +// +class OptionalParameters2 +{ + void op1(string firstName, optional(2) string emailAddress, + optional(1) string secondName); +}; + +// +// TEST: Class with different optional parameters. +// +class OptionalParameters3 +{ + void op1(string firstName, string emailAddress, + optional(1) string secondName); +}; + +// +// TEST: Class with optional return type. +// +class OptionalReturn0 +{ + optional(1) int op(); +}; + +// +// TEST: Class that changes optional return type. +// +class OptionalReturn2 +{ + int op(); +}; + +// +// TEST: Local +// +local enum LocalEnum { LocalEnum1, LocalEnum2, LocalEnum3 }; + +// +// TEST: Local +// +local sequence<string> LocalSequence; + +// +// TEST: Local +// +local dictionary<string, string> LocalDictionary; + +// +// TEST: Local +// +local struct LocalStruct +{ + string str; +}; + +// +// TEST: Local +// +local class LocalClass +{ +}; + +}; diff --git a/java/test/src/main/java/test/Ice/checksum/run.py b/java/test/src/main/java/test/Ice/checksum/run.py new file mode 100755 index 00000000000..d5fe04787c9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/checksum/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/classLoader/AbstractClassI.java b/java/test/src/main/java/test/Ice/classLoader/AbstractClassI.java new file mode 100644 index 00000000000..df7bcf8a4c4 --- /dev/null +++ b/java/test/src/main/java/test/Ice/classLoader/AbstractClassI.java @@ -0,0 +1,21 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.classLoader; + +import test.Ice.classLoader.Test.AbstractClass; + +class AbstractClassI extends AbstractClass +{ + @Override + public void + op(Ice.Current current) + { + } +} diff --git a/java/test/src/main/java/test/Ice/classLoader/AllTests.java b/java/test/src/main/java/test/Ice/classLoader/AllTests.java new file mode 100644 index 00000000000..d0181cff1a6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/classLoader/AllTests.java @@ -0,0 +1,217 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.classLoader; + +import java.io.PrintWriter; + +import test.Ice.classLoader.Test.AbstractClass; +import test.Ice.classLoader.Test.ConcreteClass; +import test.Ice.classLoader.Test.E; +import test.Ice.classLoader.Test.InitialPrx; +import test.Ice.classLoader.Test.InitialPrxHelper; +import test.Util.Application; + +public class AllTests +{ + private static class MyObjectFactory implements Ice.ObjectFactory + { + @Override + public Ice.Object create(String type) + { + if(type.equals("::Test::AbstractClass")) + { + return new AbstractClassI(); + } + + assert (false); // Should never be reached + return null; + } + + @Override + public void destroy() + { + // Nothing to do + } + } + + private static class MyClassLoader extends ClassLoader + { + @Override + protected Class<?> loadClass(String name, boolean resolve) + throws ClassNotFoundException + { + _names.add(name); + return super.loadClass(name, resolve); + } + + void reset() + { + _names.clear(); + } + + boolean check(String name) + { + return _names.contains(name); + } + + private java.util.List<String> _names = new java.util.LinkedList<String>(); + } + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + allTests(Application app, boolean collocated) + { + Ice.Communicator communicator = app.communicator(); + PrintWriter out = app.getWriter(); + + // + // Verify that the class loader is used for Slice packages. + // + { + out.print("testing package... "); + out.flush(); + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + MyClassLoader classLoader = new MyClassLoader(); + initData.classLoader = classLoader; + Ice.Communicator ic = app.initialize(initData); + test(classLoader.check("test.Ice.classLoader.Test._Marker")); + ic.destroy(); + out.println("ok"); + } + + // + // Verify that the class loader is used for Ice plug-ins. + // + { + out.print("testing plug-in... "); + out.flush(); + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + initData.properties.setProperty("Ice.Plugin.Test", "test.Ice.classLoader.PluginFactoryI"); + MyClassLoader classLoader = new MyClassLoader(); + initData.classLoader = classLoader; + Ice.Communicator ic = app.initialize(initData); + test(classLoader.check("test.Ice.classLoader.PluginFactoryI")); + ic.destroy(); + out.println("ok"); + } + + // + // Verify that the class loader is used for IceSSL certificate verifiers and password callbacks. + // + if(communicator.getProperties().getProperty("Ice.Default.Protocol").equals("ssl")) + { + out.print("testing IceSSL certificate verifier and password callback... "); + out.flush(); + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + initData.properties.setProperty("IceSSL.CertVerifier", "test.Ice.classLoader.CertificateVerifierI"); + initData.properties.setProperty("IceSSL.PasswordCallback", "test.Ice.classLoader.PasswordCallbackI"); + MyClassLoader classLoader = new MyClassLoader(); + initData.classLoader = classLoader; + Ice.Communicator ic = app.initialize(initData); + test(classLoader.check("test.Ice.classLoader.CertificateVerifierI")); + test(classLoader.check("test.Ice.classLoader.PasswordCallbackI")); + ic.destroy(); + out.println("ok"); + } + + // + // Marshaling tests. + // + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + MyClassLoader classLoader = new MyClassLoader(); + initData.classLoader = classLoader; + Ice.Communicator ic = app.initialize(initData); + + String ref = "initial:default -p 12010"; + Ice.ObjectPrx base = ic.stringToProxy(ref); + test(base != null); + + InitialPrx initial = InitialPrxHelper.checkedCast(base); + test(initial != null); + + // + // Verify that the class loader is used for concrete classes. + // + { + out.print("testing concrete class... "); + out.flush(); + ConcreteClass cc = initial.getConcreteClass(); + test(cc != null); + test(classLoader.check("Test.ConcreteClass")); + test(classLoader.check("test.Ice.classLoader.Test.ConcreteClass")); + classLoader.reset(); + out.println("ok"); + } + + // + // Verify that the class loader is invoked when a factory is not installed, and is + // not invoked when a factory is installed. + // + { + out.print("testing abstract class... "); + out.flush(); + + try + { + initial.getAbstractClass(); + } + catch(Ice.NoObjectFactoryException ex) + { + // Expected. + } + test(classLoader.check("Test.AbstractClass")); + test(classLoader.check("test.Ice.classLoader.Test.AbstractClass")); + classLoader.reset(); + + ic.addObjectFactory(new MyObjectFactory(), "::Test::AbstractClass"); + AbstractClass ac = initial.getAbstractClass(); + test(ac != null); + test(!classLoader.check("Test.AbstractClass")); + test(!classLoader.check("test.Ice.classLoader.Test.AbstractClass")); + classLoader.reset(); + + out.println("ok"); + } + + // + // Verify that the class loader is used for user exceptions. + // + out.print("testing user exception... "); + out.flush(); + try + { + initial.throwException(); + test(false); + } + catch(E ex) + { + } + test(classLoader.check("Test.E")); + test(classLoader.check("test.Ice.classLoader.Test.E")); + out.println("ok"); + + initial.shutdown(); + ic.destroy(); + } + } +} diff --git a/java/test/src/main/java/test/Ice/classLoader/CertificateVerifierI.java b/java/test/src/main/java/test/Ice/classLoader/CertificateVerifierI.java new file mode 100644 index 00000000000..3e681297f84 --- /dev/null +++ b/java/test/src/main/java/test/Ice/classLoader/CertificateVerifierI.java @@ -0,0 +1,19 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.classLoader; + +public class CertificateVerifierI implements IceSSL.CertificateVerifier +{ + @Override + public boolean verify(IceSSL.NativeConnectionInfo info) + { + return true; + } +} diff --git a/java/test/src/main/java/test/Ice/classLoader/Client.java b/java/test/src/main/java/test/Ice/classLoader/Client.java new file mode 100644 index 00000000000..20152d6b598 --- /dev/null +++ b/java/test/src/main/java/test/Ice/classLoader/Client.java @@ -0,0 +1,39 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.classLoader; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + AllTests.allTests(this, false); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + _initData = new Ice.InitializationData(); + _initData.properties = Ice.Util.createProperties(argsH); + _initData.properties.setProperty("Ice.Package.Test", "test.Ice.classLoader"); + return _initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } + + private Ice.InitializationData _initData; +} diff --git a/java/test/src/main/java/test/Ice/classLoader/InitialI.java b/java/test/src/main/java/test/Ice/classLoader/InitialI.java new file mode 100644 index 00000000000..a8056715aad --- /dev/null +++ b/java/test/src/main/java/test/Ice/classLoader/InitialI.java @@ -0,0 +1,55 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.classLoader; + +import test.Ice.classLoader.Test.AbstractClass; +import test.Ice.classLoader.Test.ConcreteClass; +import test.Ice.classLoader.Test.E; +import test.Ice.classLoader.Test._InitialDisp; + +public final class InitialI extends _InitialDisp +{ + public + InitialI(Ice.ObjectAdapter adapter) + { + _adapter = adapter; + } + + @Override + public ConcreteClass + getConcreteClass(Ice.Current current) + { + return new ConcreteClass(); + } + + @Override + public AbstractClass + getAbstractClass(Ice.Current current) + { + return new AbstractClassI(); + } + + @Override + public void + throwException(Ice.Current current) + throws E + { + throw new E(); + } + + @Override + public void + shutdown(Ice.Current current) + { + _adapter.getCommunicator().shutdown(); + } + + private Ice.ObjectAdapter _adapter; +} diff --git a/java/test/src/main/java/test/Ice/classLoader/PasswordCallbackI.java b/java/test/src/main/java/test/Ice/classLoader/PasswordCallbackI.java new file mode 100644 index 00000000000..e5eba1462dd --- /dev/null +++ b/java/test/src/main/java/test/Ice/classLoader/PasswordCallbackI.java @@ -0,0 +1,31 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.classLoader; + +public class PasswordCallbackI implements IceSSL.PasswordCallback +{ + @Override + public char[] getPassword(String alias) + { + return "password".toCharArray(); + } + + @Override + public char[] getTruststorePassword() + { + return "password".toCharArray(); + } + + @Override + public char[] getKeystorePassword() + { + return "password".toCharArray(); + } +} diff --git a/java/test/src/main/java/test/Ice/classLoader/PluginFactoryI.java b/java/test/src/main/java/test/Ice/classLoader/PluginFactoryI.java new file mode 100644 index 00000000000..2416e04c420 --- /dev/null +++ b/java/test/src/main/java/test/Ice/classLoader/PluginFactoryI.java @@ -0,0 +1,32 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.classLoader; + +public class PluginFactoryI implements Ice.PluginFactory +{ + static class PluginI implements Ice.Plugin + { + @Override + public void initialize() + { + } + + @Override + public void destroy() + { + } + } + + @Override + public Ice.Plugin create(Ice.Communicator communicator, String name, String[] args) + { + return new PluginI(); + } +} diff --git a/java/test/src/main/java/test/Ice/classLoader/Server.java b/java/test/src/main/java/test/Ice/classLoader/Server.java new file mode 100644 index 00000000000..79abca86364 --- /dev/null +++ b/java/test/src/main/java/test/Ice/classLoader/Server.java @@ -0,0 +1,44 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.classLoader; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object object = new InitialI(adapter); + adapter.add(object, communicator.stringToIdentity("initial")); + adapter.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.classLoader"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("Ice.Default.SlicedFormat", "1"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/classLoader/Test.ice b/java/test/src/main/java/test/Ice/classLoader/Test.ice new file mode 100644 index 00000000000..2df8659720e --- /dev/null +++ b/java/test/src/main/java/test/Ice/classLoader/Test.ice @@ -0,0 +1,36 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.classLoader"]] +module Test +{ + +class ConcreteClass +{ + int i; +}; + +class AbstractClass +{ + void op(); +}; + +exception E {}; + +interface Initial +{ + ConcreteClass getConcreteClass(); + AbstractClass getAbstractClass(); + void throwException() throws E; + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/classLoader/run.py b/java/test/src/main/java/test/Ice/classLoader/run.py new file mode 100755 index 00000000000..d5fe04787c9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/classLoader/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/custom/AllTests.java b/java/test/src/main/java/test/Ice/custom/AllTests.java new file mode 100644 index 00000000000..be731b43efe --- /dev/null +++ b/java/test/src/main/java/test/Ice/custom/AllTests.java @@ -0,0 +1,354 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.custom; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.nio.ByteBuffer; +import java.nio.ShortBuffer; +import java.nio.IntBuffer; +import java.nio.LongBuffer; +import java.nio.FloatBuffer; +import java.nio.DoubleBuffer; + +import test.Ice.custom.Test.BoolSeqHolder; +import test.Ice.custom.Test.ByteSeqHolder; +import test.Ice.custom.Test.C; +import test.Ice.custom.Test.CArrayHolder; +import test.Ice.custom.Test.CListHolder; +import test.Ice.custom.Test.CSeqHolder; +import test.Ice.custom.Test.DSeqHolder; +import test.Ice.custom.Test.DoubleSeqHolder; +import test.Ice.custom.Test.E; +import test.Ice.custom.Test.ESeqHolder; +import test.Ice.custom.Test.FloatSeqHolder; +import test.Ice.custom.Test.IntSeqHolder; +import test.Ice.custom.Test.LongSeqHolder; +import test.Ice.custom.Test.S; +import test.Ice.custom.Test.SSeqHolder; +import test.Ice.custom.Test.ShortSeqHolder; +import test.Ice.custom.Test.StringSeqHolder; +import test.Ice.custom.Test.StringSeqSeqHolder; +import test.Ice.custom.Test.TestIntfPrx; +import test.Ice.custom.Test.TestIntfPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static TestIntfPrx + allTests(Ice.Communicator communicator, PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + String ref = "test:default -p 12010"; + Ice.ObjectPrx obj = communicator.stringToProxy(ref); + test(obj != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + TestIntfPrx t = TestIntfPrxHelper.checkedCast(obj); + test(t != null); + test(t.equals(obj)); + out.println("ok"); + + out.print("testing custom sequences... "); + out.flush(); + + { + // + // Create a sequence of C instances, where elements 1..n simply point to element 0. + // + C[] seq = new C[5]; + seq[0] = new C(); + for(int i = 1; i < seq.length; i++) + { + seq[i] = seq[0]; + } + + // + // Invoke each operation and verify that the returned sequences have the same + // structure as the original. + // + CSeqHolder seqH = new CSeqHolder(); + C[] seqR = t.opCSeq(seq, seqH); + test(seqR.length == seq.length); + test(seqH.value.length == seq.length); + for(int i = 1; i < seq.length; i++) + { + test(seqR[i] != null); + test(seqR[i] == seqR[0]); + test(seqR[i] == seqH.value[i]); + } + + ArrayList<C> arr = new ArrayList<C>(Arrays.asList(seq)); + CArrayHolder arrH = new CArrayHolder(); + List<C> arrR = t.opCArray(arr, arrH); + test(arrR.size() == arr.size()); + test(arrH.value.size() == arr.size()); + for(int i = 1; i < arr.size(); i++) + { + test(arrR.get(i) != null); + test(arrR.get(i) == arrR.get(0)); + test(arrR.get(i) == arrH.value.get(i)); + } + + LinkedList<C> list = new LinkedList<C>(Arrays.asList(seq)); + CListHolder listH = new CListHolder(); + List<C> listR = t.opCList(list, listH); + test(listR.size() == list.size()); + test(listH.value.size() == list.size()); + for(int i = 1; i < list.size(); i++) + { + test(listR.get(i) != null); + test(listR.get(i) == listR.get(0)); + test(listR.get(i) == listH.value.get(i)); + } + } + + { + final Boolean[] seq = { Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE }; + ArrayList<Boolean> list = new ArrayList<Boolean>(Arrays.asList(seq)); + BoolSeqHolder listH = new BoolSeqHolder(); + List<Boolean> listR = t.opBoolSeq(list, listH); + test(listH.value.equals(listR)); + test(listH.value.equals(list)); + } + + { + final Byte[] seq = { new Byte((byte)0), new Byte((byte)1), new Byte((byte)2), new Byte((byte)3) }; + ArrayList<Byte> list = new ArrayList<Byte>(Arrays.asList(seq)); + ByteSeqHolder listH = new ByteSeqHolder(); + List<Byte> listR = t.opByteSeq(list, listH); + test(listH.value.equals(listR)); + test(listH.value.equals(list)); + } + + { + final Short[] seq = { new Short((short)0), new Short((short)1), new Short((short)2), new Short((short)3) }; + ArrayList<Short> list = new ArrayList<Short>(Arrays.asList(seq)); + ShortSeqHolder listH = new ShortSeqHolder(); + List<Short> listR = t.opShortSeq(list, listH); + test(listH.value.equals(listR)); + test(listH.value.equals(list)); + } + + { + final Integer[] seq = { new Integer(0), new Integer(1), new Integer(2), new Integer(3) }; + ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(seq)); + IntSeqHolder listH = new IntSeqHolder(); + List<Integer> listR = t.opIntSeq(list, listH); + test(listH.value.equals(listR)); + test(listH.value.equals(list)); + } + + { + final Long[] seq = { new Long(0), new Long(1), new Long(2), new Long(3) }; + ArrayList<Long> list = new ArrayList<Long>(Arrays.asList(seq)); + LongSeqHolder listH = new LongSeqHolder(); + List<Long> listR = t.opLongSeq(list, listH); + test(listH.value.equals(listR)); + test(listH.value.equals(list)); + } + + { + final Float[] seq = { new Float(0), new Float(1), new Float(2), new Float(3) }; + ArrayList<Float> list = new ArrayList<Float>(Arrays.asList(seq)); + FloatSeqHolder listH = new FloatSeqHolder(); + List<Float> listR = t.opFloatSeq(list, listH); + test(listH.value.equals(listR)); + test(listH.value.equals(list)); + } + + { + final Double[] seq = { new Double(0), new Double(1), new Double(2), new Double(3) }; + ArrayList<Double> list = new ArrayList<Double>(Arrays.asList(seq)); + DoubleSeqHolder listH = new DoubleSeqHolder(); + List<Double> listR = t.opDoubleSeq(list, listH); + test(listH.value.equals(listR)); + test(listH.value.equals(list)); + } + + { + final String[] seq = { "0", "1", "2", "3", "4" }; + ArrayList<String> list = new ArrayList<String>(Arrays.asList(seq)); + StringSeqHolder listH = new StringSeqHolder(); + List<String> listR = t.opStringSeq(list, listH); + test(listH.value.equals(listR)); + test(listH.value.equals(list)); + } + + { + final E[] seq = { E.E1, E.E2, E.E3 }; + ArrayList<E> list = new ArrayList<E>(Arrays.asList(seq)); + ESeqHolder listH = new ESeqHolder(); + List<E> listR = t.opESeq(list, listH); + test(listH.value.equals(listR)); + test(listH.value.equals(list)); + } + + { + S[] seq = new S[5]; + for(int i = 0; i < seq.length; i++) + { + seq[i] = new S(); + seq[i].en = E.values()[i % 3]; + } + ArrayList<S> list = new ArrayList<S>(Arrays.asList(seq)); + SSeqHolder listH = new SSeqHolder(); + List<S> listR = t.opSSeq(list, listH); + test(listH.value.equals(listR)); + test(listH.value.equals(list)); + } + + { + ArrayList<Map<Integer, String>> list = new ArrayList<Map<Integer, String>>(); + for(int i = 0; i < 5; i++) + { + Map<Integer, String> m = new HashMap<Integer, String>(); + for(int j = 0; j < 4; j++) + { + m.put(j, "" + j); + } + list.add(m); + } + DSeqHolder listH = new DSeqHolder(); + List<Map<Integer, String>> listR = t.opDSeq(list, listH); + test(listH.value.equals(listR)); + test(listH.value.equals(list)); + } + + { + List<List<String>> seq = new LinkedList<List<String>>(); + for(int i = 0; i < 5; i++) + { + final String[] arr = { "0", "1", "2", "3", "4" }; + seq.add(new ArrayList<String>(Arrays.asList(arr))); + } + StringSeqSeqHolder listH = new StringSeqSeqHolder(); + List<List<String>> listR = t.opStringSeqSeq(seq, listH); + test(listH.value.equals(listR)); + test(listH.value.equals(seq)); + } + + { + final byte[] fullSeq = new byte[] {0, 1, 2, 3, 4, 5, 6, 7}; + final byte[] usedSeq = new byte[] {2, 3, 4, 5}; + + ByteBuffer buffer = ByteBuffer.wrap(fullSeq, 2, 4); + Ice.Holder<ByteBuffer> bufferH = new Ice.Holder<ByteBuffer>(); + ByteBuffer bufferR = t.opByteBufferSeq(buffer, bufferH); + + byte[] arr = new byte[bufferH.value.limit()]; + bufferH.value.get(arr, 0, bufferH.value.limit()); + test(Arrays.equals(arr, usedSeq)); + arr = new byte[bufferR.limit()]; + bufferR.get(arr, 0, bufferR.limit()); + test(Arrays.equals(arr, usedSeq)); + } + + { + final short[] fullSeq = new short[] {0, 1, 2, 3, 4, 5, 6, 7}; + final short[] usedSeq = new short[] {2, 3, 4, 5}; + + ShortBuffer buffer = ShortBuffer.wrap(fullSeq, 2, 4); + Ice.Holder<ShortBuffer> bufferH = new Ice.Holder<ShortBuffer>(); + ShortBuffer bufferR = t.opShortBufferSeq(buffer, bufferH); + + short[] arr = new short[bufferH.value.limit()]; + bufferH.value.get(arr, 0, bufferH.value.limit()); + test(Arrays.equals(arr, usedSeq)); + arr = new short[bufferR.limit()]; + bufferR.get(arr, 0, bufferR.limit()); + test(Arrays.equals(arr, usedSeq)); + } + + { + final int[] fullSeq = new int[] {0, 1, 2, 3, 4, 5, 6, 7}; + final int[] usedSeq = new int[] {2, 3, 4, 5}; + + IntBuffer buffer = IntBuffer.wrap(fullSeq, 2, 4); + Ice.Holder<IntBuffer> bufferH = new Ice.Holder<IntBuffer>(); + IntBuffer bufferR = t.opIntBufferSeq(buffer, bufferH); + + int[] arr = new int[bufferH.value.limit()]; + bufferH.value.get(arr, 0, bufferH.value.limit()); + test(Arrays.equals(arr, usedSeq)); + arr = new int[bufferR.limit()]; + bufferR.get(arr, 0, bufferR.limit()); + test(Arrays.equals(arr, usedSeq)); + } + + { + final long[] fullSeq = new long[] {0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L}; + final long[] usedSeq = new long[] {2L, 3L, 4L, 5L}; + + LongBuffer buffer = LongBuffer.wrap(fullSeq, 2, 4); + Ice.Holder<LongBuffer> bufferH = new Ice.Holder<LongBuffer>(); + LongBuffer bufferR = t.opLongBufferSeq(buffer, bufferH); + + long[] arr = new long[bufferH.value.limit()]; + bufferH.value.get(arr, 0, bufferH.value.limit()); + test(Arrays.equals(arr, usedSeq)); + arr = new long[bufferR.limit()]; + bufferR.get(arr, 0, bufferR.limit()); + test(Arrays.equals(arr, usedSeq)); + } + + { + final float[] fullSeq = new float[] {0, 1, 2, 3, 4, 5, 6, 7}; + final float[] usedSeq = new float[] {2, 3, 4, 5}; + + FloatBuffer buffer = FloatBuffer.wrap(fullSeq, 2, 4); + Ice.Holder<FloatBuffer> bufferH = new Ice.Holder<FloatBuffer>(); + FloatBuffer bufferR = t.opFloatBufferSeq(buffer, bufferH); + + float[] arr = new float[bufferH.value.limit()]; + bufferH.value.get(arr, 0, bufferH.value.limit()); + test(Arrays.equals(arr, usedSeq)); + arr = new float[bufferR.limit()]; + bufferR.get(arr, 0, bufferR.limit()); + test(Arrays.equals(arr, usedSeq)); + } + + { + final double[] fullSeq = new double[] {0, 1, 2, 3, 4, 5, 6, 7}; + final double[] usedSeq = new double[] {2, 3, 4, 5}; + + DoubleBuffer buffer = DoubleBuffer.wrap(fullSeq, 2, 4); + Ice.Holder<DoubleBuffer> bufferH = new Ice.Holder<DoubleBuffer>(); + DoubleBuffer bufferR = t.opDoubleBufferSeq(buffer, bufferH); + + double[] arr = new double[bufferH.value.limit()]; + bufferH.value.get(arr, 0, bufferH.value.limit()); + test(Arrays.equals(arr, usedSeq)); + arr = new double[bufferR.limit()]; + bufferR.get(arr, 0, bufferR.limit()); + test(Arrays.equals(arr, usedSeq)); + } + + out.println("ok"); + + return t; + } +} diff --git a/java/test/src/main/java/test/Ice/custom/Client.java b/java/test/src/main/java/test/Ice/custom/Client.java new file mode 100644 index 00000000000..17ad54b561f --- /dev/null +++ b/java/test/src/main/java/test/Ice/custom/Client.java @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.custom; + +import test.Ice.custom.Test.TestIntfPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + TestIntfPrx test = AllTests.allTests(communicator, getWriter()); + test.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.custom"); + initData.properties.setProperty("Ice.CacheMessageBuffers", "0"); + return initData; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/custom/Collocated.java b/java/test/src/main/java/test/Ice/custom/Collocated.java new file mode 100644 index 00000000000..2d8fd94f500 --- /dev/null +++ b/java/test/src/main/java/test/Ice/custom/Collocated.java @@ -0,0 +1,46 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.custom; + +public class Collocated extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object test = new TestI(communicator); + adapter.add(test, communicator.stringToIdentity("test")); + + AllTests.allTests(communicator, getWriter()); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.custom"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("Ice.CacheMessageBuffers", "0"); + return initData; + } + + public static void main(String[] args) + { + Collocated c = new Collocated(); + int status = c.main("Collocated", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/custom/Server.java b/java/test/src/main/java/test/Ice/custom/Server.java new file mode 100644 index 00000000000..fe959c086ff --- /dev/null +++ b/java/test/src/main/java/test/Ice/custom/Server.java @@ -0,0 +1,46 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.custom; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object test = new TestI(communicator); + adapter.add(test, communicator.stringToIdentity("test")); + + adapter.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.custom"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("Ice.CacheMessageBuffers", "0"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/custom/Test.ice b/java/test/src/main/java/test/Ice/custom/Test.ice new file mode 100644 index 00000000000..4743eb95492 --- /dev/null +++ b/java/test/src/main/java/test/Ice/custom/Test.ice @@ -0,0 +1,84 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/BuiltinSequences.ice> + +[["java:package:test.Ice.custom"]] +module Test +{ + +class C {}; + +sequence<C> CSeq; +["java:type:java.util.ArrayList<C>"] sequence<C> CArray; +["java:type:java.util.LinkedList<C>"] sequence<C> CList; + +["java:type:java.util.ArrayList<Boolean>"] sequence<bool> BoolSeq; +["java:type:java.util.ArrayList<Byte>"] sequence<byte> ByteSeq; +["java:type:java.util.ArrayList<Short>"] sequence<short> ShortSeq; +["java:type:java.util.ArrayList<Integer>"] sequence<int> IntSeq; +["java:type:java.util.ArrayList<Long>"] sequence<long> LongSeq; +["java:type:java.util.ArrayList<Float>"] sequence<float> FloatSeq; +["java:type:java.util.ArrayList<Double>"] sequence<double> DoubleSeq; +["java:type:java.util.ArrayList<String>"] sequence<string> StringSeq; + +["java:buffer"] sequence<byte> ByteBuffer; +["java:buffer"] sequence<short> ShortBuffer; +["java:buffer"] sequence<int> IntBuffer; +["java:buffer"] sequence<long> LongBuffer; +["java:buffer"] sequence<float> FloatBuffer; +["java:buffer"] sequence<double> DoubleBuffer; + +enum E { E1, E2, E3 }; +["java:type:java.util.ArrayList<E>"] sequence<E> ESeq; + +struct S +{ + E en; +}; +["java:type:java.util.ArrayList<S>"] sequence<S> SSeq; + +dictionary<int, string> D; +["java:type:java.util.ArrayList<java.util.Map<Integer,String>>"] sequence<D> DSeq; + +["java:type:java.util.LinkedList<java.util.List<String>>"] sequence<StringSeq> StringSeqSeq; + +class TestIntf +{ + CSeq opCSeq(CSeq inSeq, out CSeq outSeq); + CArray opCArray(CArray inSeq, out CArray outSeq); + CList opCList(CList inSeq, out CList outSeq); + BoolSeq opBoolSeq(BoolSeq inSeq, out BoolSeq outSeq); + ByteSeq opByteSeq(ByteSeq inSeq, out ByteSeq outSeq); + ShortSeq opShortSeq(ShortSeq inSeq, out ShortSeq outSeq); + IntSeq opIntSeq(IntSeq inSeq, out IntSeq outSeq); + LongSeq opLongSeq(LongSeq inSeq, out LongSeq outSeq); + FloatSeq opFloatSeq(FloatSeq inSeq, out FloatSeq outSeq); + DoubleSeq opDoubleSeq(DoubleSeq inSeq, out DoubleSeq outSeq); + StringSeq opStringSeq(StringSeq inSeq, out StringSeq outSeq); + ESeq opESeq(ESeq inSeq, out ESeq outSeq); + SSeq opSSeq(SSeq inSeq, out SSeq outSeq); + DSeq opDSeq(DSeq inSeq, out DSeq outSeq); + StringSeqSeq opStringSeqSeq(StringSeqSeq inSeq, out StringSeqSeq outSeq); + + ByteBuffer opByteBufferSeq(ByteBuffer inSeq, out ByteBuffer outSeq); + ShortBuffer opShortBufferSeq(ShortBuffer inSeq, out ShortBuffer outSeq); + IntBuffer opIntBufferSeq(IntBuffer inSeq, out IntBuffer outSeq); + LongBuffer opLongBufferSeq(LongBuffer inSeq, out LongBuffer outSeq); + FloatBuffer opFloatBufferSeq(FloatBuffer inSeq, out FloatBuffer outSeq); + DoubleBuffer opDoubleBufferSeq(DoubleBuffer inSeq, out DoubleBuffer outSeq); + + void shutdown(); + + ["java:type:java.util.ArrayList<C>"] CSeq seq; +}; + +}; diff --git a/java/test/src/main/java/test/Ice/custom/TestI.java b/java/test/src/main/java/test/Ice/custom/TestI.java new file mode 100644 index 00000000000..e384d531ffd --- /dev/null +++ b/java/test/src/main/java/test/Ice/custom/TestI.java @@ -0,0 +1,241 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.custom; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.nio.ByteBuffer; +import java.nio.ShortBuffer; +import java.nio.IntBuffer; +import java.nio.LongBuffer; +import java.nio.FloatBuffer; +import java.nio.DoubleBuffer; + +import test.Ice.custom.Test.BoolSeqHolder; +import test.Ice.custom.Test.ByteSeqHolder; +import test.Ice.custom.Test.C; +import test.Ice.custom.Test.CArrayHolder; +import test.Ice.custom.Test.CListHolder; +import test.Ice.custom.Test.CSeqHolder; +import test.Ice.custom.Test.DSeqHolder; +import test.Ice.custom.Test.DoubleSeqHolder; +import test.Ice.custom.Test.E; +import test.Ice.custom.Test.ESeqHolder; +import test.Ice.custom.Test.FloatSeqHolder; +import test.Ice.custom.Test.IntSeqHolder; +import test.Ice.custom.Test.LongSeqHolder; +import test.Ice.custom.Test.S; +import test.Ice.custom.Test.SSeqHolder; +import test.Ice.custom.Test.ShortSeqHolder; +import test.Ice.custom.Test.StringSeqHolder; +import test.Ice.custom.Test.StringSeqSeqHolder; +import test.Ice.custom.Test.TestIntf; + +public final class TestI extends TestIntf +{ + public + TestI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + @Override + public List<C> + opCArray(List<C> inSeq, CArrayHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public List<C> + opCList(List<C> inSeq, CListHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public C[] + opCSeq(C[] inSeq, CSeqHolder outSeq, Ice.Current current) + { + seq = new ArrayList<C>(Arrays.asList(inSeq)); + outSeq.value = new C[seq.size()]; + seq.toArray(outSeq.value); + return outSeq.value; + } + + @Override + public List<Boolean> + opBoolSeq(List<Boolean> inSeq, BoolSeqHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public List<Byte> + opByteSeq(List<Byte> inSeq, ByteSeqHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public List<Map<Integer,String>> + opDSeq(List<Map<Integer,String>> inSeq, DSeqHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public List<Double> + opDoubleSeq(List<Double> inSeq, DoubleSeqHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public List<E> + opESeq(List<E> inSeq, ESeqHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public List<Float> + opFloatSeq(List<Float> inSeq, FloatSeqHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public List<Integer> + opIntSeq(List<Integer> inSeq, IntSeqHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public List<Long> + opLongSeq(List<Long> inSeq, LongSeqHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public List<S> + opSSeq(List<S> inSeq, SSeqHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public List<Short> + opShortSeq(List<Short> inSeq, ShortSeqHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public List<String> + opStringSeq(List<String> inSeq, StringSeqHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public List<List<String>> + opStringSeqSeq(List<List<String>> inSeq, StringSeqSeqHolder outSeq, Ice.Current current) + { + outSeq.value = inSeq; + return inSeq; + } + + @Override + public ByteBuffer + opByteBufferSeq(ByteBuffer inSeq, Ice.Holder<ByteBuffer> outSeq, Ice.Current current) + { + byte[] arr = new byte[inSeq.limit()]; + inSeq.get(arr); + outSeq.value = ByteBuffer.wrap(arr); + return ByteBuffer.wrap(arr); + } + + @Override + public ShortBuffer + opShortBufferSeq(ShortBuffer inSeq, Ice.Holder<ShortBuffer> outSeq, Ice.Current current) + { + short[] arr = new short[inSeq.limit()]; + inSeq.get(arr); + outSeq.value = ShortBuffer.wrap(arr); + return ShortBuffer.wrap(arr); + } + + @Override + public IntBuffer + opIntBufferSeq(IntBuffer inSeq, Ice.Holder<IntBuffer> outSeq, Ice.Current current) + { + int[] arr = new int[inSeq.limit()]; + inSeq.get(arr); + outSeq.value = IntBuffer.wrap(arr); + return IntBuffer.wrap(arr); + } + + @Override + public LongBuffer + opLongBufferSeq(LongBuffer inSeq, Ice.Holder<LongBuffer> outSeq, Ice.Current current) + { + long[] arr = new long[inSeq.limit()]; + inSeq.get(arr); + outSeq.value = LongBuffer.wrap(arr); + return LongBuffer.wrap(arr); + } + + @Override + public FloatBuffer + opFloatBufferSeq(FloatBuffer inSeq, Ice.Holder<FloatBuffer> outSeq, Ice.Current current) + { + float[] arr = new float[inSeq.limit()]; + inSeq.get(arr); + outSeq.value = FloatBuffer.wrap(arr); + return FloatBuffer.wrap(arr); + } + + @Override + public DoubleBuffer + opDoubleBufferSeq(DoubleBuffer inSeq, Ice.Holder<DoubleBuffer> outSeq, Ice.Current current) + { + double[] arr = new double[inSeq.limit()]; + inSeq.get(arr); + outSeq.value = DoubleBuffer.wrap(arr); + return DoubleBuffer.wrap(arr); + } + + @Override + public void + shutdown(Ice.Current current) + { + _communicator.shutdown(); + } + + private Ice.Communicator _communicator; +} diff --git a/java/test/src/main/java/test/Ice/custom/run.py b/java/test/src/main/java/test/Ice/custom/run.py new file mode 100755 index 00000000000..8bb456187d9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/custom/run.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/defaultServant/AllTests.java b/java/test/src/main/java/test/Ice/defaultServant/AllTests.java new file mode 100644 index 00000000000..50589050baf --- /dev/null +++ b/java/test/src/main/java/test/Ice/defaultServant/AllTests.java @@ -0,0 +1,171 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.defaultServant; +import java.io.PrintWriter; +import test.Ice.defaultServant.Test.MyObjectPrx; +import test.Ice.defaultServant.Test.MyObjectPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + allTests(test.Util.Application app, PrintWriter out) + { + Ice.Communicator communicator = app.communicator(); + Ice.ObjectAdapter oa = communicator.createObjectAdapterWithEndpoints("MyOA", "tcp -h localhost"); + oa.activate(); + + Ice.Object servant = new MyObjectI(); + + // + // Register default servant with category "foo" + // + oa.addDefaultServant(servant, "foo"); + + // + // Start test + // + out.print("testing single category... "); + out.flush(); + + Ice.Object r = oa.findDefaultServant("foo"); + test(r == servant); + + r = oa.findDefaultServant("bar"); + test(r == null); + + Ice.Identity identity = new Ice.Identity(); + identity.category = "foo"; + + String names[] = { "foo", "bar", "x", "y", "abcdefg" }; + + for(int idx = 0; idx < 5; ++idx) + { + identity.name = names[idx]; + MyObjectPrx prx = MyObjectPrxHelper.uncheckedCast(oa.createProxy(identity)); + prx.ice_ping(); + test(prx.getName().equals(names[idx])); + } + + identity.name = "ObjectNotExist"; + MyObjectPrx prx = MyObjectPrxHelper.uncheckedCast(oa.createProxy(identity)); + try + { + prx.ice_ping(); + test(false); + } + catch(Ice.ObjectNotExistException ex) + { + // Expected + } + + try + { + prx.getName(); + test(false); + } + catch(Ice.ObjectNotExistException ex) + { + // Expected + } + + identity.name = "FacetNotExist"; + prx = MyObjectPrxHelper.uncheckedCast(oa.createProxy(identity)); + try + { + prx.ice_ping(); + test(false); + } + catch(Ice.FacetNotExistException ex) + { + // Expected + } + + try + { + prx.getName(); + test(false); + } + catch(Ice.FacetNotExistException ex) + { + // Expected + } + + identity.category = "bar"; + for(int idx = 0; idx < 5; idx++) + { + identity.name = names[idx]; + prx = MyObjectPrxHelper.uncheckedCast(oa.createProxy(identity)); + + try + { + prx.ice_ping(); + test(false); + } + catch(Ice.ObjectNotExistException ex) + { + // Expected + } + + try + { + prx.getName(); + test(false); + } + catch(Ice.ObjectNotExistException ex) + { + // Expected + } + } + + oa.removeDefaultServant("foo"); + identity.category = "foo"; + prx = MyObjectPrxHelper.uncheckedCast(oa.createProxy(identity)); + try + { + prx.ice_ping(); + } + catch(Ice.ObjectNotExistException ex) + { + // Expected + } + + out.println("ok"); + + out.print("testing default category... "); + out.flush(); + + oa.addDefaultServant(servant, ""); + + r = oa.findDefaultServant("bar"); + test(r == null); + + r = oa.findDefaultServant(""); + test(r == servant); + + for(int idx = 0; idx < 5; ++idx) + { + identity.name = names[idx]; + prx = MyObjectPrxHelper.uncheckedCast(oa.createProxy(identity)); + prx.ice_ping(); + test(prx.getName().equals(names[idx])); + } + + out.println("ok"); + } +} diff --git a/java/test/src/main/java/test/Ice/defaultServant/Client.java b/java/test/src/main/java/test/Ice/defaultServant/Client.java new file mode 100644 index 00000000000..4f9b3be9ec4 --- /dev/null +++ b/java/test/src/main/java/test/Ice/defaultServant/Client.java @@ -0,0 +1,30 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.defaultServant; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + AllTests.allTests(this, getWriter()); + + return 0; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/defaultServant/MyObjectI.java b/java/test/src/main/java/test/Ice/defaultServant/MyObjectI.java new file mode 100644 index 00000000000..64d4548f920 --- /dev/null +++ b/java/test/src/main/java/test/Ice/defaultServant/MyObjectI.java @@ -0,0 +1,48 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.defaultServant; +import test.Ice.defaultServant.Test.*; + +public final class MyObjectI extends _MyObjectDisp +{ + @Override + public void + ice_ping(Ice.Current current) + { + String name = current.id.name; + + if(name.equals("ObjectNotExist")) + { + throw new Ice.ObjectNotExistException(); + } + else if(name.equals("FacetNotExist")) + { + throw new Ice.FacetNotExistException(); + } + } + + @Override + public String + getName(Ice.Current current) + { + String name = current.id.name; + + if(name.equals("ObjectNotExist")) + { + throw new Ice.ObjectNotExistException(); + } + else if(name.equals("FacetNotExist")) + { + throw new Ice.FacetNotExistException(); + } + + return name; + } +} diff --git a/java/test/src/main/java/test/Ice/defaultServant/Test.ice b/java/test/src/main/java/test/Ice/defaultServant/Test.ice new file mode 100644 index 00000000000..ce986ce32c3 --- /dev/null +++ b/java/test/src/main/java/test/Ice/defaultServant/Test.ice @@ -0,0 +1,21 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.defaultServant"]] +module Test +{ + +interface MyObject +{ + string getName(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/defaultServant/run.py b/java/test/src/main/java/test/Ice/defaultServant/run.py new file mode 100755 index 00000000000..d36e7a611b3 --- /dev/null +++ b/java/test/src/main/java/test/Ice/defaultServant/run.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +sys.stdout.write("starting client... ") +sys.stdout.flush() +clientProc = TestUtil.startClient("test.Ice.defaultServant.Client", "--Ice.Warn.Dispatch=0",startReader=False) +print("ok") +clientProc.startReader() + +clientProc.waitTestSuccess() diff --git a/java/test/src/main/java/test/Ice/defaultValue/AllTests.java b/java/test/src/main/java/test/Ice/defaultValue/AllTests.java new file mode 100644 index 00000000000..a53a798bde6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/defaultValue/AllTests.java @@ -0,0 +1,170 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.defaultValue; + +import java.io.PrintWriter; +import test.Ice.defaultValue.Test.*; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + allTests(test.Util.Application app, PrintWriter out) + { + out.print("testing default values... "); + out.flush(); + + { + Struct1 v = new Struct1(); + test(!v.boolFalse); + test(v.boolTrue); + test(v.b == (byte)254); + test(v.s == 16000); + test(v.i == 3); + test(v.l == 4); + test(v.f == 5.1F); + test(v.d == 6.2); + test(v.str == "foo \\ \"bar\n \r\n\t\u000b\f\u0007\b? \u0007 \u0007"); + test(v.c1 == Color.red); + test(v.c2 == Color.green); + test(v.c3 == Color.blue); + test(v.nc1 == test.Ice.defaultValue.Test.Nested.Color.red); + test(v.nc2 == test.Ice.defaultValue.Test.Nested.Color.green); + test(v.nc3 == test.Ice.defaultValue.Test.Nested.Color.blue); + test(v.noDefault == null); + test(v.zeroI == 0); + test(v.zeroL == 0); + test(v.zeroF == 0); + test(v.zeroDotF == 0); + test(v.zeroD == 0); + test(v.zeroDotD == 0); + } + + { + Struct2 v = new Struct2(); + test(v.boolTrue == ConstBool.value); + test(v.b == ConstByte.value); + test(v.s == ConstShort.value); + test(v.i == ConstInt.value); + test(v.l == ConstLong.value); + test(v.f == ConstFloat.value); + test(v.d == ConstDouble.value); + test(v.str.equals(ConstString.value)); + test(v.c1 == ConstColor1.value); + test(v.c2 == ConstColor2.value); + test(v.c3 == ConstColor3.value); + test(v.nc1 == ConstNestedColor1.value); + test(v.nc2 == ConstNestedColor2.value); + test(v.nc3 == ConstNestedColor3.value); + } + + { + Base v = new Base(); + test(!v.boolFalse); + test(v.boolTrue); + test(v.b == 1); + test(v.s == 2); + test(v.i == 3); + test(v.l == 4); + test(v.f == 5.1F); + test(v.d == 6.2); + test(v.str.equals("foo \\ \"bar\n \r\n\t\u000b\f\u0007\b? \007 \u0007")); + test(v.noDefault == null); + test(v.zeroI == 0); + test(v.zeroL == 0); + test(v.zeroF == 0); + test(v.zeroDotF == 0); + test(v.zeroD == 0); + test(v.zeroDotD == 0); + } + + { + Derived v = new Derived(); + test(!v.boolFalse); + test(v.boolTrue); + test(v.b == 1); + test(v.s == 2); + test(v.i == 3); + test(v.l == 4); + test(v.f == 5.1F); + test(v.d == 6.2); + test(v.str.equals("foo \\ \"bar\n \r\n\t\u000b\f\u0007\b? \007 \u0007")); + test(v.c1 == Color.red); + test(v.c2 == Color.green); + test(v.c3 == Color.blue); + test(v.nc1 == test.Ice.defaultValue.Test.Nested.Color.red); + test(v.nc2 == test.Ice.defaultValue.Test.Nested.Color.green); + test(v.nc3 == test.Ice.defaultValue.Test.Nested.Color.blue); + test(v.noDefault == null); + test(v.zeroI == 0); + test(v.zeroL == 0); + test(v.zeroF == 0); + test(v.zeroDotF == 0); + test(v.zeroD == 0); + test(v.zeroDotD == 0); + } + + { + BaseEx v = new BaseEx(); + test(!v.boolFalse); + test(v.boolTrue); + test(v.b == 1); + test(v.s == 2); + test(v.i == 3); + test(v.l == 4); + test(v.f == 5.1F); + test(v.d == 6.2); + test(v.str == "foo \\ \"bar\n \r\n\t\u000b\f\u0007\b? \007 \u0007"); + test(v.noDefault == null); + test(v.zeroI == 0); + test(v.zeroL == 0); + test(v.zeroF == 0); + test(v.zeroDotF == 0); + test(v.zeroD == 0); + test(v.zeroDotD == 0); + } + + { + DerivedEx v = new DerivedEx(); + test(!v.boolFalse); + test(v.boolTrue); + test(v.b == 1); + test(v.s == 2); + test(v.i == 3); + test(v.l == 4); + test(v.f == 5.1F); + test(v.d == 6.2); + test(v.str == "foo \\ \"bar\n \r\n\t\u000b\f\u0007\b? \007 \u0007"); + test(v.noDefault == null); + test(v.c1 == Color.red); + test(v.c2 == Color.green); + test(v.c3 == Color.blue); + test(v.nc1 == test.Ice.defaultValue.Test.Nested.Color.red); + test(v.nc2 == test.Ice.defaultValue.Test.Nested.Color.green); + test(v.nc3 == test.Ice.defaultValue.Test.Nested.Color.blue); + test(v.zeroI == 0); + test(v.zeroL == 0); + test(v.zeroF == 0); + test(v.zeroDotF == 0); + test(v.zeroD == 0); + test(v.zeroDotD == 0); + } + + out.println("ok"); + } +} diff --git a/java/test/src/main/java/test/Ice/defaultValue/Client.java b/java/test/src/main/java/test/Ice/defaultValue/Client.java new file mode 100644 index 00000000000..78685aa1939 --- /dev/null +++ b/java/test/src/main/java/test/Ice/defaultValue/Client.java @@ -0,0 +1,29 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.defaultValue; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + AllTests.allTests(this, getWriter()); + return 0; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/defaultValue/Test.ice b/java/test/src/main/java/test/Ice/defaultValue/Test.ice new file mode 100644 index 00000000000..2c41e0a3293 --- /dev/null +++ b/java/test/src/main/java/test/Ice/defaultValue/Test.ice @@ -0,0 +1,156 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.defaultValue"]] +module Test +{ + +enum Color { red, green, blue }; + +module Nested +{ + +enum Color { red, green, blue }; + +}; + +struct Struct1 +{ + bool boolFalse = false; + bool boolTrue = true; + byte b = 254; + short s = 16000; + int i = 3; + long l = 4; + float f = 5.1; + double d = 6.2; + string str = "foo \\ \"bar\n \r\n\t\v\f\a\b\? \007 \x07"; + Color c1 = ::Test::red; + Color c2 = Test::green; + Color c3 = blue; + Nested::Color nc1 = ::Test::Nested::red; + Nested::Color nc2 = Nested::green; + Nested::Color nc3 = Nested::blue; + string noDefault; + int zeroI = 0; + long zeroL = 0; + float zeroF = 0; + float zeroDotF = 0.0; + double zeroD = 0; + double zeroDotD = 0; +}; + +const bool ConstBool = true; +const byte ConstByte = 254; +const short ConstShort = 16000; +const int ConstInt = 3; +const long ConstLong = 4; +const float ConstFloat = 5.1; +const double ConstDouble = 6.2; +const string ConstString = "foo \\ \"bar\n \r\n\t\v\f\a\b\? \007 \x07"; +const Color ConstColor1 = ::Test::red; +const Color ConstColor2 = Test::green; +const Color ConstColor3 = blue; +const Nested::Color ConstNestedColor1 = ::Test::Nested::red; +const Nested::Color ConstNestedColor2 = Test::Nested::green; +const Nested::Color ConstNestedColor3 = Nested::blue; +const int ConstZeroI = 0; +const long ConstZeroL = 0; +const float ConstZeroF = 0; +const float ConstZeroDotF = 0.0; +const double ConstZeroD = 0; +const double ConstZeroDotD = 0; + +struct Struct2 +{ + bool boolTrue = ConstBool; + byte b = ConstByte; + short s = ConstShort; + int i = ConstInt; + long l = ConstLong; + float f = ConstFloat; + double d = ConstDouble; + string str = ConstString; + Color c1 = ConstColor1; + Color c2 = ConstColor2; + Color c3 = ConstColor3; + Nested::Color nc1 = ConstNestedColor1; + Nested::Color nc2 = ConstNestedColor2; + Nested::Color nc3 = ConstNestedColor3; + int zeroI = ConstZeroI; + long zeroL = ConstZeroL; + float zeroF = ConstZeroF; + float zeroDotF = ConstZeroDotF; + double zeroD = ConstZeroD; + double zeroDotD = ConstZeroDotD; +}; + +class Base +{ + bool boolFalse = false; + bool boolTrue = true; + byte b = 1; + short s = 2; + int i = 3; + long l = 4; + float f = 5.1; + double d = 6.2; + string str = "foo \\ \"bar\n \r\n\t\v\f\a\b\? \007 \x07"; + string noDefault; + int zeroI = 0; + long zeroL = 0; + float zeroF = 0; + float zeroDotF = 0.0; + double zeroD = 0; + double zeroDotD = 0; +}; + +class Derived extends Base +{ + Color c1 = ::Test::red; + Color c2 = Test::green; + Color c3 = blue; + Nested::Color nc1 = ::Test::Nested::red; + Nested::Color nc2 = Nested::green; + Nested::Color nc3 = Nested::blue; +}; + +exception BaseEx +{ + bool boolFalse = false; + bool boolTrue = true; + byte b = 1; + short s = 2; + int i = 3; + long l = 4; + float f = 5.1; + double d = 6.2; + string str = "foo \\ \"bar\n \r\n\t\v\f\a\b\? \007 \x07"; + string noDefault; + int zeroI = 0; + long zeroL = 0; + float zeroF = 0; + float zeroDotF = 0.0; + double zeroD = 0; + double zeroDotD = 0; +}; + +exception DerivedEx extends BaseEx +{ + Color c1 = ConstColor1; + Color c2 = ConstColor2; + Color c3 = ConstColor3; + Nested::Color nc1 = ConstNestedColor1; + Nested::Color nc2 = ConstNestedColor2; + Nested::Color nc3 = ConstNestedColor3; +}; + +}; diff --git a/java/test/src/main/java/test/Ice/defaultValue/run.py b/java/test/src/main/java/test/Ice/defaultValue/run.py new file mode 100755 index 00000000000..06025e5d073 --- /dev/null +++ b/java/test/src/main/java/test/Ice/defaultValue/run.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +sys.stdout.write("starting client... ") +sys.stdout.flush() +clientProc = TestUtil.startClient("test.Ice.defaultValue.Client",startReader=False) +print("ok") +clientProc.startReader() +clientProc.waitTestSuccess() diff --git a/java/test/src/main/java/test/Ice/dispatcher/AllTests.java b/java/test/src/main/java/test/Ice/dispatcher/AllTests.java new file mode 100644 index 00000000000..e1badc24a9a --- /dev/null +++ b/java/test/src/main/java/test/Ice/dispatcher/AllTests.java @@ -0,0 +1,229 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.dispatcher; + +import java.io.PrintWriter; + +import test.Ice.dispatcher.Test.TestIntfPrx; +import test.Ice.dispatcher.Test.TestIntfPrxHelper; +import test.Ice.dispatcher.Test.TestIntfControllerPrx; +import test.Ice.dispatcher.Test.TestIntfControllerPrxHelper; +import test.Ice.dispatcher.Test.Callback_TestIntf_op; +import test.Ice.dispatcher.Test.Callback_TestIntf_opWithPayload; +import test.Ice.dispatcher.Test.Callback_TestIntf_sleep; + +public class AllTests +{ + private static abstract class OpCallback extends Callback_TestIntf_op + { + OpCallback() + { + _called = false; + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + allTests(Ice.Communicator communicator, PrintWriter out, final Dispatcher dispatcher) + { + String sref = "test:default -p 12010"; + Ice.ObjectPrx obj = communicator.stringToProxy(sref); + test(obj != null); + + int mult = 1; + if(!communicator.getProperties().getPropertyWithDefault("Ice.Default.Protocol", "tcp").equals("tcp")) + { + mult = 4; + } + + TestIntfPrx p = TestIntfPrxHelper.uncheckedCast(obj); + + sref = "testController:tcp -p 12011"; + obj = communicator.stringToProxy(sref); + test(obj != null); + + TestIntfControllerPrx testController = TestIntfControllerPrxHelper.uncheckedCast(obj); + + out.print("testing dispatcher... "); + out.flush(); + { + p.op(); + + OpCallback cb = new OpCallback() + { + @Override + public void + response() + { + test(dispatcher.isDispatcherThread()); + called(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + }; + p.begin_op(cb); + cb.check(); + + TestIntfPrx i = (TestIntfPrx)p.ice_adapterId("dummy"); + cb = new OpCallback() + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(ex instanceof Ice.NoEndpointException); + test(dispatcher.isDispatcherThread()); + called(); + } + }; + i.begin_op(cb); + cb.check(); + + { + // + // Expect InvocationTimeoutException. + // + TestIntfPrx to = TestIntfPrxHelper.uncheckedCast(p.ice_invocationTimeout(250)); + class Callback_TestIntf_sleepImpl extends Callback_TestIntf_sleep + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(ex instanceof Ice.InvocationTimeoutException); + test(dispatcher.isDispatcherThread()); + called(); + } + + @Override + public void + sent(boolean sentSynchronously) + { + test(sentSynchronously || dispatcher.isDispatcherThread()); + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + private synchronized void called() + { + assert(!_called); + _called = true; + notify(); + } + private boolean _called; + }; + Callback_TestIntf_sleepImpl callback = new Callback_TestIntf_sleepImpl(); + to.begin_sleep(500 * mult, callback); + callback.check(); + } + + testController.holdAdapter(); + Callback_TestIntf_opWithPayload callback = new Callback_TestIntf_opWithPayload() + { + @Override + public void + response() + { + test(dispatcher.isDispatcherThread()); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(ex instanceof Ice.CommunicatorDestroyedException); + } + + @Override + public void + sent(boolean sentSynchronously) + { + test(sentSynchronously || dispatcher.isDispatcherThread()); + } + }; + + byte[] seq = new byte[10 * 1024]; + new java.util.Random().nextBytes(seq); // Make sure the request doesn't compress too well. + Ice.AsyncResult r; + while((r = p.begin_opWithPayload(seq, callback)).sentSynchronously()); + testController.resumeAdapter(); + r.waitForCompleted(); + } + out.println("ok"); + + p.shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/dispatcher/Client.java b/java/test/src/main/java/test/Ice/dispatcher/Client.java new file mode 100644 index 00000000000..9b490d763c1 --- /dev/null +++ b/java/test/src/main/java/test/Ice/dispatcher/Client.java @@ -0,0 +1,54 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.dispatcher; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + AllTests.allTests(communicator(), getWriter(), _dispatcher); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + assert(_dispatcher == null); + _dispatcher = new Dispatcher(); + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.dispatcher"); + initData.dispatcher = _dispatcher; + return initData; + } + + Dispatcher getDispatcher() + { + return _dispatcher; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + app.getDispatcher().terminate(); + System.gc(); + System.exit(result); + } + + // + // The Dispatcher class uses a static "_instance" member in other language + // mappings. In Java, we avoid the use of static members because we need to + // maintain support for Android (in which the client and server run in the + // same process). + // + private Dispatcher _dispatcher; +} diff --git a/java/test/src/main/java/test/Ice/dispatcher/Collocated.java b/java/test/src/main/java/test/Ice/dispatcher/Collocated.java new file mode 100644 index 00000000000..453311a3584 --- /dev/null +++ b/java/test/src/main/java/test/Ice/dispatcher/Collocated.java @@ -0,0 +1,66 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.dispatcher; + +public class Collocated extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + Ice.ObjectAdapter adapter2 = communicator().createObjectAdapter("ControllerAdapter"); + + assert(_dispatcher != null); + adapter.add(new TestI(_dispatcher), communicator().stringToIdentity("test")); + //adapter.activate(); + adapter2.add(new TestControllerI(adapter), communicator().stringToIdentity("testController")); + //adapter2.activate(); + + AllTests.allTests(communicator(), getWriter(), _dispatcher); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + assert(_dispatcher == null); + _dispatcher = new Dispatcher(); + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.dispatcher"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("ControllerAdapter.Endpoints", "tcp -p 12011"); + initData.properties.setProperty("ControllerAdapter.ThreadPool.Size", "1"); + initData.dispatcher = _dispatcher; + return initData; + } + + Dispatcher getDispatcher() + { + return _dispatcher; + } + + public static void main(String[] args) + { + Collocated app = new Collocated(); + int result = app.main("Collocated", args); + app.getDispatcher().terminate(); + System.gc(); + System.exit(result); + } + + // + // The Dispatcher class uses a static "_instance" member in other language + // mappings. In Java, we avoid the use of static members because we need to + // maintain support for Android (in which the client and server run in the + // same process). + // + private Dispatcher _dispatcher; +} diff --git a/java/test/src/main/java/test/Ice/dispatcher/Dispatcher.java b/java/test/src/main/java/test/Ice/dispatcher/Dispatcher.java new file mode 100644 index 00000000000..2ee5dbb6f4d --- /dev/null +++ b/java/test/src/main/java/test/Ice/dispatcher/Dispatcher.java @@ -0,0 +1,117 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.dispatcher; + +public class Dispatcher implements Runnable, Ice.Dispatcher +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public Dispatcher() + { + _thread = new Thread(this); + _thread.start(); + } + + @Override + public void + run() + { + while(true) + { + Runnable call = null; + synchronized(this) + { + if(!_terminated && _calls.isEmpty()) + { + try + { + wait(); + } + catch(java.lang.InterruptedException ex) + { + } + } + + if(!_calls.isEmpty()) + { + call = _calls.poll(); + } + else if(_terminated) + { + // Terminate only once all calls are dispatched. + return; + } + } + + if(call != null) + { + try + { + call.run(); + } + catch(Exception ex) + { + // Exceptions should never propagate here. + test(false); + } + } + } + } + + @Override + synchronized public void + dispatch(Runnable call, Ice.Connection con) + { + boolean added = _calls.offer(call); + assert(added); + if(_calls.size() == 1) + { + notify(); + } + } + + public void + terminate() + { + synchronized(this) + { + _terminated = true; + notify(); + } + while(true) + { + try + { + _thread.join(); + break; + } + catch(java.lang.InterruptedException ex) + { + } + } + } + + public boolean + isDispatcherThread() + { + return Thread.currentThread() == _thread; + } + + private java.util.Queue<Runnable> _calls = new java.util.LinkedList<Runnable>(); + private Thread _thread; + private boolean _terminated = false; +} diff --git a/java/test/src/main/java/test/Ice/dispatcher/Server.java b/java/test/src/main/java/test/Ice/dispatcher/Server.java new file mode 100644 index 00000000000..c4ef87e7451 --- /dev/null +++ b/java/test/src/main/java/test/Ice/dispatcher/Server.java @@ -0,0 +1,70 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.dispatcher; + +public class Server extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + Ice.ObjectAdapter adapter2 = communicator().createObjectAdapter("ControllerAdapter"); + + assert(_dispatcher != null); + adapter.add(new TestI(_dispatcher), communicator().stringToIdentity("test")); + adapter.activate(); + adapter2.add(new TestControllerI(adapter), communicator().stringToIdentity("testController")); + adapter2.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + assert(_dispatcher == null); + _dispatcher = new Dispatcher(); + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.dispatcher"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("ControllerAdapter.Endpoints", "tcp -p 12011"); + initData.properties.setProperty("ControllerAdapter.ThreadPool.Size", "1"); + initData.dispatcher = _dispatcher; + return initData; + } + + public void terminate() + { + if(_dispatcher != null) + { + _dispatcher.terminate(); + } + } + + public static void + main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + app.terminate(); + System.gc(); + System.exit(result); + } + + // + // The Dispatcher class uses a static "_instance" member in other language + // mappings. In Java, we avoid the use of static members because we need to + // maintain support for Android (in which the client and server run in the + // same process). + // + private Dispatcher _dispatcher; +} diff --git a/java/test/src/main/java/test/Ice/dispatcher/Test.ice b/java/test/src/main/java/test/Ice/dispatcher/Test.ice new file mode 100644 index 00000000000..bbeabc2210a --- /dev/null +++ b/java/test/src/main/java/test/Ice/dispatcher/Test.ice @@ -0,0 +1,32 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/BuiltinSequences.ice> + +[["java:package:test.Ice.dispatcher"]] +module Test +{ + +interface TestIntf +{ + void op(); + void sleep(int to); + void opWithPayload(Ice::ByteSeq seq); + void shutdown(); +}; + +interface TestIntfController +{ + void holdAdapter(); + void resumeAdapter(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/dispatcher/TestControllerI.java b/java/test/src/main/java/test/Ice/dispatcher/TestControllerI.java new file mode 100644 index 00000000000..cd24a7982b3 --- /dev/null +++ b/java/test/src/main/java/test/Ice/dispatcher/TestControllerI.java @@ -0,0 +1,37 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.dispatcher; + +import test.Ice.dispatcher.Test._TestIntfControllerDisp; + +class TestControllerI extends _TestIntfControllerDisp +{ + @Override + public void + holdAdapter(Ice.Current current) + { + _adapter.hold(); + } + + @Override + public void + resumeAdapter(Ice.Current current) + { + _adapter.activate(); + } + + public + TestControllerI(Ice.ObjectAdapter adapter) + { + _adapter = adapter; + } + + final private Ice.ObjectAdapter _adapter; +} diff --git a/java/test/src/main/java/test/Ice/dispatcher/TestI.java b/java/test/src/main/java/test/Ice/dispatcher/TestI.java new file mode 100644 index 00000000000..93dd8513ecc --- /dev/null +++ b/java/test/src/main/java/test/Ice/dispatcher/TestI.java @@ -0,0 +1,66 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.dispatcher; + +import test.Ice.dispatcher.Test._TestIntfDisp; + +public class TestI extends _TestIntfDisp +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + TestI(Dispatcher dispatcher) + { + _dispatcher = dispatcher; + } + + @Override + public void + op(Ice.Current current) + { + test(_dispatcher.isDispatcherThread()); + } + + @Override + public void + sleep(int to, Ice.Current current) + { + try + { + Thread.currentThread(); + Thread.sleep(to); + } + catch(InterruptedException ex) + { + } + } + + @Override + public void + opWithPayload(byte[] seq, Ice.Current current) + { + test(_dispatcher.isDispatcherThread()); + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + private Dispatcher _dispatcher; +} diff --git a/java/test/src/main/java/test/Ice/dispatcher/run.py b/java/test/src/main/java/test/Ice/dispatcher/run.py new file mode 100755 index 00000000000..6444a527f9a --- /dev/null +++ b/java/test/src/main/java/test/Ice/dispatcher/run.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("tests with regular server.") +TestUtil.clientServerTest() +print("tests with collocated server.") +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/echo/BlobjectI.java b/java/test/src/main/java/test/Ice/echo/BlobjectI.java new file mode 100644 index 00000000000..946284608c1 --- /dev/null +++ b/java/test/src/main/java/test/Ice/echo/BlobjectI.java @@ -0,0 +1,109 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.echo; + +public class BlobjectI extends Ice.BlobjectAsync +{ + class Callback extends Ice.Callback_Object_ice_invoke + { + public Callback(Ice.AMD_Object_ice_invoke cb, boolean twoway) + { + _cb = cb; + _twoway = twoway; + } + + @Override + public void response(boolean ok, byte[] encaps) + { + _cb.ice_response(ok, encaps); + } + + @Override + public void exception(Ice.LocalException ex) + { + _cb.ice_exception(ex); + } + + @Override + public void sent(boolean sync) + { + if(!_twoway) + { + _cb.ice_response(true, new byte[0]); + } + } + + final Ice.AMD_Object_ice_invoke _cb; + final boolean _twoway; + }; + + public void startBatch() + { + assert(_batchProxy == null); + _startBatch = true; + } + + public void flushBatch() + { + assert(_batchProxy != null); + _batchProxy.ice_flushBatchRequests(); + _batchProxy = null; + } + + @Override + public void + ice_invoke_async(Ice.AMD_Object_ice_invoke amdCb, byte[] inEncaps, Ice.Current current) + { + boolean twoway = current.requestId > 0; + Ice.ObjectPrx obj = current.con.createProxy(current.id); + if(!twoway) + { + if(_startBatch) + { + _startBatch = false; + _batchProxy = obj.ice_batchOneway(); + } + if(_batchProxy != null) + { + obj = _batchProxy; + } + + if(!current.facet.isEmpty()) + { + obj = obj.ice_facet(current.facet); + } + + if(_batchProxy != null) + { + Ice.ByteSeqHolder out = new Ice.ByteSeqHolder(); + obj.ice_invoke(current.operation, current.mode, inEncaps, out, current.ctx); + amdCb.ice_response(true, new byte[0]); + } + else + { + Callback cb = new Callback(amdCb, false); + obj.ice_oneway().begin_ice_invoke(current.operation, current.mode, inEncaps, current.ctx, cb); + } + } + else + { + if(!current.facet.isEmpty()) + { + obj = obj.ice_facet(current.facet); + } + + Callback cb = new Callback(amdCb, true); + obj.begin_ice_invoke(current.operation, current.mode, inEncaps, current.ctx, cb); + } + } + + private Ice.ObjectPrx _batchProxy; + private boolean _startBatch; +} diff --git a/java/test/src/main/java/test/Ice/echo/Server.java b/java/test/src/main/java/test/Ice/echo/Server.java new file mode 100644 index 00000000000..88daf466e01 --- /dev/null +++ b/java/test/src/main/java/test/Ice/echo/Server.java @@ -0,0 +1,71 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.echo; + +public class Server extends test.Util.Application +{ + class EchoI extends test.Ice.echo.Test._EchoDisp + { + public EchoI(BlobjectI blob) + { + _blob = blob; + } + + @Override + public void startBatch(Ice.Current current) + { + _blob.startBatch(); + } + + @Override + public void flushBatch(Ice.Current current) + { + _blob.flushBatch(); + } + + @Override + public void shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + final private BlobjectI _blob; + }; + + @Override + public int run(String[] args) + { + communicator().getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010"); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + BlobjectI blob = new BlobjectI(); + adapter.addDefaultServant(blob, ""); + adapter.add(new EchoI(blob), communicator().stringToIdentity("__echo")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.echo"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/echo/Test.ice b/java/test/src/main/java/test/Ice/echo/Test.ice new file mode 100644 index 00000000000..6528f1a7501 --- /dev/null +++ b/java/test/src/main/java/test/Ice/echo/Test.ice @@ -0,0 +1,26 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.echo"]] +module Test +{ + +// +// This object is available with the identity "__echo". +// +interface Echo +{ + void startBatch(); + void flushBatch(); + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/echo/run.py b/java/test/src/main/java/test/Ice/echo/run.py new file mode 100755 index 00000000000..de17f7cd696 --- /dev/null +++ b/java/test/src/main/java/test/Ice/echo/run.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +sys.stdout.write("starting server... ") +sys.stdout.flush() +p = TestUtil.startServer("test.Ice.echo.Server") +print("ok") + +p.waitTestSuccess() diff --git a/java/test/src/main/java/test/Ice/enums/AllTests.java b/java/test/src/main/java/test/Ice/enums/AllTests.java new file mode 100644 index 00000000000..47aef9c0c83 --- /dev/null +++ b/java/test/src/main/java/test/Ice/enums/AllTests.java @@ -0,0 +1,273 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.enums; + +import test.Ice.enums.Test.*; +import java.io.PrintWriter; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static TestIntfPrx + allTests(Ice.Communicator communicator, PrintWriter out) + { + String ref = "test:default -p 12010"; + Ice.ObjectPrx obj = communicator.stringToProxy(ref); + test(obj != null); + TestIntfPrx proxy = TestIntfPrxHelper.checkedCast(obj); + test(proxy != null); + + out.print("testing enum values... "); + out.flush(); + + test(ByteEnum.benum1.value() == 0); + test(ByteEnum.benum2.value() == 1); + test(ByteEnum.benum3.value() == ByteConst1.value); + test(ByteEnum.benum4.value() == ByteConst1.value + 1); + test(ByteEnum.benum5.value() == ShortConst1.value); + test(ByteEnum.benum6.value() == ShortConst1.value + 1); + test(ByteEnum.benum7.value() == IntConst1.value); + test(ByteEnum.benum8.value() == IntConst1.value + 1); + test(ByteEnum.benum9.value() == LongConst1.value); + test(ByteEnum.benum10.value() == LongConst1.value + 1); + test(ByteEnum.benum11.value() == ByteConst2.value); + + test(ByteEnum.valueOf(0) == ByteEnum.benum1); + test(ByteEnum.valueOf(1) == ByteEnum.benum2); + test(ByteEnum.valueOf(ByteConst1.value) == ByteEnum.benum3); + test(ByteEnum.valueOf(ByteConst1.value + 1) == ByteEnum.benum4); + test(ByteEnum.valueOf(ShortConst1.value) == ByteEnum.benum5); + test(ByteEnum.valueOf(ShortConst1.value + 1) == ByteEnum.benum6); + test(ByteEnum.valueOf(IntConst1.value) == ByteEnum.benum7); + test(ByteEnum.valueOf(IntConst1.value + 1) == ByteEnum.benum8); + test(ByteEnum.valueOf((int)LongConst1.value) == ByteEnum.benum9); + test(ByteEnum.valueOf((int)LongConst1.value + 1) == ByteEnum.benum10); + test(ByteEnum.valueOf(ByteConst2.value) == ByteEnum.benum11); + + test(ShortEnum.senum1.value() == 3); + test(ShortEnum.senum2.value() == 4); + test(ShortEnum.senum3.value() == ByteConst1.value); + test(ShortEnum.senum4.value() == ByteConst1.value + 1); + test(ShortEnum.senum5.value() == ShortConst1.value); + test(ShortEnum.senum6.value() == ShortConst1.value + 1); + test(ShortEnum.senum7.value() == IntConst1.value); + test(ShortEnum.senum8.value() == IntConst1.value + 1); + test(ShortEnum.senum9.value() == LongConst1.value); + test(ShortEnum.senum10.value() == LongConst1.value + 1); + test(ShortEnum.senum11.value() == ShortConst2.value); + + test(ShortEnum.valueOf(3) == ShortEnum.senum1); + test(ShortEnum.valueOf(4) == ShortEnum.senum2); + test(ShortEnum.valueOf(ByteConst1.value) == ShortEnum.senum3); + test(ShortEnum.valueOf(ByteConst1.value + 1) == ShortEnum.senum4); + test(ShortEnum.valueOf(ShortConst1.value) == ShortEnum.senum5); + test(ShortEnum.valueOf(ShortConst1.value + 1) == ShortEnum.senum6); + test(ShortEnum.valueOf(IntConst1.value) == ShortEnum.senum7); + test(ShortEnum.valueOf(IntConst1.value + 1) == ShortEnum.senum8); + test(ShortEnum.valueOf((int)LongConst1.value) == ShortEnum.senum9); + test(ShortEnum.valueOf((int)LongConst1.value + 1) == ShortEnum.senum10); + test(ShortEnum.valueOf(ShortConst2.value) == ShortEnum.senum11); + + test(IntEnum.ienum1.value() == 0); + test(IntEnum.ienum2.value() == 1); + test(IntEnum.ienum3.value() == ByteConst1.value); + test(IntEnum.ienum4.value() == ByteConst1.value + 1); + test(IntEnum.ienum5.value() == ShortConst1.value); + test(IntEnum.ienum6.value() == ShortConst1.value + 1); + test(IntEnum.ienum7.value() == IntConst1.value); + test(IntEnum.ienum8.value() == IntConst1.value + 1); + test(IntEnum.ienum9.value() == LongConst1.value); + test(IntEnum.ienum10.value() == LongConst1.value + 1); + test(IntEnum.ienum11.value() == IntConst2.value); + test(IntEnum.ienum12.value() == LongConst2.value); + + test(IntEnum.valueOf(0) == IntEnum.ienum1); + test(IntEnum.valueOf(1) == IntEnum.ienum2); + test(IntEnum.valueOf(ByteConst1.value) == IntEnum.ienum3); + test(IntEnum.valueOf(ByteConst1.value + 1) == IntEnum.ienum4); + test(IntEnum.valueOf(ShortConst1.value) == IntEnum.ienum5); + test(IntEnum.valueOf(ShortConst1.value + 1) == IntEnum.ienum6); + test(IntEnum.valueOf(IntConst1.value) == IntEnum.ienum7); + test(IntEnum.valueOf(IntConst1.value + 1) == IntEnum.ienum8); + test(IntEnum.valueOf((int)LongConst1.value) == IntEnum.ienum9); + test(IntEnum.valueOf((int)LongConst1.value + 1) == IntEnum.ienum10); + test(IntEnum.valueOf(IntConst2.value) == IntEnum.ienum11); + test(IntEnum.valueOf((int)LongConst2.value) == IntEnum.ienum12); + + test(SimpleEnum.red.value() == 0); + test(SimpleEnum.green.value() == 1); + test(SimpleEnum.blue.value() == 2); + + test(SimpleEnum.valueOf(0) == SimpleEnum.red); + test(SimpleEnum.valueOf(1) == SimpleEnum.green); + test(SimpleEnum.valueOf(2) == SimpleEnum.blue); + + out.println("ok"); + + out.print("testing enum streaming... "); + out.flush(); + + Ice.OutputStream os; + byte[] bytes; + + final boolean encoding_1_0 = + communicator.getProperties().getProperty("Ice.Default.EncodingVersion").equals("1.0"); + + os = Ice.Util.createOutputStream(communicator); + ByteEnum.benum11.ice_write(os); + bytes = os.finished(); + test(bytes.length == 1); // ByteEnum should require one byte + + os = Ice.Util.createOutputStream(communicator); + ShortEnum.senum11.ice_write(os); + bytes = os.finished(); + test(bytes.length == (encoding_1_0 ? 2 : 5)); + + os = Ice.Util.createOutputStream(communicator); + IntEnum.ienum11.ice_write(os); + bytes = os.finished(); + test(bytes.length == (encoding_1_0 ? 4 : 5)); + + os = Ice.Util.createOutputStream(communicator); + SimpleEnum.blue.ice_write(os); + bytes = os.finished(); + test(bytes.length == 1); // SimpleEnum should require one byte + + out.println("ok"); + + out.print("testing enum operations... "); + out.flush(); + + ByteEnumHolder byteEnum = new ByteEnumHolder(); + test(proxy.opByte(ByteEnum.benum1, byteEnum) == ByteEnum.benum1); + test(byteEnum.value == ByteEnum.benum1); + test(proxy.opByte(ByteEnum.benum11, byteEnum) == ByteEnum.benum11); + test(byteEnum.value == ByteEnum.benum11); + + ShortEnumHolder shortEnum = new ShortEnumHolder(); + test(proxy.opShort(ShortEnum.senum1, shortEnum) == ShortEnum.senum1); + test(shortEnum.value == ShortEnum.senum1); + test(proxy.opShort(ShortEnum.senum11, shortEnum) == ShortEnum.senum11); + test(shortEnum.value == ShortEnum.senum11); + + IntEnumHolder intEnum = new IntEnumHolder(); + test(proxy.opInt(IntEnum.ienum1, intEnum) == IntEnum.ienum1); + test(intEnum.value == IntEnum.ienum1); + test(proxy.opInt(IntEnum.ienum11, intEnum) == IntEnum.ienum11); + test(intEnum.value == IntEnum.ienum11); + test(proxy.opInt(IntEnum.ienum12, intEnum) == IntEnum.ienum12); + test(intEnum.value == IntEnum.ienum12); + + SimpleEnumHolder s = new SimpleEnumHolder(); + test(proxy.opSimple(SimpleEnum.green, s) == SimpleEnum.green); + test(s.value == SimpleEnum.green); + + out.println("ok"); + + out.print("testing enum exceptions... "); + out.flush(); + + try + { + os = Ice.Util.createOutputStream(communicator); + os.writeByte((byte)2); // Invalid enumerator + Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + ByteEnum.ice_read(in); + test(false); + } + catch(Ice.MarshalException ex) + { + } + + try + { + os = Ice.Util.createOutputStream(communicator); + os.writeByte((byte)128); // Invalid enumerator + Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + ByteEnum.ice_read(in); + test(false); + } + catch(Ice.MarshalException ex) + { + } + + try + { + os = Ice.Util.createOutputStream(communicator); + os.writeShort((short)-1); // Negative enumerators are not supported + Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + ShortEnum.ice_read(in); + test(false); + } + catch(Ice.MarshalException ex) + { + } + + try + { + os = Ice.Util.createOutputStream(communicator); + os.writeShort((short)0); // Invalid enumerator + Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + ShortEnum.ice_read(in); + test(false); + } + catch(Ice.MarshalException ex) + { + } + + try + { + os = Ice.Util.createOutputStream(communicator); + os.writeShort((short)32767); // Invalid enumerator + Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + ShortEnum.ice_read(in); + test(false); + } + catch(Ice.MarshalException ex) + { + } + + try + { + os = Ice.Util.createOutputStream(communicator); + os.writeInt(-1); // Negative enumerators are not supported + Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + IntEnum.ice_read(in); + test(false); + } + catch(Ice.MarshalException ex) + { + } + + try + { + os = Ice.Util.createOutputStream(communicator); + os.writeInt(2); // Invalid enumerator + Ice.InputStream in = Ice.Util.createInputStream(communicator, os.finished()); + IntEnum.ice_read(in); + test(false); + } + catch(Ice.MarshalException ex) + { + } + + out.println("ok"); + + return proxy; + } +} diff --git a/java/test/src/main/java/test/Ice/enums/Client.java b/java/test/src/main/java/test/Ice/enums/Client.java new file mode 100644 index 00000000000..f27ee458960 --- /dev/null +++ b/java/test/src/main/java/test/Ice/enums/Client.java @@ -0,0 +1,42 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.enums; + +import test.Ice.enums.Test.TestIntfPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + TestIntfPrx test = AllTests.allTests(communicator, getWriter()); + test.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.enums"); + return initData; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/enums/Server.java b/java/test/src/main/java/test/Ice/enums/Server.java new file mode 100644 index 00000000000..24ef6d00730 --- /dev/null +++ b/java/test/src/main/java/test/Ice/enums/Server.java @@ -0,0 +1,45 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.enums; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object test = new TestIntfI(); + adapter.add(test, communicator.stringToIdentity("test")); + + adapter.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.enums"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/enums/Test.ice b/java/test/src/main/java/test/Ice/enums/Test.ice new file mode 100644 index 00000000000..5f7f84ec899 --- /dev/null +++ b/java/test/src/main/java/test/Ice/enums/Test.ice @@ -0,0 +1,89 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.enums"]] +module Test +{ + +const byte ByteConst1 = 10; +const short ShortConst1 = 20; +const int IntConst1 = 30; +const long LongConst1 = 40; + +const byte ByteConst2 = 126; +const short ShortConst2 = 32766; +const int IntConst2 = 2147483647; +const long LongConst2 = 2147483646; + +enum ByteEnum +{ + benum1, + benum2, + benum3 = ByteConst1, + benum4, + benum5 = ShortConst1, + benum6, + benum7 = IntConst1, + benum8, + benum9 = LongConst1, + benum10, + benum11 = ByteConst2 +}; + +enum ShortEnum +{ + senum1 = 3, + senum2, + senum3 = ByteConst1, + senum4, + senum5 = ShortConst1, + senum6, + senum7 = IntConst1, + senum8, + senum9 = LongConst1, + senum10, + senum11 = ShortConst2 +}; + +enum IntEnum +{ + ienum1, + ienum2, + ienum3 = ByteConst1, + ienum4, + ienum5 = ShortConst1, + ienum6, + ienum7 = IntConst1, + ienum8, + ienum9 = LongConst1, + ienum10, + ienum11 = IntConst2, + ienum12 = LongConst2 +}; + +enum SimpleEnum +{ + red, + green, + blue +}; + +interface TestIntf +{ + ByteEnum opByte(ByteEnum b1, out ByteEnum b2); + ShortEnum opShort(ShortEnum s1, out ShortEnum s2); + IntEnum opInt(IntEnum i1, out IntEnum i2); + SimpleEnum opSimple(SimpleEnum s1, out SimpleEnum s2); + + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/enums/TestIntfI.java b/java/test/src/main/java/test/Ice/enums/TestIntfI.java new file mode 100644 index 00000000000..cbb511e7edd --- /dev/null +++ b/java/test/src/main/java/test/Ice/enums/TestIntfI.java @@ -0,0 +1,54 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.enums; + +import test.Ice.enums.Test.*; + +public final class TestIntfI extends _TestIntfDisp +{ + @Override + public ByteEnum + opByte(ByteEnum b1, ByteEnumHolder b2, Ice.Current current) + { + b2.value = b1; + return b1; + } + + @Override + public ShortEnum + opShort(ShortEnum s1, ShortEnumHolder s2, Ice.Current current) + { + s2.value = s1; + return s1; + } + + @Override + public IntEnum + opInt(IntEnum i1, IntEnumHolder i2, Ice.Current current) + { + i2.value = i1; + return i1; + } + + @Override + public SimpleEnum + opSimple(SimpleEnum s1, SimpleEnumHolder s2, Ice.Current current) + { + s2.value = s1; + return s1; + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/enums/run.py b/java/test/src/main/java/test/Ice/enums/run.py new file mode 100755 index 00000000000..946154e0d1a --- /dev/null +++ b/java/test/src/main/java/test/Ice/enums/run.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("Running test with 1.0 encoding.") +TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.EncodingVersion=1.0", + additionalServerOptions="--Ice.Default.EncodingVersion=1.0") + +print("Running test with 1.1 encoding.") +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/exceptions/AMDServer.java b/java/test/src/main/java/test/Ice/exceptions/AMDServer.java new file mode 100644 index 00000000000..afd5450bffc --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/AMDServer.java @@ -0,0 +1,51 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.exceptions; + +public class AMDServer extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object object = new AMDThrowerI(); + adapter.add(object, communicator.stringToIdentity("thrower")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + // + // For this test, we need a dummy logger, otherwise the + // assertion test will print an error message. + // + initData.logger = new DummyLogger(); + + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.exceptions.AMD"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + initData.properties.setProperty("Ice.MessageSizeMax", "10"); // 10KB max + + return initData; + } + + public static void main(String[] args) + { + AMDServer app = new AMDServer(); + int result = app.main("AMDServer", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/exceptions/AMDThrowerI.java b/java/test/src/main/java/test/Ice/exceptions/AMDThrowerI.java new file mode 100644 index 00000000000..bd1013bd589 --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/AMDThrowerI.java @@ -0,0 +1,240 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.exceptions; + +import test.Ice.exceptions.AMD.Test.A; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_shutdown; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_supportsAssertException; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_supportsUndeclaredExceptions; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwAasA; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwAorDasAorD; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwAssertException; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwMemoryLimitException; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwBasA; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwBasB; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwCasA; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwCasB; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwCasC; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwLocalException; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwLocalExceptionIdempotent; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwNonIceException; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwUndeclaredA; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwUndeclaredB; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwUndeclaredC; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwAfterResponse; +import test.Ice.exceptions.AMD.Test.AMD_Thrower_throwAfterException; +import test.Ice.exceptions.AMD.Test.B; +import test.Ice.exceptions.AMD.Test.C; +import test.Ice.exceptions.AMD.Test.D; +import test.Ice.exceptions.AMD.Test._ThrowerDisp; + +public final class AMDThrowerI extends _ThrowerDisp +{ + public + AMDThrowerI() + { + } + + @Override + public void + shutdown_async(AMD_Thrower_shutdown cb, Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + cb.ice_response(); + } + + @Override + public void + supportsUndeclaredExceptions_async(AMD_Thrower_supportsUndeclaredExceptions cb, Ice.Current current) + { + cb.ice_response(true); + } + + @Override + public void + supportsAssertException_async(AMD_Thrower_supportsAssertException cb, Ice.Current current) + { + cb.ice_response(true); + } + + @Override + public void + throwAasA_async(AMD_Thrower_throwAasA cb, int a, Ice.Current current) + throws A + { + A ex = new A(); + ex.aMem = a; + cb.ice_exception(ex); + } + + @Override + public void + throwAorDasAorD_async(AMD_Thrower_throwAorDasAorD cb, int a, Ice.Current current) + throws A, + D + { + if(a > 0) + { + A ex = new A(); + ex.aMem = a; + cb.ice_exception(ex); + } + else + { + D ex = new D(); + ex.dMem = a; + cb.ice_exception(ex); + } + } + + @Override + public void + throwBasA_async(AMD_Thrower_throwBasA cb, int a, int b, Ice.Current current) + throws A + { + B ex = new B(); + ex.aMem = a; + ex.bMem = b; + throw ex; + //cb.ice_exception(ex); + } + + @Override + public void + throwBasB_async(AMD_Thrower_throwBasB cb, int a, int b, Ice.Current current) + throws B + { + B ex = new B(); + ex.aMem = a; + ex.bMem = b; + throw ex; + //cb.ice_exception(ex); + } + + @Override + public void + throwCasA_async(AMD_Thrower_throwCasA cb, int a, int b, int c, Ice.Current current) + throws A + { + C ex = new C(); + ex.aMem = a; + ex.bMem = b; + ex.cMem = c; + cb.ice_exception(ex); + } + + @Override + public void + throwCasB_async(AMD_Thrower_throwCasB cb, int a, int b, int c, Ice.Current current) + throws B + { + C ex = new C(); + ex.aMem = a; + ex.bMem = b; + ex.cMem = c; + cb.ice_exception(ex); + } + + @Override + public void + throwCasC_async(AMD_Thrower_throwCasC cb, int a, int b, int c, Ice.Current current) + throws C + { + C ex = new C(); + ex.aMem = a; + ex.bMem = b; + ex.cMem = c; + cb.ice_exception(ex); + } + + @Override + public void + throwUndeclaredA_async(AMD_Thrower_throwUndeclaredA cb, int a, Ice.Current current) + { + A ex = new A(); + ex.aMem = a; + cb.ice_exception(ex); + } + + @Override + public void + throwUndeclaredB_async(AMD_Thrower_throwUndeclaredB cb, int a, int b, Ice.Current current) + { + B ex = new B(); + ex.aMem = a; + ex.bMem = b; + cb.ice_exception(ex); + } + + @Override + public void + throwUndeclaredC_async(AMD_Thrower_throwUndeclaredC cb, int a, int b, int c, Ice.Current current) + { + C ex = new C(); + ex.aMem = a; + ex.bMem = b; + ex.cMem = c; + cb.ice_exception(ex); + } + + @Override + public void + throwLocalException_async(AMD_Thrower_throwLocalException cb, Ice.Current current) + { + cb.ice_exception(new Ice.TimeoutException()); + } + + @Override + public void + throwNonIceException_async(AMD_Thrower_throwNonIceException cb, Ice.Current current) + { + throw new RuntimeException(); + } + + @Override + public void + throwAssertException_async(AMD_Thrower_throwAssertException cb, Ice.Current current) + { + throw new java.lang.AssertionError(); + } + + @Override + public void + throwMemoryLimitException_async(AMD_Thrower_throwMemoryLimitException cb, byte[] seq, Ice.Current current) + { + cb.ice_response(new byte[1024 * 20]); // 20KB is over the configured 10KB message size max. + } + + @Override + public void + throwLocalExceptionIdempotent_async(AMD_Thrower_throwLocalExceptionIdempotent cb, Ice.Current current) + { + cb.ice_exception(new Ice.TimeoutException()); + } + + @Override + public void + throwAfterResponse_async(AMD_Thrower_throwAfterResponse cb, Ice.Current current) + { + cb.ice_response(); + + throw new RuntimeException(); + } + + @Override + public void + throwAfterException_async(AMD_Thrower_throwAfterException cb, Ice.Current current) + throws A + { + cb.ice_exception(new A()); + + throw new RuntimeException(); + } +} diff --git a/java/test/src/main/java/test/Ice/exceptions/AllTests.java b/java/test/src/main/java/test/Ice/exceptions/AllTests.java new file mode 100644 index 00000000000..7d68606047e --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/AllTests.java @@ -0,0 +1,1491 @@ +// ********************************************************************** +// +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +package test.Ice.exceptions; + +import java.io.PrintWriter; + +import test.Ice.exceptions.Test.A; +import test.Ice.exceptions.Test.B; +import test.Ice.exceptions.Test.C; +import test.Ice.exceptions.Test.D; +import test.Ice.exceptions.Test.ThrowerPrx; +import test.Ice.exceptions.Test.ThrowerPrxHelper; +import test.Ice.exceptions.Test.WrongOperationPrx; +import test.Ice.exceptions.Test.WrongOperationPrxHelper; +import test.Ice.exceptions.Test.Callback_Thrower_throwAasA; +import test.Ice.exceptions.Test.Callback_Thrower_throwAorDasAorD; +import test.Ice.exceptions.Test.Callback_Thrower_throwAssertException; +import test.Ice.exceptions.Test.Callback_Thrower_throwBasA; +import test.Ice.exceptions.Test.Callback_Thrower_throwBasB; +import test.Ice.exceptions.Test.Callback_Thrower_throwCasA; +import test.Ice.exceptions.Test.Callback_Thrower_throwCasB; +import test.Ice.exceptions.Test.Callback_Thrower_throwCasC; +import test.Ice.exceptions.Test.Callback_Thrower_throwLocalException; +import test.Ice.exceptions.Test.Callback_Thrower_throwLocalExceptionIdempotent; +import test.Ice.exceptions.Test.Callback_Thrower_throwNonIceException; +import test.Ice.exceptions.Test.Callback_Thrower_throwUndeclaredA; +import test.Ice.exceptions.Test.Callback_Thrower_throwUndeclaredB; +import test.Ice.exceptions.Test.Callback_Thrower_throwUndeclaredC; +import test.Ice.exceptions.Test.Callback_WrongOperation_noSuchOperation; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static class Callback_Thrower_throwAasAI extends Callback_Thrower_throwAasA + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + exc.printStackTrace(); + test(false); + } + + @Override + public void exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(A ex) + { + test(ex.aMem == 1); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_Thrower_throwAasAObjectNotExistI extends Callback_Thrower_throwAasA + { + Callback_Thrower_throwAasAObjectNotExistI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + try + { + throw exc; + } + catch(Ice.ObjectNotExistException ex) + { + Ice.Identity id = _communicator.stringToIdentity("does not exist"); + test(ex.id.equals(id)); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + @Override + public void exception(Ice.UserException exc) + { + exc.printStackTrace(); + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + private Ice.Communicator _communicator; + } + + private static class Callback_Thrower_throwAasAFacetNotExistI extends Callback_Thrower_throwAasA + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + try + { + throw exc; + } + catch(Ice.FacetNotExistException ex) + { + test(ex.facet.equals("no such facet")); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + @Override + public void exception(Ice.UserException exc) + { + exc.printStackTrace(); + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_Thrower_throwAorDasAorDI extends Callback_Thrower_throwAorDasAorD + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + exc.printStackTrace(); + test(false); + } + + @Override + public void exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(A ex) + { + test(ex.aMem == 1); + } + catch(D ex) + { + test(ex.dMem == -1); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_Thrower_throwBasAI extends Callback_Thrower_throwBasA + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + exc.printStackTrace(); + test(false); + } + + @Override + public void exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(B ex) + { + test(ex.aMem == 1); + test(ex.bMem == 2); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_Thrower_throwCasAI extends Callback_Thrower_throwCasA + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + exc.printStackTrace(); + test(false); + } + + @Override + public void exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(C ex) + { + test(ex.aMem == 1); + test(ex.bMem == 2); + test(ex.cMem == 3); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_Thrower_throwBasBI extends Callback_Thrower_throwBasB + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + exc.printStackTrace(); + test(false); + } + + @Override + public void exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(B ex) + { + test(ex.aMem == 1); + test(ex.bMem == 2); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_Thrower_throwCasBI extends Callback_Thrower_throwCasB + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + exc.printStackTrace(); + test(false); + } + + @Override + public void exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(C ex) + { + test(ex.aMem == 1); + test(ex.bMem == 2); + test(ex.cMem == 3); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_Thrower_throwCasCI extends Callback_Thrower_throwCasC + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + exc.printStackTrace(); + test(false); + } + + @Override + public void exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(C ex) + { + test(ex.aMem == 1); + test(ex.bMem == 2); + test(ex.cMem == 3); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_Thrower_throwUndeclaredAI extends Callback_Thrower_throwUndeclaredA + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + try + { + throw exc; + } + catch(Ice.UnknownUserException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_Thrower_throwUndeclaredBI extends Callback_Thrower_throwUndeclaredB + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + try + { + throw exc; + } + catch(Ice.UnknownUserException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_Thrower_throwUndeclaredCI extends Callback_Thrower_throwUndeclaredC + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + try + { + throw exc; + } + catch(Ice.UnknownUserException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_Thrower_throwLocalExceptionI extends Callback_Thrower_throwLocalException + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + try + { + throw exc; + } + catch(Ice.UnknownLocalException ex) + { + } + catch(Ice.OperationNotExistException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_Thrower_throwNonIceExceptionI extends Callback_Thrower_throwNonIceException + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + try + { + throw exc; + } + catch(Ice.UnknownException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_Thrower_throwAssertExceptionI extends Callback_Thrower_throwAssertException + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + try + { + throw exc; + } + catch(Ice.ConnectionLostException ex) + { + } + catch(Ice.UnknownException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_WrongOperation_noSuchOperationI extends Callback_WrongOperation_noSuchOperation + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException exc) + { + try + { + throw exc; + } + catch(Ice.OperationNotExistException ex) + { + test(ex.operation.equals("noSuchOperation")); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + public static ThrowerPrx + allTests(Ice.Communicator communicator, PrintWriter out) + { + { + out.print("testing object adapter registration exceptions... "); + Ice.ObjectAdapter first; + try + { + first = communicator.createObjectAdapter("TestAdapter0"); + } + catch(Ice.InitializationException ex) + { + // Expected + } + + communicator.getProperties().setProperty("TestAdapter0.Endpoints", "default"); + first = communicator.createObjectAdapter("TestAdapter0"); + try + { + communicator.createObjectAdapter("TestAdapter0"); + test(false); + } + catch(Ice.AlreadyRegisteredException ex) + { + // Expected + } + + try + { + communicator.createObjectAdapterWithEndpoints("TestAdapter0", "ssl -h foo -p 12011"); + test(false); + } + catch(Ice.AlreadyRegisteredException ex) + { + // Expected + } + first.deactivate(); + out.println("ok"); + } + + { + out.print("testing servant registration exceptions... "); + communicator.getProperties().setProperty("TestAdapter1.Endpoints", "default"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter1"); + Ice.Object obj = new EmptyI(); + adapter.add(obj, communicator.stringToIdentity("x")); + try + { + adapter.add(obj, communicator.stringToIdentity("x")); + test(false); + } + catch(Ice.AlreadyRegisteredException ex) + { + } + + try + { + adapter.add(obj, communicator.stringToIdentity("")); + test(false); + } + catch(Ice.IllegalIdentityException ex) + { + test(ex.id.name.equals("")); + } + try + { + adapter.add(null, communicator.stringToIdentity("x")); + test(false); + } + catch(Ice.IllegalServantException ex) + { + } + + adapter.remove(communicator.stringToIdentity("x")); + try + { + adapter.remove(communicator.stringToIdentity("x")); + test(false); + } + catch(Ice.NotRegisteredException ex) + { + } + adapter.deactivate(); + out.println("ok"); + } + + { + out.print("testing servant locator registration exceptions... "); + communicator.getProperties().setProperty("TestAdapter2.Endpoints", "default"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter2"); + Ice.ServantLocator loc = new ServantLocatorI(); + adapter.addServantLocator(loc, "x"); + try + { + adapter.addServantLocator(loc, "x"); + test(false); + } + catch(Ice.AlreadyRegisteredException ex) + { + } + + adapter.deactivate(); + out.println("ok"); + } + + { + out.print("testing object factory registration exception... "); + Ice.ObjectFactory of = new ObjectFactoryI(); + communicator.addObjectFactory(of, "::x"); + try + { + communicator.addObjectFactory(of, "::x"); + test(false); + } + catch(Ice.AlreadyRegisteredException ex) + { + } + out.println("ok"); + } + + out.print("testing stringToProxy... "); + out.flush(); + String ref = "thrower:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + ThrowerPrx thrower = ThrowerPrxHelper.checkedCast(base); + test(thrower != null); + test(thrower.equals(base)); + out.println("ok"); + + out.print("catching exact types... "); + out.flush(); + + try + { + thrower.throwAasA(1); + test(false); + } + catch(A ex) + { + test(ex.aMem == 1); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + thrower.throwAorDasAorD(1); + test(false); + } + catch(A ex) + { + test(ex.aMem == 1); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + thrower.throwAorDasAorD(-1); + test(false); + } + catch(D ex) + { + test(ex.dMem == -1); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + thrower.throwBasB(1, 2); + test(false); + } + catch(B ex) + { + test(ex.aMem == 1); + test(ex.bMem == 2); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + thrower.throwCasC(1, 2, 3); + test(false); + } + catch(C ex) + { + test(ex.aMem == 1); + test(ex.bMem == 2); + test(ex.cMem == 3); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + out.println("ok"); + + out.print("catching base types... "); + out.flush(); + + try + { + thrower.throwBasB(1, 2); + test(false); + } + catch(A ex) + { + test(ex.aMem == 1); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + thrower.throwCasC(1, 2, 3); + test(false); + } + catch(B ex) + { + test(ex.aMem == 1); + test(ex.bMem == 2); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + out.println("ok"); + + out.print("catching derived types... "); + out.flush(); + + try + { + thrower.throwBasA(1, 2); + test(false); + } + catch(B ex) + { + test(ex.aMem == 1); + test(ex.bMem == 2); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + thrower.throwCasA(1, 2, 3); + test(false); + } + catch(C ex) + { + test(ex.aMem == 1); + test(ex.bMem == 2); + test(ex.cMem == 3); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + thrower.throwCasB(1, 2, 3); + test(false); + } + catch(C ex) + { + test(ex.aMem == 1); + test(ex.bMem == 2); + test(ex.cMem == 3); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + out.println("ok"); + + if(thrower.supportsUndeclaredExceptions()) + { + out.print("catching unknown user exception... "); + out.flush(); + + try + { + thrower.throwUndeclaredA(1); + test(false); + } + catch(Ice.UnknownUserException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + thrower.throwUndeclaredB(1, 2); + test(false); + } + catch(Ice.UnknownUserException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + thrower.throwUndeclaredC(1, 2, 3); + test(false); + } + catch(Ice.UnknownUserException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + out.println("ok"); + } + + if(thrower.supportsAssertException()) + { + out.print("testing assert in the server... "); + out.flush(); + + try + { + thrower.throwAssertException(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + } + catch(Ice.UnknownException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + out.println("ok"); + } + + out.print("testing memory limit marshal exception..."); + out.flush(); + { + try + { + thrower.throwMemoryLimitException(null); + test(false); + } + catch(Ice.UnknownLocalException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + thrower.throwMemoryLimitException(new byte[20 * 1024]); // 20KB + test(false); + } + catch(Ice.MemoryLimitException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + thrower.end_throwMemoryLimitException( + thrower.begin_throwMemoryLimitException(new byte[20 * 1024])); // 20KB + test(false); + } + catch(Ice.MemoryLimitException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + } + out.println("ok"); + + out.print("catching object not exist exception... "); + out.flush(); + + { + Ice.Identity id = communicator.stringToIdentity("does not exist"); + try + { + ThrowerPrx thrower2 = ThrowerPrxHelper.uncheckedCast(thrower.ice_identity(id)); + thrower2.ice_ping(); + test(false); + } + catch(Ice.ObjectNotExistException ex) + { + test(ex.id.equals(id)); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + } + + out.println("ok"); + + out.print("catching facet not exist exception... "); + out.flush(); + + try + { + ThrowerPrx thrower2 = ThrowerPrxHelper.uncheckedCast(thrower, "no such facet"); + try + { + thrower2.ice_ping(); + test(false); + } + catch(Ice.FacetNotExistException ex) + { + test(ex.facet.equals("no such facet")); + } + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + out.println("ok"); + + out.print("catching operation not exist exception... "); + out.flush(); + + try + { + WrongOperationPrx thrower2 = WrongOperationPrxHelper.uncheckedCast(thrower); + thrower2.noSuchOperation(); + test(false); + } + catch(Ice.OperationNotExistException ex) + { + test(ex.operation.equals("noSuchOperation")); + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + out.println("ok"); + + out.print("catching unknown local exception... "); + out.flush(); + + try + { + thrower.throwLocalException(); + test(false); + } + catch(Ice.UnknownLocalException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + thrower.throwLocalExceptionIdempotent(); + test(false); + } + catch(Ice.UnknownLocalException ex) + { + } + catch(Ice.OperationNotExistException ex) + { + } + catch(Throwable ex) + { + ex.printStackTrace(); + test(false); + } + + out.println("ok"); + + out.print("catching unknown non-Ice exception... "); + out.flush(); + + try + { + thrower.throwNonIceException(); + test(false); + } + catch(Ice.UnknownException ex) + { + } + catch(Throwable ex) + { + out.println(ex); + test(false); + } + + out.println("ok"); + + out.print("testing asynchronous exceptions... "); + out.flush(); + + try + { + thrower.throwAfterResponse(); + } + catch(Ice.LocalException ex) + { + test(false); + } + catch(Throwable ex) + { + out.println(ex); + test(false); + } + + try + { + thrower.throwAfterException(); + test(false); + } + catch(A ex) + { + } + catch(Ice.LocalException ex) + { + test(false); + } + catch(Throwable ex) + { + out.println(ex); + test(false); + } + + out.println("ok"); + + out.print("catching exact types with AMI mapping... "); + out.flush(); + + { + Callback_Thrower_throwAasAI cb = new Callback_Thrower_throwAasAI(); + thrower.begin_throwAasA(1, cb); + cb.check(); + } + + { + Callback_Thrower_throwAorDasAorDI cb = new Callback_Thrower_throwAorDasAorDI(); + thrower.begin_throwAorDasAorD(1, cb); + cb.check(); + } + + { + Callback_Thrower_throwAorDasAorDI cb = new Callback_Thrower_throwAorDasAorDI(); + thrower.begin_throwAorDasAorD(-1, cb); + cb.check(); + } + + { + Callback_Thrower_throwBasBI cb = new Callback_Thrower_throwBasBI(); + thrower.begin_throwBasB(1, 2, cb); + cb.check(); + } + + { + Callback_Thrower_throwCasCI cb = new Callback_Thrower_throwCasCI(); + thrower.begin_throwCasC(1, 2, 3, cb); + cb.check(); + } + + out.println("ok"); + + out.print("catching derived types with mapping... "); + out.flush(); + + { + Callback_Thrower_throwBasAI cb = new Callback_Thrower_throwBasAI(); + thrower.begin_throwBasA(1, 2, cb); + cb.check(); + } + + { + Callback_Thrower_throwCasAI cb = new Callback_Thrower_throwCasAI(); + thrower.begin_throwCasA(1, 2, 3, cb); + cb.check(); + } + + { + Callback_Thrower_throwCasBI cb = new Callback_Thrower_throwCasBI(); + thrower.begin_throwCasB(1, 2, 3, cb); + cb.check(); + } + + out.println("ok"); + + if(thrower.supportsUndeclaredExceptions()) + { + out.print("catching unknown user exception with mapping... "); + out.flush(); + + { + Callback_Thrower_throwUndeclaredAI cb = new Callback_Thrower_throwUndeclaredAI(); + thrower.begin_throwUndeclaredA(1, cb); + cb.check(); + } + + { + Callback_Thrower_throwUndeclaredBI cb = new Callback_Thrower_throwUndeclaredBI(); + thrower.begin_throwUndeclaredB(1, 2, cb); + cb.check(); + } + + { + Callback_Thrower_throwUndeclaredCI cb = new Callback_Thrower_throwUndeclaredCI(); + thrower.begin_throwUndeclaredC(1, 2, 3, cb); + cb.check(); + } + + out.println("ok"); + } + + if(thrower.supportsAssertException()) + { + out.print("catching assert in the server with mapping... "); + out.flush(); + + Callback_Thrower_throwAssertExceptionI cb = new Callback_Thrower_throwAssertExceptionI(); + thrower.begin_throwAssertException(cb); + cb.check(); + + out.println("ok"); + } + + out.print("catching object not exist exception with mapping... "); + out.flush(); + + { + Ice.Identity id = communicator.stringToIdentity("does not exist"); + ThrowerPrx thrower2 = ThrowerPrxHelper.uncheckedCast(thrower.ice_identity(id)); + Callback_Thrower_throwAasAObjectNotExistI cb = new Callback_Thrower_throwAasAObjectNotExistI(communicator); + thrower2.begin_throwAasA(1, cb); + cb.check(); + } + + out.println("ok"); + + out.print("catching facet not exist exception with mapping... "); + out.flush(); + + { + ThrowerPrx thrower2 = ThrowerPrxHelper.uncheckedCast(thrower, "no such facet"); + Callback_Thrower_throwAasAFacetNotExistI cb = new Callback_Thrower_throwAasAFacetNotExistI(); + thrower2.begin_throwAasA(1, cb); + cb.check(); + } + + out.println("ok"); + + out.print("catching operation not exist exception with mapping... "); + out.flush(); + + { + Callback_WrongOperation_noSuchOperationI cb = new Callback_WrongOperation_noSuchOperationI(); + WrongOperationPrx thrower2 = WrongOperationPrxHelper.uncheckedCast(thrower); + thrower2.begin_noSuchOperation(cb); + cb.check(); + } + + out.println("ok"); + + out.print("catching unknown local exception with mapping... "); + out.flush(); + + { + Callback_Thrower_throwLocalExceptionI cb = new Callback_Thrower_throwLocalExceptionI(); + thrower.begin_throwLocalException(cb); + cb.check(); + } + + { + final Callback_Thrower_throwLocalExceptionI cb = new Callback_Thrower_throwLocalExceptionI(); + thrower.begin_throwLocalExceptionIdempotent(new Callback_Thrower_throwLocalExceptionIdempotent() + { + @Override + public void response() + { + cb.response(); + } + + @Override + public void exception(Ice.LocalException exc) + { + cb.exception(exc); + } + }); + cb.check(); + } + + out.println("ok"); + + out.print("catching unknown non-Ice exception with mapping... "); + out.flush(); + + { + Callback_Thrower_throwNonIceExceptionI cb = new Callback_Thrower_throwNonIceExceptionI(); + thrower.begin_throwNonIceException(cb); + cb.check(); + } + + out.println("ok"); + + return thrower; + } +} diff --git a/java/test/src/main/java/test/Ice/exceptions/Client.java b/java/test/src/main/java/test/Ice/exceptions/Client.java new file mode 100644 index 00000000000..ef66546fa26 --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/Client.java @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.exceptions; + +import test.Ice.exceptions.Test.ThrowerPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + ThrowerPrx thrower = AllTests.allTests(communicator, getWriter()); + thrower.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.exceptions"); + initData.properties.setProperty("Ice.Warn.Connections", "0"); + initData.properties.setProperty("Ice.MessageSizeMax", "10"); // 10KB max + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/exceptions/Collocated.java b/java/test/src/main/java/test/Ice/exceptions/Collocated.java new file mode 100644 index 00000000000..b85ca002b94 --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/Collocated.java @@ -0,0 +1,55 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.exceptions; + +public class Collocated extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object object = new ThrowerI(); + adapter.add(object, communicator.stringToIdentity("thrower")); + + AllTests.allTests(communicator, getWriter()); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + // + // For this test, we need a dummy logger, otherwise the + // assertion test will print an error message. + // + initData.logger = new DummyLogger(); + + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.exceptions"); + initData.properties.setProperty("Ice.MessageSizeMax", "10"); // 10KB max + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + + return initData; + } + + public static void + main(String[] args) + { + Collocated app = new Collocated(); + int result = app.main("Collocated", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/exceptions/DummyLogger.java b/java/test/src/main/java/test/Ice/exceptions/DummyLogger.java new file mode 100644 index 00000000000..4230b744f94 --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/DummyLogger.java @@ -0,0 +1,66 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.exceptions; + + +public final class DummyLogger implements Ice.Logger +{ + @Override + public void + print(String message) + { + _logger.print(message); + } + + @Override + public void + trace(String category, String message) + { + _logger.trace(category, message); + } + + @Override + public void + warning(String message) + { + if(!message.contains("test.Ice.exceptions.ThrowerI.throwAssertException") && + !message.contains("test.Ice.exceptions.AMDThrowerI.throwAssertException_async")) + { + _logger.warning(message); + } + } + + @Override + public void + error(String message) + { + if(!message.contains("test.Ice.exceptions.ThrowerI.throwAssertException") && + !message.contains("test.Ice.exceptions.AMDThrowerI.throwAssertException_async")) + { + _logger.error(message); + } + } + + @Override + public String + getPrefix() + { + return ""; + } + + @Override + public Ice.Logger + cloneWithPrefix(String prefix) + { + return new DummyLogger(); + } + + private Ice.Logger _logger = new Ice.LoggerI("", ""); +} diff --git a/java/test/src/main/java/test/Ice/exceptions/EmptyI.java b/java/test/src/main/java/test/Ice/exceptions/EmptyI.java new file mode 100644 index 00000000000..f21f1bc484e --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/EmptyI.java @@ -0,0 +1,17 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.exceptions; + +import test.Ice.exceptions.Test._EmptyDisp; + + +public final class EmptyI extends _EmptyDisp +{ +} diff --git a/java/test/src/main/java/test/Ice/exceptions/ObjectFactoryI.java b/java/test/src/main/java/test/Ice/exceptions/ObjectFactoryI.java new file mode 100644 index 00000000000..87dd29b637b --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/ObjectFactoryI.java @@ -0,0 +1,25 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.exceptions; + + +public final class ObjectFactoryI implements Ice.ObjectFactory +{ + @Override + public Ice.Object create(String s) + { + return null; + } + + @Override + public void destroy() + { + } +} diff --git a/java/test/src/main/java/test/Ice/exceptions/ServantLocatorI.java b/java/test/src/main/java/test/Ice/exceptions/ServantLocatorI.java new file mode 100644 index 00000000000..6619cd8f40c --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/ServantLocatorI.java @@ -0,0 +1,30 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.exceptions; + + +public final class ServantLocatorI implements Ice.ServantLocator +{ + @Override + public Ice.Object locate(Ice.Current curr, Ice.LocalObjectHolder cookie) + { + return null; + } + + @Override + public void finished(Ice.Current curr, Ice.Object servant, java.lang.Object cookie) + { + } + + @Override + public void deactivate(String category) + { + } +} diff --git a/java/test/src/main/java/test/Ice/exceptions/Server.java b/java/test/src/main/java/test/Ice/exceptions/Server.java new file mode 100644 index 00000000000..539ac3bc304 --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/Server.java @@ -0,0 +1,51 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.exceptions; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object object = new ThrowerI(); + adapter.add(object, communicator.stringToIdentity("thrower")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + // + // For this test, we need a dummy logger, otherwise the + // assertion test will print an error message. + // + initData.logger = new DummyLogger(); + + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.exceptions"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + initData.properties.setProperty("Ice.MessageSizeMax", "10"); // 10KB max + + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/exceptions/Test.ice b/java/test/src/main/java/test/Ice/exceptions/Test.ice new file mode 100644 index 00000000000..c1818494ad2 --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/Test.ice @@ -0,0 +1,77 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/BuiltinSequences.ice> + +[["java:package:test.Ice.exceptions"]] +module Test +{ + +interface Empty +{ +}; + +interface Thrower; + +exception A +{ + int aMem; +}; + +exception B extends A +{ + int bMem; +}; + +exception C extends B +{ + int cMem; +}; + +exception D +{ + int dMem; +}; + +interface Thrower +{ + void shutdown(); + bool supportsUndeclaredExceptions(); + bool supportsAssertException(); + + void throwAasA(int a) throws A; + void throwAorDasAorD(int a) throws A, D; + void throwBasA(int a, int b) throws A; + void throwCasA(int a, int b, int c) throws A; + void throwBasB(int a, int b) throws B; + void throwCasB(int a, int b, int c) throws B; + void throwCasC(int a, int b, int c) throws C; + + void throwUndeclaredA(int a); + void throwUndeclaredB(int a, int b); + void throwUndeclaredC(int a, int b, int c); + void throwLocalException(); + void throwNonIceException(); + void throwAssertException(); + Ice::ByteSeq throwMemoryLimitException(Ice::ByteSeq seq); + + idempotent void throwLocalExceptionIdempotent(); + + void throwAfterResponse(); + void throwAfterException() throws A; +}; + +interface WrongOperation +{ + void noSuchOperation(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/exceptions/TestAMD.ice b/java/test/src/main/java/test/Ice/exceptions/TestAMD.ice new file mode 100644 index 00000000000..4007abf0f52 --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/TestAMD.ice @@ -0,0 +1,72 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/BuiltinSequences.ice> + +[["java:package:test.Ice.exceptions.AMD"]] +module Test +{ + +interface Thrower; + +exception A +{ + int aMem; +}; + +exception B extends A +{ + int bMem; +}; + +exception C extends B +{ + int cMem; +}; + +exception D +{ + int dMem; +}; + +["amd"] interface Thrower +{ + void shutdown(); + bool supportsUndeclaredExceptions(); + bool supportsAssertException(); + + void throwAasA(int a) throws A; + void throwAorDasAorD(int a) throws A, D; + void throwBasA(int a, int b) throws A; + void throwCasA(int a, int b, int c) throws A; + void throwBasB(int a, int b) throws B; + void throwCasB(int a, int b, int c) throws B; + void throwCasC(int a, int b, int c) throws C; + void throwUndeclaredA(int a); + void throwUndeclaredB(int a, int b); + void throwUndeclaredC(int a, int b, int c); + void throwLocalException(); + void throwNonIceException(); + void throwAssertException(); + Ice::ByteSeq throwMemoryLimitException(Ice::ByteSeq seq); + + idempotent void throwLocalExceptionIdempotent(); + + void throwAfterResponse(); + void throwAfterException() throws A; +}; + +["amd"] interface WrongOperation +{ + void noSuchOperation(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/exceptions/ThrowerI.java b/java/test/src/main/java/test/Ice/exceptions/ThrowerI.java new file mode 100644 index 00000000000..8859147bd36 --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/ThrowerI.java @@ -0,0 +1,201 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.exceptions; + +import test.Ice.exceptions.Test.A; +import test.Ice.exceptions.Test.B; +import test.Ice.exceptions.Test.C; +import test.Ice.exceptions.Test.D; +import test.Ice.exceptions.Test._ThrowerDisp; + +public final class ThrowerI extends _ThrowerDisp +{ + public + ThrowerI() + { + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + @Override + public boolean + supportsUndeclaredExceptions(Ice.Current current) + { + return false; + } + + @Override + public boolean + supportsAssertException(Ice.Current current) + { + return true; + } + + @Override + public void + throwAasA(int a, Ice.Current current) + throws A + { + A ex = new A(); + ex.aMem = a; + throw ex; + } + + @Override + public void + throwAorDasAorD(int a, Ice.Current current) + throws A, + D + { + if(a > 0) + { + A ex = new A(); + ex.aMem = a; + throw ex; + } + else + { + D ex = new D(); + ex.dMem = a; + throw ex; + } + } + + @Override + public void + throwBasA(int a, int b, Ice.Current current) + throws A + { + throwBasB(a, b, current); + } + + @Override + public void + throwBasB(int a, int b, Ice.Current current) + throws B + { + B ex = new B(); + ex.aMem = a; + ex.bMem = b; + throw ex; + } + + @Override + public void + throwCasA(int a, int b, int c, Ice.Current current) + throws A + { + throwCasC(a, b, c, current); + } + + @Override + public void + throwCasB(int a, int b, int c, Ice.Current current) + throws B + { + throwCasC(a, b, c, current); + } + + @Override + public void + throwCasC(int a, int b, int c, Ice.Current current) + throws C + { + C ex = new C(); + ex.aMem = a; + ex.bMem = b; + ex.cMem = c; + throw ex; + } + + @Override + public void + throwUndeclaredA(int a, Ice.Current current) + { + // Not possible in Java. + throw new Ice.UnknownUserException(); + } + + @Override + public void + throwUndeclaredB(int a, int b, Ice.Current current) + { + // Not possible in Java. + throw new Ice.UnknownUserException(); + } + + @Override + public void + throwUndeclaredC(int a, int b, int c, Ice.Current current) + { + // Not possible in Java. + throw new Ice.UnknownUserException(); + } + + @Override + public void + throwLocalException(Ice.Current current) + { + throw new Ice.TimeoutException(); + } + + @Override + public void + throwLocalExceptionIdempotent(Ice.Current current) + { + throw new Ice.TimeoutException(); + } + + @Override + public void + throwNonIceException(Ice.Current current) + { + throw new RuntimeException(); + } + + @Override + public void + throwAssertException(Ice.Current current) + { + throw new java.lang.AssertionError(); + } + + @Override + public byte[] + throwMemoryLimitException(byte[] seq, Ice.Current current) + { + return new byte[1024 * 20]; // 20KB is over the configured 10KB message size max. + } + + @Override + public void + throwAfterResponse(Ice.Current current) + { + // + // Only relevant for AMD. + // + } + + @Override + public void + throwAfterException(Ice.Current current) + throws A + { + // + // Only relevant for AMD. + // + throw new A(); + } +} diff --git a/java/test/src/main/java/test/Ice/exceptions/run.py b/java/test/src/main/java/test/Ice/exceptions/run.py new file mode 100755 index 00000000000..458762c1dfe --- /dev/null +++ b/java/test/src/main/java/test/Ice/exceptions/run.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("Running test with compact (default) format.") +TestUtil.clientServerTest() + +print("Running test with sliced format.") +TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.SlicedFormat", + additionalServerOptions="--Ice.Default.SlicedFormat") + +print("Running test with 1.0 encoding.") +TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.EncodingVersion=1.0", + additionalServerOptions="--Ice.Default.EncodingVersion=1.0") + +print("Running test with compact (default) format and AMD server.") +TestUtil.clientServerTest(server="test.Ice.exceptions.AMDServer") + +print("Running test with sliced format and AMD server.") +TestUtil.clientServerTest(server="test.Ice.exceptions.AMDServer", + additionalClientOptions="--Ice.Default.SlicedFormat", + additionalServerOptions="--Ice.Default.SlicedFormat") + +print("Running test with 1.0 encoding and AMD server.") +TestUtil.clientServerTest(server="test.Ice.exceptions.AMDServer", + additionalClientOptions="--Ice.Default.EncodingVersion=1.0", + additionalServerOptions="--Ice.Default.EncodingVersion=1.0") + +print("Running collocated test.") +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/facets/AI.java b/java/test/src/main/java/test/Ice/facets/AI.java new file mode 100644 index 00000000000..eb993bf3082 --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/AI.java @@ -0,0 +1,27 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.facets; + +import test.Ice.facets.Test._ADisp; + +public final class AI extends _ADisp +{ + public + AI() + { + } + + @Override + public String + callA(Ice.Current current) + { + return "A"; + } +} diff --git a/java/test/src/main/java/test/Ice/facets/AllTests.java b/java/test/src/main/java/test/Ice/facets/AllTests.java new file mode 100644 index 00000000000..79308c3b113 --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/AllTests.java @@ -0,0 +1,206 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.facets; + +import java.io.PrintWriter; + +import test.Ice.facets.Test.DPrx; +import test.Ice.facets.Test.DPrxHelper; +import test.Ice.facets.Test.FPrx; +import test.Ice.facets.Test.FPrxHelper; +import test.Ice.facets.Test.GPrx; +import test.Ice.facets.Test.GPrxHelper; +import test.Ice.facets.Test.HPrx; +import test.Ice.facets.Test.HPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static GPrx + allTests(Ice.Communicator communicator, PrintWriter out) + { + out.print("testing Ice.Admin.Facets property... "); + test(communicator.getProperties().getPropertyAsList("Ice.Admin.Facets").length == 0); + communicator.getProperties().setProperty("Ice.Admin.Facets", "foobar"); + String[] facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets"); + test(facetFilter.length == 1 && facetFilter[0].equals("foobar")); + communicator.getProperties().setProperty("Ice.Admin.Facets", "foo\\'bar"); + facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets"); + test(facetFilter.length == 1 && facetFilter[0].equals("foo'bar")); + communicator.getProperties().setProperty("Ice.Admin.Facets", "'foo bar' toto 'titi'"); + facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets"); + test(facetFilter.length == 3 && facetFilter[0].equals("foo bar") && facetFilter[1].equals("toto") + && facetFilter[2].equals("titi")); + communicator.getProperties().setProperty("Ice.Admin.Facets", "'foo bar\\' toto' 'titi'"); + facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets"); + test(facetFilter.length == 2 && facetFilter[0].equals("foo bar' toto") && facetFilter[1].equals("titi")); + // communicator.getProperties().setProperty("Ice.Admin.Facets", "'foo bar' 'toto titi"); + // facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets"); + // test(facetFilter.length == 0); + communicator.getProperties().setProperty("Ice.Admin.Facets", ""); + out.println("ok"); + + out.print("testing facet registration exceptions... "); + communicator.getProperties().setProperty("FacetExceptionTestAdapter.Endpoints", "default"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("FacetExceptionTestAdapter"); + Ice.Object obj = new EmptyI(); + adapter.add(obj, communicator.stringToIdentity("d")); + adapter.addFacet(obj, communicator.stringToIdentity("d"), "facetABCD"); + try + { + adapter.addFacet(obj, communicator.stringToIdentity("d"), "facetABCD"); + test(false); + } + catch(Ice.AlreadyRegisteredException ex) + { + } + adapter.removeFacet(communicator.stringToIdentity("d"), "facetABCD"); + try + { + adapter.removeFacet(communicator.stringToIdentity("d"), "facetABCD"); + test(false); + } + catch(Ice.NotRegisteredException ex) + { + } + out.println("ok"); + + out.print("testing removeAllFacets... "); + Ice.Object obj1 = new EmptyI(); + Ice.Object obj2 = new EmptyI(); + adapter.addFacet(obj1, communicator.stringToIdentity("id1"), "f1"); + adapter.addFacet(obj2, communicator.stringToIdentity("id1"), "f2"); + Ice.Object obj3 = new EmptyI(); + adapter.addFacet(obj1, communicator.stringToIdentity("id2"), "f1"); + adapter.addFacet(obj2, communicator.stringToIdentity("id2"), "f2"); + adapter.addFacet(obj3, communicator.stringToIdentity("id2"), ""); + java.util.Map<String, Ice.Object> fm = adapter.removeAllFacets(communicator.stringToIdentity("id1")); + test(fm.size() == 2); + test(fm.get("f1") == obj1); + test(fm.get("f2") == obj2); + try + { + adapter.removeAllFacets(communicator.stringToIdentity("id1")); + test(false); + } + catch(Ice.NotRegisteredException ex) + { + } + fm = adapter.removeAllFacets(communicator.stringToIdentity("id2")); + test(fm.size() == 3); + test(fm.get("f1") == obj1); + test(fm.get("f2") == obj2); + test(fm.get("") == obj3); + out.println("ok"); + + adapter.deactivate(); + + out.print("testing stringToProxy... "); + out.flush(); + String ref = "d:default -p 12010"; + Ice.ObjectPrx db = communicator.stringToProxy(ref); + test(db != null); + out.println("ok"); + + out.print("testing unchecked cast... "); + out.flush(); + Ice.ObjectPrx prx = Ice.ObjectPrxHelper.uncheckedCast(db); + test(prx.ice_getFacet().length() == 0); + prx = Ice.ObjectPrxHelper.uncheckedCast(db, "facetABCD"); + test(prx.ice_getFacet() == "facetABCD"); + Ice.ObjectPrx prx2 = Ice.ObjectPrxHelper.uncheckedCast(prx); + test(prx2.ice_getFacet() == "facetABCD"); + Ice.ObjectPrx prx3 = Ice.ObjectPrxHelper.uncheckedCast(prx, ""); + test(prx3.ice_getFacet().length() == 0); + DPrx d = DPrxHelper.uncheckedCast(db); + test(d.ice_getFacet().length() == 0); + DPrx df = DPrxHelper.uncheckedCast(db, "facetABCD"); + test(df.ice_getFacet() == "facetABCD"); + DPrx df2 = DPrxHelper.uncheckedCast(df); + test(df2.ice_getFacet() == "facetABCD"); + DPrx df3 = DPrxHelper.uncheckedCast(df, ""); + test(df3.ice_getFacet().length() == 0); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + prx = Ice.ObjectPrxHelper.checkedCast(db); + test(prx.ice_getFacet().length() == 0); + prx = Ice.ObjectPrxHelper.checkedCast(db, "facetABCD"); + test(prx.ice_getFacet() == "facetABCD"); + prx2 = Ice.ObjectPrxHelper.checkedCast(prx); + test(prx2.ice_getFacet() == "facetABCD"); + prx3 = Ice.ObjectPrxHelper.checkedCast(prx, ""); + test(prx3.ice_getFacet().length() == 0); + d = DPrxHelper.checkedCast(db); + test(d.ice_getFacet().length() == 0); + df = DPrxHelper.checkedCast(db, "facetABCD"); + test(df.ice_getFacet() == "facetABCD"); + df2 = DPrxHelper.checkedCast(df); + test(df2.ice_getFacet() == "facetABCD"); + df3 = DPrxHelper.checkedCast(df, ""); + test(df3.ice_getFacet().length() == 0); + out.println("ok"); + + out.print("testing non-facets A, B, C, and D... "); + out.flush(); + d = DPrxHelper.checkedCast(db); + test(d != null); + test(d.equals(db)); + test(d.callA().equals("A")); + test(d.callB().equals("B")); + test(d.callC().equals("C")); + test(d.callD().equals("D")); + out.println("ok"); + + out.print("testing facets A, B, C, and D... "); + out.flush(); + df = DPrxHelper.checkedCast(d, "facetABCD"); + test(df != null); + test(df.callA().equals("A")); + test(df.callB().equals("B")); + test(df.callC().equals("C")); + test(df.callD().equals("D")); + out.println("ok"); + + out.print("testing facets E and F... "); + out.flush(); + FPrx ff = FPrxHelper.checkedCast(d, "facetEF"); + test(ff != null); + test(ff.callE().equals("E")); + test(ff.callF().equals("F")); + out.println("ok"); + + out.print("testing facet G... "); + out.flush(); + GPrx gf = GPrxHelper.checkedCast(ff, "facetGH"); + test(gf != null); + test(gf.callG().equals("G")); + out.println("ok"); + + out.print("testing whether casting preserves the facet... "); + out.flush(); + HPrx hf = HPrxHelper.checkedCast(gf); + test(hf != null); + test(hf.callG().equals("G")); + test(hf.callH().equals("H")); + out.println("ok"); + + return gf; + } +} diff --git a/java/test/src/main/java/test/Ice/facets/BI.java b/java/test/src/main/java/test/Ice/facets/BI.java new file mode 100644 index 00000000000..bcc05365e0f --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/BI.java @@ -0,0 +1,34 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.facets; + +import test.Ice.facets.Test._BDisp; + +public final class BI extends _BDisp +{ + public + BI() + { + } + + @Override + public String + callA(Ice.Current current) + { + return "A"; + } + + @Override + public String + callB(Ice.Current current) + { + return "B"; + } +} diff --git a/java/test/src/main/java/test/Ice/facets/CI.java b/java/test/src/main/java/test/Ice/facets/CI.java new file mode 100644 index 00000000000..fab2a5758ee --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/CI.java @@ -0,0 +1,34 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.facets; + +import test.Ice.facets.Test._CDisp; + +public final class CI extends _CDisp +{ + public + CI() + { + } + + @Override + public String + callA(Ice.Current current) + { + return "A"; + } + + @Override + public String + callC(Ice.Current current) + { + return "C"; + } +} diff --git a/java/test/src/main/java/test/Ice/facets/Client.java b/java/test/src/main/java/test/Ice/facets/Client.java new file mode 100644 index 00000000000..22867839eb7 --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/Client.java @@ -0,0 +1,41 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.facets; + +import test.Ice.facets.Test.GPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + GPrx g = AllTests.allTests(communicator, getWriter()); + g.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.binding"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/facets/Collocated.java b/java/test/src/main/java/test/Ice/facets/Collocated.java new file mode 100644 index 00000000000..9503a7e7748 --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/Collocated.java @@ -0,0 +1,49 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.facets; + +public class Collocated extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object d = new DI(); + adapter.add(d, communicator.stringToIdentity("d")); + adapter.addFacet(d, communicator.stringToIdentity("d"), "facetABCD"); + Ice.Object f = new FI(); + adapter.addFacet(f, communicator.stringToIdentity("d"), "facetEF"); + Ice.Object h = new HI(communicator); + adapter.addFacet(h, communicator.stringToIdentity("d"), "facetGH"); + + AllTests.allTests(communicator, getWriter()); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.facets"); + return initData; + } + + public static void main(String[] args) + { + Collocated app = new Collocated(); + int result = app.main("Collocated", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/facets/DI.java b/java/test/src/main/java/test/Ice/facets/DI.java new file mode 100644 index 00000000000..cd4274dbaac --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/DI.java @@ -0,0 +1,48 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.facets; + +import test.Ice.facets.Test._DDisp; + +public final class DI extends _DDisp +{ + public + DI() + { + } + + @Override + public String + callA(Ice.Current current) + { + return "A"; + } + + @Override + public String + callB(Ice.Current current) + { + return "B"; + } + + @Override + public String + callC(Ice.Current current) + { + return "C"; + } + + @Override + public String + callD(Ice.Current current) + { + return "D"; + } +} diff --git a/java/test/src/main/java/test/Ice/facets/EI.java b/java/test/src/main/java/test/Ice/facets/EI.java new file mode 100644 index 00000000000..6ebeb0ee8b3 --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/EI.java @@ -0,0 +1,27 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.facets; + +import test.Ice.facets.Test._EDisp; + +public final class EI extends _EDisp +{ + public + EI() + { + } + + @Override + public String + callE(Ice.Current current) + { + return "E"; + } +} diff --git a/java/test/src/main/java/test/Ice/facets/EmptyI.java b/java/test/src/main/java/test/Ice/facets/EmptyI.java new file mode 100644 index 00000000000..89d633d6b7b --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/EmptyI.java @@ -0,0 +1,16 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.facets; + +import test.Ice.facets.Test._EmptyDisp; + +public final class EmptyI extends _EmptyDisp +{ +} diff --git a/java/test/src/main/java/test/Ice/facets/FI.java b/java/test/src/main/java/test/Ice/facets/FI.java new file mode 100644 index 00000000000..5d945d86714 --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/FI.java @@ -0,0 +1,34 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.facets; + +import test.Ice.facets.Test._FDisp; + +public final class FI extends _FDisp +{ + public + FI() + { + } + + @Override + public String + callE(Ice.Current current) + { + return "E"; + } + + @Override + public String + callF(Ice.Current current) + { + return "F"; + } +} diff --git a/java/test/src/main/java/test/Ice/facets/GI.java b/java/test/src/main/java/test/Ice/facets/GI.java new file mode 100644 index 00000000000..397501ddeb7 --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/GI.java @@ -0,0 +1,37 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.facets; + +import test.Ice.facets.Test._GDisp; + +public final class GI extends _GDisp +{ + public + GI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + @Override + public String + callG(Ice.Current current) + { + return "G"; + } + + @Override + public void + shutdown(Ice.Current current) + { + _communicator.shutdown(); + } + + private Ice.Communicator _communicator; +} diff --git a/java/test/src/main/java/test/Ice/facets/HI.java b/java/test/src/main/java/test/Ice/facets/HI.java new file mode 100644 index 00000000000..49bc8de2337 --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/HI.java @@ -0,0 +1,44 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.facets; + +import test.Ice.facets.Test._HDisp; + +public final class HI extends _HDisp +{ + public + HI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + @Override + public String + callG(Ice.Current current) + { + return "G"; + } + + @Override + public String + callH(Ice.Current current) + { + return "H"; + } + + @Override + public void + shutdown(Ice.Current current) + { + _communicator.shutdown(); + } + + private Ice.Communicator _communicator; +} diff --git a/java/test/src/main/java/test/Ice/facets/Server.java b/java/test/src/main/java/test/Ice/facets/Server.java new file mode 100644 index 00000000000..0bba8b89cdf --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/Server.java @@ -0,0 +1,49 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.facets; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object d = new DI(); + adapter.add(d, communicator.stringToIdentity("d")); + adapter.addFacet(d, communicator.stringToIdentity("d"), "facetABCD"); + Ice.Object f = new FI(); + adapter.addFacet(f, communicator.stringToIdentity("d"), "facetEF"); + Ice.Object h = new HI(communicator); + adapter.addFacet(h, communicator.stringToIdentity("d"), "facetGH"); + + adapter.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.facets"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/facets/Test.ice b/java/test/src/main/java/test/Ice/facets/Test.ice new file mode 100644 index 00000000000..fa6a545118e --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/Test.ice @@ -0,0 +1,61 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.facets"]] +module Test +{ + +interface Empty +{ +}; + +interface A +{ + string callA(); +}; + +interface B extends A +{ + string callB(); +}; + +interface C extends A +{ + string callC(); +}; + +interface D extends B, C +{ + string callD(); +}; + +interface E +{ + string callE(); +}; + +interface F extends E +{ + string callF(); +}; + +interface G +{ + void shutdown(); + string callG(); +}; + +interface H extends G +{ + string callH(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/facets/run.py b/java/test/src/main/java/test/Ice/facets/run.py new file mode 100755 index 00000000000..8bb456187d9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/facets/run.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/faultTolerance/AllTests.java b/java/test/src/main/java/test/Ice/faultTolerance/AllTests.java new file mode 100644 index 00000000000..4e334301a62 --- /dev/null +++ b/java/test/src/main/java/test/Ice/faultTolerance/AllTests.java @@ -0,0 +1,328 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.faultTolerance; + +import java.io.PrintWriter; + +import test.Ice.faultTolerance.Test.TestIntfPrx; +import test.Ice.faultTolerance.Test.TestIntfPrxHelper; +import test.Ice.faultTolerance.Test.Callback_TestIntf_pid; +import test.Ice.faultTolerance.Test.Callback_TestIntf_shutdown; + +public class AllTests +{ + public static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized void + check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void + called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static class Callback_TestIntf_pidI extends Callback_TestIntf_pid + { + @Override + public void + response(int pid) + { + _pid = pid; + callback.called(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + + public int + pid() + { + return _pid; + } + + public void + check() + { + callback.check(); + } + + private int _pid; + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_shutdownI extends Callback_TestIntf_shutdown + { + @Override + public void + response() + { + callback.called(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class AbortCallback extends Ice.Callback + { + @Override + public void + completed(Ice.AsyncResult result) + { + try + { + TestIntfPrx p = TestIntfPrxHelper.uncheckedCast(result.getProxy()); + if(result.getOperation().equals("abort")) + { + p.end_abort(result); + } + else if(result.getOperation().equals("idempotentAbort")) + { + p.end_idempotentAbort(result); + } + test(false); + } + catch(Ice.ConnectionLostException exc) + { + } + catch(Ice.ConnectFailedException exc) + { + } + catch(Ice.SocketException exc) + { + } + catch(Exception exc) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + public static void + allTests(Ice.Communicator communicator, int[] ports, PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + String ref = "test"; + for(int port : ports) + { + ref += ":default -p " + port; + } + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + TestIntfPrx obj = TestIntfPrxHelper.checkedCast(base); + test(obj != null); + test(obj.equals(base)); + out.println("ok"); + + int oldPid = 0; + boolean ami = false; + for(int i = 1, j = 0; i <= ports.length; ++i, ++j) + { + if(j > 3) + { + j = 0; + ami = !ami; + } + + if(!ami) + { + out.print("testing server #" + i + "... "); + out.flush(); + int pid = obj.pid(); + test(pid != oldPid); + out.println("ok"); + oldPid = pid; + } + else + { + out.print("testing server #" + i + " with AMI... "); + out.flush(); + Callback_TestIntf_pidI cb = new Callback_TestIntf_pidI(); + obj.begin_pid(cb); + cb.check(); + int pid = cb.pid(); + test(pid != oldPid); + out.println("ok"); + oldPid = pid; + } + + if(j == 0) + { + if(!ami) + { + out.print("shutting down server #" + i + "... "); + out.flush(); + obj.shutdown(); + out.println("ok"); + } + else + { + out.print("shutting down server #" + i + " with AMI... "); + out.flush(); + Callback_TestIntf_shutdownI cb = new Callback_TestIntf_shutdownI(); + obj.begin_shutdown(cb); + cb.check(); + out.println("ok"); + } + } + else if(j == 1 || i + 1 > ports.length) + { + if(!ami) + { + out.print("aborting server #" + i + "... "); + out.flush(); + try + { + obj.abort(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + out.println("ok"); + } + catch(Ice.ConnectFailedException exc) + { + out.println("ok"); + } + catch(Ice.SocketException ex) + { + out.println("ok"); + } + } + else + { + out.print("aborting server #" + i + " with AMI... "); + out.flush(); + AbortCallback cb = new AbortCallback(); + obj.begin_abort(cb); + cb.check(); + out.println("ok"); + } + } + else if(j == 2 || j == 3) + { + if(!ami) + { + out.print("aborting server #" + i + " and #" + (i + 1) + " with idempotent call... "); + out.flush(); + try + { + obj.idempotentAbort(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + out.println("ok"); + } + catch(Ice.ConnectFailedException exc) + { + out.println("ok"); + } + catch(Ice.SocketException ex) + { + out.println("ok"); + } + } + else + { + out.print("aborting server #" + i + " and #" + (i + 1) + " with idempotent AMI call... "); + out.flush(); + AbortCallback cb = new AbortCallback(); + obj.begin_idempotentAbort(cb); + cb.check(); + out.println("ok"); + } + + ++i; + } + else + { + assert(false); + } + } + + out.print("testing whether all servers are gone... "); + out.flush(); + try + { + obj.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + out.println("ok"); + } + } +} diff --git a/java/test/src/main/java/test/Ice/faultTolerance/Client.java b/java/test/src/main/java/test/Ice/faultTolerance/Client.java new file mode 100644 index 00000000000..7f2fb23b80e --- /dev/null +++ b/java/test/src/main/java/test/Ice/faultTolerance/Client.java @@ -0,0 +1,105 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.faultTolerance; + +import java.io.PrintWriter; + + +public class Client extends test.Util.Application +{ + private static void + usage() + { + System.err.println("Usage: Client port..."); + } + + @Override + public int + run(String[] args) + { + PrintWriter out = getWriter(); + + Ice.Communicator communicator = communicator(); + java.util.List<Integer> ports = new java.util.ArrayList<Integer>(args.length); + for(String arg : args) + { + if(arg.charAt(0) == '-') + { + // + // TODO: Arguments recognized by the communicator are not + // removed from the argument list. + // + //System.err.println("Client: unknown option `" + arg + "'"); + //usage(); + //return 1; + continue; + } + + int port = 0; + try + { + port = Integer.parseInt(arg); + } + catch(NumberFormatException ex) + { + ex.printStackTrace(); + return 1; + } + ports.add(port); + } + + if(ports.isEmpty()) + { + out.println("Client: no ports specified"); + usage(); + return 1; + } + + int[] arr = new int[ports.size()]; + for(int i = 0; i < arr.length; i++) + { + arr[i] = ports.get(i).intValue(); + } + + try + { + AllTests.allTests(communicator, arr, out); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + AllTests.test(false); + } + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.faultTolerance"); + // + // This test aborts servers, so we don't want warnings. + // + initData.properties.setProperty("Ice.Warn.Connections", "0"); + + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/faultTolerance/Server.java b/java/test/src/main/java/test/Ice/faultTolerance/Server.java new file mode 100644 index 00000000000..18d113fdeae --- /dev/null +++ b/java/test/src/main/java/test/Ice/faultTolerance/Server.java @@ -0,0 +1,91 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.faultTolerance; + +import java.io.PrintWriter; + +public class Server extends test.Util.Application +{ + private static void + usage() + { + System.err.println("Usage: Server port"); + } + + @Override + public int + run(String[] args) + { + Ice.Communicator communicator = communicator(); + int port = 0; + PrintWriter out = getWriter(); + for(String arg : args) + { + if(arg.charAt(0) == '-') + { + out.println("Server: unknown option `" + arg + "'"); + usage(); + return 1; + } + + if(port > 0) + { + out.println("Server: only one port can be specified"); + usage(); + return 1; + } + + try + { + port = Integer.parseInt(arg); + } + catch(NumberFormatException ex) + { + out.println("Server: invalid port"); + usage(); + return 1; + } + } + + if(port <= 0) + { + out.println("Server: no port specified"); + usage(); + return 1; + } + + // Don't move this, it needs the port. + communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p " + port + ":udp"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object object = new TestI(port); + adapter.add(object, communicator.stringToIdentity("test")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.faultTolerance"); + // Two minutes. + initData.properties.setProperty("Ice.ServerIdleTime", "120"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/faultTolerance/Test.ice b/java/test/src/main/java/test/Ice/faultTolerance/Test.ice new file mode 100644 index 00000000000..e5f616aa8a0 --- /dev/null +++ b/java/test/src/main/java/test/Ice/faultTolerance/Test.ice @@ -0,0 +1,24 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.faultTolerance"]] +module Test +{ + +interface TestIntf +{ + void shutdown(); + void abort(); + idempotent void idempotentAbort(); + idempotent int pid(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/faultTolerance/TestI.java b/java/test/src/main/java/test/Ice/faultTolerance/TestI.java new file mode 100644 index 00000000000..3d3b362bd0a --- /dev/null +++ b/java/test/src/main/java/test/Ice/faultTolerance/TestI.java @@ -0,0 +1,51 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.faultTolerance; + +import test.Ice.faultTolerance.Test._TestIntfDisp; + +public final class TestI extends _TestIntfDisp +{ + public + TestI(int port) + { + _pseudoPid = port; // We use the port number instead of the process ID in Java. + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + @Override + public void + abort(Ice.Current current) + { + Runtime.getRuntime().halt(0); + } + + @Override + public void + idempotentAbort(Ice.Current current) + { + Runtime.getRuntime().halt(0); + } + + @Override + public int + pid(Ice.Current current) + { + return _pseudoPid; + } + + private int _pseudoPid; +} diff --git a/java/test/src/main/java/test/Ice/faultTolerance/run.py b/java/test/src/main/java/test/Ice/faultTolerance/run.py new file mode 100755 index 00000000000..11e4dfc9efd --- /dev/null +++ b/java/test/src/main/java/test/Ice/faultTolerance/run.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +num = 12 +base = 12340 + +serverProc = [] +for i in range(0, num): + sys.stdout.write("starting server #%d... " % (i + 1)) + sys.stdout.flush() + serverProc.append(TestUtil.startServer("test.Ice.faultTolerance.Server", " %d" % (base + i))) + print("ok") + +ports = "" +for i in range(0, num): + ports = "%s %d" % (ports, base + i) +sys.stdout.write("starting client... ") +sys.stdout.flush() +clientProc = TestUtil.startClient("test.Ice.faultTolerance.Client", ports, startReader=False) +print("ok") +clientProc.startReader() + +clientProc.waitTestSuccess() +for p in serverProc: + p.waitTestSuccess() diff --git a/java/test/src/main/java/test/Ice/hash/Client.java b/java/test/src/main/java/test/Ice/hash/Client.java new file mode 100644 index 00000000000..6a01bf62285 --- /dev/null +++ b/java/test/src/main/java/test/Ice/hash/Client.java @@ -0,0 +1,445 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.hash; + +import java.io.PrintWriter; + +import test.Ice.hash.Test.*; + +public class Client extends test.Util.Application +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } + + @Override + public int run(String[] args) + { + PrintWriter out = getWriter(); + int status = 0; + try + { + java.util.Map<Integer, Ice.ObjectPrx> seenProxy = new java.util.HashMap<Integer, Ice.ObjectPrx>(); + java.util.Map<Integer, Ice.Endpoint> seenEndpoint = new java.util.HashMap<Integer, Ice.Endpoint>(); + int proxyCollisions = 0; + int endpointCollisions = 0; + int i = 0; + int maxCollisions = 10; + int maxIterations = 10000; + + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(args); + initData.properties.setProperty("Ice.Plugin.IceSSL", "IceSSL.PluginFactory"); + Ice.Communicator communicator = Ice.Util.initialize(args, initData); + + out.print("testing proxy & endpoint hash algorithm collisions... "); + out.flush(); + { + java.util.Random rand = new java.util.Random(); + for(i = 0; proxyCollisions < maxCollisions && + endpointCollisions < maxCollisions && + i < maxIterations; ++i) + { + java.io.StringWriter sw = new java.io.StringWriter(); + sw.write(Integer.toString(i)); + sw.write(":tcp -p "); + sw.write(Integer.toString(rand.nextInt(65536))); + sw.write(" -t 10"); + sw.write(Integer.toString(rand.nextInt(1000000))); + sw.write(":udp -p "); + sw.write(Integer.toString(rand.nextInt(65536))); + sw.write(" -h "); + sw.write(Integer.toString(rand.nextInt(100))); + + Ice.ObjectPrx obj = communicator.stringToProxy(sw.toString()); + java.util.List<Ice.Endpoint> endpoints = new java.util.ArrayList<Ice.Endpoint>(java.util.Arrays.asList(obj.ice_getEndpoints())); + if(seenProxy.containsKey(obj.hashCode())) + { + if(obj.equals(seenProxy.get(obj.hashCode()))) + { + continue; // Same object + } + ++proxyCollisions; + } + else + { + seenProxy.put(obj.hashCode(), obj); + } + + java.util.Iterator<Ice.Endpoint> j = endpoints.iterator(); + while(j.hasNext()) + { + Ice.Endpoint endpoint = j.next(); + if(seenEndpoint.containsKey(endpoint.hashCode())) + { + if(endpoint.equals(seenEndpoint.get(endpoint.hashCode()))) + { + continue; // Same endpoint + } + ++endpointCollisions; + } + else + { + seenEndpoint.put(endpoint.hashCode(), endpoint); + } + // + // Check the same endpoint produce always the same hash + // + test(endpoint.hashCode() == endpoint.hashCode()); + } + // + // Check the same proxy produce always the same hash + // + test(obj.hashCode() == obj.hashCode()); + } + test(proxyCollisions < maxCollisions); + test(endpointCollisions < maxCollisions); + + proxyCollisions = 0; + seenProxy = new java.util.HashMap<Integer, Ice.ObjectPrx>(); + for(i = 0; proxyCollisions < maxCollisions && + endpointCollisions < maxCollisions && + i < maxIterations; ++i) + { + java.io.StringWriter sw = new java.io.StringWriter(); + sw.write(Integer.toString(i)); + sw.write(":tcp -p "); + sw.write(Integer.toString(rand.nextInt(65536))); + sw.write(" -t 10"); + sw.write(Integer.toString(rand.nextInt(1000000))); + sw.write(":udp -p "); + sw.write(Integer.toString(rand.nextInt(65536))); + sw.write(" -h "); + sw.write(Integer.toString(rand.nextInt(100))); + + Ice.ProxyIdentityKey obj = new Ice.ProxyIdentityKey(communicator.stringToProxy(sw.toString())); + if(seenProxy.containsKey(obj.hashCode())) + { + ++proxyCollisions; + } + else + { + seenProxy.put(obj.hashCode(), obj.getProxy()); + } + // + // Check the same proxy produce always the same hash + // + test(obj.hashCode() == obj.hashCode()); + } + test(proxyCollisions < maxCollisions); + + proxyCollisions = 0; + seenProxy = new java.util.HashMap<Integer, Ice.ObjectPrx>(); + for(i = 0; proxyCollisions < maxCollisions && + endpointCollisions < maxCollisions && + i < maxIterations; ++i) + { + java.io.StringWriter sw = new java.io.StringWriter(); + sw.write(Integer.toString(i)); + sw.write(":tcp -p "); + sw.write(Integer.toString(rand.nextInt(65536))); + sw.write(" -t 10"); + sw.write(Integer.toString(rand.nextInt(1000000))); + sw.write(":udp -p "); + sw.write(Integer.toString(rand.nextInt(65536))); + sw.write(" -h "); + sw.write(Integer.toString(rand.nextInt(100))); + + Ice.ProxyIdentityFacetKey obj = new Ice.ProxyIdentityFacetKey(communicator.stringToProxy(sw.toString())); + if(seenProxy.containsKey(obj.hashCode())) + { + ++proxyCollisions; + } + else + { + seenProxy.put(obj.hashCode(), obj.getProxy()); + } + // + // Check the same proxy produce always the same hash + // + test(obj.hashCode() == obj.hashCode()); + } + test(proxyCollisions < maxCollisions); + + Ice.ObjectPrx prx1 = communicator.stringToProxy("Glacier2/router:tcp -p 10010"); + Ice.ObjectPrx prx2 = communicator.stringToProxy("Glacier2/router:ssl -p 10011"); + Ice.ObjectPrx prx3 = communicator.stringToProxy("Glacier2/router:udp -p 10012"); + Ice.ObjectPrx prx4 = communicator.stringToProxy("Glacier2/router:tcp -h zeroc.com -p 10010"); + Ice.ObjectPrx prx5 = communicator.stringToProxy("Glacier2/router:ssl -h zeroc.com -p 10011"); + Ice.ObjectPrx prx6 = communicator.stringToProxy("Glacier2/router:udp -h zeroc.com -p 10012"); + Ice.ObjectPrx prx7 = communicator.stringToProxy("Glacier2/router:tcp -p 10010 -t 10000"); + Ice.ObjectPrx prx8 = communicator.stringToProxy("Glacier2/router:ssl -p 10011 -t 10000"); + Ice.ObjectPrx prx9 = communicator.stringToProxy("Glacier2/router:tcp -h zeroc.com -p 10010 -t 10000"); + Ice.ObjectPrx prx10 = communicator.stringToProxy("Glacier2/router:ssl -h zeroc.com -p 10011 -t 10000"); + + java.util.Map<String, Integer> proxyMap = new java.util.HashMap<String, Integer>(); + proxyMap.put("prx1", prx1.hashCode()); + proxyMap.put("prx2", prx2.hashCode()); + proxyMap.put("prx3", prx3.hashCode()); + proxyMap.put("prx4", prx4.hashCode()); + proxyMap.put("prx5", prx5.hashCode()); + proxyMap.put("prx6", prx6.hashCode()); + proxyMap.put("prx7", prx7.hashCode()); + proxyMap.put("prx8", prx8.hashCode()); + proxyMap.put("prx9", prx9.hashCode()); + proxyMap.put("prx10", prx10.hashCode()); + + test(communicator.stringToProxy("Glacier2/router:tcp -p 10010").hashCode() == proxyMap.get("prx1")); + test(communicator.stringToProxy("Glacier2/router:ssl -p 10011").hashCode() == proxyMap.get("prx2")); + test(communicator.stringToProxy("Glacier2/router:udp -p 10012").hashCode() == proxyMap.get("prx3")); + test(communicator.stringToProxy("Glacier2/router:tcp -h zeroc.com -p 10010").hashCode() == proxyMap.get("prx4")); + test(communicator.stringToProxy("Glacier2/router:ssl -h zeroc.com -p 10011").hashCode() == proxyMap.get("prx5")); + test(communicator.stringToProxy("Glacier2/router:udp -h zeroc.com -p 10012").hashCode() == proxyMap.get("prx6")); + test(communicator.stringToProxy("Glacier2/router:tcp -p 10010 -t 10000").hashCode() == proxyMap.get("prx7")); + test(communicator.stringToProxy("Glacier2/router:ssl -p 10011 -t 10000").hashCode() == proxyMap.get("prx8")); + test(communicator.stringToProxy("Glacier2/router:tcp -h zeroc.com -p 10010 -t 10000").hashCode() == proxyMap.get("prx9")); + test(communicator.stringToProxy("Glacier2/router:ssl -h zeroc.com -p 10011 -t 10000").hashCode() == proxyMap.get("prx10")); + + test(new Ice.ProxyIdentityKey(prx1).hashCode() == new Ice.ProxyIdentityKey(prx1).hashCode()); + test(new Ice.ProxyIdentityFacetKey(prx1).hashCode() == new Ice.ProxyIdentityFacetKey(prx1).hashCode()); + + test(new Ice.ProxyIdentityKey(prx1).hashCode() == new Ice.ProxyIdentityKey(prx2).hashCode()); + test(new Ice.ProxyIdentityFacetKey(prx1).hashCode() == new Ice.ProxyIdentityFacetKey(prx2).hashCode()); + + test(new Ice.ProxyIdentityKey(prx1).hashCode() == new Ice.ProxyIdentityKey(prx3).hashCode()); + test(new Ice.ProxyIdentityFacetKey(prx1).hashCode() == new Ice.ProxyIdentityFacetKey(prx3).hashCode()); + + test(new Ice.ProxyIdentityKey(prx1).hashCode() == new Ice.ProxyIdentityKey(prx4).hashCode()); + test(new Ice.ProxyIdentityFacetKey(prx1).hashCode() == new Ice.ProxyIdentityFacetKey(prx4).hashCode()); + + test(new Ice.ProxyIdentityKey(prx1).hashCode() == new Ice.ProxyIdentityKey(prx5).hashCode()); + test(new Ice.ProxyIdentityFacetKey(prx1).hashCode() == new Ice.ProxyIdentityFacetKey(prx5).hashCode()); + + test(new Ice.ProxyIdentityKey(prx1).hashCode() == new Ice.ProxyIdentityKey(prx6).hashCode()); + test(new Ice.ProxyIdentityFacetKey(prx1).hashCode() == new Ice.ProxyIdentityFacetKey(prx6).hashCode()); + + test(new Ice.ProxyIdentityKey(prx1).hashCode() == new Ice.ProxyIdentityKey(prx7).hashCode()); + test(new Ice.ProxyIdentityFacetKey(prx1).hashCode() == new Ice.ProxyIdentityFacetKey(prx7).hashCode()); + + test(new Ice.ProxyIdentityKey(prx1).hashCode() == new Ice.ProxyIdentityKey(prx8).hashCode()); + test(new Ice.ProxyIdentityFacetKey(prx1).hashCode() == new Ice.ProxyIdentityFacetKey(prx8).hashCode()); + + test(new Ice.ProxyIdentityKey(prx1).hashCode() == new Ice.ProxyIdentityKey(prx9).hashCode()); + test(new Ice.ProxyIdentityFacetKey(prx1).hashCode() == new Ice.ProxyIdentityFacetKey(prx9).hashCode()); + + test(new Ice.ProxyIdentityKey(prx1).hashCode() == new Ice.ProxyIdentityKey(prx10).hashCode()); + test(new Ice.ProxyIdentityFacetKey(prx1).hashCode() == new Ice.ProxyIdentityFacetKey(prx10).hashCode()); + } + + out.println("ok"); + + out.print("testing struct hash algorithm collisions... "); + out.flush(); + { + java.util.Map<Integer, PointF> seenPointF = new java.util.HashMap<Integer, PointF>(); + java.util.Random rand = new java.util.Random(); + int structCollisions = 0; + for(i = 0; i < maxIterations && structCollisions < maxCollisions; ++i) + { + PointF pf = new PointF(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()); + if(seenPointF.containsKey(pf.hashCode())) + { + if(pf.equals(seenPointF.get(pf.hashCode()))) + { + continue; // same object + } + structCollisions++; + } + else + { + seenPointF.put(pf.hashCode(), pf); + } + // + // Check the same struct produce always the same hash + // + test(pf.hashCode() == pf.hashCode()); + } + test(structCollisions < maxCollisions); + + java.util.Map<Integer, PointD> seenPointD = new java.util.HashMap<Integer, PointD>(); + rand = new java.util.Random(); + structCollisions = 0; + for(i = 0; i < maxIterations && structCollisions < maxCollisions; ++i) + { + PointD pd = new PointD(rand.nextDouble(), rand.nextDouble(), rand.nextDouble()); + if(seenPointD.containsKey(pd.hashCode())) + { + if(pd.equals(seenPointF.get(pd.hashCode()))) + { + continue; // same object + } + structCollisions++; + } + else + { + seenPointD.put(pd.hashCode(), pd); + } + // + // Check the same struct produce always the same hash + // + test(pd.hashCode() == pd.hashCode()); + } + test(structCollisions < maxCollisions); + + java.util.Map<Integer, Polyline> seenPolyline = new java.util.HashMap<Integer, Polyline>(); + structCollisions = 0; + for(i = 0; i < maxIterations && structCollisions < maxCollisions; ++i) + { + Polyline polyline = new Polyline(); + java.util.List<Point> vertices = new java.util.ArrayList<Point>(); + for(int j = 0; j < 100; ++j) + { + vertices.add(new Point(rand.nextInt(100), rand.nextInt(100))); + } + polyline.vertices = new Point[vertices.size()]; + vertices.toArray(polyline.vertices); + + if(seenPolyline.containsKey(polyline.hashCode())) + { + if(polyline.equals(seenPolyline.get(polyline.hashCode()))) + { + continue; // same object + } + structCollisions++; + } + else + { + seenPolyline.put(polyline.hashCode(), polyline); + } + // + // Check the same struct produce always the same hash + // + test(polyline.hashCode() == polyline.hashCode()); + } + test(structCollisions < maxCollisions); + + java.util.Map<Integer, ColorPalette> seenColorPalette = new java.util.HashMap<Integer, ColorPalette>(); + structCollisions = 0; + for(i = 0; i < maxIterations && structCollisions < maxCollisions; ++i) + { + ColorPalette colorPalette = new ColorPalette(); + colorPalette.colors = new java.util.HashMap<Integer, Color>(); + for(int j = 0; j < 100; ++j) + { + colorPalette.colors.put(j, new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255), rand.nextInt(255))); + } + + if(seenColorPalette.containsKey(colorPalette.hashCode())) + { + if(colorPalette.equals(seenColorPalette.get(colorPalette.hashCode()))) + { + continue; // same object + } + structCollisions++; + } + else + { + seenColorPalette.put(colorPalette.hashCode(), colorPalette); + } + // + // Check the same struct produce always the same hash + // + test(colorPalette.hashCode() == colorPalette.hashCode()); + } + test(structCollisions < maxCollisions); + + java.util.Map<Integer, Color> seenColor = new java.util.HashMap<Integer, Color>(); + rand = new java.util.Random(); + structCollisions = 0; + for(i = 0; i < maxIterations && structCollisions < maxCollisions; ++i) + { + Color c = new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)); + if(seenColor.containsKey(c.hashCode())) + { + if(c.equals(seenColor.get(c.hashCode()))) + { + continue; // same object + } + structCollisions++; + } + else + { + seenColor.put(c.hashCode(), c); + } + // + // Check the same struct produce always the same hash + // + test(c.hashCode() == c.hashCode()); + } + test(structCollisions < maxCollisions); + + structCollisions = 0; + java.util.Map<Integer, Draw> seenDraw = new java.util.HashMap<Integer, Draw>(); + structCollisions = 0; + for(i = 0; i < maxIterations && structCollisions < maxCollisions; ++i) + { + Draw draw = new Draw( + new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)), + new Pen(rand.nextInt(10), + new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255), rand.nextInt(255))), + false); + + if(seenDraw.containsKey(draw.hashCode())) + { + if(draw.equals(seenDraw.get(draw.hashCode()))) + { + continue; // same object + } + structCollisions++; + } + else + { + seenDraw.put(draw.hashCode(), draw); + } + // + // Check the same struct produce always the same hash + // + test(draw.hashCode() == draw.hashCode()); + } + test(structCollisions < maxCollisions); + } + out.println("ok"); + + if(communicator != null) + { + try + { + communicator.destroy(); + } + catch(Ice.LocalException ex) + { + System.out.println(ex.toString()); + status = 1; + } + } + } + catch(Exception ex) + { + System.out.println(ex.toString()); + status = 1; + } + return status; + } +} + diff --git a/java/test/src/main/java/test/Ice/hash/Test.ice b/java/test/src/main/java/test/Ice/hash/Test.ice new file mode 100644 index 00000000000..e6b7243d1e7 --- /dev/null +++ b/java/test/src/main/java/test/Ice/hash/Test.ice @@ -0,0 +1,72 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.hash"]] +module Test +{ + +struct PointF +{ + float x; + float y; + float z; +}; + +struct PointD +{ + double x; + double y; + double z; +}; + +struct Point +{ + int x; + int y; +}; +sequence<Point> Points; + +struct Polyline +{ + Points vertices; +}; + +struct Color +{ + int r; + int g; + int b; + int a; +}; + + +dictionary<int, Color> StringColorMap; + +struct ColorPalette +{ + StringColorMap colors; +}; + +class Pen +{ + int thickness; + Test::Color color; +}; + +struct Draw +{ + Test::Color backgroundColor; + Test::Pen pen; + bool shared; +}; + +}; + diff --git a/java/test/src/main/java/test/Ice/hash/run.py b/java/test/src/main/java/test/Ice/hash/run.py new file mode 100755 index 00000000000..29d7f55f0f5 --- /dev/null +++ b/java/test/src/main/java/test/Ice/hash/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil +TestUtil.simpleTest("test.Ice.hash.Client") + diff --git a/java/test/src/main/java/test/Ice/hold/AllTests.java b/java/test/src/main/java/test/Ice/hold/AllTests.java new file mode 100644 index 00000000000..edb5aa78e63 --- /dev/null +++ b/java/test/src/main/java/test/Ice/hold/AllTests.java @@ -0,0 +1,228 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.hold; + +import java.io.PrintWriter; + +import test.Ice.hold.Test.HoldPrx; +import test.Ice.hold.Test.HoldPrxHelper; +import test.Ice.hold.Test.Callback_Hold_set; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static class Condition + { + public Condition(boolean value) + { + _value = value; + } + + synchronized public void + set(boolean value) + { + _value = value; + } + + synchronized boolean + value() + { + return _value; + } + + private boolean _value; + }; + + static class AMICheckSetValue extends Callback_Hold_set + { + public + AMICheckSetValue(Condition condition, int expected) + { + _condition = condition; + _expected = expected; + } + + @Override + public void + response(int value) + { + if(value != _expected) + { + _condition.set(false); + } + } + + @Override + public void + exception(Ice.LocalException ex) + { + } + + @Override + synchronized public void + sent(boolean sync) + { + } + + private Condition _condition; + private int _expected; + }; + + public static void + allTests(Ice.Communicator communicator, PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + String ref = "hold:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + String refSerialized = "hold:default -p 12011"; + Ice.ObjectPrx baseSerialized = communicator.stringToProxy(refSerialized); + test(baseSerialized != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + HoldPrx hold = HoldPrxHelper.checkedCast(base); + HoldPrx holdOneway = HoldPrxHelper.uncheckedCast(base.ice_oneway()); + test(hold != null); + test(hold.equals(base)); + HoldPrx holdSerialized = HoldPrxHelper.checkedCast(baseSerialized); + HoldPrx holdSerializedOneway = HoldPrxHelper.uncheckedCast(baseSerialized.ice_oneway()); + test(holdSerialized != null); + test(holdSerialized.equals(baseSerialized)); + out.println("ok"); + + out.print("changing state between active and hold rapidly... "); + out.flush(); + for(int i = 0; i < 100; ++i) + { + hold.putOnHold(0); + } + for(int i = 0; i < 100; ++i) + { + holdOneway.putOnHold(0); + } + for(int i = 0; i < 100; ++i) + { + holdSerialized.putOnHold(0); + } + for(int i = 0; i < 100; ++i) + { + holdSerializedOneway.putOnHold(0); + } + out.println("ok"); + + out.print("testing without serialize mode... "); + out.flush(); + java.util.Random random = new java.util.Random(); + { + Condition cond = new Condition(true); + int value = 0; + Ice.AsyncResult result = null; + while(cond.value()) + { + result = hold.begin_set(value + 1, random.nextInt(5), new AMICheckSetValue(cond, value)); + ++value; + if(value % 100 == 0) + { + result.waitForSent(); + } + } + result.waitForCompleted(); + } + out.println("ok"); + + out.print("testing with serialize mode... "); + out.flush(); + { + Condition cond = new Condition(true); + int value = 0; + Ice.AsyncResult result = null; + while(value < 3000 && cond.value()) + { + result = holdSerialized.begin_set(value + 1, random.nextInt(1), new AMICheckSetValue(cond, value)); + ++value; + if(value % 100 == 0) + { + result.waitForSent(); + } + } + result.waitForCompleted(); + test(cond.value()); + + for(int i = 0; i < 10000; ++i) + { + holdSerializedOneway.setOneway(value + 1, value); + ++value; + if((i % 100) == 0) + { + holdSerializedOneway.putOnHold(1); + } + } + } + out.println("ok"); + + out.print("testing serialization... "); + out.flush(); + { + int value = 0; + holdSerialized.set(value, 0); + Ice.AsyncResult result = null; + for(int i = 0; i < 10000; ++i) + { + // Create a new proxy for each request + result = ((HoldPrx)holdSerialized.ice_oneway()).begin_setOneway(value + 1, value); + ++value; + if((i % 100) == 0) + { + result.waitForSent(); + holdSerialized.ice_ping(); // Ensure everything's dispatched + holdSerialized.ice_getConnection().close(false); + } + } + result.waitForCompleted(); + } + out.println("ok"); + + out.print("testing waitForHold... "); + out.flush(); + { + hold.waitForHold(); + hold.waitForHold(); + for(int i = 0; i < 1000; ++i) + { + holdOneway.ice_ping(); + if((i % 20) == 0) + { + hold.putOnHold(0); + } + } + hold.putOnHold(-1); + hold.ice_ping(); + hold.putOnHold(-1); + hold.ice_ping(); + } + out.println("ok"); + + out.print("changing state to hold and shutting down server... "); + out.flush(); + hold.shutdown(); + out.println("ok"); + } +} diff --git a/java/test/src/main/java/test/Ice/hold/Client.java b/java/test/src/main/java/test/Ice/hold/Client.java new file mode 100644 index 00000000000..58e4e1abd32 --- /dev/null +++ b/java/test/src/main/java/test/Ice/hold/Client.java @@ -0,0 +1,38 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.hold; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + AllTests.allTests(communicator, getWriter()); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.hold"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/hold/HoldI.java b/java/test/src/main/java/test/Ice/hold/HoldI.java new file mode 100644 index 00000000000..b127f4bebb8 --- /dev/null +++ b/java/test/src/main/java/test/Ice/hold/HoldI.java @@ -0,0 +1,133 @@ + +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.hold; + +import test.Ice.hold.Test._HoldDisp; + +public final class HoldI extends _HoldDisp +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + HoldI(java.util.Timer timer, Ice.ObjectAdapter adapter) + { + _timer = timer; + _adapter = adapter; + _last = 0; + } + + @Override + public void + putOnHold(int milliSeconds, Ice.Current current) + { + if(milliSeconds < 0) + { + _adapter.hold(); + } + else if(milliSeconds == 0) + { + _adapter.hold(); + _adapter.activate(); + } + else + { + _timer.schedule(new java.util.TimerTask() + { + @Override + public void run() + { + try + { + putOnHold(0, null); + } + catch(Ice.ObjectAdapterDeactivatedException ex) + { + } + } + }, milliSeconds); + } + } + + @Override + public void + waitForHold(final Ice.Current current) + { + _timer.schedule(new java.util.TimerTask() + { + @Override + public void run() + { + try + { + current.adapter.waitForHold(); + + current.adapter.activate(); + } + catch(Ice.ObjectAdapterDeactivatedException ex) + { + // + // This shouldn't occur. The test ensures all the + // waitForHold timers are + // finished before shutting down the communicator. + // + test(false); + } + } + }, 0); + } + + + @Override + public int + set(int value, int delay, Ice.Current current) + { + try + { + Thread.sleep(delay); + } + catch(java.lang.InterruptedException ex) + { + } + + synchronized(this) + { + int tmp = _last; + _last = value; + return tmp; + } + } + + @Override + synchronized public void + setOneway(int value, int expected, Ice.Current current) + { + test(_last == expected); + _last = value; + } + + @Override + public void + shutdown(Ice.Current current) + { + _adapter.hold(); + _adapter.getCommunicator().shutdown(); + } + + final private java.util.Timer _timer; + final private Ice.ObjectAdapter _adapter; + int _last = 0; +} diff --git a/java/test/src/main/java/test/Ice/hold/Server.java b/java/test/src/main/java/test/Ice/hold/Server.java new file mode 100644 index 00000000000..97019f8021e --- /dev/null +++ b/java/test/src/main/java/test/Ice/hold/Server.java @@ -0,0 +1,64 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.hold; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + java.util.Timer timer = new java.util.Timer(); + + Ice.ObjectAdapter adapter1 = communicator.createObjectAdapter("TestAdapter1"); + adapter1.add(new HoldI(timer, adapter1), communicator.stringToIdentity("hold")); + + Ice.ObjectAdapter adapter2 = communicator.createObjectAdapter("TestAdapter2"); + adapter2.add(new HoldI(timer, adapter2), communicator.stringToIdentity("hold")); + + adapter1.activate(); + adapter2.activate(); + + serverReady(); + communicator.waitForShutdown(); + + timer.cancel(); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.hold"); + initData.properties.setProperty("TestAdapter1.Endpoints", "default -p 12010:udp"); + initData.properties.setProperty("TestAdapter1.ThreadPool.Size", "5"); + initData.properties.setProperty("TestAdapter1.ThreadPool.SizeMax", "5"); + initData.properties.setProperty("TestAdapter1.ThreadPool.SizeWarn", "0"); + initData.properties.setProperty("TestAdapter1.ThreadPool.Serialize", "0"); + + initData.properties.setProperty("TestAdapter2.Endpoints", "default -p 12011:udp"); + initData.properties.setProperty("TestAdapter2.ThreadPool.Size", "5"); + initData.properties.setProperty("TestAdapter2.ThreadPool.SizeMax", "5"); + initData.properties.setProperty("TestAdapter2.ThreadPool.SizeWarn", "0"); + initData.properties.setProperty("TestAdapter2.ThreadPool.Serialize", "1"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/hold/Test.ice b/java/test/src/main/java/test/Ice/hold/Test.ice new file mode 100644 index 00000000000..c77f95e299f --- /dev/null +++ b/java/test/src/main/java/test/Ice/hold/Test.ice @@ -0,0 +1,25 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.hold"]] +module Test +{ + +interface Hold +{ + void putOnHold(int seconds); + void waitForHold(); + int set(int value, int delay); + void setOneway(int value, int expected); + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/hold/run.py b/java/test/src/main/java/test/Ice/hold/run.py new file mode 100755 index 00000000000..d5fe04787c9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/hold/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/info/AllTests.java b/java/test/src/main/java/test/Ice/info/AllTests.java new file mode 100644 index 00000000000..77d4e6332a6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/info/AllTests.java @@ -0,0 +1,183 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.info; + +import java.io.PrintWriter; + +import test.Ice.info.Test.TestIntfPrx; +import test.Ice.info.Test.TestIntfPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + allTests(Ice.Communicator communicator, PrintWriter out) + { + out.print("testing proxy endpoint information... "); + out.flush(); + { + Ice.ObjectPrx p1 = communicator.stringToProxy( + "test -t:default -h tcphost -p 10000 -t 1200 -z --sourceAddress 10.10.10.10:" + + "udp -h udphost -p 10001 --interface eth0 --ttl 5 --sourceAddress 10.10.10.10:" + + "opaque -e 1.8 -t 100 -v ABCD"); + + Ice.Endpoint[] endps = p1.ice_getEndpoints(); + + + Ice.IPEndpointInfo ipEndpoint = (Ice.IPEndpointInfo)endps[0].getInfo(); + test(ipEndpoint.host.equals("tcphost")); + test(ipEndpoint.port == 10000); + test(ipEndpoint.timeout == 1200); + test(ipEndpoint.sourceAddress.equals("10.10.10.10")); + test(ipEndpoint.compress); + test(!ipEndpoint.datagram()); + test(ipEndpoint.type() == Ice.TCPEndpointType.value && !ipEndpoint.secure() || + ipEndpoint.type() == IceSSL.EndpointType.value && ipEndpoint.secure() || + ipEndpoint.type() == Ice.WSEndpointType.value && !ipEndpoint.secure() || + ipEndpoint.type() == Ice.WSSEndpointType.value && ipEndpoint.secure()); + test(ipEndpoint.type() == Ice.TCPEndpointType.value && ipEndpoint instanceof Ice.TCPEndpointInfo || + ipEndpoint.type() == IceSSL.EndpointType.value && ipEndpoint instanceof IceSSL.EndpointInfo || + ipEndpoint.type() == Ice.WSEndpointType.value && ipEndpoint instanceof Ice.WSEndpointInfo || + ipEndpoint.type() == Ice.WSSEndpointType.value && ipEndpoint instanceof Ice.WSEndpointInfo); + + Ice.UDPEndpointInfo udpEndpoint = (Ice.UDPEndpointInfo)endps[1].getInfo(); + test(udpEndpoint.host.equals("udphost")); + test(udpEndpoint.port == 10001); + test(udpEndpoint.mcastInterface.equals("eth0")); + test(udpEndpoint.mcastTtl == 5); + test(udpEndpoint.sourceAddress.equals("10.10.10.10")); + test(udpEndpoint.timeout == -1); + test(!udpEndpoint.compress); + test(!udpEndpoint.secure()); + test(udpEndpoint.datagram()); + test(udpEndpoint.type() == Ice.UDPEndpointType.value); + + Ice.OpaqueEndpointInfo opaqueEndpoint = (Ice.OpaqueEndpointInfo)endps[2].getInfo(); + test(opaqueEndpoint.rawEncoding.equals(new Ice.EncodingVersion((byte)1, (byte)8))); + } + out.println("ok"); + + String defaultHost = communicator.getProperties().getProperty("Ice.Default.Host"); + out.print("test object adapter endpoint information... "); + out.flush(); + { + communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -t 15000:udp"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + + Ice.Endpoint[] endpoints = adapter.getEndpoints(); + test(endpoints.length == 2); + Ice.Endpoint[] publishedEndpoints = adapter.getPublishedEndpoints(); + test(java.util.Arrays.equals(endpoints, publishedEndpoints)); + + Ice.IPEndpointInfo ipEndpoint = (Ice.IPEndpointInfo)endpoints[0].getInfo(); + test(ipEndpoint.type() == Ice.TCPEndpointType.value || ipEndpoint.type() == IceSSL.EndpointType.value || + ipEndpoint.type() == Ice.WSEndpointType.value || ipEndpoint.type() == Ice.WSSEndpointType.value); + test(ipEndpoint.host.equals(defaultHost)); + test(ipEndpoint.port > 0); + test(ipEndpoint.timeout == 15000); + + Ice.UDPEndpointInfo udpEndpoint = (Ice.UDPEndpointInfo)endpoints[1].getInfo(); + test(udpEndpoint.host.equals(defaultHost)); + test(udpEndpoint.datagram()); + test(udpEndpoint.port > 0); + + adapter.destroy(); + + communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -h * -p 12020"); + communicator.getProperties().setProperty("TestAdapter.PublishedEndpoints", "default -h 127.0.0.1 -p 12020"); + adapter = communicator.createObjectAdapter("TestAdapter"); + + endpoints = adapter.getEndpoints(); + test(endpoints.length >= 1); + publishedEndpoints = adapter.getPublishedEndpoints(); + test(publishedEndpoints.length == 1); + + for(Ice.Endpoint endpoint : endpoints) + { + ipEndpoint = (Ice.IPEndpointInfo)endpoint.getInfo(); + test(ipEndpoint.port == 12020); + } + + ipEndpoint = (Ice.IPEndpointInfo)publishedEndpoints[0].getInfo(); + test(ipEndpoint.host.equals("127.0.0.1")); + test(ipEndpoint.port == 12020); + + adapter.destroy(); + } + out.println("ok"); + + Ice.ObjectPrx base = communicator.stringToProxy("test:default -p 12010:udp -p 12010"); + TestIntfPrx testIntf = TestIntfPrxHelper.checkedCast(base); + + out.print("test connection endpoint information... "); + out.flush(); + { + Ice.EndpointInfo info = base.ice_getConnection().getEndpoint().getInfo(); + Ice.IPEndpointInfo ipinfo = (Ice.IPEndpointInfo)info; + test(ipinfo.port == 12010); + test(!ipinfo.compress); + test(ipinfo.host.equals(defaultHost)); + + java.util.Map<String, String> ctx = testIntf.getEndpointInfoAsContext(); + test(ctx.get("host").equals(ipinfo.host)); + test(ctx.get("compress").equals("false")); + int port = Integer.parseInt(ctx.get("port")); + test(port > 0); + + info = base.ice_datagram().ice_getConnection().getEndpoint().getInfo(); + Ice.UDPEndpointInfo udp = (Ice.UDPEndpointInfo)info; + test(udp.port == 12010); + test(udp.host.equals(defaultHost)); + } + out.println("ok"); + + out.print("testing connection information... "); + out.flush(); + { + Ice.IPConnectionInfo info = (Ice.IPConnectionInfo)base.ice_getConnection().getInfo(); + test(!info.incoming); + test(info.adapterName.length() == 0); + test(info.localPort > 0); + test(info.remotePort == 12010); + test(info.remoteAddress.equals(defaultHost)); + test(info.localAddress.equals(defaultHost)); + + java.util.Map<String, String> ctx = testIntf.getConnectionInfoAsContext(); + test(ctx.get("incoming").equals("true")); + test(ctx.get("adapterName").equals("TestAdapter")); + test(ctx.get("remoteAddress").equals(info.localAddress)); + test(ctx.get("localAddress").equals(info.remoteAddress)); + test(ctx.get("remotePort").equals(Integer.toString(info.localPort))); + test(ctx.get("localPort").equals(Integer.toString(info.remotePort))); + + info = (Ice.IPConnectionInfo)base.ice_datagram().ice_getConnection().getInfo(); + test(!info.incoming); + test(info.adapterName.length() == 0); + test(info.localPort > 0); + test(info.remotePort == 12010); + test(info.remoteAddress.equals(defaultHost)); + test(info.localAddress.equals(defaultHost)); + } + out.println("ok"); + + testIntf.shutdown(); + + communicator.shutdown(); + communicator.waitForShutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/info/Client.java b/java/test/src/main/java/test/Ice/info/Client.java new file mode 100644 index 00000000000..2cd0d5b1f8b --- /dev/null +++ b/java/test/src/main/java/test/Ice/info/Client.java @@ -0,0 +1,37 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.info; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + AllTests.allTests(communicator(), getWriter()); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.info"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/info/Server.java b/java/test/src/main/java/test/Ice/info/Server.java new file mode 100644 index 00000000000..ebb4046e721 --- /dev/null +++ b/java/test/src/main/java/test/Ice/info/Server.java @@ -0,0 +1,41 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.info; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new TestI(), communicator.stringToIdentity("test")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.proxy"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010:udp -p 12010"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/info/Test.ice b/java/test/src/main/java/test/Ice/info/Test.ice new file mode 100644 index 00000000000..55bbc2ce48f --- /dev/null +++ b/java/test/src/main/java/test/Ice/info/Test.ice @@ -0,0 +1,27 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/Current.ice> + +[["java:package:test.Ice.info"]] +module Test +{ + +interface TestIntf +{ + void shutdown(); + + Ice::Context getEndpointInfoAsContext(); + + Ice::Context getConnectionInfoAsContext(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/info/TestI.java b/java/test/src/main/java/test/Ice/info/TestI.java new file mode 100644 index 00000000000..316cf7e438f --- /dev/null +++ b/java/test/src/main/java/test/Ice/info/TestI.java @@ -0,0 +1,66 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.info; +import test.Ice.info.Test._TestIntfDisp; + +public class TestI extends _TestIntfDisp +{ + TestI() + { + } + + @Override + public void shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + @Override + public java.util.Map<String, String> getEndpointInfoAsContext(Ice.Current c) + { + java.util.Map<String, String> ctx = new java.util.HashMap<String, String>(); + Ice.EndpointInfo info = c.con.getEndpoint().getInfo(); + ctx.put("timeout", Integer.toString(info.timeout)); + ctx.put("compress", info.compress ? "true" : "false"); + ctx.put("datagram", info.datagram() ? "true" : "false"); + ctx.put("secure", info.datagram() ? "true" : "false"); + ctx.put("type", Integer.toString(info.type())); + + Ice.IPEndpointInfo ipinfo = (Ice.IPEndpointInfo)info; + ctx.put("host", ipinfo.host); + ctx.put("port", Integer.toString(ipinfo.port)); + + if(ipinfo instanceof Ice.UDPEndpointInfo) + { + Ice.UDPEndpointInfo udp = (Ice.UDPEndpointInfo)ipinfo; + ctx.put("mcastInterface", udp.mcastInterface); + ctx.put("mcastTtl", Integer.toString(udp.mcastTtl)); + } + + return ctx; + } + + @Override + public java.util.Map<String, String> getConnectionInfoAsContext(Ice.Current c) + { + java.util.Map<String, String> ctx = new java.util.HashMap<String, String>(); + Ice.ConnectionInfo info = c.con.getInfo(); + ctx.put("adapterName", info.adapterName); + ctx.put("incoming", info.incoming ? "true" : "false"); + + Ice.IPConnectionInfo ipinfo = (Ice.IPConnectionInfo)info; + ctx.put("localAddress", ipinfo.localAddress); + ctx.put("localPort", Integer.toString(ipinfo.localPort)); + ctx.put("remoteAddress", ipinfo.remoteAddress); + ctx.put("remotePort", Integer.toString(ipinfo.remotePort)); + + return ctx; + } +} diff --git a/java/test/src/main/java/test/Ice/info/run.py b/java/test/src/main/java/test/Ice/info/run.py new file mode 100755 index 00000000000..d5fe04787c9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/info/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/inheritance/AllTests.java b/java/test/src/main/java/test/Ice/inheritance/AllTests.java new file mode 100644 index 00000000000..5a53c6916a1 --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/AllTests.java @@ -0,0 +1,248 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.inheritance; + +import java.io.PrintWriter; + +import test.Ice.inheritance.Test.InitialPrx; +import test.Ice.inheritance.Test.InitialPrxHelper; +import test.Ice.inheritance.Test.MA.CAPrx; +import test.Ice.inheritance.Test.MA.CCPrx; +import test.Ice.inheritance.Test.MA.CDPrx; +import test.Ice.inheritance.Test.MA.IAPrx; +import test.Ice.inheritance.Test.MA.ICPrx; +import test.Ice.inheritance.Test.MB.CBPrx; +import test.Ice.inheritance.Test.MB.IB1Prx; +import test.Ice.inheritance.Test.MB.IB2Prx; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static InitialPrx + allTests(Ice.Communicator communicator, PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + String ref = "initial:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + InitialPrx initial = InitialPrxHelper.checkedCast(base); + test(initial != null); + test(initial.equals(base)); + out.println("ok"); + + out.print("getting proxies for class hierarchy... "); + out.flush(); + CAPrx ca = initial.caop(); + CBPrx cb = initial.cbop(); + CCPrx cc = initial.ccop(); + CDPrx cd = initial.cdop(); + test(ca != cb); + test(ca != cc); + test(ca != cd); + test(cb != cc); + test(cb != cd); + test(cc != cd); + out.println("ok"); + + out.print("getting proxies for interface hierarchy... "); + out.flush(); + IAPrx ia = initial.iaop(); + IB1Prx ib1 = initial.ib1op(); + IB2Prx ib2 = initial.ib2op(); + ICPrx ic = initial.icop(); + test(ia != ib1); + test(ia != ib2); + test(ia != ic); + test(ib1 != ic); + test(ib2 != ic); + out.println("ok"); + + out.print("invoking proxy operations on class hierarchy... "); + out.flush(); + CAPrx cao; + CBPrx cbo; + CCPrx cco; + + cao = ca.caop(ca); + test(cao.equals(ca)); + cao = ca.caop(cb); + test(cao.equals(cb)); + cao = ca.caop(cc); + test(cao.equals(cc)); + cao = cb.caop(ca); + test(cao.equals(ca)); + cao = cb.caop(cb); + test(cao.equals(cb)); + cao = cb.caop(cc); + test(cao.equals(cc)); + cao = cc.caop(ca); + test(cao.equals(ca)); + cao = cc.caop(cb); + test(cao.equals(cb)); + cao = cc.caop(cc); + test(cao.equals(cc)); + + cao = cb.cbop(cb); + test(cao.equals(cb)); + cbo = cb.cbop(cb); + test(cbo.equals(cb)); + cao = cb.cbop(cc); + test(cao.equals(cc)); + cbo = cb.cbop(cc); + test(cbo.equals(cc)); + cao = cc.cbop(cb); + test(cao.equals(cb)); + cbo = cc.cbop(cb); + test(cbo.equals(cb)); + cao = cc.cbop(cc); + test(cao.equals(cc)); + cbo = cc.cbop(cc); + test(cbo.equals(cc)); + + cao = cc.ccop(cc); + test(cao.equals(cc)); + cbo = cc.ccop(cc); + test(cbo.equals(cc)); + cco = cc.ccop(cc); + test(cco.equals(cc)); + out.println("ok"); + + out.print("ditto, but for interface hierarchy... "); + out.flush(); + IAPrx iao; + IB1Prx ib1o; + IB2Prx ib2o; + ICPrx ico; + + iao = ia.iaop(ia); + test(iao.equals(ia)); + iao = ia.iaop(ib1); + test(iao.equals(ib1)); + iao = ia.iaop(ib2); + test(iao.equals(ib2)); + iao = ia.iaop(ic); + test(iao.equals(ic)); + iao = ib1.iaop(ia); + test(iao.equals(ia)); + iao = ib1.iaop(ib1); + test(iao.equals(ib1)); + iao = ib1.iaop(ib2); + test(iao.equals(ib2)); + iao = ib1.iaop(ic); + test(iao.equals(ic)); + iao = ib2.iaop(ia); + test(iao.equals(ia)); + iao = ib2.iaop(ib1); + test(iao.equals(ib1)); + iao = ib2.iaop(ib2); + test(iao.equals(ib2)); + iao = ib2.iaop(ic); + test(iao.equals(ic)); + iao = ic.iaop(ia); + test(iao.equals(ia)); + iao = ic.iaop(ib1); + test(iao.equals(ib1)); + iao = ic.iaop(ib2); + test(iao.equals(ib2)); + iao = ic.iaop(ic); + test(iao.equals(ic)); + + iao = ib1.ib1op(ib1); + test(iao.equals(ib1)); + ib1o = ib1.ib1op(ib1); + test(ib1o.equals(ib1)); + iao = ib1.ib1op(ic); + test(iao.equals(ic)); + ib1o = ib1.ib1op(ic); + test(ib1o.equals(ic)); + iao = ic.ib1op(ib1); + test(iao.equals(ib1)); + ib1o = ic.ib1op(ib1); + test(ib1o.equals(ib1)); + iao = ic.ib1op(ic); + test(iao.equals(ic)); + ib1o = ic.ib1op(ic); + test(ib1o.equals(ic)); + + iao = ib2.ib2op(ib2); + test(iao.equals(ib2)); + ib2o = ib2.ib2op(ib2); + test(ib2o.equals(ib2)); + iao = ib2.ib2op(ic); + test(iao.equals(ic)); + ib2o = ib2.ib2op(ic); + test(ib2o.equals(ic)); + iao = ic.ib2op(ib2); + test(iao.equals(ib2)); + ib2o = ic.ib2op(ib2); + test(ib2o.equals(ib2)); + iao = ic.ib2op(ic); + test(iao.equals(ic)); + ib2o = ic.ib2op(ic); + test(ib2o.equals(ic)); + + iao = ic.icop(ic); + test(iao.equals(ic)); + ib1o = ic.icop(ic); + test(ib1o.equals(ic)); + ib2o = ic.icop(ic); + test(ib2o.equals(ic)); + ico = ic.icop(ic); + test(ico.equals(ic)); + out.println("ok"); + + out.print("ditto, but for class implementing interfaces... "); + out.flush(); + + cao = cd.caop(cd); + test(cao.equals(cd)); + cbo = cd.cbop(cd); + test(cbo.equals(cd)); + cco = cd.ccop(cd); + test(cco.equals(cd)); + + iao = cd.iaop(cd); + test(iao.equals(cd)); + ib1o = cd.ib1op(cd); + test(ib1o.equals(cd)); + ib2o = cd.ib2op(cd); + test(ib2o.equals(cd)); + + cao = cd.cdop(cd); + test(cao.equals(cd)); + cbo = cd.cdop(cd); + test(cbo.equals(cd)); + cco = cd.cdop(cd); + test(cco.equals(cd)); + + iao = cd.cdop(cd); + test(iao.equals(cd)); + ib1o = cd.cdop(cd); + test(ib1o.equals(cd)); + ib2o = cd.cdop(cd); + test(ib2o.equals(cd)); + out.println("ok"); + + return initial; + } +} diff --git a/java/test/src/main/java/test/Ice/inheritance/CAI.java b/java/test/src/main/java/test/Ice/inheritance/CAI.java new file mode 100644 index 00000000000..b867eb6f836 --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/CAI.java @@ -0,0 +1,28 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.inheritance; + +import test.Ice.inheritance.Test.MA.CA; +import test.Ice.inheritance.Test.MA.CAPrx; + +public final class CAI extends CA +{ + public + CAI() + { + } + + @Override + public CAPrx + caop(CAPrx p, Ice.Current current) + { + return p; + } +} diff --git a/java/test/src/main/java/test/Ice/inheritance/CBI.java b/java/test/src/main/java/test/Ice/inheritance/CBI.java new file mode 100644 index 00000000000..6f07ec9b167 --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/CBI.java @@ -0,0 +1,36 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.inheritance; + +import test.Ice.inheritance.Test.MA.CAPrx; +import test.Ice.inheritance.Test.MB.CB; +import test.Ice.inheritance.Test.MB.CBPrx; + +public final class CBI extends CB +{ + public + CBI() + { + } + + @Override + public CAPrx + caop(CAPrx p, Ice.Current current) + { + return p; + } + + @Override + public CBPrx + cbop(CBPrx p, Ice.Current current) + { + return p; + } +} diff --git a/java/test/src/main/java/test/Ice/inheritance/CCI.java b/java/test/src/main/java/test/Ice/inheritance/CCI.java new file mode 100644 index 00000000000..1d88806b959 --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/CCI.java @@ -0,0 +1,44 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.inheritance; + +import test.Ice.inheritance.Test.MA.CAPrx; +import test.Ice.inheritance.Test.MA.CC; +import test.Ice.inheritance.Test.MA.CCPrx; +import test.Ice.inheritance.Test.MB.CBPrx; + +public final class CCI extends CC +{ + public + CCI() + { + } + + @Override + public CAPrx + caop(CAPrx p, Ice.Current current) + { + return p; + } + + @Override + public CCPrx + ccop(CCPrx p, Ice.Current current) + { + return p; + } + + @Override + public CBPrx + cbop(CBPrx p, Ice.Current current) + { + return p; + } +} diff --git a/java/test/src/main/java/test/Ice/inheritance/CDI.java b/java/test/src/main/java/test/Ice/inheritance/CDI.java new file mode 100644 index 00000000000..a1ac62fdf14 --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/CDI.java @@ -0,0 +1,76 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.inheritance; + +import test.Ice.inheritance.Test.MA.CAPrx; +import test.Ice.inheritance.Test.MA.CCPrx; +import test.Ice.inheritance.Test.MA.CD; +import test.Ice.inheritance.Test.MA.CDPrx; +import test.Ice.inheritance.Test.MA.IAPrx; +import test.Ice.inheritance.Test.MB.CBPrx; +import test.Ice.inheritance.Test.MB.IB1Prx; +import test.Ice.inheritance.Test.MB.IB2Prx; + +public final class CDI extends CD +{ + public + CDI() + { + } + + @Override + public CAPrx + caop(CAPrx p, Ice.Current current) + { + return p; + } + + @Override + public CCPrx + ccop(CCPrx p, Ice.Current current) + { + return p; + } + + @Override + public CDPrx + cdop(CDPrx p, Ice.Current current) + { + return p; + } + + @Override + public IAPrx + iaop(IAPrx p, Ice.Current current) + { + return p; + } + + @Override + public CBPrx + cbop(CBPrx p, Ice.Current current) + { + return p; + } + + @Override + public IB1Prx + ib1op(IB1Prx p, Ice.Current current) + { + return p; + } + + @Override + public IB2Prx + ib2op(IB2Prx p, Ice.Current current) + { + return p; + } +} diff --git a/java/test/src/main/java/test/Ice/inheritance/Client.java b/java/test/src/main/java/test/Ice/inheritance/Client.java new file mode 100644 index 00000000000..1fc5bdb3214 --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/Client.java @@ -0,0 +1,42 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.inheritance; + +import test.Ice.inheritance.Test.InitialPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + InitialPrx initial = AllTests.allTests(communicator, getWriter()); + initial.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.inheritance"); + return initData; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/inheritance/Collocated.java b/java/test/src/main/java/test/Ice/inheritance/Collocated.java new file mode 100644 index 00000000000..3c92c35545c --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/Collocated.java @@ -0,0 +1,46 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.inheritance; + +public class Collocated extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object object = new InitialI(adapter); + adapter.add(object, communicator.stringToIdentity("initial")); + + AllTests.allTests(communicator, getWriter()); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.inheritance"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + return initData; + } + + public static void main(String[] args) + { + Collocated c = new Collocated(); + int status = c.main("Collocated", args); + + System.gc(); + System.exit(status); + } + +} diff --git a/java/test/src/main/java/test/Ice/inheritance/IAI.java b/java/test/src/main/java/test/Ice/inheritance/IAI.java new file mode 100644 index 00000000000..6f783f0bc58 --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/IAI.java @@ -0,0 +1,28 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.inheritance; + +import test.Ice.inheritance.Test.MA.IAPrx; +import test.Ice.inheritance.Test.MA._IADisp; + +public final class IAI extends _IADisp +{ + public + IAI() + { + } + + @Override + public IAPrx + iaop(IAPrx p, Ice.Current current) + { + return p; + } +} diff --git a/java/test/src/main/java/test/Ice/inheritance/IB1I.java b/java/test/src/main/java/test/Ice/inheritance/IB1I.java new file mode 100644 index 00000000000..0c1de6cfb99 --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/IB1I.java @@ -0,0 +1,36 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.inheritance; + +import test.Ice.inheritance.Test.MA.IAPrx; +import test.Ice.inheritance.Test.MB.IB1Prx; +import test.Ice.inheritance.Test.MB._IB1Disp; + +public final class IB1I extends _IB1Disp +{ + public + IB1I() + { + } + + @Override + public IAPrx + iaop(IAPrx p, Ice.Current current) + { + return p; + } + + @Override + public IB1Prx + ib1op(IB1Prx p, Ice.Current current) + { + return p; + } +} diff --git a/java/test/src/main/java/test/Ice/inheritance/IB2I.java b/java/test/src/main/java/test/Ice/inheritance/IB2I.java new file mode 100644 index 00000000000..07fc2e53baa --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/IB2I.java @@ -0,0 +1,36 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.inheritance; + +import test.Ice.inheritance.Test.MA.IAPrx; +import test.Ice.inheritance.Test.MB.IB2Prx; +import test.Ice.inheritance.Test.MB._IB2Disp; + +public final class IB2I extends _IB2Disp +{ + public + IB2I() + { + } + + @Override + public IAPrx + iaop(IAPrx p, Ice.Current current) + { + return p; + } + + @Override + public IB2Prx + ib2op(IB2Prx p, Ice.Current current) + { + return p; + } +} diff --git a/java/test/src/main/java/test/Ice/inheritance/ICI.java b/java/test/src/main/java/test/Ice/inheritance/ICI.java new file mode 100644 index 00000000000..4ff569dbf16 --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/ICI.java @@ -0,0 +1,52 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.inheritance; + +import test.Ice.inheritance.Test.MA.IAPrx; +import test.Ice.inheritance.Test.MA.ICPrx; +import test.Ice.inheritance.Test.MA._ICDisp; +import test.Ice.inheritance.Test.MB.IB1Prx; +import test.Ice.inheritance.Test.MB.IB2Prx; + +public final class ICI extends _ICDisp +{ + public + ICI() + { + } + + @Override + public IAPrx + iaop(IAPrx p, Ice.Current current) + { + return p; + } + + @Override + public ICPrx + icop(ICPrx p, Ice.Current current) + { + return p; + } + + @Override + public IB1Prx + ib1op(IB1Prx p, Ice.Current current) + { + return p; + } + + @Override + public IB2Prx + ib2op(IB2Prx p, Ice.Current current) + { + return p; + } +} diff --git a/java/test/src/main/java/test/Ice/inheritance/InitialI.java b/java/test/src/main/java/test/Ice/inheritance/InitialI.java new file mode 100644 index 00000000000..083314cf62d --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/InitialI.java @@ -0,0 +1,116 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.inheritance; + +import test.Ice.inheritance.Test._InitialDisp; +import test.Ice.inheritance.Test.MA.CAPrx; +import test.Ice.inheritance.Test.MA.CAPrxHelper; +import test.Ice.inheritance.Test.MA.CCPrx; +import test.Ice.inheritance.Test.MA.CCPrxHelper; +import test.Ice.inheritance.Test.MA.CDPrx; +import test.Ice.inheritance.Test.MA.CDPrxHelper; +import test.Ice.inheritance.Test.MA.IAPrx; +import test.Ice.inheritance.Test.MA.IAPrxHelper; +import test.Ice.inheritance.Test.MA.ICPrx; +import test.Ice.inheritance.Test.MA.ICPrxHelper; +import test.Ice.inheritance.Test.MB.CBPrx; +import test.Ice.inheritance.Test.MB.CBPrxHelper; +import test.Ice.inheritance.Test.MB.IB1Prx; +import test.Ice.inheritance.Test.MB.IB1PrxHelper; +import test.Ice.inheritance.Test.MB.IB2Prx; +import test.Ice.inheritance.Test.MB.IB2PrxHelper; + +public final class InitialI extends _InitialDisp +{ + public + InitialI(Ice.ObjectAdapter adapter) + { + _ca = CAPrxHelper.uncheckedCast(adapter.addWithUUID(new CAI())); + _cb = CBPrxHelper.uncheckedCast(adapter.addWithUUID(new CBI())); + _cc = CCPrxHelper.uncheckedCast(adapter.addWithUUID(new CCI())); + _cd = CDPrxHelper.uncheckedCast(adapter.addWithUUID(new CDI())); + _ia = IAPrxHelper.uncheckedCast(adapter.addWithUUID(new IAI())); + _ib1 = IB1PrxHelper.uncheckedCast(adapter.addWithUUID(new IB1I())); + _ib2 = IB2PrxHelper.uncheckedCast(adapter.addWithUUID(new IB2I())); + _ic = ICPrxHelper.uncheckedCast(adapter.addWithUUID(new ICI())); + } + + @Override + public CAPrx + caop(Ice.Current current) + { + return _ca; + } + + @Override + public CBPrx + cbop(Ice.Current current) + { + return _cb; + } + + @Override + public CCPrx + ccop(Ice.Current current) + { + return _cc; + } + + @Override + public CDPrx + cdop(Ice.Current current) + { + return _cd; + } + + @Override + public IAPrx + iaop(Ice.Current current) + { + return _ia; + } + + @Override + public IB1Prx + ib1op(Ice.Current current) + { + return _ib1; + } + + @Override + public IB2Prx + ib2op(Ice.Current current) + { + return _ib2; + } + + @Override + public ICPrx + icop(Ice.Current current) + { + return _ic; + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + private CAPrx _ca; + private CBPrx _cb; + private CCPrx _cc; + private CDPrx _cd; + private IAPrx _ia; + private IB1Prx _ib1; + private IB2Prx _ib2; + private ICPrx _ic; +} diff --git a/java/test/src/main/java/test/Ice/inheritance/Server.java b/java/test/src/main/java/test/Ice/inheritance/Server.java new file mode 100644 index 00000000000..7ff0278c2a6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/Server.java @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.inheritance; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object object = new InitialI(adapter); + adapter.add(object, communicator.stringToIdentity("initial")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.inheritance"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/inheritance/Test.ice b/java/test/src/main/java/test/Ice/inheritance/Test.ice new file mode 100644 index 00000000000..82d63b5078f --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/Test.ice @@ -0,0 +1,84 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.inheritance"]] +module Test +{ + +module MA +{ + +interface IA +{ + IA* iaop(IA* p); +}; + +class CA +{ + CA* caop(CA* p); +}; + +}; + +module MB +{ + +interface IB1 extends MA::IA +{ + IB1* ib1op(IB1* p); +}; + +interface IB2 extends MA::IA +{ + IB2* ib2op(IB2* p); +}; + +class CB extends MA::CA +{ + CB* cbop(CB* p); +}; + +}; + +module MA +{ + +interface IC extends MB::IB1, MB::IB2 +{ + IC* icop(IC* p); +}; + +class CC extends MB::CB +{ + CC* ccop(CC* p); +}; + +class CD extends CC implements MB::IB1, MB::IB2 +{ + CD* cdop(CD* p); +}; + +}; + +interface Initial +{ + void shutdown(); + MA::CA* caop(); + MB::CB* cbop(); + MA::CC* ccop(); + MA::CD* cdop(); + MA::IA* iaop(); + MB::IB1* ib1op(); + MB::IB2* ib2op(); + MA::IC* icop(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/inheritance/run.py b/java/test/src/main/java/test/Ice/inheritance/run.py new file mode 100755 index 00000000000..8bb456187d9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/inheritance/run.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/interceptor/AMDInterceptorI.java b/java/test/src/main/java/test/Ice/interceptor/AMDInterceptorI.java new file mode 100644 index 00000000000..e9cc88a1ba5 --- /dev/null +++ b/java/test/src/main/java/test/Ice/interceptor/AMDInterceptorI.java @@ -0,0 +1,120 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.interceptor; + +import test.Ice.interceptor.Test.RetryException; + +// +// A dispatch interceptor with special handling for AMD requests +// + +class AMDInterceptorI extends InterceptorI implements Ice.DispatchInterceptorAsyncCallback +{ + AMDInterceptorI(Ice.Object servant) + { + super(servant); + } + + @Override + public Ice.DispatchStatus + dispatch(Ice.Request request) + { + Ice.Current current = request.getCurrent(); + _lastOperation = current.operation; + + if(_lastOperation.equals("amdAddWithRetry")) + { + for(int i = 0; i < 10; ++i) + { + Ice.DispatchInterceptorAsyncCallback cb = new Ice.DispatchInterceptorAsyncCallback() + { + @Override + public boolean response(boolean ok) + { + test(ok); + return false; + } + + @Override + public boolean exception(java.lang.Exception ex) + { + test(ex instanceof RetryException); + return false; + } + }; + + _lastStatus = _servant.ice_dispatch(request, cb); + test(_lastStatus == Ice.DispatchStatus.DispatchAsync); + } + + request.getCurrent().ctx.put("retry", "no"); + } + + + _lastStatus = _servant.ice_dispatch(request, this); + return _lastStatus; + } + + @Override + public boolean response(boolean ok) + { + setActualStatus(ok ? Ice.DispatchStatus.DispatchOK : Ice.DispatchStatus.DispatchUserException); + return true; + } + + @Override + public boolean exception(java.lang.Exception ex) + { + setActualStatus(ex); + return true; + } + + @Override + void + clear() + { + super.clear(); + synchronized(this) + { + _actualStatus = null; + _exception = null; + } + } + + + synchronized void + setActualStatus(Ice.DispatchStatus status) + { + _actualStatus = status; + _exception = null; + } + + synchronized void + setActualStatus(java.lang.Exception ex) + { + _exception = ex; + _actualStatus = null; + } + + synchronized Ice.DispatchStatus + getActualStatus() + { + return _actualStatus; + } + + synchronized java.lang.Exception + getException() + { + return _exception; + } + + private Ice.DispatchStatus _actualStatus; + private java.lang.Exception _exception; +} diff --git a/java/test/src/main/java/test/Ice/interceptor/Client.java b/java/test/src/main/java/test/Ice/interceptor/Client.java new file mode 100644 index 00000000000..12c913296b0 --- /dev/null +++ b/java/test/src/main/java/test/Ice/interceptor/Client.java @@ -0,0 +1,270 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.interceptor; + +import java.io.PrintWriter; + +import test.Ice.interceptor.Test.InvalidInputException; +import test.Ice.interceptor.Test.MyObjectPrx; +import test.Ice.interceptor.Test.MyObjectPrxHelper; + +public class Client extends test.Util.Application +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private int + run(MyObjectPrx prx, InterceptorI interceptor) + { + PrintWriter out = getWriter(); + out.print("testing simple interceptor... "); + out.flush(); + test(interceptor.getLastOperation() == null); + test(interceptor.getLastStatus() == null); + prx.ice_ping(); + test(interceptor.getLastOperation().equals("ice_ping")); + test(interceptor.getLastStatus() == Ice.DispatchStatus.DispatchOK); + String typeId = prx.ice_id(); + test(interceptor.getLastOperation().equals("ice_id")); + test(interceptor.getLastStatus() == Ice.DispatchStatus.DispatchOK); + test(prx.ice_isA(typeId)); + test(interceptor.getLastOperation().equals("ice_isA")); + test(interceptor.getLastStatus() == Ice.DispatchStatus.DispatchOK); + test(prx.add(33, 12) == 45); + test(interceptor.getLastOperation().equals("add")); + test(interceptor.getLastStatus().equals(Ice.DispatchStatus.DispatchOK)); + out.println("ok"); + out.print("testing retry... "); + out.flush(); + test(prx.addWithRetry(33, 12) == 45); + test(interceptor.getLastOperation().equals("addWithRetry")); + test(interceptor.getLastStatus().equals(Ice.DispatchStatus.DispatchOK)); + out.println("ok"); + out.print("testing user exception... "); + out.flush(); + try + { + prx.badAdd(33, 12); + test(false); + } + catch(InvalidInputException e) + { + // expected + } + test(interceptor.getLastOperation().equals("badAdd")); + test(interceptor.getLastStatus().equals(Ice.DispatchStatus.DispatchUserException)); + out.println("ok"); + out.print("testing ONE... "); + out.flush(); + interceptor.clear(); + try + { + prx.notExistAdd(33, 12); + test(false); + } + catch(Ice.ObjectNotExistException e) + { + // expected + } + test(interceptor.getLastOperation().equals("notExistAdd")); + test(interceptor.getLastStatus() == null); + out.println("ok"); + out.print("testing system exception... "); + out.flush(); + interceptor.clear(); + try + { + prx.badSystemAdd(33, 12); + test(false); + } + catch(Ice.UnknownException e) + { + test(!prx.ice_isCollocationOptimized()); + } + catch(MySystemException e) + { + test(prx.ice_isCollocationOptimized()); + } + catch(Throwable ex) + { + test(false); + } + test(interceptor.getLastOperation().equals("badSystemAdd")); + test(interceptor.getLastStatus() == null); + out.println("ok"); + + out.print("testing simple AMD... "); + out.flush(); + test(prx.amdAdd(33, 12) == 45); + test(interceptor.getLastOperation().equals("amdAdd")); + test(interceptor.getLastStatus().equals(Ice.DispatchStatus.DispatchAsync)); + out.println("ok"); + + return 0; + } + + private int + runAmd(MyObjectPrx prx, AMDInterceptorI interceptor, PrintWriter out) + { + out.print("testing simple interceptor... "); + out.flush(); + test(interceptor.getLastOperation() == null); + test(interceptor.getLastStatus() == null); + test(prx.amdAdd(33, 12) == 45); + test(interceptor.getLastOperation().equals("amdAdd")); + test(interceptor.getLastStatus().equals(Ice.DispatchStatus.DispatchAsync)); + test(interceptor.getActualStatus().equals(Ice.DispatchStatus.DispatchOK)); + out.println("ok"); + out.print("testing retry... "); + out.flush(); + test(prx.amdAddWithRetry(33, 12) == 45); + test(interceptor.getLastOperation().equals("amdAddWithRetry")); + test(interceptor.getLastStatus().equals(Ice.DispatchStatus.DispatchAsync)); + test(interceptor.getActualStatus().equals(Ice.DispatchStatus.DispatchOK)); + out.println("ok"); + out.print("testing user exception... "); + out.flush(); + try + { + prx.amdBadAdd(33, 12); + test(false); + } + catch(InvalidInputException e) + { + // expected + } + test(interceptor.getLastOperation().equals("amdBadAdd")); + test(interceptor.getLastStatus().equals(Ice.DispatchStatus.DispatchAsync)); + test(interceptor.getActualStatus().equals(Ice.DispatchStatus.DispatchUserException)); + out.println("ok"); + out.print("testing ONE... "); + out.flush(); + interceptor.clear(); + try + { + prx.amdNotExistAdd(33, 12); + test(false); + } + catch(Ice.ObjectNotExistException e) + { + // expected + } + test(interceptor.getLastOperation().equals("amdNotExistAdd")); + test(interceptor.getLastStatus().equals(Ice.DispatchStatus.DispatchAsync)); + test(interceptor.getActualStatus() == null); + test(interceptor.getException() instanceof Ice.ObjectNotExistException); + out.println("ok"); + out.print("testing system exception... "); + out.flush(); + interceptor.clear(); + try + { + prx.amdBadSystemAdd(33, 12); + test(false); + } + catch(Ice.UnknownException e) + { + test(!prx.ice_isCollocationOptimized()); + } + catch(MySystemException e) + { + test(prx.ice_isCollocationOptimized()); + } + catch(Throwable ex) + { + test(false); + } + test(interceptor.getLastOperation().equals("amdBadSystemAdd")); + test(interceptor.getLastStatus().equals(Ice.DispatchStatus.DispatchAsync)); + test(interceptor.getActualStatus() == null); + test(interceptor.getException() instanceof MySystemException); + out.println("ok"); + return 0; + } + + @Override + public int + run(String[] args) + { + // + // Create OA and servants + // + communicator().getProperties().setProperty("MyOA.AdapterId", "myOA"); + + Ice.ObjectAdapter oa = communicator().createObjectAdapterWithEndpoints("MyOA2", "tcp -h localhost"); + + Ice.Object servant = new MyObjectI(); + InterceptorI interceptor = new InterceptorI(servant); + AMDInterceptorI amdInterceptor = new AMDInterceptorI(servant); + + MyObjectPrx prx = MyObjectPrxHelper.uncheckedCast(oa.addWithUUID(interceptor)); + MyObjectPrx prxForAMD = MyObjectPrxHelper.uncheckedCast(oa.addWithUUID(amdInterceptor)); + + PrintWriter out = getWriter(); + out.println("Collocation optimization on"); + int rs = run(prx, interceptor); + if(rs != 0) + { + return rs; + } + + out.println("Now with AMD"); + rs = runAmd(prxForAMD, amdInterceptor, out); + if(rs != 0) + { + return rs; + } + + oa.activate(); // Only necessary for non-collocation optimized tests + + out.println("Collocation optimization off"); + interceptor.clear(); + prx = MyObjectPrxHelper.uncheckedCast(prx.ice_collocationOptimized(false)); + rs = run(prx, interceptor); + if(rs != 0) + { + return rs; + } + + out.println("Now with AMD"); + amdInterceptor.clear(); + prxForAMD = MyObjectPrxHelper.uncheckedCast(prxForAMD.ice_collocationOptimized(false)); + rs = runAmd(prxForAMD, amdInterceptor, out); + + return rs; + } + + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.interceptor"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int status = app.main("Interceptor", args); + System.gc(); + System.exit(status); + } +} + + + diff --git a/java/test/src/main/java/test/Ice/interceptor/InterceptorI.java b/java/test/src/main/java/test/Ice/interceptor/InterceptorI.java new file mode 100644 index 00000000000..04458722e3a --- /dev/null +++ b/java/test/src/main/java/test/Ice/interceptor/InterceptorI.java @@ -0,0 +1,84 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.interceptor; + +import test.Ice.interceptor.Test.RetryException; + +class InterceptorI extends Ice.DispatchInterceptor +{ + InterceptorI(Ice.Object servant) + { + _servant = servant; + } + + protected static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + + @Override + public Ice.DispatchStatus + dispatch(Ice.Request request) + { + Ice.Current current = request.getCurrent(); + _lastOperation = current.operation; + + if(_lastOperation.equals("addWithRetry")) + { + for(int i = 0; i < 10; ++i) + { + try + { + _servant.ice_dispatch(request); + test(false); + } + catch(RetryException re) + { + // + // Expected, retry + // + } + } + + current.ctx.put("retry", "no"); + } + + _lastStatus = _servant.ice_dispatch(request); + return _lastStatus; + } + + Ice.DispatchStatus + getLastStatus() + { + return _lastStatus; + } + + String + getLastOperation() + { + return _lastOperation; + } + + void + clear() + { + _lastOperation = null; + _lastStatus = null; + } + + protected final Ice.Object _servant; + protected String _lastOperation; + protected Ice.DispatchStatus _lastStatus; +} diff --git a/java/test/src/main/java/test/Ice/interceptor/MyObjectI.java b/java/test/src/main/java/test/Ice/interceptor/MyObjectI.java new file mode 100644 index 00000000000..a2c10f04d38 --- /dev/null +++ b/java/test/src/main/java/test/Ice/interceptor/MyObjectI.java @@ -0,0 +1,201 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.interceptor; + +import test.Ice.interceptor.Test.AMD_MyObject_amdAdd; +import test.Ice.interceptor.Test.AMD_MyObject_amdAddWithRetry; +import test.Ice.interceptor.Test.AMD_MyObject_amdBadAdd; +import test.Ice.interceptor.Test.AMD_MyObject_amdBadSystemAdd; +import test.Ice.interceptor.Test.AMD_MyObject_amdNotExistAdd; +import test.Ice.interceptor.Test.InvalidInputException; +import test.Ice.interceptor.Test.RetryException; +import test.Ice.interceptor.Test._MyObjectDisp; + +class MyObjectI extends _MyObjectDisp +{ + + @Override + public int + add(int x, int y, Ice.Current current) + { + return x + y; + } + + @Override + public int + addWithRetry(int x, int y, Ice.Current current) + { + String val = current.ctx.get("retry"); + + if(val == null || !val.equals("no")) + { + throw new RetryException(); + } + return x + y; + } + + @Override + public int + badAdd(int x, int y, Ice.Current current) throws InvalidInputException + { + throw new InvalidInputException(); + } + + @Override + public int + notExistAdd(int x, int y, Ice.Current current) + { + throw new Ice.ObjectNotExistException(); + } + + @Override + public int + badSystemAdd(int x, int y, Ice.Current current) + { + throw new MySystemException(); + } + + + // + // AMD + // + + @Override + public void + amdAdd_async(final AMD_MyObject_amdAdd cb, final int x, final int y, Ice.Current current) + { + Thread thread = new Thread() + { + @Override + public void + run() + { + try + { + Thread.sleep(10); + } + catch(InterruptedException e) + { + } + cb.ice_response(x + y); + } + }; + + thread.setDaemon(true); + thread.start(); + } + + @Override + public void + amdAddWithRetry_async(final AMD_MyObject_amdAddWithRetry cb, final int x, final int y, Ice.Current current) + { + Thread thread = new Thread() + { + @Override + public void + run() + { + try + { + Thread.sleep(10); + } + catch(InterruptedException e) + { + } + cb.ice_response(x + y); + } + }; + + thread.setDaemon(true); + thread.start(); + + String val = current.ctx.get("retry"); + + if(val == null || !val.equals("no")) + { + throw new RetryException(); + } + } + + @Override + public void + amdBadAdd_async(final AMD_MyObject_amdBadAdd cb, int x, int y, Ice.Current current) + { + Thread thread = new Thread() + { + @Override + public void + run() + { + try + { + Thread.sleep(10); + } + catch(InterruptedException e) + { + } + cb.ice_exception(new InvalidInputException()); + } + }; + + thread.setDaemon(true); + thread.start(); + } + + @Override + public void + amdNotExistAdd_async(final AMD_MyObject_amdNotExistAdd cb, int x, int y, Ice.Current current) + { + Thread thread = new Thread() + { + @Override + public void + run() + { + try + { + Thread.sleep(10); + } + catch(InterruptedException e) + { + } + cb.ice_exception(new Ice.ObjectNotExistException()); + } + }; + + thread.setDaemon(true); + thread.start(); + } + + @Override + public void + amdBadSystemAdd_async(final AMD_MyObject_amdBadSystemAdd cb, int x, int y, Ice.Current current) + { + Thread thread = new Thread() + { + @Override + public void + run() + { + try + { + Thread.sleep(10); + } + catch(InterruptedException e) + { + } + cb.ice_exception(new MySystemException()); + } + }; + + thread.setDaemon(true); + thread.start(); + } +} diff --git a/java/test/src/main/java/test/Ice/interceptor/MySystemException.java b/java/test/src/main/java/test/Ice/interceptor/MySystemException.java new file mode 100644 index 00000000000..ee7bc5a626b --- /dev/null +++ b/java/test/src/main/java/test/Ice/interceptor/MySystemException.java @@ -0,0 +1,25 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.interceptor; + + +public class MySystemException extends Ice.SystemException +{ + public MySystemException() + { + } + + @Override + public String + ice_name() + { + return "MySystemException"; + } +} diff --git a/java/test/src/main/java/test/Ice/interceptor/Test.ice b/java/test/src/main/java/test/Ice/interceptor/Test.ice new file mode 100644 index 00000000000..04c460b8b5e --- /dev/null +++ b/java/test/src/main/java/test/Ice/interceptor/Test.ice @@ -0,0 +1,84 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.interceptor"]] +module Test +{ + +exception InvalidInputException +{ + string message; +}; + +local exception RetryException +{ +}; + +interface MyObject +{ + // + // A simple addition + // + int add(int x, int y); + + // + // Will throw RetryException until current.ctx["retry"] is "no" + // + int addWithRetry(int x, int y); + + // + // Raise user exception + // + int badAdd(int x, int y) throws InvalidInputException; + + // + // Raise ONE + // + int notExistAdd(int x, int y); + + // + // Raise system exception + // + int badSystemAdd(int x, int y); + + // + // AMD version of the above: + // + + // + // Simple add + // + ["amd"] int amdAdd(int x, int y); + + // + // Will throw RetryException until current.ctx["retry"] is "no" + // + ["amd"] int amdAddWithRetry(int x, int y); + + // + // Raise user exception + // + ["amd"] int amdBadAdd(int x, int y) throws InvalidInputException; + + // + // Raise ONE + // + ["amd"] int amdNotExistAdd(int x, int y); + + // + // Raise system exception + // + ["amd"] int amdBadSystemAdd(int x, int y); + +}; + + +}; diff --git a/java/test/src/main/java/test/Ice/interceptor/run.py b/java/test/src/main/java/test/Ice/interceptor/run.py new file mode 100755 index 00000000000..04638dadfa6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/interceptor/run.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +sys.stdout.write("starting client... ") +sys.stdout.flush() +clientProc = TestUtil.startClient("test.Ice.interceptor.Client", "--Ice.Warn.Dispatch=0",startReader=False) +print("ok") +clientProc.startReader() + +clientProc.waitTestSuccess() diff --git a/java/test/src/main/java/test/Ice/interrupt/AllTests.java b/java/test/src/main/java/test/Ice/interrupt/AllTests.java new file mode 100644 index 00000000000..dbc7c159ddd --- /dev/null +++ b/java/test/src/main/java/test/Ice/interrupt/AllTests.java @@ -0,0 +1,806 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.interrupt; + +import java.io.PrintWriter; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; + +import test.Ice.interrupt.Test.Callback_TestIntf_op; +import test.Ice.interrupt.Test.Callback_TestIntf_sleep; +import test.Ice.interrupt.Test.CannotInterruptException; +import test.Ice.interrupt.Test.TestIntfControllerPrx; +import test.Ice.interrupt.Test.TestIntfControllerPrxHelper; +import test.Ice.interrupt.Test.TestIntfPrx; +import test.Ice.interrupt.Test.TestIntfPrxHelper; +import Ice.AsyncResult; +import Ice.Callback_Communicator_flushBatchRequests; +import Ice.Callback_Connection_flushBatchRequests; +import Ice.Callback_Object_ice_flushBatchRequests; +import Ice.Callback_Object_ice_getConnection; +import Ice.Connection; +import Ice.LocalException; + +public class AllTests +{ + private static class CallbackBase + { + CallbackBase() + { + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called = false; + } + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static void failIfNotInterrupted() + { + if(Thread.currentThread().isInterrupted()) + { + Thread.interrupted(); + } + else + { + test(false); + } + } + + public static void + allTests(test.Util.Application app, Ice.Communicator communicator, PrintWriter out) + throws InterruptedException + { + String sref = "test:default -p 12010"; + Ice.ObjectPrx obj = communicator.stringToProxy(sref); + test(obj != null); + + final TestIntfPrx p = TestIntfPrxHelper.uncheckedCast(obj); + + sref = "testController:tcp -p 12011"; + obj = communicator.stringToProxy(sref); + test(obj != null); + + TestIntfControllerPrx testController = TestIntfControllerPrxHelper.uncheckedCast(obj); + + out.print("testing client interrupt... "); + out.flush(); + { + final Thread mainThread = Thread.currentThread(); + mainThread.interrupt(); + try + { + // Synchronous invocations are interruption points. If the + // interrupt flag is set at the start of the operation + // OperationInterruptedException must be thrown. + p.op(); + test(false); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + test(!mainThread.isInterrupted()); + } + + // Same test with the AMI API. + try + { + Ice.AsyncResult r = p.begin_op(); + mainThread.interrupt(); + p.end_op(r); + test(false); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + test(!mainThread.isInterrupted()); + } + + final CallbackBase cb = new CallbackBase(); + mainThread.interrupt(); + p.begin_op(new Callback_TestIntf_op() + { + @Override + public void response() + { + cb.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + }); + test(Thread.interrupted()); + cb.check(); + + p.begin_op(new Ice.Callback() + { + @Override + public void completed(AsyncResult r) + { + try + { + Thread.currentThread().interrupt(); + p.end_op(r); + test(false); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + test(!Thread.currentThread().isInterrupted()); + } + } + }); + + ExecutorService executor = java.util.concurrent.Executors.newFixedThreadPool(1); + executor.submit(new Runnable() { + @Override + public void run() + { + try + { + Thread.sleep(500); + } + catch(InterruptedException e) + { + test(false); + } + mainThread.interrupt(); + } + }); + + try + { + test(!mainThread.isInterrupted()); + p.sleep(2000); + test(false); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + } + catch(test.Ice.interrupt.Test.InterruptedException e) + { + test(false); + } + + executor.submit(new Runnable() { + @Override + public void run() + { + try + { + Thread.sleep(500); + } + catch(InterruptedException e) + { + test(false); + } + mainThread.interrupt(); + } + }); + + try + { + test(!mainThread.isInterrupted()); + Ice.AsyncResult r = p.begin_sleep(2000); + p.end_sleep(r); + test(false); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + } + catch(test.Ice.interrupt.Test.InterruptedException e) + { + test(false); + } + + executor.submit(new Runnable() { + @Override + public void run() + { + try + { + Thread.sleep(500); + } + catch(InterruptedException e) + { + test(false); + } + mainThread.interrupt(); + } + }); + + try + { + test(!mainThread.isInterrupted()); + p.opIdempotent(); + test(false); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + } + catch(Ice.ConnectionLostException ex) + { + test(false); + } + + // Test waitForCompleted is an interruption point. + try + { + Ice.AsyncResult r = p.begin_op(); + try + { + Thread.currentThread().interrupt(); + r.waitForCompleted(); + test(false); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + } + + // end_ should still work. + p.end_op(r); + } + catch(Ice.OperationInterruptedException ex) + { + test(false); + } + + // Test waitForSent is an interruption point. + try + { + Ice.AsyncResult r = p.begin_op(); + try + { + Thread.currentThread().interrupt(); + r.waitForSent(); + test(false); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + } + + // end_ should still work. + p.end_op(r); + } + catch(Ice.OperationInterruptedException ex) + { + test(false); + } + + // This section of the test doesn't run when collocated. + if(p.ice_getConnection() != null) + { + // + // Test interrupt of waitForSent. Here hold the adapter and send a large payload. The + // thread is interrupted in 500ms which should result in a operation interrupted exception. + // + executor.submit(new Runnable() { + @Override + public void run() + { + try + { + Thread.sleep(500); + } + catch(InterruptedException e) + { + test(false); + } + mainThread.interrupt(); + } + }); + + testController.holdAdapter(); + Ice.AsyncResult r = null; + // The sequence needs to be large enough to fill the write/recv buffers + byte[] seq = new byte[20000000]; + r = p.begin_opWithPayload(seq); + try + { + r.waitForSent(); + test(false); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + } + // + // Resume the adapter. + // + testController.resumeAdapter(); + r.waitForSent(); + r.waitForCompleted(); + p.end_opWithPayload(r); + } + + // + // The executor is all done. + // + executor.shutdown(); + executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); + } + out.println("ok"); + + if(p.ice_getCachedConnection() != null) + { + out.print("testing getConnection interrupt... "); + out.flush(); + { + final Thread mainThread = Thread.currentThread(); + + p.ice_getConnection().close(false); + + AsyncResult r = p.begin_ice_getConnection(); + mainThread.interrupt(); + try + { + p.end_ice_getConnection(r); + test(false); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + } + + p.ice_getConnection().close(false); + + final CallbackBase cb = new CallbackBase(); + mainThread.interrupt(); + p.begin_ice_getConnection(new Callback_Object_ice_getConnection() + { + @Override + public void exception(LocalException ex) + { + test(false); + } + + @Override + public void response(Connection con) + { + cb.called(); + } + }); + test(Thread.interrupted()); + cb.check(); + } + out.println("ok"); + } + + out.print("testing batch proxy flush interrupt... "); + out.flush(); + { + final TestIntfPrx p2 = TestIntfPrxHelper.uncheckedCast(p.ice_batchOneway()); + final Thread mainThread = Thread.currentThread(); + + p2.op(); + p2.op(); + p2.op(); + + AsyncResult r = p2.begin_ice_flushBatchRequests(); + mainThread.interrupt(); + try + { + p2.end_ice_flushBatchRequests(r); + test(false); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + } + + p2.op(); + p2.op(); + p2.op(); + + final CallbackBase cb = new CallbackBase(); + mainThread.interrupt(); + p2.begin_ice_flushBatchRequests(new Callback_Object_ice_flushBatchRequests() + { + @Override + public void sent(boolean sentSynchronously) + { + cb.called(); + } + + @Override + public void exception(LocalException ex) + { + test(false); + } + }); + test(Thread.interrupted()); + cb.check(); + } + out.println("ok"); + + if(p.ice_getCachedConnection() != null) + { + out.print("testing batch connection flush interrupt... "); + out.flush(); + { + final TestIntfPrx p2 = TestIntfPrxHelper.uncheckedCast(p.ice_batchOneway()); + final Thread mainThread = Thread.currentThread(); + + p2.op(); + p2.op(); + p2.op(); + + AsyncResult r = p2.ice_getConnection().begin_flushBatchRequests(); + mainThread.interrupt(); + try + { + p2.ice_getCachedConnection().end_flushBatchRequests(r); + test(false); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + } + + p2.op(); + p2.op(); + p2.op(); + + final CallbackBase cb = new CallbackBase(); + Ice.Connection con = p2.ice_getConnection(); + mainThread.interrupt(); + con.begin_flushBatchRequests(new Callback_Connection_flushBatchRequests() + { + @Override + public void sent(boolean sentSynchronously) + { + cb.called(); + } + + @Override + public void exception(LocalException ex) + { + test(false); + } + }); + test(Thread.interrupted()); + cb.check(); + } + out.println("ok"); + } + + out.print("testing batch communicator flush interrupt... "); + out.flush(); + { + final TestIntfPrx p2 = TestIntfPrxHelper.uncheckedCast(p.ice_batchOneway()); + final Thread mainThread = Thread.currentThread(); + + p2.op(); + p2.op(); + p2.op(); + + AsyncResult r = communicator.begin_flushBatchRequests(); + mainThread.interrupt(); + try + { + communicator.end_flushBatchRequests(r); + test(false); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + } + + p2.op(); + p2.op(); + p2.op(); + + final CallbackBase cb = new CallbackBase(); + mainThread.interrupt(); + communicator.begin_flushBatchRequests(new Callback_Communicator_flushBatchRequests() + { + @Override + public void sent(boolean sentSynchronously) + { + cb.called(); + } + + @Override + public void exception(LocalException ex) + { + test(false); + } + }); + test(Thread.interrupted()); + cb.check(); + } + out.println("ok"); + + out.print("testing Communicator.destroy interrupt... "); + out.flush(); + { + // + // Check that CommunicatorDestroyedException is raised directly. + // + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + Ice.Communicator ic = app.initialize(initData); + + Thread.currentThread().interrupt(); + try + { + ic.destroy(); + failIfNotInterrupted(); + } + catch(Ice.OperationInterruptedException ex) + { + // Expected + } + ic.destroy(); + + ExecutorService executor = java.util.concurrent.Executors.newFixedThreadPool(2); + + ic = app.initialize(initData); + Ice.ObjectPrx o = ic.stringToProxy(p.toString()); + + final Thread[] thread = new Thread[1]; + + final CallbackBase cb = new CallbackBase(); + final TestIntfPrx p2 = TestIntfPrxHelper.checkedCast(o); + final CountDownLatch waitSignal = new CountDownLatch(1); + p2.begin_op(new Callback_TestIntf_op() + { + @Override + public void response() + { + try + { + Thread.sleep(250); + } + catch(InterruptedException e1) + { + test(false); + } + thread[0] = Thread.currentThread(); + waitSignal.countDown(); + try + { + Thread.sleep(10000); + test(false); + } + catch(InterruptedException e) + { + // Expected + } + cb.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + + } + }); + executor.submit(new Runnable() { + @Override + public void run() + { + try + { + waitSignal.await(); + } + catch(InterruptedException e) + { + test(false); + } + thread[0].interrupt(); + } + }); + + try + { + waitSignal.await(); + } + catch(InterruptedException e) + { + test(false); + } + ic.destroy(); + + cb.check(); + + executor.shutdown(); + executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); + } + out.println("ok"); + + out.print("testing server interrupt... "); + out.flush(); + { + final CallbackBase cb = new CallbackBase(); + p.begin_sleep(2000, new Callback_TestIntf_sleep() + { + @Override + public void response() + { + test(false); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + @Override + public void exception(Ice.UserException ex) + { + test(ex instanceof test.Ice.interrupt.Test.InterruptedException); + cb.called(); + } + }); + try + { + Thread.sleep(250); + } + catch(InterruptedException e) + { + test(false); + } + try + { + testController.interrupt(); + } + catch(CannotInterruptException e) + { + test(false); + } + cb.check(); + } + out.println("ok"); + + out.print("testing wait methods... "); + out.flush(); + { + final Thread mainThread = Thread.currentThread(); + ExecutorService executor = java.util.concurrent.Executors.newFixedThreadPool(1); + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + initData.properties.setProperty("ClientTestAdapter.Endpoints", "default -p 12030"); + Ice.Communicator ic = app.initialize(initData); + final Ice.ObjectAdapter adapter = ic.createObjectAdapter("ClientTestAdapter"); + adapter.activate(); + + try + { + mainThread.interrupt(); + adapter.waitForHold(); + test(false); + } + catch(Ice.OperationInterruptedException e) + { + // Expected. + } + + try + { + mainThread.interrupt(); + adapter.waitForDeactivate(); + test(false); + } + catch(Ice.OperationInterruptedException e) + { + // Expected. + } + + try + { + mainThread.interrupt(); + ic.waitForShutdown(); + test(false); + } + catch(Ice.OperationInterruptedException e) + { + // Expected. + } + + Runnable interruptMainThread = new Runnable() { + @Override + public void run() + { + try + { + Thread.sleep(250); + } + catch(InterruptedException e) + { + test(false); + } + mainThread.interrupt(); + } + }; + + executor.execute(interruptMainThread); + try + { + adapter.waitForHold(); + test(false); + } + catch(Ice.OperationInterruptedException e) + { + // Expected. + } + + executor.execute(interruptMainThread); + try + { + adapter.waitForDeactivate(); + test(false); + } + catch(Ice.OperationInterruptedException e) + { + // Expected. + } + + executor.execute(interruptMainThread); + try + { + ic.waitForShutdown(); + test(false); + } + catch(Ice.OperationInterruptedException e) + { + // Expected. + } + + ic.destroy(); + + executor.shutdown(); + executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); + } + out.println("ok"); + + p.shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/interrupt/Client.java b/java/test/src/main/java/test/Ice/interrupt/Client.java new file mode 100644 index 00000000000..edd6dfaa6ae --- /dev/null +++ b/java/test/src/main/java/test/Ice/interrupt/Client.java @@ -0,0 +1,60 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.interrupt; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + try + { + AllTests.allTests(this, communicator(), getWriter()); + } + catch (InterruptedException e) + { + e.printStackTrace(); + throw new RuntimeException(); + } + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.interrupt"); + // + // We need to enable the ThreadInterruptSafe property so that Ice is + // interrupt safe for this test. + // + initData.properties.setProperty("Ice.ThreadInterruptSafe", "1"); + // + // We need to send messages large enough to cause the transport + // buffers to fill up. + // + initData.properties.setProperty("Ice.MessageSizeMax", "20000"); + // + // Retry up to 2 times, sleep 1s for the last retry. This is + // useful to test interrupting the retry sleep + // + initData.properties.setProperty("Ice.RetryIntervals", "0 1000"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/interrupt/Collocated.java b/java/test/src/main/java/test/Ice/interrupt/Collocated.java new file mode 100644 index 00000000000..6e164020aee --- /dev/null +++ b/java/test/src/main/java/test/Ice/interrupt/Collocated.java @@ -0,0 +1,71 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.interrupt; + +public class Collocated extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + Ice.ObjectAdapter adapter2 = communicator().createObjectAdapter("ControllerAdapter"); + TestControllerI controller = new TestControllerI(adapter); + adapter.add(new TestI(controller), communicator().stringToIdentity("test")); + adapter.activate(); + adapter2.add(controller, communicator().stringToIdentity("testController")); + adapter2.activate(); + + try + { + AllTests.allTests(this, communicator(), getWriter()); + } + catch (InterruptedException e) + { + e.printStackTrace(); + throw new RuntimeException(); + } + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.interrupt"); + // + // We need to enable the ThreadInterruptSafe property so that Ice is + // interrupt safe for this test. + // + initData.properties.setProperty("Ice.ThreadInterruptSafe", "1"); + // + // We need to send messages large enough to cause the transport + // buffers to fill up. + // + initData.properties.setProperty("Ice.MessageSizeMax", "20000"); + + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("ControllerAdapter.Endpoints", "tcp -p 12011"); + initData.properties.setProperty("ControllerAdapter.ThreadPool.Size", "1"); + + return initData; + } + + public static void main(String[] args) + { + Collocated c = new Collocated(); + int status = c.main("Collocated", args); + + System.gc(); + System.exit(status); + } + +} diff --git a/java/test/src/main/java/test/Ice/interrupt/Server.java b/java/test/src/main/java/test/Ice/interrupt/Server.java new file mode 100644 index 00000000000..9ec7a725d77 --- /dev/null +++ b/java/test/src/main/java/test/Ice/interrupt/Server.java @@ -0,0 +1,66 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.interrupt; + +public class Server extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + Ice.ObjectAdapter adapter2 = communicator().createObjectAdapter("ControllerAdapter"); + + TestControllerI controller = new TestControllerI(adapter); + adapter.add(new TestI(controller), communicator().stringToIdentity("test")); + adapter.activate(); + adapter2.add(controller, communicator().stringToIdentity("testController")); + adapter2.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.interrupt"); + // + // We need to enable the ThreadInterruptSafe property so that Ice is + // interrupt safe for this test. + // + initData.properties.setProperty("Ice.ThreadInterruptSafe", "1"); + // + // We need to send messages large enough to cause the transport + // buffers to fill up. + // + initData.properties.setProperty("Ice.MessageSizeMax", "20000"); + // + // opIndempotent raises UnknownException, we disable dispatch + // warnings to prevent warnings. + // + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("ControllerAdapter.Endpoints", "tcp -p 12011"); + initData.properties.setProperty("ControllerAdapter.ThreadPool.Size", "1"); + return initData; + } + + public static void + main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/interrupt/Test.ice b/java/test/src/main/java/test/Ice/interrupt/Test.ice new file mode 100644 index 00000000000..5ff03302d8e --- /dev/null +++ b/java/test/src/main/java/test/Ice/interrupt/Test.ice @@ -0,0 +1,44 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/BuiltinSequences.ice> + +[["java:package:test.Ice.interrupt"]] +module Test +{ + +exception InterruptedException +{ +}; + +interface TestIntf +{ + void op(); + idempotent void opIdempotent(); + void sleep(int to) + throws InterruptedException; + void opWithPayload(Ice::ByteSeq seq); + void shutdown(); +}; + +exception CannotInterruptException +{ +}; + +interface TestIntfController +{ + void holdAdapter(); + void resumeAdapter(); + void interrupt() + throws CannotInterruptException; +}; + +}; diff --git a/java/test/src/main/java/test/Ice/interrupt/TestControllerI.java b/java/test/src/main/java/test/Ice/interrupt/TestControllerI.java new file mode 100644 index 00000000000..c3b9088393f --- /dev/null +++ b/java/test/src/main/java/test/Ice/interrupt/TestControllerI.java @@ -0,0 +1,69 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.interrupt; + +import java.util.ArrayList; +import java.util.List; + +class TestControllerI extends test.Ice.interrupt.Test._TestIntfControllerDisp +{ + synchronized void + addUpcallThread() + { + _threads.add(Thread.currentThread()); + } + + synchronized void + removeUpcallThread() + { + _threads.remove(Thread.currentThread()); + // + // Clear the interrupted state after removing the thread. + // + Thread.interrupted(); + } + + @Override + synchronized public void + interrupt(Ice.Current __current) + throws test.Ice.interrupt.Test.CannotInterruptException + { + if(_threads.isEmpty()) + { + throw new test.Ice.interrupt.Test.CannotInterruptException(); + } + for(Thread t : _threads) + { + t.interrupt(); + } + } + + @Override + public void + holdAdapter(Ice.Current current) + { + _adapter.hold(); + } + + @Override + public void + resumeAdapter(Ice.Current current) + { + _adapter.activate(); + } + + TestControllerI(Ice.ObjectAdapter adapter) + { + _adapter = adapter; + } + + final private Ice.ObjectAdapter _adapter; + final private List<Thread> _threads = new ArrayList<Thread>(); +} diff --git a/java/test/src/main/java/test/Ice/interrupt/TestI.java b/java/test/src/main/java/test/Ice/interrupt/TestI.java new file mode 100644 index 00000000000..35016d42489 --- /dev/null +++ b/java/test/src/main/java/test/Ice/interrupt/TestI.java @@ -0,0 +1,67 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.interrupt; + +public class TestI extends test.Ice.interrupt.Test._TestIntfDisp +{ + TestI(TestControllerI controller) + { + _controller = controller; + } + + @Override + public void + op(Ice.Current current) + { + } + + @Override + public void + opIdempotent(Ice.Current current) + { + throw new Ice.UnknownException(); + } + + + @Override + public void + sleep(int to, Ice.Current current) + throws test.Ice.interrupt.Test.InterruptedException + { + _controller.addUpcallThread(); + try + { + Thread.sleep(to); + } + catch(InterruptedException ex) + { + throw new test.Ice.interrupt.Test.InterruptedException(); + } + finally + { + _controller.removeUpcallThread(); + } + } + + @Override + public void + opWithPayload(byte[] seq, Ice.Current current) + { + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + private TestControllerI _controller; +} diff --git a/java/test/src/main/java/test/Ice/interrupt/run.py b/java/test/src/main/java/test/Ice/interrupt/run.py new file mode 100755 index 00000000000..a15d0a9c9e3 --- /dev/null +++ b/java/test/src/main/java/test/Ice/interrupt/run.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("tests with regular server.") +TestUtil.clientServerTest() + +print("tests with collocated server.") +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/invoke/AllTests.java b/java/test/src/main/java/test/Ice/invoke/AllTests.java new file mode 100644 index 00000000000..b22f4027b32 --- /dev/null +++ b/java/test/src/main/java/test/Ice/invoke/AllTests.java @@ -0,0 +1,387 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.invoke; +import java.io.PrintWriter; + +import test.Ice.invoke.Test.MyClassPrx; +import test.Ice.invoke.Test.MyClassPrxHelper; +import test.Ice.invoke.Test.MyException; + +public class AllTests +{ + final static String testString = "This is a test string"; + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static class opStringI extends Ice.Callback + { + public opStringI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + @Override + public void completed(Ice.AsyncResult result) + { + Ice.ByteSeqHolder outEncaps = new Ice.ByteSeqHolder(); + if(result.getProxy().end_ice_invoke(outEncaps, result)) + { + Ice.InputStream inS = Ice.Util.createInputStream(_communicator, outEncaps.value); + inS.startEncapsulation(); + String s = inS.readString(); + test(s.equals(testString)); + s = inS.readString(); + test(s.equals(testString)); + inS.endEncapsulation(); + callback.called(); + } + else + { + test(false); + } + } + + public void check() + { + callback.check(); + } + + private Ice.Communicator _communicator; + private Callback callback = new Callback(); + } + + private static class opExceptionI extends Ice.Callback + { + public opExceptionI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + @Override + public void completed(Ice.AsyncResult result) + { + Ice.ByteSeqHolder outEncaps = new Ice.ByteSeqHolder(); + if(result.getProxy().end_ice_invoke(outEncaps, result)) + { + test(false); + } + else + { + Ice.InputStream inS = Ice.Util.createInputStream(_communicator, outEncaps.value); + inS.startEncapsulation(); + try + { + inS.throwException(); + } + catch(MyException ex) + { + inS.endEncapsulation(); + callback.called(); + } + catch(java.lang.Exception ex) + { + test(false); + } + } + } + + public void check() + { + callback.check(); + } + + private Ice.Communicator _communicator; + private Callback callback = new Callback(); + } + + private static class Callback_Object_opStringI extends Ice.Callback_Object_ice_invoke + { + public Callback_Object_opStringI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + @Override + public void response(boolean ok, byte[] outEncaps) + { + if(ok) + { + Ice.InputStream inS = Ice.Util.createInputStream(_communicator, outEncaps); + inS.startEncapsulation(); + String s = inS.readString(); + test(s.equals(testString)); + s = inS.readString(); + test(s.equals(testString)); + inS.endEncapsulation(); + callback.called(); + } + else + { + test(false); + } + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Ice.Communicator _communicator; + private Callback callback = new Callback(); + } + + private static class Callback_Object_opExceptionI extends Ice.Callback_Object_ice_invoke + { + public Callback_Object_opExceptionI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + @Override + public void response(boolean ok, byte[] outEncaps) + { + if(ok) + { + test(false); + } + else + { + Ice.InputStream inS = Ice.Util.createInputStream(_communicator, outEncaps); + inS.startEncapsulation(); + try + { + inS.throwException(); + } + catch(MyException ex) + { + inS.endEncapsulation(); + callback.called(); + } + catch(java.lang.Exception ex) + { + test(false); + } + } + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Ice.Communicator _communicator; + private Callback callback = new Callback(); + } + + public static MyClassPrx + allTests(Ice.Communicator communicator, PrintWriter out) + { + String ref = "test:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + MyClassPrx cl = MyClassPrxHelper.checkedCast(base); + MyClassPrx oneway = MyClassPrxHelper.uncheckedCast(cl.ice_oneway()); + + out.print("testing ice_invoke... "); + out.flush(); + + { + if(!oneway.ice_invoke("opOneway", Ice.OperationMode.Normal, null, null)) + { + test(false); + } + + Ice.OutputStream outS = Ice.Util.createOutputStream(communicator); + outS.startEncapsulation(); + outS.writeString(testString); + outS.endEncapsulation(); + byte[] inEncaps = outS.finished(); + Ice.ByteSeqHolder outEncaps = new Ice.ByteSeqHolder(); + if(cl.ice_invoke("opString", Ice.OperationMode.Normal, inEncaps, outEncaps)) + { + Ice.InputStream inS = Ice.Util.createInputStream(communicator, outEncaps.value); + inS.startEncapsulation(); + String s = inS.readString(); + test(s.equals(testString)); + s = inS.readString(); + inS.endEncapsulation(); + test(s.equals(testString)); + } + else + { + test(false); + } + } + + { + Ice.ByteSeqHolder outEncaps = new Ice.ByteSeqHolder(); + if(cl.ice_invoke("opException", Ice.OperationMode.Normal, null, outEncaps)) + { + test(false); + } + else + { + Ice.InputStream inS = Ice.Util.createInputStream(communicator, outEncaps.value); + inS.startEncapsulation(); + try + { + inS.throwException(); + } + catch(MyException ex) + { + } + catch(java.lang.Exception ex) + { + test(false); + } + inS.endEncapsulation(); + } + } + + out.println("ok"); + + out.print("testing asynchronous ice_invoke... "); + out.flush(); + + { + Ice.AsyncResult result = oneway.begin_ice_invoke("opOneway", Ice.OperationMode.Normal, null); + Ice.ByteSeqHolder outEncaps = new Ice.ByteSeqHolder(); + if(!oneway.end_ice_invoke(outEncaps, result)) + { + test(false); + } + + Ice.OutputStream outS = Ice.Util.createOutputStream(communicator); + outS.startEncapsulation(); + outS.writeString(testString); + outS.endEncapsulation(); + byte[] inEncaps = outS.finished(); + + // begin_ice_invoke with no callback + result = cl.begin_ice_invoke("opString", Ice.OperationMode.Normal, inEncaps); + if(cl.end_ice_invoke(outEncaps, result)) + { + Ice.InputStream inS = Ice.Util.createInputStream(communicator, outEncaps.value); + inS.startEncapsulation(); + String s = inS.readString(); + test(s.equals(testString)); + s = inS.readString(); + inS.endEncapsulation(); + test(s.equals(testString)); + } + else + { + test(false); + } + + // begin_ice_invoke with Callback + opStringI cb1 = new opStringI(communicator); + cl.begin_ice_invoke("opString", Ice.OperationMode.Normal, inEncaps, cb1); + cb1.check(); + + // begin_ice_invoke with Callback_Object_ice_invoke + Callback_Object_opStringI cb2 = new Callback_Object_opStringI(communicator); + cl.begin_ice_invoke("opString", Ice.OperationMode.Normal, inEncaps, cb2); + cb2.check(); + } + + { + // begin_ice_invoke with no callback + Ice.AsyncResult result = cl.begin_ice_invoke("opException", Ice.OperationMode.Normal, null); + Ice.ByteSeqHolder outEncaps = new Ice.ByteSeqHolder(); + if(cl.end_ice_invoke(outEncaps, result)) + { + test(false); + } + else + { + Ice.InputStream inS = Ice.Util.createInputStream(communicator, outEncaps.value); + inS.startEncapsulation(); + try + { + inS.throwException(); + } + catch(MyException ex) + { + } + catch(java.lang.Exception ex) + { + test(false); + } + inS.endEncapsulation(); + } + + // begin_ice_invoke with Callback + opExceptionI cb1 = new opExceptionI(communicator); + cl.begin_ice_invoke("opException", Ice.OperationMode.Normal, null, cb1); + cb1.check(); + + // begin_ice_invoke with Callback_Object_ice_invoke + Callback_Object_opExceptionI cb2 = new Callback_Object_opExceptionI(communicator); + cl.begin_ice_invoke("opException", Ice.OperationMode.Normal, null, cb2); + cb2.check(); + } + + out.println("ok"); + + return cl; + } +} diff --git a/java/test/src/main/java/test/Ice/invoke/BlobjectAsyncI.java b/java/test/src/main/java/test/Ice/invoke/BlobjectAsyncI.java new file mode 100644 index 00000000000..c7e0837b946 --- /dev/null +++ b/java/test/src/main/java/test/Ice/invoke/BlobjectAsyncI.java @@ -0,0 +1,72 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.invoke; + +import test.Ice.invoke.Test.MyException; + +public class BlobjectAsyncI extends Ice.BlobjectAsync +{ + @Override + public void + ice_invoke_async(Ice.AMD_Object_ice_invoke cb, byte[] inParams, Ice.Current current) + { + Ice.Communicator communicator = current.adapter.getCommunicator(); + Ice.InputStream in = Ice.Util.createInputStream(communicator, inParams); + in.startEncapsulation(); + Ice.OutputStream out = Ice.Util.createOutputStream(communicator); + out.startEncapsulation(); + if(current.operation.equals("opOneway")) + { + cb.ice_response(true, new byte[0]); + } + else if(current.operation.equals("opString")) + { + String s = in.readString(); + out.writeString(s); + out.writeString(s); + out.endEncapsulation(); + cb.ice_response(true, out.finished()); + } + else if(current.operation.equals("opException")) + { + MyException ex = new MyException(); + out.writeException(ex); + out.endEncapsulation(); + cb.ice_response(false, out.finished()); + } + else if(current.operation.equals("shutdown")) + { + communicator.shutdown(); + cb.ice_response(true, null); + } + else if(current.operation.equals("ice_isA")) + { + String s = in.readString(); + if(s.equals("::Test::MyClass")) + { + out.writeBool(true); + } + else + { + out.writeBool(false); + } + out.endEncapsulation(); + cb.ice_response(true, out.finished()); + } + else + { + Ice.OperationNotExistException ex = new Ice.OperationNotExistException(); + ex.id = current.id; + ex.facet = current.facet; + ex.operation = current.operation; + throw ex; + } + } +} diff --git a/java/test/src/main/java/test/Ice/invoke/BlobjectI.java b/java/test/src/main/java/test/Ice/invoke/BlobjectI.java new file mode 100644 index 00000000000..c676c38dc63 --- /dev/null +++ b/java/test/src/main/java/test/Ice/invoke/BlobjectI.java @@ -0,0 +1,76 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.invoke; + +import test.Ice.invoke.Test.MyException; + +public class BlobjectI extends Ice.Blobject +{ + @Override + public boolean + ice_invoke(byte[] inParams, Ice.ByteSeqHolder outParams, Ice.Current current) + { + Ice.Communicator communicator = current.adapter.getCommunicator(); + Ice.InputStream in = Ice.Util.createInputStream(communicator, inParams); + in.startEncapsulation(); + Ice.OutputStream out = Ice.Util.createOutputStream(communicator); + out.startEncapsulation(); + if(current.operation.equals("opOneway")) + { + outParams.value = new byte[0]; + return true; + } + else if(current.operation.equals("opString")) + { + String s = in.readString(); + out.writeString(s); + out.writeString(s); + out.endEncapsulation(); + outParams.value = out.finished(); + return true; + } + else if(current.operation.equals("opException")) + { + MyException ex = new MyException(); + out.writeException(ex); + out.endEncapsulation(); + outParams.value = out.finished(); + return false; + } + else if(current.operation.equals("shutdown")) + { + communicator.shutdown(); + return true; + } + else if(current.operation.equals("ice_isA")) + { + String s = in.readString(); + if(s.equals("::Test::MyClass")) + { + out.writeBool(true); + } + else + { + out.writeBool(false); + } + out.endEncapsulation(); + outParams.value = out.finished(); + return true; + } + else + { + Ice.OperationNotExistException ex = new Ice.OperationNotExistException(); + ex.id = current.id; + ex.facet = current.facet; + ex.operation = current.operation; + throw ex; + } + } +} diff --git a/java/test/src/main/java/test/Ice/invoke/Client.java b/java/test/src/main/java/test/Ice/invoke/Client.java new file mode 100644 index 00000000000..e589d32075c --- /dev/null +++ b/java/test/src/main/java/test/Ice/invoke/Client.java @@ -0,0 +1,69 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.invoke; + +import test.Ice.invoke.Test.MyClassPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + MyClassPrx myClass = AllTests.allTests(communicator(), getWriter()); + + // + // Use reflection to load lambda.AllTests as that is only supported with Java >= 1.8 + // + try + { + Class<?> cls = IceInternal.Util.findClass("test.Ice.invoke.lambda.AllTests", null); + if(cls != null) + { + java.lang.reflect.Method allTests = cls.getDeclaredMethod("allTests", + new Class<?>[]{Ice.Communicator.class, java.io.PrintWriter.class}); + allTests.invoke(null, communicator(), getWriter()); + } + } + catch(java.lang.NoSuchMethodException ex) + { + throw new RuntimeException(ex); + } + catch(java.lang.IllegalAccessException ex) + { + throw new RuntimeException(ex); + } + catch(java.lang.reflect.InvocationTargetException ex) + { + throw new RuntimeException(ex); + } + + myClass.shutdown(); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.invoke"); + return initData; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/invoke/ServantLocatorI.java b/java/test/src/main/java/test/Ice/invoke/ServantLocatorI.java new file mode 100644 index 00000000000..9ed2262b995 --- /dev/null +++ b/java/test/src/main/java/test/Ice/invoke/ServantLocatorI.java @@ -0,0 +1,46 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.invoke; + +public class ServantLocatorI implements Ice.ServantLocator +{ + public ServantLocatorI( boolean async) + { + if(async) + { + _blobject = new BlobjectAsyncI(); + } + else + { + _blobject = new BlobjectI(); + } + } + + @Override + public Ice.Object + locate(Ice.Current current, Ice.LocalObjectHolder cookie) + { + return _blobject; + } + + @Override + public void + finished(Ice.Current current, Ice.Object servant, java.lang.Object cookie) + { + } + + @Override + public void + deactivate(String category) + { + } + + private Ice.Object _blobject; +} diff --git a/java/test/src/main/java/test/Ice/invoke/Server.java b/java/test/src/main/java/test/Ice/invoke/Server.java new file mode 100644 index 00000000000..a6f315d5cf9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/invoke/Server.java @@ -0,0 +1,50 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.invoke; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + boolean async = false; + for(int i = 0; i < args.length; ++i) + { + if(args[i].equals("--async")) + { + async = true; + } + } + + communicator().getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.addServantLocator(new ServantLocatorI(async), ""); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.invoke"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/invoke/Test.ice b/java/test/src/main/java/test/Ice/invoke/Test.ice new file mode 100644 index 00000000000..6aae90da746 --- /dev/null +++ b/java/test/src/main/java/test/Ice/invoke/Test.ice @@ -0,0 +1,31 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.invoke"]] +module Test +{ + +exception MyException +{ +}; + +class MyClass +{ + void opOneway(); + + string opString(string s1, out string s2); + + void opException() throws MyException; + + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/invoke/lambda/AllTests.java b/java/test/src/main/java/test/Ice/invoke/lambda/AllTests.java new file mode 100644 index 00000000000..5b7764615a3 --- /dev/null +++ b/java/test/src/main/java/test/Ice/invoke/lambda/AllTests.java @@ -0,0 +1,199 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.invoke.lambda; +import java.io.PrintWriter; + +import test.Ice.invoke.Test.MyClassPrx; +import test.Ice.invoke.Test.MyClassPrxHelper; +import test.Ice.invoke.Test.MyException; + +public class AllTests +{ + final static String testString = "This is a test string"; + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static class Callback_Object_opStringI + { + public Callback_Object_opStringI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + public void response(boolean ok, byte[] outEncaps) + { + if(ok) + { + Ice.InputStream inS = Ice.Util.createInputStream(_communicator, outEncaps); + inS.startEncapsulation(); + String s = inS.readString(); + test(s.equals(testString)); + s = inS.readString(); + test(s.equals(testString)); + inS.endEncapsulation(); + callback.called(); + } + else + { + test(false); + } + } + + public void exception(Ice.Exception ex) + { + test(false); + } + + public void sent(boolean sent) + { + } + + public void check() + { + callback.check(); + } + + private Ice.Communicator _communicator; + private Callback callback = new Callback(); + } + + private static class Callback_Object_opExceptionI + { + public Callback_Object_opExceptionI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + public void response(boolean ok, byte[] outEncaps) + { + if(ok) + { + test(false); + } + else + { + Ice.InputStream inS = Ice.Util.createInputStream(_communicator, outEncaps); + inS.startEncapsulation(); + try + { + inS.throwException(); + } + catch(MyException ex) + { + inS.endEncapsulation(); + callback.called(); + } + catch(java.lang.Exception ex) + { + test(false); + } + } + } + + public void exception(Ice.Exception ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + public void sent(boolean sent) + { + } + + private Ice.Communicator _communicator; + private Callback callback = new Callback(); + } + + public static MyClassPrx + allTests(Ice.Communicator communicator, PrintWriter out) + { + String ref = "test:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + MyClassPrx cl = MyClassPrxHelper.checkedCast(base); + MyClassPrx oneway = MyClassPrxHelper.uncheckedCast(cl.ice_oneway()); + + out.print("testing asynchronous ice_invoke with lambda callbacks... "); + out.flush(); + + { + Ice.OutputStream outS = Ice.Util.createOutputStream(communicator); + outS.startEncapsulation(); + outS.writeString(testString); + outS.endEncapsulation(); + byte[] inEncaps = outS.finished(); + + // begin_ice_invoke with Callback_Object_ice_invoke + Callback_Object_opStringI cb2 = new Callback_Object_opStringI(communicator); + cl.begin_ice_invoke("opString", Ice.OperationMode.Normal, inEncaps, + (boolean ret, byte[] outParams) -> cb2.response(ret, outParams), + (Ice.Exception ex) -> cb2.exception(ex), + (boolean sent) -> cb2.sent(sent)); + cb2.check(); + } + + { + // begin_ice_invoke with Callback_Object_ice_invoke + Callback_Object_opExceptionI cb2 = new Callback_Object_opExceptionI(communicator); + cl.begin_ice_invoke("opException", Ice.OperationMode.Normal, null, + (boolean ret, byte[] outParams) -> cb2.response(ret, outParams), + (Ice.Exception ex) -> cb2.exception(ex), + (boolean sent) -> cb2.sent(sent)); + cb2.check(); + } + + out.println("ok"); + + return cl; + } +} diff --git a/java/test/src/main/java/test/Ice/invoke/run.py b/java/test/src/main/java/test/Ice/invoke/run.py new file mode 100755 index 00000000000..50be82e58ca --- /dev/null +++ b/java/test/src/main/java/test/Ice/invoke/run.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("tests with Blobject server.") +TestUtil.clientServerTest() + +print("tests with BlobjectAsync server.") +TestUtil.clientServerTest(additionalServerOptions = "--async") diff --git a/java/test/src/main/java/test/Ice/location/AllTests.java b/java/test/src/main/java/test/Ice/location/AllTests.java new file mode 100644 index 00000000000..636376a0253 --- /dev/null +++ b/java/test/src/main/java/test/Ice/location/AllTests.java @@ -0,0 +1,696 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.location; + +import java.io.PrintWriter; + +import test.Ice.location.Test.Callback_Hello_sayHello; +import test.Ice.location.Test.HelloPrx; +import test.Ice.location.Test.HelloPrxHelper; +import test.Ice.location.Test.ServerManagerPrx; +import test.Ice.location.Test.ServerManagerPrxHelper; +import test.Ice.location.Test.TestIntfPrx; +import test.Ice.location.Test.TestIntfPrxHelper; +import test.Ice.location.Test.TestLocatorPrx; +import test.Ice.location.Test.TestLocatorPrxHelper; +import test.Ice.location.Test.TestLocatorRegistryPrx; +import test.Ice.location.Test.TestLocatorRegistryPrxHelper; +import test.Util.Application; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + allTests(Application app) + throws Ice.AdapterAlreadyActiveException, Ice.AdapterNotFoundException, InterruptedException + { + Ice.Communicator communicator = app.communicator(); + PrintWriter out = app.getWriter(); + + ServerManagerPrx manager = ServerManagerPrxHelper.checkedCast( + communicator.stringToProxy("ServerManager :default -p 12010")); + test(manager != null); + + TestLocatorPrx locator = TestLocatorPrxHelper.uncheckedCast(communicator.getDefaultLocator()); + test(locator != null); + + TestLocatorRegistryPrx registry = TestLocatorRegistryPrxHelper.checkedCast(locator.getRegistry()); + test(registry != null); + + out.print("testing stringToProxy... "); + out.flush(); + Ice.ObjectPrx base = communicator.stringToProxy("test @ TestAdapter"); + Ice.ObjectPrx base2 = communicator.stringToProxy("test @ TestAdapter"); + Ice.ObjectPrx base3 = communicator.stringToProxy("test"); + Ice.ObjectPrx base4 = communicator.stringToProxy("ServerManager"); + Ice.ObjectPrx base5 = communicator.stringToProxy("test2"); + Ice.ObjectPrx base6 = communicator.stringToProxy("test @ ReplicatedAdapter"); + out.println("ok"); + + out.print("testing ice_locator and ice_getLocator... "); + test(Ice.Util.proxyIdentityCompare(base.ice_getLocator(), communicator.getDefaultLocator()) == 0); + Ice.LocatorPrx anotherLocator = + Ice.LocatorPrxHelper.uncheckedCast(communicator.stringToProxy("anotherLocator")); + base = base.ice_locator(anotherLocator); + test(Ice.Util.proxyIdentityCompare(base.ice_getLocator(), anotherLocator) == 0); + communicator.setDefaultLocator(null); + base = communicator.stringToProxy("test @ TestAdapter"); + test(base.ice_getLocator() == null); + base = base.ice_locator(anotherLocator); + test(Ice.Util.proxyIdentityCompare(base.ice_getLocator(), anotherLocator) == 0); + communicator.setDefaultLocator(locator); + base = communicator.stringToProxy("test @ TestAdapter"); + test(Ice.Util.proxyIdentityCompare(base.ice_getLocator(), communicator.getDefaultLocator()) == 0); + + // + // We also test ice_router/ice_getRouter (perhaps we should add a + // test/Ice/router test?) + // + test(base.ice_getRouter() == null); + Ice.RouterPrx anotherRouter = Ice.RouterPrxHelper.uncheckedCast(communicator.stringToProxy("anotherRouter")); + base = base.ice_router(anotherRouter); + test(Ice.Util.proxyIdentityCompare(base.ice_getRouter(), anotherRouter) == 0); + Ice.RouterPrx router = Ice.RouterPrxHelper.uncheckedCast(communicator.stringToProxy("dummyrouter")); + communicator.setDefaultRouter(router); + base = communicator.stringToProxy("test @ TestAdapter"); + test(Ice.Util.proxyIdentityCompare(base.ice_getRouter(), communicator.getDefaultRouter()) == 0); + communicator.setDefaultRouter(null); + base = communicator.stringToProxy("test @ TestAdapter"); + test(base.ice_getRouter() == null); + out.println("ok"); + + out.print("starting server... "); + out.flush(); + manager.startServer(); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + TestIntfPrx obj = TestIntfPrxHelper.checkedCast(base); + test(obj != null); + TestIntfPrx obj2 = TestIntfPrxHelper.checkedCast(base2); + test(obj2 != null); + TestIntfPrx obj3 = TestIntfPrxHelper.checkedCast(base3); + test(obj3 != null); + ServerManagerPrx obj4 = ServerManagerPrxHelper.checkedCast(base4); + test(obj4 != null); + TestIntfPrx obj5 = TestIntfPrxHelper.checkedCast(base5); + test(obj5 != null); + TestIntfPrx obj6 = TestIntfPrxHelper.checkedCast(base6); + test(obj6 != null); + out.println("ok"); + + out.print("testing id@AdapterId indirect proxy... "); + out.flush(); + obj.shutdown(); + manager.startServer(); + try + { + obj2.ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + out.println("ok"); + + out.print("testing id@ReplicaGroupId indirect proxy... "); + out.flush(); + obj.shutdown(); + manager.startServer(); + try + { + obj6.ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + out.println("ok"); + + out.print("testing identity indirect proxy... "); + out.flush(); + obj.shutdown(); + manager.startServer(); + try + { + obj3.ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + try + { + obj2.ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + obj.shutdown(); + manager.startServer(); + try + { + obj2.ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + try + { + obj3.ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + obj.shutdown(); + manager.startServer(); + + try + { + obj2.ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + obj.shutdown(); + manager.startServer(); + try + { + obj3.ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + obj.shutdown(); + manager.startServer(); + try + { + obj2.ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + obj.shutdown(); + manager.startServer(); + + try + { + obj5.ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + out.println("ok"); + + out.print("testing proxy with unknown identity... "); + out.flush(); + try + { + base = communicator.stringToProxy("unknown/unknown"); + base.ice_ping(); + test(false); + } + catch(Ice.NotRegisteredException ex) + { + test(ex.kindOfObject.equals("object")); + test(ex.id.equals("unknown/unknown")); + } + out.println("ok"); + + out.print("testing proxy with unknown adapter... "); + out.flush(); + try + { + base = communicator.stringToProxy("test @ TestAdapterUnknown"); + base.ice_ping(); + test(false); + } + catch(Ice.NotRegisteredException ex) + { + test(ex.kindOfObject.equals("object adapter")); + test(ex.id.equals("TestAdapterUnknown")); + } + out.println("ok"); + + out.print("testing locator cache timeout... "); + out.flush(); + + int count = locator.getRequestCount(); + communicator.stringToProxy("test@TestAdapter").ice_locatorCacheTimeout(0).ice_ping(); // No locator cache. + test(++count == locator.getRequestCount()); + communicator.stringToProxy("test@TestAdapter").ice_locatorCacheTimeout(0).ice_ping(); // No locator cache. + test(++count == locator.getRequestCount()); + communicator.stringToProxy("test@TestAdapter").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout. + test(count == locator.getRequestCount()); + Thread.sleep(1200); + communicator.stringToProxy("test@TestAdapter").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout. + test(++count == locator.getRequestCount()); + + communicator.stringToProxy("test").ice_locatorCacheTimeout(0).ice_ping(); // No locator cache. + count += 2; + test(count == locator.getRequestCount()); + communicator.stringToProxy("test").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout + test(count == locator.getRequestCount()); + Thread.sleep(1200); + communicator.stringToProxy("test").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout + count += 2; + test(count == locator.getRequestCount()); + + communicator.stringToProxy("test@TestAdapter").ice_locatorCacheTimeout(-1).ice_ping(); + test(count == locator.getRequestCount()); + communicator.stringToProxy("test").ice_locatorCacheTimeout(-1).ice_ping(); + test(count == locator.getRequestCount()); + communicator.stringToProxy("test@TestAdapter").ice_ping(); + test(count == locator.getRequestCount()); + communicator.stringToProxy("test").ice_ping(); + test(count == locator.getRequestCount()); + + test(communicator.stringToProxy("test").ice_locatorCacheTimeout(99).ice_getLocatorCacheTimeout() == 99); + + out.println("ok"); + + out.print("testing proxy from server... "); + out.flush(); + obj = TestIntfPrxHelper.checkedCast(communicator.stringToProxy("test@TestAdapter")); + HelloPrx hello = obj.getHello(); + test(hello.ice_getAdapterId().equals("TestAdapter")); + hello = obj.getReplicatedHello(); + test(hello.ice_getAdapterId().equals("ReplicatedAdapter")); + hello.sayHello(); + out.println("ok"); + + out.print("testing proxy from server after shutdown... "); + out.flush(); + obj.shutdown(); + manager.startServer(); + hello.sayHello(); + out.println("ok"); + + out.print("testing locator request queuing... "); + out.flush(); + hello = (HelloPrx)obj.getReplicatedHello().ice_locatorCacheTimeout(0).ice_connectionCached(false); + count = locator.getRequestCount(); + hello.ice_ping(); + test(++count == locator.getRequestCount()); + java.util.List<Ice.AsyncResult> results = new java.util.LinkedList<Ice.AsyncResult>(); + for(int i = 0; i < 1000; i++) + { + class AMICallback extends Callback_Hello_sayHello + { + @Override + public void + exception(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + + @Override + public void + response() + { + } + }; + Ice.AsyncResult result = hello.begin_sayHello(new AMICallback()); + results.add(result); + } + while(!results.isEmpty()) + { + Ice.AsyncResult result = results.remove(0); + result.waitForCompleted(); + } + test(locator.getRequestCount() > count && locator.getRequestCount() < count + 999); + if(locator.getRequestCount() > count + 800) + { + out.print("queuing = " + (locator.getRequestCount() - count)); + } + count = locator.getRequestCount(); + hello = (HelloPrx)hello.ice_adapterId("unknown"); + for(int i = 0; i < 1000; i++) + { + class AMICallback extends Callback_Hello_sayHello + { + @Override + public void + exception(Ice.LocalException ex) + { + if(ex instanceof Ice.CommunicatorDestroyedException) + { + ex.printStackTrace(); + assert false; + } + test(ex instanceof Ice.NotRegisteredException); + } + + @Override + public void + response() + { + test(false); + } + }; + Ice.AsyncResult result = hello.begin_sayHello(new AMICallback()); + results.add(result); + } + while(!results.isEmpty()) + { + Ice.AsyncResult result = results.remove(0); + result.waitForCompleted(); + } + // Take into account the retries. + test(locator.getRequestCount() > count && locator.getRequestCount() < count + 1999); + if(locator.getRequestCount() > count + 800) + { + out.print("queuing = " + (locator.getRequestCount() - count)); + } + out.println("ok"); + + out.print("testing adapter locator cache... "); + out.flush(); + try + { + communicator.stringToProxy("test@TestAdapter3").ice_ping(); + test(false); + } + catch(Ice.NotRegisteredException ex) + { + test(ex.kindOfObject == "object adapter"); + test(ex.id.equals("TestAdapter3")); + } + registry.setAdapterDirectProxy("TestAdapter3", locator.findAdapterById("TestAdapter")); + try + { + communicator.stringToProxy("test@TestAdapter3").ice_ping(); + registry.setAdapterDirectProxy("TestAdapter3", communicator.stringToProxy("dummy:tcp")); + communicator.stringToProxy("test@TestAdapter3").ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + communicator.stringToProxy("test@TestAdapter3").ice_locatorCacheTimeout(0).ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + try + { + communicator.stringToProxy("test@TestAdapter3").ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + registry.setAdapterDirectProxy("TestAdapter3", locator.findAdapterById("TestAdapter")); + try + { + communicator.stringToProxy("test@TestAdapter3").ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + out.println("ok"); + + out.print("testing well-known object locator cache... "); + out.flush(); + + registry.addObject(communicator.stringToProxy("test3@TestUnknown")); + try + { + communicator.stringToProxy("test3").ice_ping(); + test(false); + } + catch(Ice.NotRegisteredException ex) + { + test(ex.kindOfObject == "object adapter"); + test(ex.id.equals("TestUnknown")); + } + registry.addObject(communicator.stringToProxy("test3@TestAdapter4")); // Update + registry.setAdapterDirectProxy("TestAdapter4", communicator.stringToProxy("dummy:tcp")); + + try + { + communicator.stringToProxy("test3").ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + registry.setAdapterDirectProxy("TestAdapter4", locator.findAdapterById("TestAdapter")); + try + { + communicator.stringToProxy("test3").ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + + registry.setAdapterDirectProxy("TestAdapter4", communicator.stringToProxy("dummy:tcp")); + try + { + communicator.stringToProxy("test3").ice_ping(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + + try + { + communicator.stringToProxy("test@TestAdapter4").ice_locatorCacheTimeout(0).ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + try + { + communicator.stringToProxy("test@TestAdapter4").ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + try + { + communicator.stringToProxy("test3").ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + registry.addObject(communicator.stringToProxy("test3@TestAdapter")); + try + { + communicator.stringToProxy("test3").ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + + registry.addObject(communicator.stringToProxy("test4")); + try + { + communicator.stringToProxy("test4").ice_ping(); + test(false); + } + catch(Ice.NoEndpointException ex) + { + } + out.println("ok"); + + out.print("testing locator cache background updates... "); + out.flush(); + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + initData.properties.setProperty("Ice.BackgroundLocatorCacheUpdates", "1"); + Ice.Communicator ic = app.initialize(initData); + + registry.setAdapterDirectProxy("TestAdapter5", locator.findAdapterById("TestAdapter")); + registry.addObject(communicator.stringToProxy("test3@TestAdapter")); + + count = locator.getRequestCount(); + ic.stringToProxy("test@TestAdapter5").ice_locatorCacheTimeout(0).ice_ping(); // No locator cache. + ic.stringToProxy("test3").ice_locatorCacheTimeout(0).ice_ping(); // No locator cache. + count += 3; + test(count == locator.getRequestCount()); + registry.setAdapterDirectProxy("TestAdapter5", null); + registry.addObject(communicator.stringToProxy("test3:tcp")); + 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()); + Thread.sleep(1200); + + // The following request should trigger the background updates but still use the cached endpoints + // and therefore succeed. + ic.stringToProxy("test@TestAdapter5").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout. + ic.stringToProxy("test3").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout. + + try + { + while(true) + { + ic.stringToProxy("test@TestAdapter5").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout. + Thread.sleep(10); + } + } + catch(Ice.LocalException ex) + { + // Expected to fail once they endpoints have been updated in the background. + } + try + { + while(true) + { + ic.stringToProxy("test3").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout. + Thread.sleep(10); + } + } + catch(Ice.LocalException ex) + { + // Expected to fail once they endpoints have been updated in the background. + } + ic.destroy(); + } + out.println("ok"); + + out.print("testing proxy from server after shutdown... "); + out.flush(); + hello = obj.getReplicatedHello(); + obj.shutdown(); + manager.startServer(); + hello.sayHello(); + out.println("ok"); + + out.print("testing object migration..."); + out.flush(); + hello = HelloPrxHelper.checkedCast(communicator.stringToProxy("hello")); + obj.migrateHello(); + hello.ice_getConnection().close(false); + hello.sayHello(); + obj.migrateHello(); + hello.sayHello(); + obj.migrateHello(); + hello.sayHello(); + out.println("ok"); + + out.print("testing locator encoding resolution... "); + out.flush(); + hello = HelloPrxHelper.checkedCast(communicator.stringToProxy("hello")); + count = locator.getRequestCount(); + communicator.stringToProxy("test@TestAdapter").ice_encodingVersion(Ice.Util.Encoding_1_1).ice_ping(); + test(count == locator.getRequestCount()); + communicator.stringToProxy("test@TestAdapter10").ice_encodingVersion(Ice.Util.Encoding_1_0).ice_ping(); + test(++count == locator.getRequestCount()); + communicator.stringToProxy("test -e 1.0@TestAdapter10-2").ice_ping(); + test(++count == locator.getRequestCount()); + out.println("ok"); + + out.print("shutdown server... "); + out.flush(); + obj.shutdown(); + out.println("ok"); + + out.print("testing whether server is gone... "); + out.flush(); + try + { + obj2.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + try + { + obj3.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + try + { + obj5.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + out.println("ok"); + + out.print("testing indirect proxies to collocated objects... "); + // + // Set up test for calling a collocated object through an + // indirect, adapterless reference. + // + Ice.Properties properties = communicator.getProperties(); + properties.setProperty("Ice.PrintAdapterReady", "0"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapterWithEndpoints("Hello", "default"); + adapter.setLocator(locator); + + Ice.Identity id = new Ice.Identity(); + id.name = java.util.UUID.randomUUID().toString(); + registry.addObject(adapter.add(new HelloI(), id)); + adapter.activate(); + + // Note the quotes are necessary here due to ":" in the + // java generated UUID. + HelloPrx helloPrx = HelloPrxHelper.checkedCast( + communicator.stringToProxy("\"" + communicator.identityToString(id) + "\"")); + test(helloPrx.ice_getConnection() == null); + + adapter.deactivate(); + out.println("ok"); + + out.print("shutdown server manager... "); + out.flush(); + manager.shutdown(); + out.println("ok"); + } +} diff --git a/java/test/src/main/java/test/Ice/location/Client.java b/java/test/src/main/java/test/Ice/location/Client.java new file mode 100644 index 00000000000..4fc8e67893b --- /dev/null +++ b/java/test/src/main/java/test/Ice/location/Client.java @@ -0,0 +1,57 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.location; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + try + { + AllTests.allTests(this); + } + catch(Ice.AdapterAlreadyActiveException ex) + { + ex.printStackTrace(); + throw new RuntimeException(); + } + catch(Ice.AdapterNotFoundException ex) + { + ex.printStackTrace(); + throw new RuntimeException(); + } + catch(InterruptedException ex) + { + ex.printStackTrace(); + throw new RuntimeException(); + } + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.location"); + initData.properties.setProperty("Ice.Default.Locator", "locator:default -p 12010"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/location/HelloI.java b/java/test/src/main/java/test/Ice/location/HelloI.java new file mode 100644 index 00000000000..5036d4cbc18 --- /dev/null +++ b/java/test/src/main/java/test/Ice/location/HelloI.java @@ -0,0 +1,22 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.location; + +import test.Ice.location.Test._HelloDisp; + + +public class HelloI extends _HelloDisp +{ + @Override + public void + sayHello(Ice.Current current) + { + } +} diff --git a/java/test/src/main/java/test/Ice/location/Server.java b/java/test/src/main/java/test/Ice/location/Server.java new file mode 100644 index 00000000000..4b09338d2ee --- /dev/null +++ b/java/test/src/main/java/test/Ice/location/Server.java @@ -0,0 +1,70 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.location; + +public class Server extends test.Util.Application +{ + private Ice.InitializationData _initData; + + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + + // + // Register the server manager. The server manager creates a new + // 'server' (a server isn't a different process, it's just a new + // communicator and object adapter). + // + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("ServerManagerAdapter"); + + // + // We also register a sample server locator which implements the + // locator interface, this locator is used by the clients and the + // 'servers' created with the server manager interface. + // + ServerLocatorRegistry registry = new ServerLocatorRegistry(); + registry.addObject(adapter.createProxy(communicator.stringToIdentity("ServerManager"))); + Ice.Object object = new ServerManagerI(registry, _initData, this); + adapter.add(object, communicator.stringToIdentity("ServerManager")); + + Ice.LocatorRegistryPrx registryPrx = Ice.LocatorRegistryPrxHelper.uncheckedCast(adapter.add(registry, + communicator.stringToIdentity("registry"))); + + ServerLocator locator = new ServerLocator(registry, registryPrx); + adapter.add(locator, communicator.stringToIdentity("locator")); + + adapter.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.location"); + initData.properties.setProperty("Ice.ThreadPool.Server.Size", "2"); + initData.properties.setProperty("Ice.ThreadPool.Server.SizeWarn", "0"); + initData.properties.setProperty("ServerManagerAdapter.Endpoints", "default -p 12010:udp"); + + _initData = initData; + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/location/ServerLocator.java b/java/test/src/main/java/test/Ice/location/ServerLocator.java new file mode 100644 index 00000000000..0e27e888eb7 --- /dev/null +++ b/java/test/src/main/java/test/Ice/location/ServerLocator.java @@ -0,0 +1,86 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.location; + +import test.Ice.location.Test._TestLocatorDisp; + +public class ServerLocator extends _TestLocatorDisp +{ + public + ServerLocator(ServerLocatorRegistry registry, Ice.LocatorRegistryPrx registryPrx) + { + _registry = registry; + _registryPrx = registryPrx; + _requestCount = 0; + } + + @Override + public void + findAdapterById_async(Ice.AMD_Locator_findAdapterById response, String adapter, Ice.Current current) + throws Ice.AdapterNotFoundException + { + ++_requestCount; + if(adapter.equals("TestAdapter10") || adapter.equals("TestAdapter10-2")) + { + assert(current.encoding.equals(Ice.Util.Encoding_1_0)); + response.ice_response(_registry.getAdapter("TestAdapter")); + return; + } + + // 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)); + } + + @Override + public void + findObjectById_async(Ice.AMD_Locator_findObjectById response, Ice.Identity id, Ice.Current current) + 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)); + } + + @Override + public Ice.LocatorRegistryPrx + getRegistry(Ice.Current current) + { + return _registryPrx; + } + + @Override + public int + getRequestCount(Ice.Current current) + { + return _requestCount; + } + + private ServerLocatorRegistry _registry; + private Ice.LocatorRegistryPrx _registryPrx; + private int _requestCount; + +} + diff --git a/java/test/src/main/java/test/Ice/location/ServerLocatorRegistry.java b/java/test/src/main/java/test/Ice/location/ServerLocatorRegistry.java new file mode 100644 index 00000000000..7a9fbc50ac8 --- /dev/null +++ b/java/test/src/main/java/test/Ice/location/ServerLocatorRegistry.java @@ -0,0 +1,91 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.location; + +import test.Ice.location.Test._TestLocatorRegistryDisp; + +public class ServerLocatorRegistry extends _TestLocatorRegistryDisp +{ + @Override + public void + setAdapterDirectProxy_async(Ice.AMD_LocatorRegistry_setAdapterDirectProxy cb, String adapter, + Ice.ObjectPrx object, Ice.Current current) + { + if(object != null) + { + _adapters.put(adapter, object); + } + else + { + _adapters.remove(adapter); + } + cb.ice_response(); + } + + @Override + public void + setReplicatedAdapterDirectProxy_async(Ice.AMD_LocatorRegistry_setReplicatedAdapterDirectProxy cb, String adapter, + String replica, Ice.ObjectPrx object, Ice.Current current) + { + if(object != null) + { + _adapters.put(adapter, object); + _adapters.put(replica, object); + } + else + { + _adapters.remove(adapter); + _adapters.remove(replica); + } + cb.ice_response(); + } + + @Override + public void + setServerProcessProxy_async(Ice.AMD_LocatorRegistry_setServerProcessProxy cb, String id, Ice.ProcessPrx proxy, + Ice.Current current) + { + } + + @Override + public void + addObject(Ice.ObjectPrx object, Ice.Current current) + { + _objects.put(object.ice_getIdentity(), object); + } + + public Ice.ObjectPrx + getAdapter(String adapter) + throws Ice.AdapterNotFoundException + { + Ice.ObjectPrx obj = _adapters.get(adapter); + if(obj == null) + { + throw new Ice.AdapterNotFoundException(); + } + return obj; + } + + public Ice.ObjectPrx + getObject(Ice.Identity id) + throws Ice.ObjectNotFoundException + { + Ice.ObjectPrx obj = _objects.get(id); + if(obj == null) + { + throw new Ice.ObjectNotFoundException(); + } + return obj; + } + + private java.util.HashMap<String, Ice.ObjectPrx> _adapters = new java.util.HashMap<String, Ice.ObjectPrx>(); + private java.util.HashMap<Ice.Identity, Ice.ObjectPrx> _objects = + new java.util.HashMap<Ice.Identity, Ice.ObjectPrx>(); +} diff --git a/java/test/src/main/java/test/Ice/location/ServerManagerI.java b/java/test/src/main/java/test/Ice/location/ServerManagerI.java new file mode 100644 index 00000000000..2ac89074ad7 --- /dev/null +++ b/java/test/src/main/java/test/Ice/location/ServerManagerI.java @@ -0,0 +1,92 @@ + +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.location; + +import test.Ice.location.Test._ServerManagerDisp; + + +public class ServerManagerI extends _ServerManagerDisp +{ + ServerManagerI(ServerLocatorRegistry registry, Ice.InitializationData initData, test.Util.Application app) + { + _registry = registry; + _communicators = new java.util.ArrayList<Ice.Communicator>(); + + _app = app; + _initData = initData; + + _initData.properties.setProperty("TestAdapter.AdapterId", "TestAdapter"); + _initData.properties.setProperty("TestAdapter.ReplicaGroupId", "ReplicatedAdapter"); + _initData.properties.setProperty("TestAdapter2.AdapterId", "TestAdapter2"); + } + + @Override + public void + startServer(Ice.Current current) + { + for(Ice.Communicator c : _communicators) + { + c.waitForShutdown(); + c.destroy(); + } + _communicators.clear(); + + // + // Simulate a server: create a new communicator and object + // adapter. The object adapter is started on a system allocated + // port. The configuration used here contains the Ice.Locator + // configuration variable. The new object adapter will register + // its endpoints with the locator and create references containing + // the adapter id instead of the endpoints. + // + Ice.Communicator serverCommunicator = _app.initialize(_initData); + _communicators.add(serverCommunicator); + + // + // 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"); + adapter.setLocator(Ice.LocatorPrxHelper.uncheckedCast(locator)); + adapter2.setLocator(Ice.LocatorPrxHelper.uncheckedCast(locator)); + + Ice.Object object = new TestI(adapter, adapter2, _registry); + _registry.addObject(adapter.add(object, serverCommunicator.stringToIdentity("test"))); + _registry.addObject(adapter.add(object, serverCommunicator.stringToIdentity("test2"))); + adapter.add(object, serverCommunicator.stringToIdentity("test3")); + + adapter.activate(); + adapter2.activate(); + } + + @Override + public void + shutdown(Ice.Current current) + { + for(Ice.Communicator c : _communicators) + { + c.destroy(); + } + current.adapter.getCommunicator().shutdown(); + } + + private ServerLocatorRegistry _registry; + private java.util.List<Ice.Communicator> _communicators; + private Ice.InitializationData _initData; + private test.Util.Application _app; + private int _nextPort = 12011; +} diff --git a/java/test/src/main/java/test/Ice/location/Test.ice b/java/test/src/main/java/test/Ice/location/Test.ice new file mode 100644 index 00000000000..f6d0dfd0a94 --- /dev/null +++ b/java/test/src/main/java/test/Ice/location/Test.ice @@ -0,0 +1,56 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/Locator.ice> + +[["java:package:test.Ice.location"]] +module Test +{ + +interface TestLocatorRegistry extends ::Ice::LocatorRegistry +{ + // + // Allow remote addition of objects to the locator registry. + // + void addObject(Object* obj); +}; + +interface TestLocator extends ::Ice::Locator +{ + // + // Returns the number of request on the locator interface. + // + idempotent int getRequestCount(); +}; + +interface ServerManager +{ + void startServer(); + void shutdown(); +}; + +interface Hello +{ + void sayHello(); +}; + +interface TestIntf +{ + void shutdown(); + + Hello* getHello(); + + Hello* getReplicatedHello(); + + void migrateHello(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/location/TestI.java b/java/test/src/main/java/test/Ice/location/TestI.java new file mode 100644 index 00000000000..de3c6213bd7 --- /dev/null +++ b/java/test/src/main/java/test/Ice/location/TestI.java @@ -0,0 +1,68 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.location; + +import test.Ice.location.Test.HelloPrx; +import test.Ice.location.Test.HelloPrxHelper; +import test.Ice.location.Test._TestIntfDisp; + + +public class TestI extends _TestIntfDisp +{ + TestI(Ice.ObjectAdapter adapter1, Ice.ObjectAdapter adapter2, ServerLocatorRegistry registry) + { + _adapter1 = adapter1; + _adapter2 = adapter2; + _registry = registry; + + _registry.addObject(_adapter1.add(new HelloI(), _adapter1.getCommunicator().stringToIdentity("hello"))); + } + + @Override + public void + shutdown(Ice.Current current) + { + _adapter1.getCommunicator().shutdown(); + } + + @Override + public HelloPrx + getHello(Ice.Current current) + { + return HelloPrxHelper.uncheckedCast(_adapter1.createIndirectProxy( + _adapter1.getCommunicator().stringToIdentity("hello"))); + } + + @Override + public HelloPrx + getReplicatedHello(Ice.Current current) + { + return HelloPrxHelper.uncheckedCast(_adapter1.createProxy(_adapter1.getCommunicator().stringToIdentity("hello"))); + } + + @Override + public void + migrateHello(Ice.Current current) + { + final Ice.Identity id = _adapter1.getCommunicator().stringToIdentity("hello"); + try + { + _registry.addObject(_adapter2.add(_adapter1.remove(id), id)); + } + catch(Ice.NotRegisteredException ex) + { + _registry.addObject(_adapter1.add(_adapter2.remove(id), id)); + } + } + + private ServerLocatorRegistry _registry; + private Ice.ObjectAdapter _adapter1; + private Ice.ObjectAdapter _adapter2; +} diff --git a/java/test/src/main/java/test/Ice/location/run.py b/java/test/src/main/java/test/Ice/location/run.py new file mode 100755 index 00000000000..d5fe04787c9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/location/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/metrics/AMDMetricsI.java b/java/test/src/main/java/test/Ice/metrics/AMDMetricsI.java new file mode 100644 index 00000000000..e557e728a4e --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/AMDMetricsI.java @@ -0,0 +1,84 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; +import test.Ice.metrics.AMD.Test.*; + +public final class AMDMetricsI extends _MetricsDisp +{ + public + AMDMetricsI() + { + } + + @Override + public void + op_async(AMD_Metrics_op cb, Ice.Current current) + { + cb.ice_response(); + } + + @Override + public void + fail_async(AMD_Metrics_fail cb, Ice.Current current) + { + current.con.close(true); + cb.ice_response(); + } + + @Override + public void + opWithUserException_async(AMD_Metrics_opWithUserException cb, Ice.Current current) + throws UserEx + { + cb.ice_exception(new UserEx()); + } + + @Override + public void + opWithRequestFailedException_async(AMD_Metrics_opWithRequestFailedException cb, Ice.Current current) + { + cb.ice_exception(new Ice.ObjectNotExistException()); + } + + @Override + public void + opWithLocalException_async(AMD_Metrics_opWithLocalException cb, Ice.Current current) + { + cb.ice_exception(new Ice.SyscallException()); + } + + @Override + public void + opWithUnknownException_async(AMD_Metrics_opWithUnknownException cb, Ice.Current current) + { + cb.ice_exception(new IllegalArgumentException()); + } + + @Override + public void + opByteS_async(AMD_Metrics_opByteS cb, byte[] bs, Ice.Current current) + { + cb.ice_response(); + } + + @Override + public Ice.ObjectPrx + getAdmin(Ice.Current current) + { + return current.adapter.getCommunicator().getAdmin(); + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/metrics/AMDServer.java b/java/test/src/main/java/test/Ice/metrics/AMDServer.java new file mode 100644 index 00000000000..dc559764811 --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/AMDServer.java @@ -0,0 +1,52 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +public class AMDServer extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new AMDMetricsI(), communicator.stringToIdentity("metrics")); + adapter.activate(); + + communicator.getProperties().setProperty("ControllerAdapter.Endpoints", "default -p 12011"); + Ice.ObjectAdapter controllerAdapter = communicator.createObjectAdapter("ControllerAdapter"); + controllerAdapter.add(new ControllerI(adapter), communicator.stringToIdentity("controller")); + controllerAdapter.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.retry"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("Ice.Admin.Endpoints", "tcp"); + initData.properties.setProperty("Ice.Admin.InstanceName", "server"); + initData.properties.setProperty("Ice.Warn.Connections", "0"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("Ice.MessageSizeMax", "50000"); + return initData; + } + + public static void main(String[] args) + { + AMDServer app = new AMDServer(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/metrics/AllTests.java b/java/test/src/main/java/test/Ice/metrics/AllTests.java new file mode 100644 index 00000000000..48d1fdb8a80 --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/AllTests.java @@ -0,0 +1,1263 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +import java.io.PrintWriter; +import java.util.Map; + +import test.Ice.metrics.Test.*; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static IceMX.ConnectionMetrics + getServerConnectionMetrics(IceMX.MetricsAdminPrx metrics, long expected) + { + try + { + IceMX.ConnectionMetrics s; + Ice.LongHolder timestamp = new Ice.LongHolder(); + s = (IceMX.ConnectionMetrics)metrics.getMetricsView("View", timestamp).get("Connection")[0]; + int nRetry = 30; + while(s.sentBytes != expected && nRetry-- > 0) + { + // On some platforms, it's necessary to wait a little before obtaining the server metrics + // to get an accurate sentBytes metric. The sentBytes metric is updated before the response + // to the operation is sent and getMetricsView can be dispatched before the metric is really + // updated. + try + { + Thread.sleep(100); + } + catch(InterruptedException ex) + { + } + s = (IceMX.ConnectionMetrics)metrics.getMetricsView("View", timestamp).get("Connection")[0]; + } + return s; + } + catch(IceMX.UnknownMetricsView ex) + { + assert(false); + return null; + } + } + + static class Callback extends Ice.Callback + { + public Callback() + { + _wait = true; + } + + @Override + synchronized public void completed(Ice.AsyncResult result) + { + _wait = false; + notify(); + } + + synchronized public void waitForResponse() + { + while(_wait) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + _wait = true; + } + + private boolean _wait; + }; + + static private Map<String, String> + getClientProps(Ice.PropertiesAdminPrx p, Map<String, String> orig, String m) + { + Map<String, String> props = p.getPropertiesForPrefix("IceMX.Metrics"); + for(Map.Entry<String, String> e : props.entrySet()) + { + e.setValue(""); + } + for(Map.Entry<String, String> e : orig.entrySet()) + { + props.put(e.getKey(), e.getValue()); + } + String map = ""; + if(!m.isEmpty()) + { + map += "Map." + m + '.'; + } + props.put("IceMX.Metrics.View." + map + "Reject.parent", "Ice\\.Admin"); + props.put("IceMX.Metrics.View." + map + "Accept.endpointPort", "12010"); + props.put("IceMX.Metrics.View." + map + "Reject.identity", ".*/admin|controller"); + return props; + } + + static private Map<String, String> + getServerProps(Ice.PropertiesAdminPrx p, Map<String, String> orig , String m) + { + Map<String, String> props = p.getPropertiesForPrefix("IceMX.Metrics"); + for(Map.Entry<String, String> e : props.entrySet()) + { + e.setValue(""); + } + for(Map.Entry<String, String> e : orig.entrySet()) + { + props.put(e.getKey(), e.getValue()); + } + String map = ""; + if(!m.isEmpty()) + { + map += "Map." + m + '.'; + } + props.put("IceMX.Metrics.View." + map + "Reject.parent", "Ice\\.Admin|Controller"); + props.put("IceMX.Metrics.View." + map + "Accept.endpointPort", "12010"); + return props; + } + + static class UpdateCallbackI implements Ice.PropertiesAdminUpdateCallback + { + public UpdateCallbackI(Ice.PropertiesAdminPrx serverProps) + { + _updated = false; + _serverProps = serverProps; + } + + public void + waitForUpdate() + { + synchronized(this) + { + while(!_updated) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + } + // Ensure that the previous updates were committed, the setProperties call returns before + // notifying the callbacks so to ensure all the update callbacks have be notified we call + // a second time, this will block until all the notifications from the first update have + // completed. + _serverProps.setProperties(new java.util.HashMap<String, String>()); + synchronized(this) + { + _updated = false; + } + } + + @Override + public synchronized void + updated(Map<String, String> dict) + { + _updated = true; + notify(); + } + + private boolean _updated; + private Ice.PropertiesAdminPrx _serverProps; + }; + + static void + waitForCurrent(IceMX.MetricsAdminPrx metrics, String viewName, String map, int value) + throws IceMX.UnknownMetricsView + { + while(true) + { + Ice.LongHolder timestamp = new Ice.LongHolder(); + Map<String, IceMX.Metrics[]> view = metrics.getMetricsView(viewName, timestamp); + test(view.containsKey(map)); + boolean ok = true; + for(IceMX.Metrics m : view.get(map)) + { + if(m.current != value) + { + ok = false; + break; + } + } + if(ok) + { + break; + } + try + { + Thread.sleep(50); + } + catch(InterruptedException ex) + { + } + } + } + + static void + testAttribute(IceMX.MetricsAdminPrx metrics, + Ice.PropertiesAdminPrx props, + UpdateCallbackI update, + String map, + String attr, + String value, + Runnable func, + PrintWriter out) + throws IceMX.UnknownMetricsView + { + Map<String, String> dict = new java.util.HashMap<String, String>(); + dict.put("IceMX.Metrics.View.Map." + map + ".GroupBy", attr); + if(props.ice_getIdentity().category.equals("client")) + { + props.setProperties(getClientProps(props, dict, map)); + update.waitForUpdate(); + } + else + { + props.setProperties(getServerProps(props, dict, map)); + props.setProperties(new java.util.HashMap<String, String>()); + } + + func.run(); + Ice.LongHolder timestamp = new Ice.LongHolder(); + Map<String, IceMX.Metrics[]> view = metrics.getMetricsView("View", timestamp); + if(!view.containsKey(map) || view.get(map).length == 0) + { + if(!value.isEmpty()) + { + out.println("no map `" + map + "' for group by = `" + attr + "'"); + test(false); + } + } + else if(!view.get(map)[0].id.equals(value)) + { + out.println("invalid attribute value: " + attr + " = " + value + " got " + view.get(map)[0].id); + test(false); + } + + dict.clear(); + if(props.ice_getIdentity().category.equals("client")) + { + props.setProperties(getClientProps(props, dict, map)); + update.waitForUpdate(); + } + else + { + props.setProperties(getServerProps(props, dict, map)); + props.setProperties(new java.util.HashMap<String, String>()); + } + } + + static class Void implements Runnable + { + @Override + public void run() + { + } + }; + + static class Connect implements Runnable + { + public Connect(Ice.ObjectPrx proxy) + { + this.proxy = proxy; + } + + @Override + public void run() + { + if(proxy.ice_getCachedConnection() != null) + { + proxy.ice_getCachedConnection().close(false); + } + + try + { + proxy.ice_ping(); + } + catch(Ice.LocalException ex) + { + } + + if(proxy.ice_getCachedConnection() != null) + { + proxy.ice_getCachedConnection().close(false); + } + } + + final private Ice.ObjectPrx proxy; + }; + + static class InvokeOp implements Runnable + { + public InvokeOp(MetricsPrx proxy) + { + this.proxy = proxy; + } + + @Override + public void run() + { + Map<String, String> ctx = new java.util.HashMap<String, String>(); + ctx.put("entry1", "test"); + ctx.put("entry2", ""); + proxy.op(ctx); + } + + final private MetricsPrx proxy; + }; + + static void + testAttribute(IceMX.MetricsAdminPrx metrics, + Ice.PropertiesAdminPrx props, + UpdateCallbackI update, + String map, + String attr, + String value, + PrintWriter out) + throws IceMX.UnknownMetricsView + { + testAttribute(metrics, props, update, map, attr, value, new Void(), out); + } + + static void + updateProps(Ice.PropertiesAdminPrx cprops, + Ice.PropertiesAdminPrx sprops, + UpdateCallbackI callback, + Map<String, String> props, + String map) + { + if(sprops.ice_getConnection() != null) + { + cprops.setProperties(getClientProps(cprops, props, map)); + sprops.setProperties(getServerProps(sprops, props, map)); + } + else + { + Map<String, String> clientProps = getClientProps(cprops, props, map); + Map<String, String> serverProps = getServerProps(sprops, props, map); + serverProps.putAll(clientProps); + cprops.setProperties(serverProps); + } + callback.waitForUpdate(); + } + + static void + clearView(Ice.PropertiesAdminPrx cprops, Ice.PropertiesAdminPrx sprops, UpdateCallbackI callback) + { + Map<String, String> dict; + + dict = cprops.getPropertiesForPrefix("IceMX.Metrics"); + dict.put("IceMX.Metrics.View.Disabled", "1"); + cprops.setProperties(dict); + + dict = sprops.getPropertiesForPrefix("IceMX.Metrics"); + dict.put("IceMX.Metrics.View.Disabled", "1"); + sprops.setProperties(dict); + + callback.waitForUpdate(); + + dict = cprops.getPropertiesForPrefix("IceMX.Metrics"); + dict.put("IceMX.Metrics.View.Disabled", ""); + cprops.setProperties(dict); + + dict = sprops.getPropertiesForPrefix("IceMX.Metrics"); + dict.put("IceMX.Metrics.View.Disabled", ""); + sprops.setProperties(dict); + + callback.waitForUpdate(); + } + + static void + checkFailure(IceMX.MetricsAdminPrx m, String map, String id, String failure, int count, PrintWriter out) + throws IceMX.UnknownMetricsView + { + IceMX.MetricsFailures f = m.getMetricsFailures("View", map, id); + if(!f.failures.containsKey(failure)) + { + out.println("couldn't find failure `" + failure + "' for `" + id + "'"); + test(false); + } + if(count > 0 && f.failures.get(failure) != count) + { + out.print("count for failure `" + failure + "' of `" + id + "' is different from expected: "); + out.println(count + " != " + f.failures.get(failure)); + test(false); + } + } + + static Map<String, IceMX.Metrics> + toMap(IceMX.Metrics[] mmap) + { + Map<String, IceMX.Metrics> m = new java.util.HashMap<String, IceMX.Metrics>(); + for(IceMX.Metrics e : mmap) + { + m.put(e.id, e); + } + return m; + } + + static MetricsPrx + allTests(Ice.Communicator communicator, PrintWriter out, CommunicatorObserverI obsv) + throws IceMX.UnknownMetricsView + { + MetricsPrx metrics = MetricsPrxHelper.checkedCast(communicator.stringToProxy("metrics:default -p 12010")); + boolean collocated = metrics.ice_getConnection() == null; + + int threadCount = 4; + if(collocated && communicator.getProperties().getPropertyAsInt("Ice.ThreadInterruptSafe") > 0) + { + threadCount = 6; + } + + out.print("testing metrics admin facet checkedCast... "); + out.flush(); + Ice.ObjectPrx admin = communicator.getAdmin(); + Ice.PropertiesAdminPrx clientProps = Ice.PropertiesAdminPrxHelper.checkedCast(admin, "Properties"); + IceMX.MetricsAdminPrx clientMetrics = IceMX.MetricsAdminPrxHelper.checkedCast(admin, "Metrics"); + test(clientProps != null && clientMetrics != null); + + admin = metrics.getAdmin(); + Ice.PropertiesAdminPrx serverProps = Ice.PropertiesAdminPrxHelper.checkedCast(admin, "Properties"); + IceMX.MetricsAdminPrx serverMetrics = IceMX.MetricsAdminPrxHelper.checkedCast(admin, "Metrics"); + test(serverProps != null && serverMetrics != null); + + UpdateCallbackI update = new UpdateCallbackI(serverProps); + ((Ice.NativePropertiesAdmin)communicator.findAdminFacet("Properties")).addUpdateCallback(update); + + out.println("ok"); + + Map<String, String> props = new java.util.HashMap<String, String>(); + + out.print("testing group by none..."); + out.flush(); + + props.put("IceMX.Metrics.View.GroupBy", "none"); + updateProps(clientProps, serverProps, update, props, ""); + Ice.LongHolder timestamp = new Ice.LongHolder(); + Map<String, IceMX.Metrics[]> view = clientMetrics.getMetricsView("View", timestamp); + if(!collocated) + { + test(view.get("Connection").length == 1 && view.get("Connection")[0].current == 1 && + view.get("Connection")[0].total == 1); + } + test(view.get("Thread").length == 1 && view.get("Thread")[0].current == threadCount && + view.get("Thread")[0].total == threadCount); + out.println("ok"); + + out.print("testing group by id..."); + out.flush(); + + props.put("IceMX.Metrics.View.GroupBy", "id"); + updateProps(clientProps, serverProps, update, props, ""); + + metrics.ice_ping(); + metrics.ice_ping(); + metrics.ice_connectionId("Con1").ice_ping(); + metrics.ice_connectionId("Con1").ice_ping(); + metrics.ice_connectionId("Con1").ice_ping(); + + view = clientMetrics.getMetricsView("View", timestamp); + test(view.get("Thread").length == threadCount); + if(!collocated) + { + test(view.get("Connection").length == 2); + } + test(view.get("Invocation").length == 1); + + IceMX.InvocationMetrics invoke = (IceMX.InvocationMetrics)view.get("Invocation")[0]; + test(invoke.id.indexOf("[ice_ping]") > 0 && invoke.current == 0 && invoke.total == 5); + if(!collocated) + { + test(invoke.remotes.length == 2); + test(invoke.remotes[0].total >= 2 && invoke.remotes[1].total >= 2); + test((invoke.remotes[0].total + invoke.remotes[1].total) == 5); + } + else + { + test(invoke.collocated.length == 1); + test(invoke.collocated[0].total == 5); + } + view = serverMetrics.getMetricsView("View", timestamp); + if(!collocated) + { + test(view.get("Thread").length > 3); + test(view.get("Connection").length == 2); + } + test(view.get("Dispatch").length == 1); + test(view.get("Dispatch")[0].current <= 1 && view.get("Dispatch")[0].total == 5); + test(view.get("Dispatch")[0].id.indexOf("[ice_ping]") > 0); + + if(!collocated) + { + metrics.ice_getConnection().close(false); + metrics.ice_connectionId("Con1").ice_getConnection().close(false); + + waitForCurrent(clientMetrics, "View", "Connection", 0); + waitForCurrent(serverMetrics, "View", "Connection", 0); + } + clearView(clientProps, serverProps, update); + + out.println("ok"); + + Map<String, IceMX.Metrics> map; + + if(!collocated) + { + out.print("testing connection metrics... "); + out.flush(); + + props.put("IceMX.Metrics.View.Map.Connection.GroupBy", "none"); + updateProps(clientProps, serverProps, update, props, "Connection"); + + test(clientMetrics.getMetricsView("View", timestamp).get("Connection").length == 0); + test(serverMetrics.getMetricsView("View", timestamp).get("Connection").length == 0); + + metrics.ice_ping(); + + IceMX.ConnectionMetrics cm1, sm1, cm2, sm2; + cm1 = (IceMX.ConnectionMetrics)clientMetrics.getMetricsView("View", timestamp).get("Connection")[0]; + sm1 = getServerConnectionMetrics(serverMetrics, 25); + test(cm1.total == 1 && sm1.total == 1); + + metrics.ice_ping(); + + cm2 = (IceMX.ConnectionMetrics)clientMetrics.getMetricsView("View", timestamp).get("Connection")[0]; + sm2 = getServerConnectionMetrics(serverMetrics, 50); + + test(cm2.sentBytes - cm1.sentBytes == 45); // 45 for ice_ping request + test(cm2.receivedBytes - cm1.receivedBytes == 25); // 25 bytes for ice_ping response + test(sm2.receivedBytes - sm1.receivedBytes == 45); + test(sm2.sentBytes - sm1.sentBytes == 25); + + cm1 = cm2; + sm1 = sm2; + + byte[] bs = new byte[0]; + metrics.opByteS(bs); + + cm2 = (IceMX.ConnectionMetrics)clientMetrics.getMetricsView("View", timestamp).get("Connection")[0]; + sm2 = getServerConnectionMetrics(serverMetrics, sm1.sentBytes + cm2.receivedBytes - cm1.receivedBytes); + long requestSz = cm2.sentBytes - cm1.sentBytes; + long replySz = cm2.receivedBytes - cm1.receivedBytes; + + cm1 = cm2; + sm1 = sm2; + + bs = new byte[456]; + metrics.opByteS(bs); + + cm2 = (IceMX.ConnectionMetrics)clientMetrics.getMetricsView("View", timestamp).get("Connection")[0]; + sm2 = getServerConnectionMetrics(serverMetrics, sm1.sentBytes + replySz); + + test(cm2.sentBytes - cm1.sentBytes == requestSz + bs.length + 4); // 4 is for the seq variable size + test(cm2.receivedBytes - cm1.receivedBytes == replySz); + test(sm2.receivedBytes - sm1.receivedBytes == requestSz + bs.length + 4); + test(sm2.sentBytes - sm1.sentBytes == replySz); + + cm1 = cm2; + sm1 = sm2; + + bs = new byte[1024 * 1024 * 10]; // Try with large amount of data which should be sent in several chunks + metrics.opByteS(bs); + + cm2 = (IceMX.ConnectionMetrics)clientMetrics.getMetricsView("View", timestamp).get("Connection")[0]; + sm2 = getServerConnectionMetrics(serverMetrics, sm1.sentBytes + replySz); + + test((cm2.sentBytes - cm1.sentBytes) == (requestSz + bs.length + 4)); // 4 is for the seq variable size + test((cm2.receivedBytes - cm1.receivedBytes) == replySz); + test((sm2.receivedBytes - sm1.receivedBytes) == (requestSz + bs.length + 4)); + test((sm2.sentBytes - sm1.sentBytes) == replySz); + + props.put("IceMX.Metrics.View.Map.Connection.GroupBy", "state"); + updateProps(clientProps, serverProps, update, props, "Connection"); + + map = toMap(serverMetrics.getMetricsView("View", timestamp).get("Connection")); + + test(map.get("active").current == 1); + + ControllerPrx controller = ControllerPrxHelper.checkedCast( + communicator.stringToProxy("controller:default -p 12011")); + controller.hold(); + + map = toMap(clientMetrics.getMetricsView("View", timestamp).get("Connection")); + test(map.get("active").current == 1); + map = toMap(serverMetrics.getMetricsView("View", timestamp).get("Connection")); + test(map.get("holding").current == 1); + + metrics.ice_getConnection().close(false); + + map = toMap(clientMetrics.getMetricsView("View", timestamp).get("Connection")); + test(map.get("closing").current == 1); + map = toMap(serverMetrics.getMetricsView("View", timestamp).get("Connection")); + test(map.get("holding").current == 1); + + controller.resume(); + + map = toMap(serverMetrics.getMetricsView("View", timestamp).get("Connection")); + test(map.get("holding").current == 0); + + props.put("IceMX.Metrics.View.Map.Connection.GroupBy", "none"); + updateProps(clientProps, serverProps, update, props, "Connection"); + + metrics.ice_getConnection().close(false); + + metrics.ice_timeout(500).ice_ping(); + controller.hold(); + try + { + ((MetricsPrx)metrics.ice_timeout(500)).opByteS(new byte[10000000]); + test(false); + } + catch(Ice.TimeoutException ex) + { + } + controller.resume(); + + cm1 = (IceMX.ConnectionMetrics)clientMetrics.getMetricsView("View", timestamp).get("Connection")[0]; + while(true) + { + sm1 = (IceMX.ConnectionMetrics)serverMetrics.getMetricsView("View", timestamp).get("Connection")[0]; + if(sm1.failures >= 2) + { + break; + } + try + { + Thread.sleep(10); + } + catch(InterruptedException ex) + { + } + } + test(cm1.failures == 2 && sm1.failures >= 2); + + checkFailure(clientMetrics, "Connection", cm1.id, "Ice::TimeoutException", 1, out); + checkFailure(clientMetrics, "Connection", cm1.id, "Ice::ConnectTimeoutException", 1, out); + checkFailure(serverMetrics, "Connection", sm1.id, "Ice::ConnectionLostException", 0, out); + + MetricsPrx m = (MetricsPrx)metrics.ice_timeout(500).ice_connectionId("Con1"); + m.ice_ping(); + + testAttribute(clientMetrics, clientProps, update, "Connection", "parent", "Communicator", out); + //testAttribute(clientMetrics, clientProps, update, "Connection", "id", ""); + testAttribute(clientMetrics, clientProps, update, "Connection", "endpoint", + "tcp -h 127.0.0.1 -p 12010 -t 500", out); + + testAttribute(clientMetrics, clientProps, update, "Connection", "endpointType", "1", out); + testAttribute(clientMetrics, clientProps, update, "Connection", "endpointIsDatagram", "false", out); + testAttribute(clientMetrics, clientProps, update, "Connection", "endpointIsSecure", "false", out); + testAttribute(clientMetrics, clientProps, update, "Connection", "endpointTimeout", "500", out); + testAttribute(clientMetrics, clientProps, update, "Connection", "endpointCompress", "false", out); + testAttribute(clientMetrics, clientProps, update, "Connection", "endpointHost", "127.0.0.1", out); + testAttribute(clientMetrics, clientProps, update, "Connection", "endpointPort", "12010", out); + + testAttribute(clientMetrics, clientProps, update, "Connection", "incoming", "false", out); + testAttribute(clientMetrics, clientProps, update, "Connection", "adapterName", "", out); + testAttribute(clientMetrics, clientProps, update, "Connection", "connectionId", "Con1", out); + testAttribute(clientMetrics, clientProps, update, "Connection", "localHost", "127.0.0.1", out); + //testAttribute(clientMetrics, clientProps, update, "Connection", "localPort", "", out); + testAttribute(clientMetrics, clientProps, update, "Connection", "remoteHost", "127.0.0.1", out); + testAttribute(clientMetrics, clientProps, update, "Connection", "remotePort", "12010", out); + testAttribute(clientMetrics, clientProps, update, "Connection", "mcastHost", "", out); + testAttribute(clientMetrics, clientProps, update, "Connection", "mcastPort", "", out); + + m.ice_getConnection().close(false); + + waitForCurrent(clientMetrics, "View", "Connection", 0); + waitForCurrent(serverMetrics, "View", "Connection", 0); + + out.println("ok"); + + out.print("testing connection establishment metrics... "); + out.flush(); + + props.put("IceMX.Metrics.View.Map.ConnectionEstablishment.GroupBy", "id"); + updateProps(clientProps, serverProps, update, props, "ConnectionEstablishment"); + test(clientMetrics.getMetricsView("View", timestamp).get("ConnectionEstablishment").length == 0); + + metrics.ice_ping(); + + test(clientMetrics.getMetricsView("View", timestamp).get("ConnectionEstablishment").length == 1); + IceMX.Metrics m1 = clientMetrics.getMetricsView("View", timestamp).get("ConnectionEstablishment")[0]; + test(m1.current == 0 && m1.total == 1 && m1.id.equals("127.0.0.1:12010")); + + metrics.ice_getConnection().close(false); + controller.hold(); + try + { + communicator.stringToProxy("test:tcp -p 12010 -h 127.0.0.1").ice_timeout(10).ice_ping(); + test(false); + } + catch(Ice.ConnectTimeoutException ex) + { + } + catch(Ice.LocalException ex) + { + test(false); + } + controller.resume(); + test(clientMetrics.getMetricsView("View", timestamp).get("ConnectionEstablishment").length == 1); + m1 = clientMetrics.getMetricsView("View", timestamp).get("ConnectionEstablishment")[0]; + test(m1.id.equals("127.0.0.1:12010") && m1.total == 3 && m1.failures == 2); + + checkFailure(clientMetrics, "ConnectionEstablishment", m1.id, "Ice::ConnectTimeoutException", 2, out); + + Connect c = new Connect(metrics); + testAttribute(clientMetrics, clientProps, update, "ConnectionEstablishment", "parent", "Communicator", c, + out); + testAttribute(clientMetrics, clientProps, update, "ConnectionEstablishment", "id", "127.0.0.1:12010", c, + out); + testAttribute(clientMetrics, clientProps, update, "ConnectionEstablishment", "endpoint", + "tcp -h 127.0.0.1 -p 12010 -t 60000", c, out); + + testAttribute(clientMetrics, clientProps, update, "ConnectionEstablishment", "endpointType", "1", c, out); + testAttribute(clientMetrics, clientProps, update, "ConnectionEstablishment", "endpointIsDatagram", "false", + c, out); + testAttribute(clientMetrics, clientProps, update, "ConnectionEstablishment", "endpointIsSecure", "false", c, + out); + testAttribute(clientMetrics, clientProps, update, "ConnectionEstablishment", "endpointTimeout", "60000", c, + out); + testAttribute(clientMetrics, clientProps, update, "ConnectionEstablishment", "endpointCompress", "false", c, + out); + testAttribute(clientMetrics, clientProps, update, "ConnectionEstablishment", "endpointHost", "127.0.0.1", c, + out); + testAttribute(clientMetrics, clientProps, update, "ConnectionEstablishment", "endpointPort", "12010", c, + out); + + out.println("ok"); + + out.print("testing endpoint lookup metrics... "); + out.flush(); + + props.put("IceMX.Metrics.View.Map.ConnectionEstablishment.GroupBy", "id"); + updateProps(clientProps, serverProps, update, props, "EndpointLookup"); + test(clientMetrics.getMetricsView("View", timestamp).get("EndpointLookup").length == 0); + + Ice.ObjectPrx prx = communicator.stringToProxy("metrics:default -p 12010 -h localhost -t infinite"); + prx.ice_ping(); + + test(clientMetrics.getMetricsView("View", timestamp).get("EndpointLookup").length == 1); + m1 = clientMetrics.getMetricsView("View", timestamp).get("EndpointLookup")[0]; + test(m1.current <= 1 && m1.total == 1 && m1.id.equals("tcp -h localhost -p 12010 -t infinite")); + + prx.ice_getConnection().close(false); + + boolean dnsException = false; + try + { + communicator.stringToProxy("test:tcp -t 500 -p 12010 -h unknownfoo.zeroc.com").ice_ping(); + test(false); + } + catch(Ice.DNSException ex) + { + dnsException = true; + } + catch(Ice.LocalException ex) + { + // Some DNS servers don't fail on unknown DNS names. + } + test(clientMetrics.getMetricsView("View", timestamp).get("EndpointLookup").length == 2); + m1 = clientMetrics.getMetricsView("View", timestamp).get("EndpointLookup")[0]; + if(!m1.id.equals("tcp -h unknownfoo.zeroc.com -p 12010 -t 500")) + { + m1 = clientMetrics.getMetricsView("View", timestamp).get("EndpointLookup")[1]; + } + test(m1.id.equals("tcp -h unknownfoo.zeroc.com -p 12010 -t 500") && m1.total == 2 && + (!dnsException || m1.failures == 2)); + if(dnsException) + { + checkFailure(clientMetrics, "EndpointLookup", m1.id, "Ice::DNSException", 2, out); + } + + c = new Connect(prx); + + testAttribute(clientMetrics, clientProps, update, "EndpointLookup", "parent", "Communicator", c, out); + testAttribute(clientMetrics, clientProps, update, "EndpointLookup", "id", + "tcp -h localhost -p 12010 -t infinite", c, out); + testAttribute(clientMetrics, clientProps, update, "EndpointLookup", "endpoint", + "tcp -h localhost -p 12010 -t infinite", c, out); + + testAttribute(clientMetrics, clientProps, update, "EndpointLookup", "endpointType", "1", c, out); + testAttribute(clientMetrics, clientProps, update, "EndpointLookup", "endpointIsDatagram", "false", c, out); + testAttribute(clientMetrics, clientProps, update, "EndpointLookup", "endpointIsSecure", "false", c, out); + testAttribute(clientMetrics, clientProps, update, "EndpointLookup", "endpointTimeout", "-1", c, out); + testAttribute(clientMetrics, clientProps, update, "EndpointLookup", "endpointCompress", "false", c, out); + testAttribute(clientMetrics, clientProps, update, "EndpointLookup", "endpointHost", "localhost", c, out); + testAttribute(clientMetrics, clientProps, update, "EndpointLookup", "endpointPort", "12010", c, out); + + out.println("ok"); + } + + out.print("testing dispatch metrics... "); + out.flush(); + + props.put("IceMX.Metrics.View.Map.Dispatch.GroupBy", "operation"); + updateProps(clientProps, serverProps, update, props, "Dispatch"); + test(serverMetrics.getMetricsView("View", timestamp).get("Dispatch").length == 0); + + metrics.op(); + try + { + metrics.opWithUserException(); + test(false); + } + catch(UserEx ex) + { + } + try + { + metrics.opWithRequestFailedException(); + test(false); + } + catch(Ice.RequestFailedException ex) + { + } + try + { + metrics.opWithLocalException(); + test(false); + } + catch(Ice.LocalException ex) + { + } + try + { + metrics.opWithUnknownException(); + test(false); + } + catch(Ice.UnknownException ex) + { + } + if(!collocated) + { + try + { + metrics.fail(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + } + } + map = toMap(serverMetrics.getMetricsView("View", timestamp).get("Dispatch")); + test(map.size() == (!collocated ? 6 : 5)); + + IceMX.DispatchMetrics dm1 = (IceMX.DispatchMetrics)map.get("op"); + test(dm1.current <= 1 && dm1.total == 1 && dm1.failures == 0 && dm1.userException == 0); + test(dm1.size == 21 && dm1.replySize == 7); + + dm1 = (IceMX.DispatchMetrics)map.get("opWithUserException"); + test(dm1.current <= 1 &dm1.total == 1 && dm1.failures == 0 && dm1.userException == 1); + test(dm1.size == 38 && dm1.replySize == 23); + + dm1 = (IceMX.DispatchMetrics)map.get("opWithLocalException"); + test(dm1.current <= 1 && dm1.total == 1 && dm1.failures == 1 && dm1.userException == 0); + checkFailure(serverMetrics, "Dispatch", dm1.id, "Ice::SyscallException", 1, out); + test(dm1.size == 39 && dm1.replySize > 7); // Reply contains the exception stack depending on the OS. + + dm1 = (IceMX.DispatchMetrics)map.get("opWithRequestFailedException"); + test(dm1.current <= 1 && dm1.total == 1 && dm1.failures == 1 && dm1.userException == 0); + checkFailure(serverMetrics, "Dispatch", dm1.id, "Ice::ObjectNotExistException", 1, out); + test(dm1.size == 47 && dm1.replySize == 40); + + dm1 = (IceMX.DispatchMetrics)map.get("opWithUnknownException"); + test(dm1.current <= 1 && dm1.total == 1 && dm1.failures == 1 && dm1.userException == 0); + checkFailure(serverMetrics, "Dispatch", dm1.id, "java.lang.IllegalArgumentException", 1, out); + test(dm1.size == 41 && dm1.replySize > 7); // Reply contains the exception stack depending on the OS. + + InvokeOp op = new InvokeOp(metrics); + + testAttribute(serverMetrics, serverProps, update, "Dispatch", "parent", "TestAdapter", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "id", "metrics [op]", op, out); + if(!collocated) + { + testAttribute(serverMetrics, serverProps, update, "Dispatch", "endpoint", + "tcp -h 127.0.0.1 -p 12010 -t 60000", op, out); + //testAttribute(serverMetrics, serverProps, update, "Dispatch", "connection", "", op); + + testAttribute(serverMetrics, serverProps, update, "Dispatch", "endpointType", "1", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "endpointIsDatagram", "false", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "endpointIsSecure", "false", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "endpointTimeout", "60000", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "endpointCompress", "false", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "endpointHost", "127.0.0.1", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "endpointPort", "12010", op, out); + + testAttribute(serverMetrics, serverProps, update, "Dispatch", "incoming", "true", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "adapterName", "TestAdapter", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "connectionId", "", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "localHost", "127.0.0.1", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "localPort", "12010", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "remoteHost", "127.0.0.1", op, out); + //testAttribute(serverMetrics, serverProps, update, "Dispatch", "remotePort", "12010", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "mcastHost", "", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "mcastPort", "", op, out); + } + + testAttribute(serverMetrics, serverProps, update, "Dispatch", "operation", "op", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "identity", "metrics", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "facet", "", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "mode", "twoway", op, out); + + testAttribute(serverMetrics, serverProps, update, "Dispatch", "context.entry1", "test", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "context.entry2", "", op, out); + testAttribute(serverMetrics, serverProps, update, "Dispatch", "context.entry3", "", op, out); + + out.println("ok"); + + out.print("testing invocation metrics... "); + out.flush(); + + props.put("IceMX.Metrics.View.Map.Invocation.GroupBy", "operation"); + props.put("IceMX.Metrics.View.Map.Invocation.Map.Remote.GroupBy", "localPort"); + props.put("IceMX.Metrics.View.Map.Invocation.Map.Collocated.GroupBy", "id"); + updateProps(clientProps, serverProps, update, props, "Invocation"); + test(serverMetrics.getMetricsView("View", timestamp).get("Invocation").length == 0); + + Callback cb = new Callback(); + + // + // Twoway tests + // + metrics.op(); + metrics.end_op(metrics.begin_op()); + metrics.begin_op(cb); + cb.waitForResponse(); + + try + { + metrics.opWithUserException(); + test(false); + } + catch(UserEx ex) + { + } + try + { + metrics.end_opWithUserException(metrics.begin_opWithUserException()); + test(false); + } + catch(UserEx ex) + { + } + metrics.begin_opWithUserException(cb); + cb.waitForResponse(); + + try + { + metrics.opWithRequestFailedException(); + test(false); + } + catch(Ice.RequestFailedException ex) + { + } + try + { + metrics.end_opWithRequestFailedException(metrics.begin_opWithRequestFailedException()); + test(false); + } + catch(Ice.RequestFailedException ex) + { + } + metrics.begin_opWithRequestFailedException(cb); + cb.waitForResponse(); + + try + { + metrics.opWithLocalException(); + test(false); + } + catch(Ice.LocalException ex) + { + } + try + { + metrics.end_opWithLocalException(metrics.begin_opWithLocalException()); + test(false); + } + catch(Ice.LocalException ex) + { + } + metrics.begin_opWithLocalException(cb); + cb.waitForResponse(); + + try + { + metrics.opWithUnknownException(); + test(false); + } + catch(Ice.UnknownException ex) + { + } + try + { + metrics.end_opWithUnknownException(metrics.begin_opWithUnknownException()); + test(false); + } + catch(Ice.UnknownException ex) + { + } + metrics.begin_opWithUnknownException(cb); + cb.waitForResponse(); + + if(!collocated) + { + try + { + metrics.fail(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + } + try + { + metrics.end_fail(metrics.begin_fail()); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + } + metrics.begin_fail(cb); + cb.waitForResponse(); + } + + map = toMap(clientMetrics.getMetricsView("View", timestamp).get("Invocation")); + test(map.size() == (!collocated ? 6 : 5)); + + IceMX.InvocationMetrics im1; + IceMX.ChildInvocationMetrics rim1; + im1 = (IceMX.InvocationMetrics)map.get("op"); + test(im1.current <= 1 && im1.total == 3 && im1.failures == 0 && im1.retry == 0); + test(!collocated ? im1.remotes.length == 1 : im1.collocated.length == 1); + rim1 = (IceMX.ChildInvocationMetrics)(!collocated ? im1.remotes[0] : im1.collocated[0]); + test(rim1.current == 0 && rim1.total == 3 && rim1.failures == 0); + test(rim1.size == 63 && rim1.replySize == 21); + + im1 = (IceMX.InvocationMetrics)map.get("opWithUserException"); + test(im1.current == 0 && im1.total == 3 && im1.failures == 0 && im1.retry == 0); + test(!collocated ? im1.remotes.length == 1 : im1.collocated.length == 1); + rim1 = (IceMX.ChildInvocationMetrics)(!collocated ? im1.remotes[0] : im1.collocated[0]); + test(rim1.current == 0 && rim1.total == 3 && rim1.failures == 0); + test(rim1.size == 114 && rim1.replySize == 69); + test(im1.userException == 3); + + im1 = (IceMX.InvocationMetrics)map.get("opWithLocalException"); + test(im1.current <= 1 && im1.total == 3 && im1.failures == 3 && im1.retry == 0); + test(!collocated ? im1.remotes.length == 1 : im1.collocated.length == 1); + rim1 = (IceMX.ChildInvocationMetrics)(!collocated ? im1.remotes[0] : im1.collocated[0]); + test(rim1.current == 0 && rim1.total == 3 && rim1.failures == 0); + test(rim1.size == 117 && rim1.replySize > 7); + checkFailure(clientMetrics, "Invocation", im1.id, "Ice::UnknownLocalException", 3, out); + + im1 = (IceMX.InvocationMetrics)map.get("opWithRequestFailedException"); + test(im1.current <= 1 && im1.total == 3 && im1.failures == 3 && im1.retry == 0); + test(!collocated ? im1.remotes.length == 1 : im1.collocated.length == 1); + rim1 = (IceMX.ChildInvocationMetrics)(!collocated ? im1.remotes[0] : im1.collocated[0]); + test(rim1.current == 0 && rim1.total == 3 && rim1.failures == 0); + test(rim1.size == 141 && rim1.replySize == 120); + checkFailure(clientMetrics, "Invocation", im1.id, "Ice::ObjectNotExistException", 3, out); + + im1 = (IceMX.InvocationMetrics)map.get("opWithUnknownException"); + test(im1.current <= 1 && im1.total == 3 && im1.failures == 3 && im1.retry == 0); + test(!collocated ? im1.remotes.length == 1 : im1.collocated.length == 1); + rim1 = (IceMX.ChildInvocationMetrics)(!collocated ? im1.remotes[0] : im1.collocated[0]); + test(rim1.current == 0 && rim1.total == 3 && rim1.failures == 0); + test(rim1.size == 123 && rim1.replySize > 7); + checkFailure(clientMetrics, "Invocation", im1.id, "Ice::UnknownException", 3, out); + + if(!collocated) + { + im1 = (IceMX.InvocationMetrics)map.get("fail"); + test(im1.current <= 1 && im1.total == 3 && im1.failures == 3 && im1.retry == 3 && im1.remotes.length == 6); + test(im1.remotes[0].current == 0 && im1.remotes[0].total == 1 && im1.remotes[0].failures == 1); + test(im1.remotes[1].current == 0 && im1.remotes[1].total == 1 && im1.remotes[1].failures == 1); + test(im1.remotes[2].current == 0 && im1.remotes[2].total == 1 && im1.remotes[2].failures == 1); + test(im1.remotes[3].current == 0 && im1.remotes[3].total == 1 && im1.remotes[3].failures == 1); + test(im1.remotes[4].current == 0 && im1.remotes[4].total == 1 && im1.remotes[4].failures == 1); + test(im1.remotes[5].current == 0 && im1.remotes[5].total == 1 && im1.remotes[5].failures == 1); + checkFailure(clientMetrics, "Invocation", im1.id, "Ice::ConnectionLostException", 3, out); + } + + testAttribute(clientMetrics, clientProps, update, "Invocation", "parent", "Communicator", op, out); + testAttribute(clientMetrics, clientProps, update, "Invocation", "id", "metrics -t -e 1.1 [op]", op, out); + + testAttribute(clientMetrics, clientProps, update, "Invocation", "operation", "op", op, out); + testAttribute(clientMetrics, clientProps, update, "Invocation", "identity", "metrics", op, out); + testAttribute(clientMetrics, clientProps, update, "Invocation", "facet", "", op, out); + testAttribute(clientMetrics, clientProps, update, "Invocation", "encoding", "1.1", op, out); + testAttribute(clientMetrics, clientProps, update, "Invocation", "mode", "twoway", op, out); + testAttribute(clientMetrics, clientProps, update, "Invocation", "proxy", + "metrics -t -e 1.1:tcp -h 127.0.0.1 -p 12010 -t 60000", op, out); + + testAttribute(clientMetrics, clientProps, update, "Invocation", "context.entry1", "test", op, out); + testAttribute(clientMetrics, clientProps, update, "Invocation", "context.entry2", "", op, out); + testAttribute(clientMetrics, clientProps, update, "Invocation", "context.entry3", "", op, out); + + // + // Oneway tests + // + clearView(clientProps, serverProps, update); + props.put("IceMX.Metrics.View.Map.Invocation.GroupBy", "operation"); + props.put("IceMX.Metrics.View.Map.Invocation.Map.Remote.GroupBy", "localPort"); + updateProps(clientProps, serverProps, update, props, "Invocation"); + + MetricsPrx metricsOneway = (MetricsPrx)metrics.ice_oneway(); + metricsOneway.op(); + metricsOneway.end_op(metricsOneway.begin_op()); + metricsOneway.begin_op(cb).waitForSent(); + + map = toMap(clientMetrics.getMetricsView("View", timestamp).get("Invocation")); + test(map.size() == 1); + + im1 = (IceMX.InvocationMetrics)map.get("op"); + test(im1.current <= 1 && im1.total == 3 && im1.failures == 0 && im1.retry == 0); + test(!collocated ? (im1.remotes.length == 1) : (im1.collocated.length == 1)); + rim1 = (IceMX.ChildInvocationMetrics)(!collocated ? im1.remotes[0] : im1.collocated[0]); + test(rim1.current <= 1 && rim1.total == 3 && rim1.failures == 0); + test(rim1.size == 63 && rim1.replySize == 0); + + testAttribute(clientMetrics, clientProps, update, "Invocation", "mode", "oneway", new InvokeOp(metricsOneway), + out); + + // + // Batch oneway tests + // + props.put("IceMX.Metrics.View.Map.Invocation.GroupBy", "operation"); + props.put("IceMX.Metrics.View.Map.Invocation.Map.Remote.GroupBy", "localPort"); + updateProps(clientProps, serverProps, update, props, "Invocation"); + + MetricsPrx metricsBatchOneway = (MetricsPrx)metrics.ice_batchOneway(); + metricsBatchOneway.op(); + metricsBatchOneway.end_op(metricsBatchOneway.begin_op()); + //metricsBatchOneway.begin_op(cb).waitForSent(); + + map = toMap(clientMetrics.getMetricsView("View", timestamp).get("Invocation")); + test(map.size() == 1); + + im1 = (IceMX.InvocationMetrics)map.get("op"); + test(im1.current == 0 && im1.total == 2 && im1.failures == 0 && im1.retry == 0); + test(im1.remotes.length == 0); + + testAttribute(clientMetrics, clientProps, update, "Invocation", "mode", "batch-oneway", + new InvokeOp(metricsBatchOneway), out); + + out.println("ok"); + + out.print("testing metrics view enable/disable..."); + out.flush(); + + Ice.StringSeqHolder disabledViews = new Ice.StringSeqHolder(); + props.put("IceMX.Metrics.View.GroupBy", "none"); + props.put("IceMX.Metrics.View.Disabled", "0"); + updateProps(clientProps, serverProps, update, props, "Thread"); + test(clientMetrics.getMetricsView("View", timestamp).get("Thread").length != 0); + test(clientMetrics.getMetricsViewNames(disabledViews).length == 1 && disabledViews.value.length == 0); + + props.put("IceMX.Metrics.View.Disabled", "1"); + updateProps(clientProps, serverProps, update, props, "Thread"); + test(clientMetrics.getMetricsView("View", timestamp).get("Thread") == null); + test(clientMetrics.getMetricsViewNames(disabledViews).length == 0 && disabledViews.value.length == 1); + + clientMetrics.enableMetricsView("View"); + test(clientMetrics.getMetricsView("View", timestamp).get("Thread").length != 0); + test(clientMetrics.getMetricsViewNames(disabledViews).length == 1 && disabledViews.value.length == 0); + + clientMetrics.disableMetricsView("View"); + test(clientMetrics.getMetricsView("View", timestamp).get("Thread") == null); + test(clientMetrics.getMetricsViewNames(disabledViews).length == 0 && disabledViews.value.length == 1); + + try + { + clientMetrics.enableMetricsView("UnknownView"); + } + catch(IceMX.UnknownMetricsView ex) + { + } + + out.println("ok"); + + out.print("testing instrumentation observer delegate... "); + out.flush(); + + test(obsv.threadObserver.getTotal() > 0); + if(!collocated) + { + test(obsv.connectionObserver.getTotal() > 0); + test(obsv.connectionEstablishmentObserver.getTotal() > 0); + test(obsv.endpointLookupObserver.getTotal() > 0); + test(obsv.invocationObserver.remoteObserver.getTotal() > 0); + } + else + { + test(obsv.invocationObserver.collocatedObserver.getTotal() > 0); + } + test(obsv.dispatchObserver.getTotal() > 0); + test(obsv.invocationObserver.getTotal() > 0); + + test(obsv.threadObserver.getCurrent() > 0); + if(!collocated) + { + test(obsv.connectionObserver.getCurrent() > 0); + test(obsv.connectionEstablishmentObserver.getCurrent() == 0); + test(obsv.endpointLookupObserver.getCurrent() == 0); + test(obsv.invocationObserver.remoteObserver.getCurrent() == 0); + } + else + { + test(obsv.invocationObserver.collocatedObserver.getCurrent() == 0); + } + test(obsv.dispatchObserver.getCurrent() == 0); + test(obsv.invocationObserver.getCurrent() == 0); + + test(obsv.threadObserver.getFailedCount() == 0); + if(!collocated) + { + test(obsv.connectionObserver.getFailedCount() > 0); + test(obsv.connectionEstablishmentObserver.getFailedCount() > 0); + test(obsv.endpointLookupObserver.getFailedCount() > 0); + test(obsv.invocationObserver.remoteObserver.getFailedCount() > 0); + } + //test(obsv.dispatchObserver.getFailedCount() > 0); + test(obsv.invocationObserver.getFailedCount() > 0); + + if(!collocated) + { + test(obsv.threadObserver.states > 0); + test(obsv.connectionObserver.received > 0 && obsv.connectionObserver.sent > 0); + test(obsv.invocationObserver.retriedCount > 0); + test(obsv.invocationObserver.remoteObserver.replySize > 0); + } + else + { + test(obsv.invocationObserver.collocatedObserver.replySize > 0); + } + //test(obsv.dispatchObserver.userExceptionCount > 0); + test(obsv.invocationObserver.userExceptionCount > 0); + + out.println("ok"); + + return metrics; + } +} diff --git a/java/test/src/main/java/test/Ice/metrics/ChildInvocationObserverI.java b/java/test/src/main/java/test/Ice/metrics/ChildInvocationObserverI.java new file mode 100644 index 00000000000..da56f726250 --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/ChildInvocationObserverI.java @@ -0,0 +1,31 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +class ChildInvocationObserverI extends ObserverI implements Ice.Instrumentation.ChildInvocationObserver +{ + @Override + public synchronized void + reset() + { + super.reset(); + replySize = 0; + } + + @Override + public synchronized void + reply(int s) + { + replySize += s; + } + + int replySize; +}; + diff --git a/java/test/src/main/java/test/Ice/metrics/Client.java b/java/test/src/main/java/test/Ice/metrics/Client.java new file mode 100644 index 00000000000..48acc9244b1 --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/Client.java @@ -0,0 +1,58 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +import test.Ice.metrics.Test.MetricsPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + try + { + MetricsPrx metrics = AllTests.allTests(communicator, getWriter(), _observer); + metrics.shutdown(); + } + catch(Ice.UserException ex) + { + ex.printStackTrace(); + assert(false); + return 1; + } + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.metrics"); + initData.properties.setProperty("Ice.Admin.Endpoints", "tcp"); + initData.properties.setProperty("Ice.Admin.InstanceName", "client"); + initData.properties.setProperty("Ice.Admin.DelayCreation", "1"); + initData.properties.setProperty("Ice.Warn.Connections", "0"); + initData.properties.setProperty("Ice.MessageSizeMax", "50000"); + initData.observer = _observer; + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } + + private CommunicatorObserverI _observer = new CommunicatorObserverI(); +} diff --git a/java/test/src/main/java/test/Ice/metrics/Collocated.java b/java/test/src/main/java/test/Ice/metrics/Collocated.java new file mode 100644 index 00000000000..e1191a4de99 --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/Collocated.java @@ -0,0 +1,77 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +import test.Ice.metrics.Test.MetricsPrx; + +public class Collocated extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new MetricsI(), communicator.stringToIdentity("metrics")); + //adapter.activate(); + + communicator.getProperties().setProperty("ControllerAdapter.Endpoints", "default -p 12011"); + Ice.ObjectAdapter controllerAdapter = communicator.createObjectAdapter("ControllerAdapter"); + controllerAdapter.add(new ControllerI(adapter), communicator.stringToIdentity("controller")); + //controllerAdapter.activate(); + + try + { + MetricsPrx metrics = AllTests.allTests(communicator, getWriter(), _observer); + metrics.shutdown(); + } + catch(Ice.UserException ex) + { + ex.printStackTrace(); + assert(false); + return 1; + } + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + if(initData.properties.getPropertyAsInt("Ice.ThreadInterruptSafe") > 0) + { + // With background IO, collocated invocations are + // dispatched on the server thread pool. This test needs + // at least 3 threads in the server thread pool to work. + initData.properties.setProperty("Ice.ThreadPool.Server.Size", "3"); + } + initData.properties.setProperty("Ice.Package.Test", "test.Ice.metrics"); + initData.properties.setProperty("Ice.Admin.Endpoints", "tcp"); + initData.properties.setProperty("Ice.Admin.InstanceName", "client"); + initData.properties.setProperty("Ice.Admin.DelayCreation", "1"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("Ice.Warn.Connections", "0"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("Ice.MessageSizeMax", "50000"); + initData.observer = _observer; + return initData; + } + + public static void main(String[] args) + { + Collocated app = new Collocated(); + int result = app.main("Collocated", args); + System.gc(); + System.exit(result); + } + + private CommunicatorObserverI _observer = new CommunicatorObserverI(); +} diff --git a/java/test/src/main/java/test/Ice/metrics/CollocatedObserverI.java b/java/test/src/main/java/test/Ice/metrics/CollocatedObserverI.java new file mode 100644 index 00000000000..607da015366 --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/CollocatedObserverI.java @@ -0,0 +1,15 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +class CollocatedObserverI extends ChildInvocationObserverI implements Ice.Instrumentation.CollocatedObserver +{ +}; + diff --git a/java/test/src/main/java/test/Ice/metrics/CommunicatorObserverI.java b/java/test/src/main/java/test/Ice/metrics/CommunicatorObserverI.java new file mode 100644 index 00000000000..996d5a83b1a --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/CommunicatorObserverI.java @@ -0,0 +1,147 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +class CommunicatorObserverI implements Ice.Instrumentation.CommunicatorObserver +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + @Override + public void + setObserverUpdater(Ice.Instrumentation.ObserverUpdater u) + { + updater = u; + } + + @Override + synchronized public Ice.Instrumentation.Observer + getConnectionEstablishmentObserver(Ice.Endpoint e, String s) + { + if(connectionEstablishmentObserver == null) + { + connectionEstablishmentObserver = new ObserverI(); + connectionEstablishmentObserver.reset(); + } + return connectionEstablishmentObserver; + } + + + @Override + synchronized public Ice.Instrumentation.Observer + getEndpointLookupObserver(Ice.Endpoint e) + { + if(endpointLookupObserver == null) + { + endpointLookupObserver = new ObserverI(); + endpointLookupObserver.reset(); + } + return endpointLookupObserver; + } + + @Override + synchronized public Ice.Instrumentation.ConnectionObserver + getConnectionObserver(Ice.ConnectionInfo c, + Ice.Endpoint e, + Ice.Instrumentation.ConnectionState s, + Ice.Instrumentation.ConnectionObserver old) + { + test(old == null || old instanceof ConnectionObserverI); + if(connectionObserver == null) + { + connectionObserver = new ConnectionObserverI(); + connectionObserver.reset(); + } + return connectionObserver; + } + + @Override + synchronized public Ice.Instrumentation.ThreadObserver + getThreadObserver(String p, String id, Ice.Instrumentation.ThreadState s, + Ice.Instrumentation.ThreadObserver old) + { + test(old == null || old instanceof ThreadObserverI); + if(threadObserver == null) + { + threadObserver = new ThreadObserverI(); + threadObserver.reset(); + } + return threadObserver; + } + + @Override + synchronized public Ice.Instrumentation.InvocationObserver + getInvocationObserver(Ice.ObjectPrx p, String op, java.util.Map<String, String> ctx) + { + if(invocationObserver == null) + { + invocationObserver = new InvocationObserverI(); + invocationObserver.reset(); + } + return invocationObserver; + } + + @Override + synchronized public Ice.Instrumentation.DispatchObserver + getDispatchObserver(Ice.Current current, int s) + { + if(dispatchObserver == null) + { + dispatchObserver = new DispatchObserverI(); + dispatchObserver.reset(); + } + return dispatchObserver; + } + + synchronized void + reset() + { + if(connectionEstablishmentObserver != null) + { + connectionEstablishmentObserver.reset(); + } + if(endpointLookupObserver != null) + { + endpointLookupObserver.reset(); + } + if(connectionObserver != null) + { + connectionObserver.reset(); + } + if(threadObserver != null) + { + threadObserver.reset(); + } + if(invocationObserver != null) + { + invocationObserver.reset(); + } + if(dispatchObserver != null) + { + dispatchObserver.reset(); + } + } + + Ice.Instrumentation.ObserverUpdater updater; + + ObserverI connectionEstablishmentObserver; + ObserverI endpointLookupObserver; + ConnectionObserverI connectionObserver; + ThreadObserverI threadObserver; + InvocationObserverI invocationObserver; + DispatchObserverI dispatchObserver; +}; + diff --git a/java/test/src/main/java/test/Ice/metrics/ConnectionObserverI.java b/java/test/src/main/java/test/Ice/metrics/ConnectionObserverI.java new file mode 100644 index 00000000000..395c31733e9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/ConnectionObserverI.java @@ -0,0 +1,40 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +class ConnectionObserverI extends ObserverI implements Ice.Instrumentation.ConnectionObserver +{ + @Override + public synchronized void + reset() + { + super.reset(); + received = 0; + sent = 0; + } + + @Override + public synchronized void + sentBytes(int s) + { + sent += s; + } + + @Override + public synchronized void + receivedBytes(int s) + { + received += s; + } + + int sent; + int received; +}; + diff --git a/java/test/src/main/java/test/Ice/metrics/ControllerI.java b/java/test/src/main/java/test/Ice/metrics/ControllerI.java new file mode 100644 index 00000000000..2f1434d523a --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/ControllerI.java @@ -0,0 +1,34 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; +import test.Ice.metrics.Test._ControllerDisp; + +public final class ControllerI extends _ControllerDisp +{ + public ControllerI(Ice.ObjectAdapter adapter) + { + _adapter = adapter; + } + + @Override + public void hold(Ice.Current current) + { + _adapter.hold(); + _adapter.waitForHold(); + } + + @Override + public void resume(Ice.Current current) + { + _adapter.activate(); + } + + final private Ice.ObjectAdapter _adapter; +}; diff --git a/java/test/src/main/java/test/Ice/metrics/DispatchObserverI.java b/java/test/src/main/java/test/Ice/metrics/DispatchObserverI.java new file mode 100644 index 00000000000..43b0683696c --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/DispatchObserverI.java @@ -0,0 +1,40 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +class DispatchObserverI extends ObserverI implements Ice.Instrumentation.DispatchObserver +{ + @Override + public synchronized void + reset() + { + super.reset(); + userExceptionCount = 0; + replySize = 0; + } + + @Override + public synchronized void + userException() + { + ++userExceptionCount; + } + + @Override + public synchronized void + reply(int s) + { + replySize += s; + } + + int userExceptionCount; + int replySize; +}; + diff --git a/java/test/src/main/java/test/Ice/metrics/InvocationObserverI.java b/java/test/src/main/java/test/Ice/metrics/InvocationObserverI.java new file mode 100644 index 00000000000..cfb7e2c6547 --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/InvocationObserverI.java @@ -0,0 +1,75 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +class InvocationObserverI extends ObserverI implements Ice.Instrumentation.InvocationObserver +{ + @Override + public synchronized void + reset() + { + super.reset(); + retriedCount = 0; + userExceptionCount = 0; + if(remoteObserver != null) + { + remoteObserver.reset(); + } + if(collocatedObserver != null) + { + collocatedObserver.reset(); + } + } + + @Override + public synchronized void + retried() + { + ++retriedCount; + } + + @Override + public synchronized void + userException() + { + ++userExceptionCount; + } + + @Override + public synchronized Ice.Instrumentation.RemoteObserver + getRemoteObserver(Ice.ConnectionInfo c, Ice.Endpoint e, int a, int b) + { + if(remoteObserver == null) + { + remoteObserver = new RemoteObserverI(); + remoteObserver.reset(); + } + return remoteObserver; + } + + + @Override + public synchronized Ice.Instrumentation.CollocatedObserver + getCollocatedObserver(Ice.ObjectAdapter adapter, int a, int b) + { + if(collocatedObserver == null) + { + collocatedObserver = new CollocatedObserverI(); + collocatedObserver.reset(); + } + return collocatedObserver; + } + + int userExceptionCount; + int retriedCount; + + RemoteObserverI remoteObserver = null; + CollocatedObserverI collocatedObserver = null; +}; diff --git a/java/test/src/main/java/test/Ice/metrics/MetricsI.java b/java/test/src/main/java/test/Ice/metrics/MetricsI.java new file mode 100644 index 00000000000..51f10fd2661 --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/MetricsI.java @@ -0,0 +1,81 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; +import test.Ice.metrics.Test.*; + +public final class MetricsI extends _MetricsDisp +{ + public + MetricsI() + { + } + + @Override + public void + op(Ice.Current current) + { + } + + @Override + public void + fail(Ice.Current current) + { + current.con.close(true); + } + + @Override + public void + opWithUserException(Ice.Current current) + throws UserEx + { + throw new UserEx(); + } + + @Override + public void + opWithRequestFailedException(Ice.Current current) + { + throw new Ice.ObjectNotExistException(); + } + + @Override + public void + opWithLocalException(Ice.Current current) + { + throw new Ice.SyscallException(); + } + + @Override + public void + opWithUnknownException(Ice.Current current) + { + throw new IllegalArgumentException(); + } + + @Override + public void + opByteS(byte[] bs, Ice.Current current) + { + } + + @Override + public Ice.ObjectPrx + getAdmin(Ice.Current current) + { + return current.adapter.getCommunicator().getAdmin(); + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/metrics/ObserverI.java b/java/test/src/main/java/test/Ice/metrics/ObserverI.java new file mode 100644 index 00000000000..1dadf4d63d8 --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/ObserverI.java @@ -0,0 +1,63 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +class ObserverI implements Ice.Instrumentation.Observer +{ + synchronized public void + reset() + { + total = 0; + current = 0; + failedCount = 0; + } + + @Override + synchronized public void + attach() + { + ++total; + ++current; + } + @Override + synchronized public void + detach() + { + --current; + } + @Override + synchronized public void + failed(String s) + { + ++failedCount; + } + + synchronized int + getTotal() + { + return total; + } + + synchronized int + getCurrent() + { + return current; + } + + synchronized int + getFailedCount() + { + return failedCount; + } + + int total; + int current; + int failedCount; +}; diff --git a/java/test/src/main/java/test/Ice/metrics/RemoveObserverI.java b/java/test/src/main/java/test/Ice/metrics/RemoveObserverI.java new file mode 100644 index 00000000000..6a5ad4817db --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/RemoveObserverI.java @@ -0,0 +1,15 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +class RemoteObserverI extends ChildInvocationObserverI implements Ice.Instrumentation.RemoteObserver +{ +}; + diff --git a/java/test/src/main/java/test/Ice/metrics/Server.java b/java/test/src/main/java/test/Ice/metrics/Server.java new file mode 100644 index 00000000000..70788ea876f --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/Server.java @@ -0,0 +1,52 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new MetricsI(), communicator.stringToIdentity("metrics")); + adapter.activate(); + + communicator.getProperties().setProperty("ControllerAdapter.Endpoints", "default -p 12011"); + Ice.ObjectAdapter controllerAdapter = communicator.createObjectAdapter("ControllerAdapter"); + controllerAdapter.add(new ControllerI(adapter), communicator.stringToIdentity("controller")); + controllerAdapter.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.retry"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("Ice.Admin.Endpoints", "tcp"); + initData.properties.setProperty("Ice.Admin.InstanceName", "server"); + initData.properties.setProperty("Ice.Warn.Connections", "0"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("Ice.MessageSizeMax", "50000"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/metrics/Test.ice b/java/test/src/main/java/test/Ice/metrics/Test.ice new file mode 100644 index 00000000000..41930f8c10a --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/Test.ice @@ -0,0 +1,51 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.metrics"]] +module Test +{ + +exception UserEx +{ +}; + +sequence<byte> ByteSeq; + +interface Metrics +{ + void op(); + + idempotent void fail(); + + void opWithUserException() + throws UserEx; + + void opWithRequestFailedException(); + + void opWithLocalException(); + + void opWithUnknownException(); + + void opByteS(ByteSeq bs); + + Object* getAdmin(); + + void shutdown(); +}; + +interface Controller +{ + void hold(); + + void resume(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/metrics/TestAMD.ice b/java/test/src/main/java/test/Ice/metrics/TestAMD.ice new file mode 100644 index 00000000000..0a9bf0209a9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/TestAMD.ice @@ -0,0 +1,51 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.metrics.AMD"]] +module Test +{ + +exception UserEx +{ +}; + +sequence<byte> ByteSeq; + +interface Metrics +{ + ["amd"] void op(); + + ["amd"] idempotent void fail(); + + ["amd"] void opWithUserException() + throws UserEx; + + ["amd"] void opWithRequestFailedException(); + + ["amd"] void opWithLocalException(); + + ["amd"] void opWithUnknownException(); + + ["amd"] void opByteS(ByteSeq bs); + + Object* getAdmin(); + + void shutdown(); +}; + +interface Controller +{ + void hold(); + + void resume(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/metrics/ThreadObserverI.java b/java/test/src/main/java/test/Ice/metrics/ThreadObserverI.java new file mode 100644 index 00000000000..af24dfd7df1 --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/ThreadObserverI.java @@ -0,0 +1,31 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.metrics; + +class ThreadObserverI extends ObserverI implements Ice.Instrumentation.ThreadObserver +{ + @Override + public synchronized void + reset() + { + super.reset(); + states = 0; + } + + @Override + public synchronized void + stateChanged(Ice.Instrumentation.ThreadState o, Ice.Instrumentation.ThreadState n) + { + ++states; + } + + int states; +}; + diff --git a/java/test/src/main/java/test/Ice/metrics/run.py b/java/test/src/main/java/test/Ice/metrics/run.py new file mode 100755 index 00000000000..7254e6ab696 --- /dev/null +++ b/java/test/src/main/java/test/Ice/metrics/run.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("tests with regular server.") +TestUtil.clientServerTest() +print("tests with AMD server.") +TestUtil.clientServerTest(server="test.Ice.metrics.AMDServer") +print("tests with collocated server.") +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/networkProxy/AllTests.java b/java/test/src/main/java/test/Ice/networkProxy/AllTests.java new file mode 100644 index 00000000000..f0b53afd8c3 --- /dev/null +++ b/java/test/src/main/java/test/Ice/networkProxy/AllTests.java @@ -0,0 +1,77 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.networkProxy; + +import java.io.PrintWriter; + +import test.Ice.networkProxy.Test.TestIntfPrx; +import test.Ice.networkProxy.Test.TestIntfPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + allTests(test.Util.Application app) + { + Ice.Communicator communicator = app.communicator(); + PrintWriter out = app.getWriter(); + + String sref = "test:default -p 12010"; + Ice.ObjectPrx obj = communicator.stringToProxy(sref); + test(obj != null); + + TestIntfPrx test = TestIntfPrxHelper.checkedCast(obj); + test(test != null); + + out.print("testing connection... "); + out.flush(); + { + test.ice_ping(); + } + out.println("ok"); + + out.print("testing connection information... "); + out.flush(); + { + Ice.IPConnectionInfo info = (Ice.IPConnectionInfo)test.ice_getConnection().getInfo(); + test(info.remotePort == 12030 || info.remotePort == 12031); // make sure we are connected to the proxy port. + } + out.println("ok"); + + out.print("shutting down server... "); + out.flush(); + { + test.shutdown(); + } + out.println("ok"); + + out.print("testing connection failure... "); + out.flush(); + { + try + { + test.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + } + out.println("ok"); + } +} diff --git a/java/test/src/main/java/test/Ice/networkProxy/Client.java b/java/test/src/main/java/test/Ice/networkProxy/Client.java new file mode 100644 index 00000000000..411b276ac9a --- /dev/null +++ b/java/test/src/main/java/test/Ice/networkProxy/Client.java @@ -0,0 +1,39 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.networkProxy; + +import test.Ice.networkProxy.Test.TestIntfPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + AllTests.allTests(this); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.networkProxy"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/networkProxy/Server.java b/java/test/src/main/java/test/Ice/networkProxy/Server.java new file mode 100644 index 00000000000..fe6e7c04ea9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/networkProxy/Server.java @@ -0,0 +1,51 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.networkProxy; + +import test.Ice.networkProxy.Test._TestIntfDisp; + +public class Server extends test.Util.Application +{ + static public class TestI extends _TestIntfDisp + { + public void shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + } + + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new TestI(), communicator.stringToIdentity("test")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.networkProxy"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/networkProxy/Test.ice b/java/test/src/main/java/test/Ice/networkProxy/Test.ice new file mode 100644 index 00000000000..3e084d8a65e --- /dev/null +++ b/java/test/src/main/java/test/Ice/networkProxy/Test.ice @@ -0,0 +1,21 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.networkProxy"]] +module Test +{ + +interface TestIntf +{ + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/networkProxy/run.py b/java/test/src/main/java/test/Ice/networkProxy/run.py new file mode 100755 index 00000000000..766bcb373f6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/networkProxy/run.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil, NetworkProxy + +sys.stdout.write("starting SOCKS proxy... ") +sys.stdout.flush() +socksProxy = NetworkProxy.SocksProxy(12030) +print("ok") + +TestUtil.clientServerTest(additionalClientOptions="--Ice.SOCKSProxyHost=localhost --Ice.SOCKSProxyPort=12030") + +sys.stdout.write("terminating SOCKS proxy... ") +sys.stdout.flush() +socksProxy.terminate() +print("ok") + +sys.stdout.write("starting HTTP proxy... ") +sys.stdout.flush() +httpProxy = NetworkProxy.HttpProxy(12031) +print("ok") + +TestUtil.clientServerTest(additionalClientOptions="--Ice.HTTPProxyHost=localhost --Ice.HTTPProxyPort=12031") + +sys.stdout.write("terminating HTTP proxy... ") +sys.stdout.flush() +httpProxy.terminate() +print("ok") diff --git a/java/test/src/main/java/test/Ice/objects/AllTests.java b/java/test/src/main/java/test/Ice/objects/AllTests.java new file mode 100644 index 00000000000..ab43e76c368 --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/AllTests.java @@ -0,0 +1,259 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +import java.io.PrintWriter; + +import test.Ice.objects.Test.B; +import test.Ice.objects.Test.BHolder; +import test.Ice.objects.Test.C; +import test.Ice.objects.Test.CHolder; +import test.Ice.objects.Test.D; +import test.Ice.objects.Test.DHolder; +import test.Ice.objects.Test.E; +import test.Ice.objects.Test.F; +import test.Ice.objects.Test.H; +import test.Ice.objects.Test.I; +import test.Ice.objects.Test.Base; +import test.Ice.objects.Test.S; +import test.Ice.objects.Test.BaseSeqHolder; +import test.Ice.objects.Test.InitialPrx; +import test.Ice.objects.Test.InitialPrxHelper; +import test.Ice.objects.Test.J; +import test.Ice.objects.Test.UnexpectedObjectExceptionTestPrx; +import test.Ice.objects.Test.UnexpectedObjectExceptionTestPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static InitialPrx + allTests(Ice.Communicator communicator, PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + String ref = "initial:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + InitialPrx initial = InitialPrxHelper.checkedCast(base); + test(initial != null); + test(initial.equals(base)); + out.println("ok"); + + out.print("getting B1... "); + out.flush(); + B b1 = initial.getB1(); + test(b1 != null); + out.println("ok"); + + out.print("getting B2... "); + out.flush(); + B b2 = initial.getB2(); + test(b2 != null); + out.println("ok"); + + out.print("getting C... "); + out.flush(); + C c = initial.getC(); + test(c != null); + out.println("ok"); + + out.print("getting D... "); + out.flush(); + D d = initial.getD(); + test(d != null); + out.println("ok"); + + out.print("checking consistency... "); + out.flush(); + test(b1 != b2); + //test(b1 != c); + //test(b1 != d); + //test(b2 != c); + //test(b2 != d); + //test(c != d); + test(b1.theB == b1); + test(b1.theC == null); + test(b1.theA instanceof B); + test(((B)b1.theA).theA == b1.theA); + test(((B)b1.theA).theB == b1); + test(((B)b1.theA).theC instanceof C); + test((((B)b1.theA).theC).theB == b1.theA); + test(b1.preMarshalInvoked); + test(b1.postUnmarshalInvoked(null)); + test(b1.theA.preMarshalInvoked); + test(b1.theA.postUnmarshalInvoked(null)); + test(((B)b1.theA).theC.preMarshalInvoked); + test(((B)b1.theA).theC.postUnmarshalInvoked(null)); + + // More tests possible for b2 and d, but I think this is already + // sufficient. + test(b2.theA == b2); + test(d.theC == null); + out.println("ok"); + + out.print("getting B1, B2, C, and D all at once... "); + out.flush(); + BHolder b1H = new BHolder(); + BHolder b2H = new BHolder(); + CHolder cH = new CHolder(); + DHolder dH = new DHolder(); + initial.getAll(b1H, b2H, cH, dH); + b1 = b1H.value; + b2 = b2H.value; + c = cH.value; + d = dH.value; + test(b1 != null); + test(b2 != null); + test(c != null); + test(d != null); + out.println("ok"); + + out.print("checking consistency... "); + out.flush(); + test(b1 != b2); + //test(b1 != c); + //test(b1 != d); + //test(b2 != c); + //test(b2 != d); + //test(c != d); + test(b1.theA == b2); + test(b1.theB == b1); + test(b1.theC == null); + test(b2.theA == b2); + test(b2.theB == b1); + test(b2.theC == c); + test(c.theB == b2); + test(d.theA == b1); + test(d.theB == b2); + test(d.theC == null); + test(d.preMarshalInvoked); + test(d.postUnmarshalInvoked(null)); + test(d.theA.preMarshalInvoked); + test(d.theA.postUnmarshalInvoked(null)); + test(d.theB.preMarshalInvoked); + test(d.theB.postUnmarshalInvoked(null)); + test(d.theB.theC.preMarshalInvoked); + test(d.theB.theC.postUnmarshalInvoked(null)); + + out.println("ok"); + + out.print("testing protected members... "); + out.flush(); + E e = initial.getE(); + test(e.checkValues()); + try + { + test((E.class.getDeclaredField("i").getModifiers() & java.lang.reflect.Modifier.PROTECTED) != 0); + test((E.class.getDeclaredField("s").getModifiers() & java.lang.reflect.Modifier.PROTECTED) != 0); + } + catch(Exception ex) + { + test(false); + } + F f = initial.getF(); + test(f.checkValues()); + test(f.e2.checkValues()); + try + { + test((F.class.getDeclaredField("e1").getModifiers() & java.lang.reflect.Modifier.PROTECTED) != 0); + test((F.class.getDeclaredField("e2").getModifiers() & java.lang.reflect.Modifier.PROTECTED) == 0); + } + catch(Exception ex) + { + test(false); + } + out.println("ok"); + + out.print("getting I, J and H... "); + out.flush(); + I i = initial.getI(); + test(i != null); + I j = initial.getJ(); + test(j != null && ((J)j) != null); + I h = initial.getH(); + test(h != null && ((H)h) != null); + out.println("ok"); + + out.print("setting I... "); + out.flush(); + initial.setI(i); + initial.setI(j); + initial.setI(h); + out.println("ok"); + + out.print("testing sequences..."); + try + { + out.flush(); + Base[] inS = new Base[0]; + BaseSeqHolder outS = new BaseSeqHolder(); + Base[] retS; + retS = initial.opBaseSeq(inS, outS); + + inS = new Base[1]; + inS[0] = new Base(new S(), ""); + retS = initial.opBaseSeq(inS, outS); + test(retS.length == 1 && outS.value.length == 1); + } + catch(Ice.OperationNotExistException ex) + { + } + out.println("ok"); + + out.print("testing compact ID..."); + out.flush(); + try + { + test(initial.getCompact() != null); + } + catch(Ice.OperationNotExistException ex) + { + } + out.println("ok"); + + out.print("testing UnexpectedObjectException..."); + out.flush(); + ref = "uoet:default -p 12010"; + base = communicator.stringToProxy(ref); + test(base != null); + UnexpectedObjectExceptionTestPrx uoet = UnexpectedObjectExceptionTestPrxHelper.uncheckedCast(base); + test(uoet != null); + try + { + uoet.op(); + test(false); + } + catch(Ice.UnexpectedObjectException ex) + { + test(ex.type.equals("::Test::AlsoEmpty")); + test(ex.expectedType.equals("::Test::Empty")); + } + catch(java.lang.Exception ex) + { + out.println(ex); + test(false); + } + out.println("ok"); + + return initial; + } +} diff --git a/java/test/src/main/java/test/Ice/objects/BI.java b/java/test/src/main/java/test/Ice/objects/BI.java new file mode 100644 index 00000000000..09aebe13501 --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/BI.java @@ -0,0 +1,44 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +import test.Ice.objects.Test.B; + +public final class BI extends B +{ + public + BI() + { + _postUnmarshalInvoked = false; + } + + @Override + public boolean + postUnmarshalInvoked(Ice.Current current) + { + return _postUnmarshalInvoked; + } + + @Override + public void + ice_preMarshal() + { + preMarshalInvoked = true; + } + + @Override + public void + ice_postUnmarshal() + { + _postUnmarshalInvoked = true; + } + + private boolean _postUnmarshalInvoked; +} diff --git a/java/test/src/main/java/test/Ice/objects/CI.java b/java/test/src/main/java/test/Ice/objects/CI.java new file mode 100644 index 00000000000..f46501a241c --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/CI.java @@ -0,0 +1,45 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +import test.Ice.objects.Test.C; + + +public final class CI extends C +{ + public + CI() + { + _postUnmarshalInvoked = false; + } + + @Override + public boolean + postUnmarshalInvoked(Ice.Current current) + { + return _postUnmarshalInvoked; + } + + @Override + public void + ice_preMarshal() + { + preMarshalInvoked = true; + } + + @Override + public void + ice_postUnmarshal() + { + _postUnmarshalInvoked = true; + } + + private boolean _postUnmarshalInvoked; +} diff --git a/java/test/src/main/java/test/Ice/objects/Client.java b/java/test/src/main/java/test/Ice/objects/Client.java new file mode 100644 index 00000000000..3d9f3803bc5 --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/Client.java @@ -0,0 +1,100 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +import test.Ice.objects.Test.InitialPrx; + +public class Client extends test.Util.Application +{ + private static class MyObjectFactory implements Ice.ObjectFactory + { + @Override + public Ice.Object create(String type) + { + if(type.equals("::Test::B")) + { + return new BI(); + } + else if(type.equals("::Test::C")) + { + return new CI(); + } + else if(type.equals("::Test::D")) + { + return new DI(); + } + else if(type.equals("::Test::E")) + { + return new EI(); + } + else if(type.equals("::Test::F")) + { + return new FI(); + } + else if(type.equals("::Test::I")) + { + return new II(); + } + else if(type.equals("::Test::J")) + { + return new JI(); + } + else if(type.equals("::Test::H")) + { + return new HI(); + } + + assert (false); // Should never be reached + return null; + } + + @Override + public void destroy() + { + // Nothing to do + } + } + + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectFactory factory = new MyObjectFactory(); + communicator.addObjectFactory(factory, "::Test::B"); + communicator.addObjectFactory(factory, "::Test::C"); + communicator.addObjectFactory(factory, "::Test::D"); + communicator.addObjectFactory(factory, "::Test::E"); + communicator.addObjectFactory(factory, "::Test::F"); + communicator.addObjectFactory(factory, "::Test::I"); + communicator.addObjectFactory(factory, "::Test::J"); + communicator.addObjectFactory(factory, "::Test::H"); + + InitialPrx initial = AllTests.allTests(communicator, getWriter()); + initial.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.objects"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/objects/Collocated.java b/java/test/src/main/java/test/Ice/objects/Collocated.java new file mode 100644 index 00000000000..06d1f4bf5fd --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/Collocated.java @@ -0,0 +1,108 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +import test.Ice.objects.Test.Initial; + +public class Collocated extends test.Util.Application +{ + private static class MyObjectFactory implements Ice.ObjectFactory + { + @Override + public Ice.Object create(String type) + { + if(type.equals("::Test::B")) + { + return new BI(); + } + else if(type.equals("::Test::C")) + { + return new CI(); + } + else if(type.equals("::Test::D")) + { + return new DI(); + } + else if(type.equals("::Test::E")) + { + return new EI(); + } + else if(type.equals("::Test::F")) + { + return new FI(); + } + else if(type.equals("::Test::I")) + { + return new II(); + } + else if(type.equals("::Test::J")) + { + return new JI(); + } + else if(type.equals("::Test::H")) + { + return new HI(); + } + + assert (false); // Should never be reached + return null; + } + + @Override + public void destroy() + { + // Nothing to do + } + } + + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectFactory factory = new MyObjectFactory(); + communicator.addObjectFactory(factory, "::Test::B"); + communicator.addObjectFactory(factory, "::Test::C"); + communicator.addObjectFactory(factory, "::Test::D"); + communicator.addObjectFactory(factory, "::Test::E"); + communicator.addObjectFactory(factory, "::Test::F"); + communicator.addObjectFactory(factory, "::Test::I"); + communicator.addObjectFactory(factory, "::Test::J"); + communicator.addObjectFactory(factory, "::Test::H"); + + communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Initial initial = new InitialI(adapter); + adapter.add(initial, communicator.stringToIdentity("initial")); + UnexpectedObjectExceptionTestI object = new UnexpectedObjectExceptionTestI(); + adapter.add(object, communicator.stringToIdentity("uoet")); + AllTests.allTests(communicator, getWriter()); + // We must call shutdown even in the collocated case for cyclic + // dependency cleanup + initial.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.objects"); + return initData; + } + + public static void main(String[] args) + { + Collocated app = new Collocated(); + int result = app.main("Collocated", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/objects/DI.java b/java/test/src/main/java/test/Ice/objects/DI.java new file mode 100644 index 00000000000..660efcd277c --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/DI.java @@ -0,0 +1,45 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +import test.Ice.objects.Test.D; + + +public final class DI extends D +{ + public + DI() + { + _postUnmarshalInvoked = false; + } + + @Override + public boolean + postUnmarshalInvoked(Ice.Current current) + { + return _postUnmarshalInvoked; + } + + @Override + public void + ice_preMarshal() + { + preMarshalInvoked = true; + } + + @Override + public void + ice_postUnmarshal() + { + _postUnmarshalInvoked = true; + } + + private boolean _postUnmarshalInvoked; +} diff --git a/java/test/src/main/java/test/Ice/objects/EI.java b/java/test/src/main/java/test/Ice/objects/EI.java new file mode 100644 index 00000000000..e4930e1644d --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/EI.java @@ -0,0 +1,29 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +import test.Ice.objects.Test.E; + + +public final class EI extends E +{ + public + EI() + { + super(1, "hello"); + } + + @Override + public boolean + checkValues(Ice.Current current) + { + return i == 1 && s.equals("hello"); + } +} diff --git a/java/test/src/main/java/test/Ice/objects/FI.java b/java/test/src/main/java/test/Ice/objects/FI.java new file mode 100644 index 00000000000..d51461c8031 --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/FI.java @@ -0,0 +1,35 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +import test.Ice.objects.Test.E; +import test.Ice.objects.Test.F; + + +public final class FI extends F +{ + public + FI() + { + } + + public + FI(E e) + { + super(e, e); + } + + @Override + public boolean + checkValues(Ice.Current current) + { + return e1 != null && e1 == e2; + } +} diff --git a/java/test/src/main/java/test/Ice/objects/HI.java b/java/test/src/main/java/test/Ice/objects/HI.java new file mode 100644 index 00000000000..e41ec794c82 --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/HI.java @@ -0,0 +1,17 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +import test.Ice.objects.Test.H; + + +public final class HI extends H +{ +} diff --git a/java/test/src/main/java/test/Ice/objects/II.java b/java/test/src/main/java/test/Ice/objects/II.java new file mode 100644 index 00000000000..8061d20e2cd --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/II.java @@ -0,0 +1,16 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +import test.Ice.objects.Test._IDisp; + +public final class II extends _IDisp +{ +} diff --git a/java/test/src/main/java/test/Ice/objects/InitialI.java b/java/test/src/main/java/test/Ice/objects/InitialI.java new file mode 100644 index 00000000000..eaa1be7785b --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/InitialI.java @@ -0,0 +1,208 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +import test.Ice.objects.Test.B; +import test.Ice.objects.Test.BHolder; +import test.Ice.objects.Test.C; +import test.Ice.objects.Test.CHolder; +import test.Ice.objects.Test.D; +import test.Ice.objects.Test.DHolder; +import test.Ice.objects.Test.E; +import test.Ice.objects.Test.F; +import test.Ice.objects.Test.I; +import test.Ice.objects.Test.Base; +import test.Ice.objects.Test.BaseSeqHolder; +import test.Ice.objects.Test.Initial; +import test.Ice.objects.Test.Compact; +import test.Ice.objects.Test.CompactExt; + +public final class InitialI extends Initial +{ + public + InitialI(Ice.ObjectAdapter adapter) + { + _adapter = adapter; + _b1 = new BI(); + _b2 = new BI(); + _c = new CI(); + _d = new DI(); + _e = new EI(); + _f = new FI(_e); + + _b1.theA = _b2; // Cyclic reference to another B + _b1.theB = _b1; // Self reference. + _b1.theC = null; // Null reference. + + _b2.theA = _b2; // Self reference, using base. + _b2.theB = _b1; // Cyclic reference to another B + _b2.theC = _c; // Cyclic reference to a C. + + _c.theB = _b2; // Cyclic reference to a B. + + _d.theA = _b1; // Reference to a B. + _d.theB = _b2; // Reference to a B. + _d.theC = null; // Reference to a C. + } + + @Override + public void + getAll(BHolder b1, BHolder b2, CHolder c, DHolder d, Ice.Current current) + { + _b1.preMarshalInvoked = false; + _b2.preMarshalInvoked = false; + _c.preMarshalInvoked = false; + _d.preMarshalInvoked = false; + b1.value = _b1; + b2.value = _b2; + c.value = _c; + d.value = _d; + } + + @Override + public B + getB1(Ice.Current current) + { + _b1.preMarshalInvoked = false; + _b2.preMarshalInvoked = false; + _c.preMarshalInvoked = false; + return _b1; + } + + @Override + public B + getB2(Ice.Current current) + { + _b1.preMarshalInvoked = false; + _b2.preMarshalInvoked = false; + _c.preMarshalInvoked = false; + return _b2; + } + + @Override + public C + getC(Ice.Current current) + { + _b1.preMarshalInvoked = false; + _b2.preMarshalInvoked = false; + _c.preMarshalInvoked = false; + return _c; + } + + @Override + public D + getD(Ice.Current current) + { + _b1.preMarshalInvoked = false; + _b2.preMarshalInvoked = false; + _c.preMarshalInvoked = false; + _d.preMarshalInvoked = false; + return _d; + } + + @Override + public E + getE(Ice.Current current) + { + return _e; + } + + @Override + public F + getF(Ice.Current current) + { + return _f; + } + + @Override + public I + getI(Ice.Current current) + { + return new II(); + } + + @Override + public I + getJ(Ice.Current current) + { + return new JI(); + } + + @Override + public I + getH(Ice.Current current) + { + return new HI(); + } + + @Override + public void + setI(I theI, Ice.Current current) + { + } + + @Override + public Base[] + opBaseSeq(Base[] inS, BaseSeqHolder outS, Ice.Current current) + { + outS.value = inS; + return inS; + } + + @Override + public Compact + getCompact(Ice.Current current) + { + return new CompactExt(); + } + + @Override + public test.Ice.objects.Test.Inner.A + getInnerA(Ice.Current current) + { + return new test.Ice.objects.Test.Inner.A(_b1); + } + + @Override + public test.Ice.objects.Test.Inner.Sub.A + getInnerSubA(Ice.Current current) + { + return new test.Ice.objects.Test.Inner.Sub.A(new test.Ice.objects.Test.Inner.A(_b1)); + } + + @Override + public void throwInnerEx(Ice.Current current) + throws test.Ice.objects.Test.Inner.Ex + { + throw new test.Ice.objects.Test.Inner.Ex("Inner::Ex"); + } + + @Override + public void throwInnerSubEx(Ice.Current current) + throws test.Ice.objects.Test.Inner.Sub.Ex + { + throw new test.Ice.objects.Test.Inner.Sub.Ex("Inner::Sub::Ex"); + } + + @Override + public void + shutdown(Ice.Current current) + { + _adapter.getCommunicator().shutdown(); + } + + private Ice.ObjectAdapter _adapter; + private B _b1; + private B _b2; + private C _c; + private D _d; + private E _e; + private F _f; +} diff --git a/java/test/src/main/java/test/Ice/objects/JI.java b/java/test/src/main/java/test/Ice/objects/JI.java new file mode 100644 index 00000000000..ff82d0dac25 --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/JI.java @@ -0,0 +1,17 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +import test.Ice.objects.Test._JDisp; + + +public final class JI extends _JDisp +{ +} diff --git a/java/test/src/main/java/test/Ice/objects/Server.java b/java/test/src/main/java/test/Ice/objects/Server.java new file mode 100644 index 00000000000..d327e7d5b53 --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/Server.java @@ -0,0 +1,79 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +public class Server extends test.Util.Application +{ + private static class MyObjectFactory implements Ice.ObjectFactory + { + @Override + public Ice.Object create(String type) + { + if(type.equals("::Test::I")) + { + return new II(); + } + else if(type.equals("::Test::J")) + { + return new JI(); + } + else if(type.equals("::Test::H")) + { + return new HI(); + } + + assert (false); // Should never be reached + return null; + } + + @Override + public void destroy() + { + // Nothing to do + } + } + + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectFactory factory = new MyObjectFactory(); + communicator.addObjectFactory(factory, "::Test::I"); + communicator.addObjectFactory(factory, "::Test::J"); + communicator.addObjectFactory(factory, "::Test::H"); + + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object object = new InitialI(adapter); + adapter.add(object, communicator.stringToIdentity("initial")); + object = new UnexpectedObjectExceptionTestI(); + adapter.add(object, communicator.stringToIdentity("uoet")); + adapter.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.objects"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/objects/Test.ice b/java/test/src/main/java/test/Ice/objects/Test.ice new file mode 100644 index 00000000000..d4644b11a64 --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/Test.ice @@ -0,0 +1,221 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.objects"]] +module Test +{ + +struct S +{ + string str; +}; + +class Base +{ + S theS; + string str; +}; + +class AbstractBase extends Base +{ + void op(); +}; + +class B; +class C; + +class A +{ + B theB; + C theC; + + bool preMarshalInvoked; + bool postUnmarshalInvoked(); +}; + +class B extends A +{ + A theA; +}; + +class C +{ + B theB; + + bool preMarshalInvoked; + bool postUnmarshalInvoked(); +}; + +class D +{ + A theA; + B theB; + C theC; + + bool preMarshalInvoked; + bool postUnmarshalInvoked(); +}; + +["protected"] class E +{ + int i; + string s; + + bool checkValues(); +}; + +class F +{ + ["protected"] E e1; + E e2; + + bool checkValues(); +}; + +interface I +{ +}; + +interface J extends I +{ +}; + +class H implements I +{ +}; + +sequence<Base> BaseSeq; + +class CompactExt; + +class Compact(1) +{ +}; + +const int CompactExtId = 789; + +class CompactExt(CompactExtId) extends Compact +{ +}; + +module Inner +{ + +class A +{ + ::Test::A theA; +}; + +exception Ex +{ + string reason; +}; + +module Sub +{ + +class A +{ + ::Test::Inner::A theA; +}; + +exception Ex +{ + string reason; +}; + +}; + +}; + +class Initial +{ + void shutdown(); + B getB1(); + B getB2(); + C getC(); + D getD(); + E getE(); + F getF(); + + void getAll(out B b1, out B b2, out C theC, out D theD); + + I getI(); + I getJ(); + I getH(); + + void setI(I theI); + + BaseSeq opBaseSeq(BaseSeq inSeq, out BaseSeq outSeq); + + Compact getCompact(); + + Inner::A getInnerA(); + Inner::Sub::A getInnerSubA(); + + void throwInnerEx() throws Inner::Ex; + void throwInnerSubEx() throws Inner::Sub::Ex; +}; + +class Empty +{ +}; + +class AlsoEmpty +{ +}; + +interface UnexpectedObjectExceptionTest +{ + Empty op(); +}; + +// +// Remaining definitions are here to ensure that the generated code compiles. +// + +class COneMember +{ + Empty e; +}; + +class CTwoMembers +{ + Empty e1; + Empty e2; +}; + +exception EOneMember +{ + Empty e; +}; + +exception ETwoMembers +{ + Empty e1; + Empty e2; +}; + +struct SOneMember +{ + Empty e; +}; + +struct STwoMembers +{ + Empty e1; + Empty e2; +}; + +dictionary<int, COneMember> DOneMember; +dictionary<int, CTwoMembers> DTwoMembers; + +}; diff --git a/java/test/src/main/java/test/Ice/objects/UnexpectedObjectExceptionTestI.java b/java/test/src/main/java/test/Ice/objects/UnexpectedObjectExceptionTestI.java new file mode 100644 index 00000000000..f9b0e8deb7a --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/UnexpectedObjectExceptionTestI.java @@ -0,0 +1,32 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.objects; + +import test.Ice.objects.Test.AlsoEmpty; +import test.Ice.objects.Test.AlsoEmptyHelper; + + +public final class UnexpectedObjectExceptionTestI extends Ice.Blobject +{ + @Override + public boolean + ice_invoke(byte[] inParams, Ice.ByteSeqHolder outParams, Ice.Current current) + { + Ice.Communicator communicator = current.adapter.getCommunicator(); + Ice.OutputStream out = Ice.Util.createOutputStream(communicator); + out.startEncapsulation(current.encoding, Ice.FormatType.DefaultFormat); + AlsoEmpty ae = new AlsoEmpty(); + AlsoEmptyHelper.write(out, ae); + out.writePendingObjects(); + out.endEncapsulation(); + outParams.value = out.finished(); + return true; + } +} diff --git a/java/test/src/main/java/test/Ice/objects/run.py b/java/test/src/main/java/test/Ice/objects/run.py new file mode 100755 index 00000000000..89d67e015aa --- /dev/null +++ b/java/test/src/main/java/test/Ice/objects/run.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("Running test with compact (default) format.") +TestUtil.clientServerTest() + +print("Running test with sliced format.") +TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.SlicedFormat", + additionalServerOptions="--Ice.Default.SlicedFormat") + +print("Running test with 1.0 encoding.") +TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.EncodingVersion=1.0", + additionalServerOptions="--Ice.Default.EncodingVersion=1.0") + +print("Running collocated test.") +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/operations/AMDMyDerivedClassI.java b/java/test/src/main/java/test/Ice/operations/AMDMyDerivedClassI.java new file mode 100644 index 00000000000..f577db345c1 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/AMDMyDerivedClassI.java @@ -0,0 +1,613 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +import test.Ice.operations.AMD.Test.AMD_MyClass_opBool; +import test.Ice.operations.AMD.Test.AMD_MyClass_opBoolS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opBoolSS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opByte; +import test.Ice.operations.AMD.Test.AMD_MyClass_opByteBoolD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opByteS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opByteSOneway; +import test.Ice.operations.AMD.Test.AMD_MyClass_opByteSS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opContext; +import test.Ice.operations.AMD.Test.AMD_MyClass_opDoubleMarshaling; +import test.Ice.operations.AMD.Test.AMD_MyClass_opFloatDouble; +import test.Ice.operations.AMD.Test.AMD_MyClass_opFloatDoubleS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opFloatDoubleSS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opIdempotent; +import test.Ice.operations.AMD.Test.AMD_MyClass_opIntS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opLongFloatD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opMyClass; +import test.Ice.operations.AMD.Test.AMD_MyClass_opMyEnum; +import test.Ice.operations.AMD.Test.AMD_MyClass_opMyStructMyEnumD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opNonmutating; +import test.Ice.operations.AMD.Test.AMD_MyClass_opShortIntD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opShortIntLong; +import test.Ice.operations.AMD.Test.AMD_MyClass_opShortIntLongS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opShortIntLongSS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opString; +import test.Ice.operations.AMD.Test.AMD_MyClass_opStringMyEnumD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opMyEnumStringD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opStringS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opStringSS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opStringSSS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opStringStringD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opStruct; +import test.Ice.operations.AMD.Test.AMD_MyClass_opVoid; +import test.Ice.operations.AMD.Test.AMD_MyClass_shutdown; +import test.Ice.operations.AMD.Test.AMD_MyClass_delay; +import test.Ice.operations.AMD.Test.AMD_MyDerivedClass_opDerived; +import test.Ice.operations.AMD.Test.MyClassPrx; +import test.Ice.operations.AMD.Test.MyClassPrxHelper; +import test.Ice.operations.AMD.Test.MyDerivedClass; +import test.Ice.operations.AMD.Test.MyEnum; +import test.Ice.operations.AMD.Test.MyStruct; +import test.Ice.operations.AMD.Test.Structure; + +public final class AMDMyDerivedClassI extends MyDerivedClass +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static class Thread_opVoid extends Thread + { + public + Thread_opVoid(AMD_MyClass_opVoid cb) + { + _cb = cb; + } + + @Override + public void + run() + { + _cb.ice_response(); + } + + private AMD_MyClass_opVoid _cb; + } + + // + // Override the Object "pseudo" operations to verify the operation mode. + // + + @Override + public boolean + ice_isA(String id, Ice.Current current) + { + test(current.mode == Ice.OperationMode.Nonmutating); + return super.ice_isA(id, current); + } + + @Override + public void + ice_ping(Ice.Current current) + { + test(current.mode == Ice.OperationMode.Nonmutating); + super.ice_ping(current); + } + + @Override + public String[] + ice_ids(Ice.Current current) + { + test(current.mode == Ice.OperationMode.Nonmutating); + return super.ice_ids(current); + } + + @Override + public String + ice_id(Ice.Current current) + { + test(current.mode == Ice.OperationMode.Nonmutating); + return super.ice_id(current); + } + + @Override + synchronized public void + shutdown_async(AMD_MyClass_shutdown cb, + Ice.Current current) + { + while(_opVoidThread != null) + { + try + { + _opVoidThread.join(); + _opVoidThread = null; + } + catch(java.lang.InterruptedException ex) + { + } + } + + current.adapter.getCommunicator().shutdown(); + cb.ice_response(); + } + + @Override + public void + delay_async(AMD_MyClass_delay cb, int ms, Ice.Current current) + { + try + { + Thread.sleep(ms); + } + catch(InterruptedException ex) + { + } + cb.ice_response(); + } + + @Override + synchronized public void + opVoid_async(AMD_MyClass_opVoid cb, + Ice.Current current) + { + test(current.mode == Ice.OperationMode.Normal); + + while(_opVoidThread != null) + { + try + { + _opVoidThread.join(); + _opVoidThread = null; + } + catch(java.lang.InterruptedException ex) + { + } + } + + _opVoidThread = new Thread_opVoid(cb); + _opVoidThread.start(); + } + + @Override + public void + opBool_async(AMD_MyClass_opBool cb, + boolean p1, boolean p2, + Ice.Current current) + { + cb.ice_response(p2, p1); + } + + @Override + public void + opBoolS_async(AMD_MyClass_opBoolS cb, + boolean[] p1, boolean[] p2, + Ice.Current current) + { + boolean[] p3 = new boolean[p1.length + p2.length]; + System.arraycopy(p1, 0, p3, 0, p1.length); + System.arraycopy(p2, 0, p3, p1.length, p2.length); + + boolean[] r = new boolean[p1.length]; + for(int i = 0; i < p1.length; i++) + { + r[i] = p1[p1.length - (i + 1)]; + } + cb.ice_response(r, p3); + } + + @Override + public void + opBoolSS_async(AMD_MyClass_opBoolSS cb, + boolean[][] p1, boolean[][] p2, + Ice.Current current) + { + boolean[][] p3 = new boolean[p1.length + p2.length][]; + System.arraycopy(p1, 0, p3, 0, p1.length); + System.arraycopy(p2, 0, p3, p1.length, p2.length); + + boolean[][] r = new boolean[p1.length][]; + for(int i = 0; i < p1.length; i++) + { + r[i] = p1[p1.length - (i + 1)]; + } + cb.ice_response(r, p3); + } + + @Override + public void + opByte_async(AMD_MyClass_opByte cb, + byte p1, byte p2, + Ice.Current current) + { + cb.ice_response(p1, (byte)(p1 ^ p2)); + } + + @Override + public void + opByteBoolD_async(AMD_MyClass_opByteBoolD cb, + java.util.Map<Byte, Boolean> p1, java.util.Map<Byte, Boolean> p2, + Ice.Current current) + { + java.util.Map<Byte, Boolean> p3 = p1; + java.util.Map<Byte, Boolean> r = new java.util.HashMap<Byte, Boolean>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opByteS_async(AMD_MyClass_opByteS cb, + byte[] p1, byte[] p2, + Ice.Current current) + { + byte[] p3 = new byte[p1.length]; + for(int i = 0; i < p1.length; i++) + { + p3[i] = p1[p1.length - (i + 1)]; + } + + byte[] r = new byte[p1.length + p2.length]; + System.arraycopy(p1, 0, r, 0, p1.length); + System.arraycopy(p2, 0, r, p1.length, p2.length); + cb.ice_response(r, p3); + } + + @Override + public void + opByteSS_async(AMD_MyClass_opByteSS cb, + byte[][] p1, byte[][] p2, + Ice.Current current) + { + byte[][] p3 = new byte[p1.length][]; + for(int i = 0; i < p1.length; i++) + { + p3[i] = p1[p1.length - (i + 1)]; + } + + byte[][] r = new byte[p1.length + p2.length][]; + System.arraycopy(p1, 0, r, 0, p1.length); + System.arraycopy(p2, 0, r, p1.length, p2.length); + cb.ice_response(r, p3); + } + + @Override + public void + opFloatDouble_async(AMD_MyClass_opFloatDouble cb, + float p1, double p2, + Ice.Current current) + { + cb.ice_response(p2, p1, p2); + } + + @Override + public void + opFloatDoubleS_async(AMD_MyClass_opFloatDoubleS cb, + float[] p1, double[] p2, + Ice.Current current) + { + float[] p3 = p1; + double[] p4 = new double[p2.length]; + for(int i = 0; i < p2.length; i++) + { + p4[i] = p2[p2.length - (i + 1)]; + } + double[] r = new double[p2.length + p1.length]; + System.arraycopy(p2, 0, r, 0, p2.length); + for(int i = 0; i < p1.length; i++) + { + r[p2.length + i] = p1[i]; + } + cb.ice_response(r, p3, p4); + } + + @Override + public void + opFloatDoubleSS_async(AMD_MyClass_opFloatDoubleSS cb, + float[][] p1, double[][] p2, + Ice.Current current) + { + float[][] p3 = p1; + double[][] p4 = new double[p2.length][]; + for(int i = 0; i < p2.length; i++) + { + p4[i] = p2[p2.length - (i + 1)]; + } + double[][] r = new double[p2.length * 2][]; + System.arraycopy(p2, 0, r, 0, p2.length); + System.arraycopy(p2, 0, r, p2.length, p2.length); + cb.ice_response(r, p3, p4); + } + + @Override + public void + opLongFloatD_async(AMD_MyClass_opLongFloatD cb, + java.util.Map<Long, Float> p1, java.util.Map<Long, Float> p2, + Ice.Current current) + { + java.util.Map<Long, Float> p3 = p1; + java.util.Map<Long, Float> r = new java.util.HashMap<Long, Float>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opMyClass_async(AMD_MyClass_opMyClass cb, + MyClassPrx p1, + Ice.Current current) + { + MyClassPrx p2 = p1; + MyClassPrx p3 = MyClassPrxHelper.uncheckedCast( + current.adapter.createProxy(current.adapter.getCommunicator().stringToIdentity("noSuchIdentity"))); + cb.ice_response(MyClassPrxHelper.uncheckedCast(current.adapter.createProxy(current.id)), p2, p3); + } + + @Override + public void + opMyEnum_async(AMD_MyClass_opMyEnum cb, + MyEnum p1, + Ice.Current current) + { + cb.ice_response(MyEnum.enum3, p1); + } + + @Override + public void + opShortIntD_async(AMD_MyClass_opShortIntD cb, + java.util.Map<Short, Integer> p1, java.util.Map<Short, Integer> p2, + Ice.Current current) + { + java.util.Map<Short, Integer> p3 = p1; + java.util.Map<Short, Integer> r = new java.util.HashMap<Short, Integer>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opShortIntLong_async(AMD_MyClass_opShortIntLong cb, + short p1, int p2, long p3, + Ice.Current current) + { + cb.ice_response(p3, p1, p2, p3); + } + + @Override + public void + opShortIntLongS_async(AMD_MyClass_opShortIntLongS cb, + short[] p1, int[] p2, long[] p3, + Ice.Current current) + { + short[] p4 = p1; + int[] p5 = new int[p2.length]; + for(int i = 0; i < p2.length; i++) + { + p5[i] = p2[p2.length - (i + 1)]; + } + long[] p6 = new long[p3.length * 2]; + System.arraycopy(p3, 0, p6, 0, p3.length); + System.arraycopy(p3, 0, p6, p3.length, p3.length); + cb.ice_response(p3, p4, p5, p6); + } + + @Override + public void + opShortIntLongSS_async(AMD_MyClass_opShortIntLongSS cb, + short[][] p1, int[][] p2, long[][] p3, + Ice.Current current) + { + short[][] p4 = p1; + int[][] p5 = new int[p2.length][]; + for(int i = 0; i < p2.length; i++) + { + p5[i] = p2[p2.length - (i + 1)]; + } + long[][] p6 = new long[p3.length * 2][]; + System.arraycopy(p3, 0, p6, 0, p3.length); + System.arraycopy(p3, 0, p6, p3.length, p3.length); + cb.ice_response(p3, p4, p5, p6); + } + + @Override + public void + opString_async(AMD_MyClass_opString cb, + String p1, String p2, + Ice.Current current) + { + cb.ice_response(p1 + " " + p2, p2 + " " + p1); + } + + @Override + public void + opStringMyEnumD_async(AMD_MyClass_opStringMyEnumD cb, + java.util.Map<String, MyEnum> p1, java.util.Map<String, MyEnum> p2, + Ice.Current current) + { + java.util.Map<String, MyEnum> p3 = p1; + java.util.Map<String, MyEnum> r = new java.util.HashMap<String, MyEnum>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opMyEnumStringD_async(AMD_MyClass_opMyEnumStringD cb, + java.util.Map<MyEnum, String> p1, java.util.Map<MyEnum, String> p2, + Ice.Current current) + { + java.util.Map<MyEnum, String> p3 = p1; + java.util.Map<MyEnum, String> r = new java.util.HashMap<MyEnum, String>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opMyStructMyEnumD_async(AMD_MyClass_opMyStructMyEnumD cb, + java.util.Map<MyStruct, MyEnum> p1, java.util.Map<MyStruct, MyEnum> p2, + Ice.Current current) + { + java.util.Map<MyStruct, MyEnum> p3 = p1; + java.util.Map<MyStruct, MyEnum> r = new java.util.HashMap<MyStruct, MyEnum>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opIntS_async(AMD_MyClass_opIntS cb, int[] s, Ice.Current current) + { + int[] r = new int[s.length]; + for(int i = 0; i < r.length; ++i) + { + r[i] = -s[i]; + } + cb.ice_response(r); + } + + @Override + public void + opByteSOneway_async(AMD_MyClass_opByteSOneway cb, byte[] s, Ice.Current current) + { + cb.ice_response(); + } + + @Override + public void + opContext_async(AMD_MyClass_opContext cb, Ice.Current current) + { + cb.ice_response(current.ctx); + } + + @Override + public void + opDoubleMarshaling_async(AMD_MyClass_opDoubleMarshaling cb, double p1, double[] p2, Ice.Current current) + { + double d = 1278312346.0 / 13.0; + test(p1 == d); + for(int i = 0; i < p2.length; ++i) + { + test(p2[i] == d); + } + cb.ice_response(); + } + + @Override + public void + opStringS_async(AMD_MyClass_opStringS cb, + String[] p1, String[] p2, + Ice.Current current) + { + String[] p3 = new String[p1.length + p2.length]; + System.arraycopy(p1, 0, p3, 0, p1.length); + System.arraycopy(p2, 0, p3, p1.length, p2.length); + + String[] r = new String[p1.length]; + for(int i = 0; i < p1.length; i++) + { + r[i] = p1[p1.length - (i + 1)]; + } + cb.ice_response(r, p3); + } + + @Override + public void + opStringSS_async(AMD_MyClass_opStringSS cb, + String[][] p1, String[][] p2, + Ice.Current current) + { + String[][] p3 = new String[p1.length + p2.length][]; + System.arraycopy(p1, 0, p3, 0, p1.length); + System.arraycopy(p2, 0, p3, p1.length, p2.length); + + String[][] r = new String[p2.length][]; + for(int i = 0; i < p2.length; i++) + { + r[i] = p2[p2.length - (i + 1)]; + } + cb.ice_response(r, p3); + } + + @Override + public void + opStringSSS_async(AMD_MyClass_opStringSSS cb, + String[][][] p1, String[][][] p2, + Ice.Current current) + { + String[][][] p3 = new String[p1.length + p2.length][][]; + System.arraycopy(p1, 0, p3, 0, p1.length); + System.arraycopy(p2, 0, p3, p1.length, p2.length); + + String[][][] r = new String[p2.length][][]; + for(int i = 0; i < p2.length; i++) + { + r[i] = p2[p2.length - (i + 1)]; + } + cb.ice_response(r, p3); + } + + @Override + public void + opStringStringD_async(AMD_MyClass_opStringStringD cb, + java.util.Map<String, String> p1, java.util.Map<String, String> p2, + Ice.Current current) + { + java.util.Map<String, String> p3 = p1; + java.util.Map<String, String> r = new java.util.HashMap<String, String>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opStruct_async(AMD_MyClass_opStruct cb, + Structure p1, Structure p2, + Ice.Current current) + { + Structure p3 = p1; + p3.s.s = "a new string"; + cb.ice_response(p2, p3); + } + + @Override + public void + opIdempotent_async(AMD_MyClass_opIdempotent cb, + Ice.Current current) + { + test(current.mode == Ice.OperationMode.Idempotent); + cb.ice_response(); + } + + @Override + public void + opNonmutating_async(AMD_MyClass_opNonmutating cb, + Ice.Current current) + { + test(current.mode == Ice.OperationMode.Nonmutating); + cb.ice_response(); + } + + @Override + public void + opDerived_async(AMD_MyDerivedClass_opDerived cb, + Ice.Current current) + { + cb.ice_response(); + } + + private Thread _opVoidThread; +} diff --git a/java/test/src/main/java/test/Ice/operations/AMDServer.java b/java/test/src/main/java/test/Ice/operations/AMDServer.java new file mode 100644 index 00000000000..063af513e84 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/AMDServer.java @@ -0,0 +1,48 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +public class AMDServer extends test.Util.Application +{ + @Override + public int run(String[] args) + { + communicator().getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.add(new AMDMyDerivedClassI(), communicator().stringToIdentity("test")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + // + // It's possible to have batch oneway requests dispatched + // after the adapter is deactivated due to thread + // scheduling so we suppress this warning. + // + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.operations.AMD"); + + return initData; + } + + public static void main(String[] args) + { + AMDServer c = new AMDServer(); + int status = c.main("AMDServer", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/operations/AMDTieMyDerivedClassI.java b/java/test/src/main/java/test/Ice/operations/AMDTieMyDerivedClassI.java new file mode 100644 index 00000000000..8d2e26b48d1 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/AMDTieMyDerivedClassI.java @@ -0,0 +1,577 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +import test.Ice.operations.AMD.Test.AMD_MyClass_opBool; +import test.Ice.operations.AMD.Test.AMD_MyClass_opBoolS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opBoolSS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opByte; +import test.Ice.operations.AMD.Test.AMD_MyClass_opByteBoolD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opByteS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opByteSOneway; +import test.Ice.operations.AMD.Test.AMD_MyClass_opByteSS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opContext; +import test.Ice.operations.AMD.Test.AMD_MyClass_opDoubleMarshaling; +import test.Ice.operations.AMD.Test.AMD_MyClass_opFloatDouble; +import test.Ice.operations.AMD.Test.AMD_MyClass_opFloatDoubleS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opFloatDoubleSS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opIdempotent; +import test.Ice.operations.AMD.Test.AMD_MyClass_opIntS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opLongFloatD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opMyClass; +import test.Ice.operations.AMD.Test.AMD_MyClass_opMyEnum; +import test.Ice.operations.AMD.Test.AMD_MyClass_opMyStructMyEnumD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opNonmutating; +import test.Ice.operations.AMD.Test.AMD_MyClass_opShortIntD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opShortIntLong; +import test.Ice.operations.AMD.Test.AMD_MyClass_opShortIntLongS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opShortIntLongSS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opString; +import test.Ice.operations.AMD.Test.AMD_MyClass_opStringMyEnumD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opMyEnumStringD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opStringS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opStringSS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opStringSSS; +import test.Ice.operations.AMD.Test.AMD_MyClass_opStringStringD; +import test.Ice.operations.AMD.Test.AMD_MyClass_opStruct; +import test.Ice.operations.AMD.Test.AMD_MyClass_opVoid; +import test.Ice.operations.AMD.Test.AMD_MyClass_shutdown; +import test.Ice.operations.AMD.Test.AMD_MyClass_delay; +import test.Ice.operations.AMD.Test.AMD_MyDerivedClass_opDerived; +import test.Ice.operations.AMD.Test.MyClassPrx; +import test.Ice.operations.AMD.Test.MyClassPrxHelper; +import test.Ice.operations.AMD.Test._MyDerivedClassOperations; +import test.Ice.operations.AMD.Test.MyEnum; +import test.Ice.operations.AMD.Test.MyStruct; +import test.Ice.operations.AMD.Test.Structure; + +public final class AMDTieMyDerivedClassI implements _MyDerivedClassOperations +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static class Thread_opVoid extends Thread + { + public + Thread_opVoid(AMD_MyClass_opVoid cb) + { + _cb = cb; + } + + @Override + public void + run() + { + _cb.ice_response(); + } + + private AMD_MyClass_opVoid _cb; + } + + @Override + synchronized public void + shutdown_async(AMD_MyClass_shutdown cb, + Ice.Current current) + { + while(_opVoidThread != null) + { + try + { + _opVoidThread.join(); + _opVoidThread = null; + } + catch(java.lang.InterruptedException ex) + { + } + } + + current.adapter.getCommunicator().shutdown(); + cb.ice_response(); + } + + @Override + public void + delay_async(AMD_MyClass_delay cb, int ms, Ice.Current current) + { + try + { + Thread.sleep(ms); + } + catch(InterruptedException ex) + { + } + cb.ice_response(); + } + + @Override + synchronized public void + opVoid_async(AMD_MyClass_opVoid cb, + Ice.Current current) + { + test(current.mode == Ice.OperationMode.Normal); + + while(_opVoidThread != null) + { + try + { + _opVoidThread.join(); + _opVoidThread = null; + } + catch(java.lang.InterruptedException ex) + { + } + } + + _opVoidThread = new Thread_opVoid(cb); + _opVoidThread.start(); + } + + @Override + public void + opBool_async(AMD_MyClass_opBool cb, + boolean p1, boolean p2, + Ice.Current current) + { + cb.ice_response(p2, p1); + } + + @Override + public void + opBoolS_async(AMD_MyClass_opBoolS cb, + boolean[] p1, boolean[] p2, + Ice.Current current) + { + boolean[] p3 = new boolean[p1.length + p2.length]; + System.arraycopy(p1, 0, p3, 0, p1.length); + System.arraycopy(p2, 0, p3, p1.length, p2.length); + + boolean[] r = new boolean[p1.length]; + for(int i = 0; i < p1.length; i++) + { + r[i] = p1[p1.length - (i + 1)]; + } + cb.ice_response(r, p3); + } + + @Override + public void + opBoolSS_async(AMD_MyClass_opBoolSS cb, + boolean[][] p1, boolean[][] p2, + Ice.Current current) + { + boolean[][] p3 = new boolean[p1.length + p2.length][]; + System.arraycopy(p1, 0, p3, 0, p1.length); + System.arraycopy(p2, 0, p3, p1.length, p2.length); + + boolean[][] r = new boolean[p1.length][]; + for(int i = 0; i < p1.length; i++) + { + r[i] = p1[p1.length - (i + 1)]; + } + cb.ice_response(r, p3); + } + + @Override + public void + opByte_async(AMD_MyClass_opByte cb, + byte p1, byte p2, + Ice.Current current) + { + cb.ice_response(p1, (byte)(p1 ^ p2)); + } + + @Override + public void + opByteBoolD_async(AMD_MyClass_opByteBoolD cb, + java.util.Map<Byte, Boolean> p1, java.util.Map<Byte, Boolean> p2, + Ice.Current current) + { + java.util.Map<Byte, Boolean> p3 = p1; + java.util.Map<Byte, Boolean> r = new java.util.HashMap<Byte, Boolean>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opByteS_async(AMD_MyClass_opByteS cb, + byte[] p1, byte[] p2, + Ice.Current current) + { + byte[] p3 = new byte[p1.length]; + for(int i = 0; i < p1.length; i++) + { + p3[i] = p1[p1.length - (i + 1)]; + } + + byte[] r = new byte[p1.length + p2.length]; + System.arraycopy(p1, 0, r, 0, p1.length); + System.arraycopy(p2, 0, r, p1.length, p2.length); + cb.ice_response(r, p3); + } + + @Override + public void + opByteSS_async(AMD_MyClass_opByteSS cb, + byte[][] p1, byte[][] p2, + Ice.Current current) + { + byte[][] p3 = new byte[p1.length][]; + for(int i = 0; i < p1.length; i++) + { + p3[i] = p1[p1.length - (i + 1)]; + } + + byte[][] r = new byte[p1.length + p2.length][]; + System.arraycopy(p1, 0, r, 0, p1.length); + System.arraycopy(p2, 0, r, p1.length, p2.length); + cb.ice_response(r, p3); + } + + @Override + public void + opFloatDouble_async(AMD_MyClass_opFloatDouble cb, + float p1, double p2, + Ice.Current current) + { + cb.ice_response(p2, p1, p2); + } + + @Override + public void + opFloatDoubleS_async(AMD_MyClass_opFloatDoubleS cb, + float[] p1, double[] p2, + Ice.Current current) + { + float[] p3 = p1; + double[] p4 = new double[p2.length]; + for(int i = 0; i < p2.length; i++) + { + p4[i] = p2[p2.length - (i + 1)]; + } + double[] r = new double[p2.length + p1.length]; + System.arraycopy(p2, 0, r, 0, p2.length); + for(int i = 0; i < p1.length; i++) + { + r[p2.length + i] = p1[i]; + } + cb.ice_response(r, p3, p4); + } + + @Override + public void + opFloatDoubleSS_async(AMD_MyClass_opFloatDoubleSS cb, + float[][] p1, double[][] p2, + Ice.Current current) + { + float[][] p3 = p1; + double[][] p4 = new double[p2.length][]; + for(int i = 0; i < p2.length; i++) + { + p4[i] = p2[p2.length - (i + 1)]; + } + double[][] r = new double[p2.length * 2][]; + System.arraycopy(p2, 0, r, 0, p2.length); + System.arraycopy(p2, 0, r, p2.length, p2.length); + cb.ice_response(r, p3, p4); + } + + @Override + public void + opLongFloatD_async(AMD_MyClass_opLongFloatD cb, + java.util.Map<Long, Float> p1, java.util.Map<Long, Float> p2, + Ice.Current current) + { + java.util.Map<Long, Float> p3 = p1; + java.util.Map<Long, Float> r = new java.util.HashMap<Long, Float>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opMyClass_async(AMD_MyClass_opMyClass cb, + MyClassPrx p1, + Ice.Current current) + { + MyClassPrx p2 = p1; + MyClassPrx p3 = MyClassPrxHelper.uncheckedCast( + current.adapter.createProxy(current.adapter.getCommunicator().stringToIdentity("noSuchIdentity"))); + cb.ice_response(MyClassPrxHelper.uncheckedCast(current.adapter.createProxy(current.id)), p2, p3); + } + + @Override + public void + opMyEnum_async(AMD_MyClass_opMyEnum cb, + MyEnum p1, + Ice.Current current) + { + cb.ice_response(MyEnum.enum3, p1); + } + + @Override + public void + opShortIntD_async(AMD_MyClass_opShortIntD cb, + java.util.Map<Short, Integer> p1, java.util.Map<Short, Integer> p2, + Ice.Current current) + { + java.util.Map<Short, Integer> p3 = p1; + java.util.Map<Short, Integer> r = new java.util.HashMap<Short, Integer>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opShortIntLong_async(AMD_MyClass_opShortIntLong cb, + short p1, int p2, long p3, + Ice.Current current) + { + cb.ice_response(p3, p1, p2, p3); + } + + @Override + public void + opShortIntLongS_async(AMD_MyClass_opShortIntLongS cb, + short[] p1, int[] p2, long[] p3, + Ice.Current current) + { + short[] p4 = p1; + int[] p5 = new int[p2.length]; + for(int i = 0; i < p2.length; i++) + { + p5[i] = p2[p2.length - (i + 1)]; + } + long[] p6 = new long[p3.length * 2]; + System.arraycopy(p3, 0, p6, 0, p3.length); + System.arraycopy(p3, 0, p6, p3.length, p3.length); + cb.ice_response(p3, p4, p5, p6); + } + + @Override + public void + opShortIntLongSS_async(AMD_MyClass_opShortIntLongSS cb, + short[][] p1, int[][] p2, long[][] p3, + Ice.Current current) + { + short[][] p4 = p1; + int[][] p5 = new int[p2.length][]; + for(int i = 0; i < p2.length; i++) + { + p5[i] = p2[p2.length - (i + 1)]; + } + long[][] p6 = new long[p3.length * 2][]; + System.arraycopy(p3, 0, p6, 0, p3.length); + System.arraycopy(p3, 0, p6, p3.length, p3.length); + cb.ice_response(p3, p4, p5, p6); + } + + @Override + public void + opString_async(AMD_MyClass_opString cb, + String p1, String p2, + Ice.Current current) + { + cb.ice_response(p1 + " " + p2, p2 + " " + p1); + } + + @Override + public void + opStringMyEnumD_async(AMD_MyClass_opStringMyEnumD cb, + java.util.Map<String, MyEnum> p1, java.util.Map<String, MyEnum> p2, + Ice.Current current) + { + java.util.Map<String, MyEnum> p3 = p1; + java.util.Map<String, MyEnum> r = new java.util.HashMap<String, MyEnum>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opMyEnumStringD_async(AMD_MyClass_opMyEnumStringD cb, + java.util.Map<MyEnum, String> p1, java.util.Map<MyEnum, String> p2, + Ice.Current current) + { + java.util.Map<MyEnum, String> p3 = p1; + java.util.Map<MyEnum, String> r = new java.util.HashMap<MyEnum, String>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opMyStructMyEnumD_async(AMD_MyClass_opMyStructMyEnumD cb, + java.util.Map<MyStruct, MyEnum> p1, java.util.Map<MyStruct, MyEnum> p2, + Ice.Current current) + { + java.util.Map<MyStruct, MyEnum> p3 = p1; + java.util.Map<MyStruct, MyEnum> r = new java.util.HashMap<MyStruct, MyEnum>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opIntS_async(AMD_MyClass_opIntS cb, int[] s, Ice.Current current) + { + int[] r = new int[s.length]; + for(int i = 0; i < r.length; ++i) + { + r[i] = -s[i]; + } + cb.ice_response(r); + } + + @Override + public void + opByteSOneway_async(AMD_MyClass_opByteSOneway cb, byte[] s, Ice.Current current) + { + cb.ice_response(); + } + + @Override + public void + opContext_async(AMD_MyClass_opContext cb, Ice.Current current) + { + cb.ice_response(current.ctx); + } + + @Override + public void + opDoubleMarshaling_async(AMD_MyClass_opDoubleMarshaling cb, double p1, double[] p2, Ice.Current current) + { + double d = 1278312346.0 / 13.0; + test(p1 == d); + for(int i = 0; i < p2.length; ++i) + { + test(p2[i] == d); + } + cb.ice_response(); + } + + @Override + public void + opStringS_async(AMD_MyClass_opStringS cb, + String[] p1, String[] p2, + Ice.Current current) + { + String[] p3 = new String[p1.length + p2.length]; + System.arraycopy(p1, 0, p3, 0, p1.length); + System.arraycopy(p2, 0, p3, p1.length, p2.length); + + String[] r = new String[p1.length]; + for(int i = 0; i < p1.length; i++) + { + r[i] = p1[p1.length - (i + 1)]; + } + cb.ice_response(r, p3); + } + + @Override + public void + opStringSS_async(AMD_MyClass_opStringSS cb, + String[][] p1, String[][] p2, + Ice.Current current) + { + String[][] p3 = new String[p1.length + p2.length][]; + System.arraycopy(p1, 0, p3, 0, p1.length); + System.arraycopy(p2, 0, p3, p1.length, p2.length); + + String[][] r = new String[p2.length][]; + for(int i = 0; i < p2.length; i++) + { + r[i] = p2[p2.length - (i + 1)]; + } + cb.ice_response(r, p3); + } + + @Override + public void + opStringSSS_async(AMD_MyClass_opStringSSS cb, + String[][][] p1, String[][][] p2, + Ice.Current current) + { + String[][][] p3 = new String[p1.length + p2.length][][]; + System.arraycopy(p1, 0, p3, 0, p1.length); + System.arraycopy(p2, 0, p3, p1.length, p2.length); + + String[][][] r = new String[p2.length][][]; + for(int i = 0; i < p2.length; i++) + { + r[i] = p2[p2.length - (i + 1)]; + } + cb.ice_response(r, p3); + } + + @Override + public void + opStringStringD_async(AMD_MyClass_opStringStringD cb, + java.util.Map<String, String> p1, java.util.Map<String, String> p2, + Ice.Current current) + { + java.util.Map<String, String> p3 = p1; + java.util.Map<String, String> r = new java.util.HashMap<String, String>(); + r.putAll(p1); + r.putAll(p2); + cb.ice_response(r, p3); + } + + @Override + public void + opStruct_async(AMD_MyClass_opStruct cb, + Structure p1, Structure p2, + Ice.Current current) + { + Structure p3 = p1; + p3.s.s = "a new string"; + cb.ice_response(p2, p3); + } + + @Override + public void + opIdempotent_async(AMD_MyClass_opIdempotent cb, + Ice.Current current) + { + test(current.mode == Ice.OperationMode.Idempotent); + cb.ice_response(); + } + + @Override + public void + opNonmutating_async(AMD_MyClass_opNonmutating cb, + Ice.Current current) + { + test(current.mode == Ice.OperationMode.Nonmutating); + cb.ice_response(); + } + + @Override + public void + opDerived_async(AMD_MyDerivedClass_opDerived cb, + Ice.Current current) + { + cb.ice_response(); + } + + private Thread _opVoidThread; +} diff --git a/java/test/src/main/java/test/Ice/operations/AMDTieServer.java b/java/test/src/main/java/test/Ice/operations/AMDTieServer.java new file mode 100644 index 00000000000..af88539eb00 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/AMDTieServer.java @@ -0,0 +1,50 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +import test.Ice.operations.AMD.Test._MyDerivedClassTie; + +public class AMDTieServer extends test.Util.Application +{ + @Override + public int run(String[] args) + { + communicator().getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.add(new _MyDerivedClassTie(new AMDTieMyDerivedClassI()), communicator().stringToIdentity("test")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + // + // It's possible to have batch oneway requests dispatched + // after the adapter is deactivated due to thread + // scheduling so we suppress this warning. + // + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.operations.AMD"); + + return initData; + } + + public static void main(String[] args) + { + AMDServer c = new AMDServer(); + int status = c.main("AMDServer", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/operations/AllTests.java b/java/test/src/main/java/test/Ice/operations/AllTests.java new file mode 100644 index 00000000000..b89c85f3745 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/AllTests.java @@ -0,0 +1,127 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; +import java.io.PrintWriter; + +import test.Ice.operations.Test.MyClassPrx; +import test.Ice.operations.Test.MyClassPrxHelper; +import test.Ice.operations.Test.MyDerivedClassPrx; +import test.Ice.operations.Test.MyDerivedClassPrxHelper; + +public class AllTests +{ + public static MyClassPrx + allTests(test.Util.Application app, PrintWriter out) + { + Ice.Communicator communicator = app.communicator(); + String ref = "test:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + MyClassPrx cl = MyClassPrxHelper.checkedCast(base); + MyDerivedClassPrx derived = MyDerivedClassPrxHelper.checkedCast(cl); + + out.print("testing twoway operations... "); + out.flush(); + Twoways.twoways(app, cl); + Twoways.twoways(app, derived); + derived.opDerived(); + out.println("ok"); + + out.print("testing oneway operations... "); + out.flush(); + Oneways.oneways(app, cl); + out.println("ok"); + + out.print("testing twoway operations with AMI... "); + out.flush(); + TwowaysAMI.twowaysAMI(app, cl); + TwowaysAMI.twowaysAMI(app, derived); + out.println("ok"); + + // + // Use reflection to load TwowaysLambdaAMI as that is only supported with Java >= 1.8 + // + try + { + Class<?> cls = IceInternal.Util.findClass("test.Ice.operations.lambda.TwowaysLambdaAMI", null); + if(cls != null) + { + java.lang.reflect.Method twowaysLambdaAMI = + cls.getDeclaredMethod("twowaysLambdaAMI", + new Class<?>[]{test.Util.Application.class, MyClassPrx.class}); + out.print("testing twoway operations with lambda AMI mapping... "); + out.flush(); + twowaysLambdaAMI.invoke(null, app, cl); + twowaysLambdaAMI.invoke(null, app, derived); + out.println("ok"); + } + } + catch(java.lang.NoSuchMethodException ex) + { + throw new RuntimeException(ex); + } + catch(java.lang.IllegalAccessException ex) + { + throw new RuntimeException(ex); + } + catch(java.lang.reflect.InvocationTargetException ex) + { + throw new RuntimeException(ex); + } + + out.print("testing oneway operations with AMI... "); + out.flush(); + OnewaysAMI.onewaysAMI(app, cl); + out.println("ok"); + + // + // Use reflection to load OnewaysLambdaAMI as that is only supported with Java >= 1.8 + // + try + { + Class<?> cls = IceInternal.Util.findClass("test.Ice.operations.lambda.OnewaysLambdaAMI", null); + if(cls != null) + { + java.lang.reflect.Method onewaysLambdaAMI = + cls.getDeclaredMethod("onewaysLambdaAMI", + new Class<?>[]{test.Util.Application.class, MyClassPrx.class}); + out.print("testing twoway operations with lambda AMI mapping... "); + out.flush(); + onewaysLambdaAMI.invoke(null, app, cl); + onewaysLambdaAMI.invoke(null, app, derived); + out.println("ok"); + } + } + catch(java.lang.NoSuchMethodException ex) + { + throw new RuntimeException(ex); + } + catch(java.lang.IllegalAccessException ex) + { + throw new RuntimeException(ex); + } + catch(java.lang.reflect.InvocationTargetException ex) + { + throw new RuntimeException(ex); + } + + out.print("testing batch oneway operations... "); + out.flush(); + BatchOneways.batchOneways(cl, out); + BatchOneways.batchOneways(derived, out); + out.println("ok"); + + out.print("testing batch AMI oneway operations... "); + out.flush(); + BatchOnewaysAMI.batchOneways(cl, out); + BatchOnewaysAMI.batchOneways(derived, out); + out.println("ok"); + return cl; + } +} diff --git a/java/test/src/main/java/test/Ice/operations/BatchOneways.java b/java/test/src/main/java/test/Ice/operations/BatchOneways.java new file mode 100644 index 00000000000..fc20955e9d2 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/BatchOneways.java @@ -0,0 +1,127 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +import java.io.PrintWriter; + +import test.Ice.operations.Test.MyClassPrx; +import test.Ice.operations.Test.MyClassPrxHelper; + +class BatchOneways +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static void + batchOneways(MyClassPrx p, PrintWriter out) + { + final byte[] bs1 = new byte[10 * 1024]; + final byte[] bs2 = new byte[99 * 1024]; + final byte[] bs3 = new byte[100 * 1024]; + + try + { + p.opByteSOneway(bs1); + } + catch(Ice.MemoryLimitException ex) + { + test(false); + } + + try + { + p.opByteSOneway(bs2); + } + catch(Ice.MemoryLimitException ex) + { + test(false); + } + + try + { + p.opByteSOneway(bs3); + test(false); + } + catch(Ice.MemoryLimitException ex) + { + } + + MyClassPrx batch = MyClassPrxHelper.uncheckedCast(p.ice_batchOneway()); + batch.ice_flushBatchRequests(); + + for(int i = 0 ; i < 30 ; ++i) + { + try + { + batch.opByteSOneway(bs1); + } + catch(Ice.MemoryLimitException ex) + { + test(false); + } + } + + if(batch.ice_getConnection() != null) + { + batch.ice_getConnection().flushBatchRequests(); + + MyClassPrx batch2 = MyClassPrxHelper.uncheckedCast(p.ice_batchOneway()); + + batch.ice_ping(); + batch2.ice_ping(); + batch.ice_flushBatchRequests(); + batch.ice_getConnection().close(false); + batch.ice_ping(); + batch2.ice_ping(); + + batch.ice_getConnection(); + batch2.ice_getConnection(); + + batch.ice_ping(); + batch.ice_getConnection().close(false); + try + { + batch.ice_ping(); + test(false); + } + catch(Ice.CloseConnectionException ex) + { + } + try + { + batch2.ice_ping(); + test(false); + } + catch(Ice.CloseConnectionException ex) + { + } + batch.ice_ping(); + batch2.ice_ping(); + } + + Ice.Identity identity = new Ice.Identity(); + identity.name = "invalid"; + Ice.ObjectPrx batch3 = batch.ice_identity(identity); + batch3.ice_ping(); + batch3.ice_flushBatchRequests(); + + // Make sure that a bogus batch request doesn't cause troubles to other ones. + batch3.ice_ping(); + batch.ice_ping(); + batch.ice_flushBatchRequests(); + batch.ice_ping(); + } +} diff --git a/java/test/src/main/java/test/Ice/operations/BatchOnewaysAMI.java b/java/test/src/main/java/test/Ice/operations/BatchOnewaysAMI.java new file mode 100644 index 00000000000..f11df72b019 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/BatchOnewaysAMI.java @@ -0,0 +1,208 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +import java.io.PrintWriter; + +import Ice.LocalException; +import test.Ice.operations.Test.Callback_MyClass_opByteSOneway; +import test.Ice.operations.Test.MyClassPrx; +import test.Ice.operations.Test.MyClassPrxHelper; + +class BatchOnewaysAMI +{ + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void called() + { + assert (!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static void test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static void batchOneways(MyClassPrx p, PrintWriter out) + { + final byte[] bs1 = new byte[10 * 1024]; + final byte[] bs2 = new byte[99 * 1024]; + final byte[] bs3 = new byte[100 * 1024]; + + final Callback cb = new Callback(); + p.begin_opByteSOneway(bs1, new Callback_MyClass_opByteSOneway() + { + @Override + public void exception(LocalException ex) + { + test(false); + } + + @Override + public void response() + { + cb.called(); + } + }); + cb.check(); + p.begin_opByteSOneway(bs2, new Callback_MyClass_opByteSOneway() + { + @Override + public void exception(LocalException ex) + { + test(false); + } + + @Override + public void response() + { + cb.called(); + } + }); + cb.check(); + + p.begin_opByteSOneway(bs3, new Callback_MyClass_opByteSOneway() + { + @Override + public void exception(LocalException ex) + { + test(ex instanceof Ice.MemoryLimitException); + cb.called(); + } + + @Override + public void response() + { + test(false); + } + }); + cb.check(); + + MyClassPrx batch = MyClassPrxHelper.uncheckedCast(p.ice_batchOneway()); + batch.end_ice_flushBatchRequests(batch.begin_ice_flushBatchRequests()); + + for(int i = 0; i < 30; ++i) + { + batch.begin_opByteSOneway(bs1, new Callback_MyClass_opByteSOneway() + { + @Override + public void exception(LocalException ex) + { + test(false); + } + + @Override + public void response() + { + } + }); + } + + if(batch.ice_getConnection() != null) + { + batch.ice_getConnection().end_flushBatchRequests(batch.ice_getConnection().begin_flushBatchRequests()); + + MyClassPrx batch2 = MyClassPrxHelper.uncheckedCast(p.ice_batchOneway()); + + batch.begin_ice_ping(); + batch2.begin_ice_ping(); + batch.end_ice_flushBatchRequests(batch.begin_ice_flushBatchRequests()); + batch.ice_getConnection().close(false); + batch.begin_ice_ping(); + batch2.begin_ice_ping(); + + batch.ice_getConnection(); + batch2.ice_getConnection(); + + batch.begin_ice_ping(); + batch.ice_getConnection().close(false); + batch.begin_ice_ping(new Ice.Callback_Object_ice_ping() + { + + @Override + public void response() + { + test(false); + } + + @Override + public void exception(LocalException ex) + { + test(ex instanceof Ice.CloseConnectionException); + cb.called(); + } + + }); + cb.check(); + batch2.begin_ice_ping(new Ice.Callback_Object_ice_ping() + { + + @Override + public void response() + { + test(false); + } + + @Override + public void exception(LocalException ex) + { + test(ex instanceof Ice.CloseConnectionException); + cb.called(); + } + + }); + cb.check(); + batch.begin_ice_ping(); + batch2.begin_ice_ping(); + } + + Ice.Identity identity = new Ice.Identity(); + identity.name = "invalid"; + Ice.ObjectPrx batch3 = batch.ice_identity(identity); + batch3.begin_ice_ping(); + batch3.end_ice_flushBatchRequests(batch3.begin_ice_flushBatchRequests()); + + // Make sure that a bogus batch request doesn't cause troubles to other + // ones. + batch3.begin_ice_ping(); + batch.begin_ice_ping(); + batch.end_ice_flushBatchRequests(batch.begin_ice_flushBatchRequests()); + batch.begin_ice_ping(); + } +} diff --git a/java/test/src/main/java/test/Ice/operations/Client.java b/java/test/src/main/java/test/Ice/operations/Client.java new file mode 100644 index 00000000000..2c957a13e34 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/Client.java @@ -0,0 +1,63 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +import test.Ice.operations.Test.MyClassPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + java.io.PrintWriter out = getWriter(); + MyClassPrx myClass = AllTests.allTests(this, out); + + out.print("testing server shutdown... "); + out.flush(); + myClass.shutdown(); + try + { + myClass.opVoid(); + throw new RuntimeException(); + } + catch(Ice.LocalException ex) + { + out.println("ok"); + } + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.ThreadPool.Client.Size", "2"); + initData.properties.setProperty("Ice.ThreadPool.Client.SizeWarn", "0"); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.operations"); + // + // We must set MessageSizeMax to an explicit values, + // because we run tests to check whether + // Ice.MemoryLimitException is raised as expected. + // + initData.properties.setProperty("Ice.MessageSizeMax", "100"); + return initData; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/operations/Collocated.java b/java/test/src/main/java/test/Ice/operations/Collocated.java new file mode 100644 index 00000000000..ecfab090c8c --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/Collocated.java @@ -0,0 +1,69 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +public class Collocated extends test.Util.Application +{ + @Override + public int run(String[] args) + { + communicator().getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + java.io.PrintWriter out = getWriter(); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + Ice.ObjectPrx prx = adapter.add(new MyDerivedClassI(), communicator().stringToIdentity("test")); + adapter.activate(); + + if(prx.ice_getConnection() != null) + { + throw new RuntimeException(); + } + + AllTests.allTests(this, out); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + if(initData.properties.getPropertyAsInt("Ice.ThreadInterruptSafe") > 0) + { + initData.properties.setProperty("Ice.ThreadPool.Server.Size", "2"); + } + initData.properties.setProperty("Ice.Package.Test", "test.Ice.operations"); + + // + // We must set MessageSizeMax to an explicit values, + // because we run tests to check whether + // Ice.MemoryLimitException is raised as expected. + // + initData.properties.setProperty("Ice.MessageSizeMax", "100"); + + // + // Its possible to have batch oneway requests dispatched + // after the adapter is deactivated due to thread + // scheduling so we supress this warning. + // + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + + return initData; + } + + public static void main(String[] args) + { + Collocated c = new Collocated(); + int status = c.main("Collocated", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/operations/MyDerivedClassI.java b/java/test/src/main/java/test/Ice/operations/MyDerivedClassI.java new file mode 100644 index 00000000000..5fddb73a3d5 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/MyDerivedClassI.java @@ -0,0 +1,547 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +import test.Ice.operations.Test.BoolSHolder; +import test.Ice.operations.Test.BoolSSHolder; +import test.Ice.operations.Test.ByteBoolDHolder; +import test.Ice.operations.Test.ByteSHolder; +import test.Ice.operations.Test.ByteSSHolder; +import test.Ice.operations.Test.DoubleSHolder; +import test.Ice.operations.Test.DoubleSSHolder; +import test.Ice.operations.Test.FloatSHolder; +import test.Ice.operations.Test.FloatSSHolder; +import test.Ice.operations.Test.IntSHolder; +import test.Ice.operations.Test.IntSSHolder; +import test.Ice.operations.Test.LongFloatDHolder; +import test.Ice.operations.Test.LongSHolder; +import test.Ice.operations.Test.LongSSHolder; +import test.Ice.operations.Test.MyClassPrx; +import test.Ice.operations.Test.MyClassPrxHelper; +import test.Ice.operations.Test.MyClassPrxHolder; +import test.Ice.operations.Test.MyDerivedClass; +import test.Ice.operations.Test.MyEnum; +import test.Ice.operations.Test.MyEnumHolder; +import test.Ice.operations.Test.MyStruct; +import test.Ice.operations.Test.MyStructMyEnumDHolder; +import test.Ice.operations.Test.ShortIntDHolder; +import test.Ice.operations.Test.ShortSHolder; +import test.Ice.operations.Test.ShortSSHolder; +import test.Ice.operations.Test.StringMyEnumDHolder; +import test.Ice.operations.Test.MyEnumStringDHolder; +import test.Ice.operations.Test.StringSHolder; +import test.Ice.operations.Test.StringSSHolder; +import test.Ice.operations.Test.StringSSSHolder; +import test.Ice.operations.Test.StringStringDHolder; +import test.Ice.operations.Test.Structure; +import test.Ice.operations.Test.StructureHolder; + +public final class MyDerivedClassI extends MyDerivedClass +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + // + // Override the Object "pseudo" operations to verify the operation mode. + // + + @Override + public boolean + ice_isA(String id, Ice.Current current) + { + test(current.mode == Ice.OperationMode.Nonmutating); + return super.ice_isA(id, current); + } + + @Override + public void + ice_ping(Ice.Current current) + { + test(current.mode == Ice.OperationMode.Nonmutating); + super.ice_ping(current); + } + + @Override + public String[] + ice_ids(Ice.Current current) + { + test(current.mode == Ice.OperationMode.Nonmutating); + return super.ice_ids(current); + } + + @Override + public String + ice_id(Ice.Current current) + { + test(current.mode == Ice.OperationMode.Nonmutating); + return super.ice_id(current); + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + @Override + public void + delay(int ms, Ice.Current current) + { + try + { + Thread.sleep(ms); + } + catch(InterruptedException ex) + { + } + } + + @Override + public void + opVoid(Ice.Current current) + { + test(current.mode == Ice.OperationMode.Normal); + } + + @Override + public boolean + opBool(boolean p1, boolean p2, + Ice.BooleanHolder p3, + Ice.Current current) + { + p3.value = p1; + return p2; + } + + @Override + public boolean[] + opBoolS(boolean[] p1, boolean[] p2, + BoolSHolder p3, + Ice.Current current) + { + p3.value = new boolean[p1.length + p2.length]; + System.arraycopy(p1, 0, p3.value, 0, p1.length); + System.arraycopy(p2, 0, p3.value, p1.length, p2.length); + + boolean[] r = new boolean[p1.length]; + for(int i = 0; i < p1.length; i++) + { + r[i] = p1[p1.length - (i + 1)]; + } + return r; + } + + @Override + public boolean[][] + opBoolSS(boolean[][] p1, boolean[][] p2, + BoolSSHolder p3, + Ice.Current current) + { + p3.value = new boolean[p1.length + p2.length][]; + System.arraycopy(p1, 0, p3.value, 0, p1.length); + System.arraycopy(p2, 0, p3.value, p1.length, p2.length); + + boolean[][] r = new boolean[p1.length][]; + for(int i = 0; i < p1.length; i++) + { + r[i] = p1[p1.length - (i + 1)]; + } + return r; + } + + @Override + public byte + opByte(byte p1, byte p2, + Ice.ByteHolder p3, + Ice.Current current) + { + p3.value = (byte)(p1 ^ p2); + return p1; + } + + @Override + public java.util.Map<Byte, Boolean> + opByteBoolD(java.util.Map<Byte, Boolean> p1, java.util.Map<Byte, Boolean> p2, ByteBoolDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<Byte, Boolean> r = new java.util.HashMap<Byte, Boolean>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public byte[] + opByteS(byte[] p1, byte[] p2, + ByteSHolder p3, + Ice.Current current) + { + p3.value = new byte[p1.length]; + for(int i = 0; i < p1.length; i++) + { + p3.value[i] = p1[p1.length - (i + 1)]; + } + + byte[] r = new byte[p1.length + p2.length]; + System.arraycopy(p1, 0, r, 0, p1.length); + System.arraycopy(p2, 0, r, p1.length, p2.length); + return r; + } + + @Override + public byte[][] + opByteSS(byte[][] p1, byte[][] p2, + ByteSSHolder p3, + Ice.Current current) + { + p3.value = new byte[p1.length][]; + for(int i = 0; i < p1.length; i++) + { + p3.value[i] = p1[p1.length - (i + 1)]; + } + + byte[][] r = new byte[p1.length + p2.length][]; + System.arraycopy(p1, 0, r, 0, p1.length); + System.arraycopy(p2, 0, r, p1.length, p2.length); + return r; + } + + @Override + public double + opFloatDouble(float p1, double p2, + Ice.FloatHolder p3, Ice.DoubleHolder p4, + Ice.Current current) + { + p3.value = p1; + p4.value = p2; + return p2; + } + + @Override + public double[] + opFloatDoubleS(float[] p1, double[] p2, + FloatSHolder p3, DoubleSHolder p4, + Ice.Current current) + { + p3.value = p1; + p4.value = new double[p2.length]; + for(int i = 0; i < p2.length; i++) + { + p4.value[i] = p2[p2.length - (i + 1)]; + } + double[] r = new double[p2.length + p1.length]; + System.arraycopy(p2, 0, r, 0, p2.length); + for(int i = 0; i < p1.length; i++) + { + r[p2.length + i] = p1[i]; + } + return r; + } + + @Override + public double[][] + opFloatDoubleSS(float[][] p1, double[][] p2, + FloatSSHolder p3, DoubleSSHolder p4, + Ice.Current current) + { + p3.value = p1; + p4.value = new double[p2.length][]; + for(int i = 0; i < p2.length; i++) + { + p4.value[i] = p2[p2.length - (i + 1)]; + } + double[][] r = new double[p2.length * 2][]; + System.arraycopy(p2, 0, r, 0, p2.length); + System.arraycopy(p2, 0, r, p2.length, p2.length); + return r; + } + + @Override + public java.util.Map<Long, Float> + opLongFloatD(java.util.Map<Long, Float> p1, java.util.Map<Long, Float> p2, LongFloatDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<Long, Float> r = new java.util.HashMap<Long, Float>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public MyClassPrx + opMyClass(MyClassPrx p1, + MyClassPrxHolder p2, MyClassPrxHolder p3, + Ice.Current current) + { + p2.value = p1; + p3.value = MyClassPrxHelper.uncheckedCast( + current.adapter.createProxy(current.adapter.getCommunicator().stringToIdentity("noSuchIdentity"))); + return MyClassPrxHelper.uncheckedCast(current.adapter.createProxy(current.id)); + } + + @Override + public MyEnum + opMyEnum(MyEnum p1, + MyEnumHolder p2, + Ice.Current current) + { + p2.value = p1; + return MyEnum.enum3; + } + + @Override + public java.util.Map<Short, Integer> + opShortIntD(java.util.Map<Short, Integer> p1, java.util.Map<Short, Integer> p2, ShortIntDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<Short, Integer> r = new java.util.HashMap<Short, Integer>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public long + opShortIntLong(short p1, int p2, long p3, + Ice.ShortHolder p4, Ice.IntHolder p5, Ice.LongHolder p6, + Ice.Current current) + { + p4.value = p1; + p5.value = p2; + p6.value = p3; + return p3; + } + + @Override + public long[] + opShortIntLongS(short[] p1, int[] p2, long[] p3, + ShortSHolder p4, IntSHolder p5, LongSHolder p6, + Ice.Current current) + { + p4.value = p1; + p5.value = new int[p2.length]; + for(int i = 0; i < p2.length; i++) + { + p5.value[i] = p2[p2.length - (i + 1)]; + } + p6.value = new long[p3.length * 2]; + System.arraycopy(p3, 0, p6.value, 0, p3.length); + System.arraycopy(p3, 0, p6.value, p3.length, p3.length); + return p3; + } + + @Override + public long[][] + opShortIntLongSS(short[][] p1, int[][] p2, long[][] p3, + ShortSSHolder p4, IntSSHolder p5, LongSSHolder p6, + Ice.Current current) + { + p4.value = p1; + p5.value = new int[p2.length][]; + for(int i = 0; i < p2.length; i++) + { + p5.value[i] = p2[p2.length - (i + 1)]; + } + p6.value = new long[p3.length * 2][]; + System.arraycopy(p3, 0, p6.value, 0, p3.length); + System.arraycopy(p3, 0, p6.value, p3.length, p3.length); + return p3; + } + + @Override + public String + opString(String p1, String p2, + Ice.StringHolder p3, + Ice.Current current) + { + p3.value = p2 + " " + p1; + return p1 + " " + p2; + } + + @Override + public java.util.Map<String, MyEnum> + opStringMyEnumD(java.util.Map<String, MyEnum> p1, java.util.Map<String, MyEnum> p2, StringMyEnumDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<String, MyEnum> r = new java.util.HashMap<String, MyEnum>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public java.util.Map<MyEnum, String> + opMyEnumStringD(java.util.Map<MyEnum, String> p1, java.util.Map<MyEnum, String> p2, MyEnumStringDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<MyEnum, String> r = new java.util.HashMap<MyEnum, String>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public java.util.Map<MyStruct, MyEnum> + opMyStructMyEnumD(java.util.Map<MyStruct, MyEnum> p1, java.util.Map<MyStruct, MyEnum> p2, MyStructMyEnumDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<MyStruct, MyEnum> r = new java.util.HashMap<MyStruct, MyEnum>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public int[] + opIntS(int[] s, Ice.Current current) + { + int[] r = new int[s.length]; + for(int i = 0; i < r.length; ++i) + { + r[i] = -s[i]; + } + return r; + } + + @Override + public void + opByteSOneway(byte[] s, Ice.Current current) + { + } + + @Override + public java.util.Map<String, String> + opContext(Ice.Current current) + { + return current.ctx; + } + + @Override + public void + opDoubleMarshaling(double p1, double[] p2, Ice.Current current) + { + double d = 1278312346.0 / 13.0; + test(p1 == d); + for(int i = 0; i < p2.length; ++i) + { + test(p2[i] == d); + } + } + + @Override + public String[] + opStringS(String[] p1, String[] p2, + StringSHolder p3, + Ice.Current current) + { + p3.value = new String[p1.length + p2.length]; + System.arraycopy(p1, 0, p3.value, 0, p1.length); + System.arraycopy(p2, 0, p3.value, p1.length, p2.length); + + String[] r = new String[p1.length]; + for(int i = 0; i < p1.length; i++) + { + r[i] = p1[p1.length - (i + 1)]; + } + return r; + } + + @Override + public String[][] + opStringSS(String[][] p1, String[][] p2, + StringSSHolder p3, + Ice.Current current) + { + p3.value = new String[p1.length + p2.length][]; + System.arraycopy(p1, 0, p3.value, 0, p1.length); + System.arraycopy(p2, 0, p3.value, p1.length, p2.length); + + String[][] r = new String[p2.length][]; + for(int i = 0; i < p2.length; i++) + { + r[i] = p2[p2.length - (i + 1)]; + } + return r; + } + + @Override + public String[][][] + opStringSSS(String[][][] p1, String[][][] p2, + StringSSSHolder p3, + Ice.Current current) + { + p3.value = new String[p1.length + p2.length][][]; + System.arraycopy(p1, 0, p3.value, 0, p1.length); + System.arraycopy(p2, 0, p3.value, p1.length, p2.length); + + String[][][] r = new String[p2.length][][]; + for(int i = 0; i < p2.length; i++) + { + r[i] = p2[p2.length - (i + 1)]; + } + return r; + } + + @Override + public java.util.Map<String, String> + opStringStringD(java.util.Map<String, String> p1, java.util.Map<String, String> p2, StringStringDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<String, String> r = new java.util.HashMap<String, String>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public Structure + opStruct(Structure p1, Structure p2, + StructureHolder p3, + Ice.Current current) + { + p3.value = p1; + p3.value.s.s = "a new string"; + return p2; + } + + @Override + public void + opIdempotent(Ice.Current current) + { + test(current.mode == Ice.OperationMode.Idempotent); + } + + @Override + public void + opNonmutating(Ice.Current current) + { + test(current.mode == Ice.OperationMode.Nonmutating); + } + + @Override + public void + opDerived(Ice.Current current) + { + } +} diff --git a/java/test/src/main/java/test/Ice/operations/Oneways.java b/java/test/src/main/java/test/Ice/operations/Oneways.java new file mode 100644 index 00000000000..ded8ee39b3d --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/Oneways.java @@ -0,0 +1,60 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +import test.Ice.operations.Test.MyClassPrx; +import test.Ice.operations.Test.MyClassPrxHelper; + +class Oneways +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static void + oneways(test.Util.Application app, MyClassPrx p) + { + p = MyClassPrxHelper.uncheckedCast(p.ice_oneway()); + + { + p.ice_ping(); + } + + { + p.opVoid(); + } + + { + p.opIdempotent(); + } + + { + p.opNonmutating(); + } + + { + + Ice.ByteHolder b = new Ice.ByteHolder(); + try + { + p.opByte((byte)0xff, (byte)0x0f, b); + test(false); + } + catch(Ice.TwowayOnlyException ex) + { + } + } + } +} diff --git a/java/test/src/main/java/test/Ice/operations/OnewaysAMI.java b/java/test/src/main/java/test/Ice/operations/OnewaysAMI.java new file mode 100644 index 00000000000..dfaca37f114 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/OnewaysAMI.java @@ -0,0 +1,244 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +import test.Ice.operations.Test.Callback_MyClass_opIdempotent; +import test.Ice.operations.Test.Callback_MyClass_opNonmutating; +import test.Ice.operations.Test.Callback_MyClass_opVoid; +import test.Ice.operations.Test.MyClassPrx; + +class OnewaysAMI +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class CallbackBase + { + CallbackBase() + { + _called = false; + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + static class Callback extends CallbackBase + { + public Callback() + { + } + + public void + sent(boolean sentSynchronously) + { + called(); + } + + void noException(Ice.LocalException ex) + { + test(false); + } + } + + static void + onewaysAMI(test.Util.Application app, MyClassPrx proxy) + { + MyClassPrx p = (MyClassPrx)proxy.ice_oneway(); + + { + final Callback cb = new Callback(); + Ice.Callback_Object_ice_ping callback = new Ice.Callback_Object_ice_ping() + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.noException(ex); + } + + @Override + public void + sent(boolean sentSynchronously) + { + cb.sent(sentSynchronously); + } + }; + p.begin_ice_ping(callback); + cb.check(); + } + + { + try + { + p.begin_ice_isA("::Test::MyClass"); + test(false); + } + catch(java.lang.IllegalArgumentException ex) + { + } + } + + { + try + { + p.begin_ice_id(); + test(false); + } + catch(java.lang.IllegalArgumentException ex) + { + } + } + + { + try + { + p.begin_ice_ids(); + test(false); + } + catch(java.lang.IllegalArgumentException ex) + { + } + } + + { + final Callback cb = new Callback(); + Callback_MyClass_opVoid callback = new Callback_MyClass_opVoid() + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.noException(ex); + } + + @Override + public void + sent(boolean sentSynchronously) + { + cb.sent(sentSynchronously); + } + }; + p.begin_opVoid(callback); + cb.check(); + } + + { + final Callback cb = new Callback(); + Callback_MyClass_opIdempotent callback = new Callback_MyClass_opIdempotent() + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.noException(ex); + } + + @Override + public void + sent(boolean sentSynchronously) + { + cb.sent(sentSynchronously); + } + }; + p.begin_opIdempotent(callback); + cb.check(); + } + + { + final Callback cb = new Callback(); + Callback_MyClass_opNonmutating callback = new Callback_MyClass_opNonmutating() + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException ex) + { + cb.noException(ex); + } + + @Override + public void + sent(boolean sentSynchronously) + { + cb.sent(sentSynchronously); + } + }; + p.begin_opNonmutating(callback); + cb.check(); + } + + { + try + { + p.begin_opByte((byte)0xff, (byte)0x0f); + test(false); + } + catch(java.lang.IllegalArgumentException ex) + { + } + } + } +} diff --git a/java/test/src/main/java/test/Ice/operations/Server.java b/java/test/src/main/java/test/Ice/operations/Server.java new file mode 100644 index 00000000000..22dba1da02b --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/Server.java @@ -0,0 +1,47 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + communicator().getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.add(new MyDerivedClassI(), communicator().stringToIdentity("test")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + // + // It's possible to have batch oneway requests dispatched + // after the adapter is deactivated due to thread + // scheduling so we suppress this warning. + // + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.operations"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/operations/Test.ice b/java/test/src/main/java/test/Ice/operations/Test.ice new file mode 100644 index 00000000000..38ab55f5909 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/Test.ice @@ -0,0 +1,180 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/Current.ice> + +[["java:package:test.Ice.operations"]] +module Test +{ + +enum MyEnum +{ + enum1, + enum2, + enum3 +}; + +class MyClass; + +struct AnotherStruct +{ + string s; +}; + +struct Structure +{ + MyClass* p; + MyEnum e; + AnotherStruct s; +}; + +sequence<byte> ByteS; +sequence<bool> BoolS; +sequence<short> ShortS; +sequence<int> IntS; +sequence<long> LongS; +sequence<float> FloatS; +sequence<double> DoubleS; +sequence<string> StringS; +sequence<MyEnum> MyEnumS; +sequence<MyClass*> MyClassS; + +sequence<ByteS> ByteSS; +sequence<BoolS> BoolSS; +sequence<ShortS> ShortSS; +sequence<IntS> IntSS; +sequence<LongS> LongSS; +sequence<FloatS> FloatSS; +sequence<DoubleS> DoubleSS; +sequence<StringS> StringSS; +sequence<MyEnumS> MyEnumSS; +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<MyEnum, string> MyEnumStringD; +dictionary<MyStruct, MyEnum> MyStructMyEnumD; + +class MyClass +{ + void shutdown(); + + void delay(int ms); + + void opVoid(); + + byte opByte(byte p1, byte p2, + out byte p3); + + bool opBool(bool p1, bool p2, + out bool p3); + + long opShortIntLong(short p1, int p2, long p3, + out short p4, out int p5, out long p6); + + double opFloatDouble(float p1, double p2, + out float p3, out double p4); + + string opString(string p1, string p2, + out string p3); + + MyEnum opMyEnum(MyEnum p1, out MyEnum p2); + + MyClass* opMyClass(MyClass* p1, out MyClass* p2, out MyClass* p3); + + Structure opStruct(Structure p1, Structure p2, + out Structure p3); + + ByteS opByteS(ByteS p1, ByteS p2, + out ByteS p3); + + BoolS opBoolS(BoolS p1, BoolS p2, + out BoolS p3); + + LongS opShortIntLongS(Test::ShortS p1, IntS p2, LongS p3, + out ::Test::ShortS p4, out IntS p5, out LongS p6); + + DoubleS opFloatDoubleS(FloatS p1, DoubleS p2, + out FloatS p3, out DoubleS p4); + + StringS opStringS(StringS p1, StringS p2, + out StringS p3); + + ByteSS opByteSS(ByteSS p1, ByteSS p2, + out ByteSS p3); + + BoolSS opBoolSS(BoolSS p1, BoolSS p2, + out BoolSS p3); + + LongSS opShortIntLongSS(ShortSS p1, IntSS p2, LongSS p3, + out ShortSS p4, out IntSS p5, out LongSS p6); + + + DoubleSS opFloatDoubleSS(FloatSS p1, DoubleSS p2, + out FloatSS p3, out DoubleSS p4); + + StringSS opStringSS(StringSS p1, StringSS p2, + out StringSS p3); + + StringSSS opStringSSS(StringSSS p1, StringSSS p2, + out StringSSS p3); + + ByteBoolD opByteBoolD(ByteBoolD p1, ByteBoolD p2, + out ByteBoolD p3); + + ShortIntD opShortIntD(ShortIntD p1, ShortIntD p2, + out ShortIntD p3); + + LongFloatD opLongFloatD(LongFloatD p1, LongFloatD p2, + out LongFloatD p3); + + StringStringD opStringStringD(StringStringD p1, StringStringD p2, + out StringStringD p3); + + StringMyEnumD opStringMyEnumD(StringMyEnumD p1, StringMyEnumD p2, + out StringMyEnumD p3); + + MyEnumStringD opMyEnumStringD(MyEnumStringD p1, MyEnumStringD p2, + out MyEnumStringD p3); + + MyStructMyEnumD opMyStructMyEnumD(MyStructMyEnumD p1, MyStructMyEnumD p2, + out MyStructMyEnumD p3); + + IntS opIntS(IntS s); + + void opByteSOneway(ByteS s); + + Ice::Context opContext(); + + void opDoubleMarshaling(double p1, DoubleS p2); + + idempotent void opIdempotent(); + + ["nonmutating"] idempotent void opNonmutating(); +}; + +class MyDerivedClass extends MyClass +{ + void opDerived(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/operations/TestAMD.ice b/java/test/src/main/java/test/Ice/operations/TestAMD.ice new file mode 100644 index 00000000000..edcb970b236 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/TestAMD.ice @@ -0,0 +1,180 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/Current.ice> + +[["java:package:test.Ice.operations.AMD"]] +module Test +{ + +enum MyEnum +{ + enum1, + enum2, + enum3 +}; + +class MyClass; + +struct AnotherStruct +{ + string s; +}; + +struct Structure +{ + MyClass* p; + MyEnum e; + AnotherStruct s; +}; + +sequence<byte> ByteS; +sequence<bool> BoolS; +sequence<short> ShortS; +sequence<int> IntS; +sequence<long> LongS; +sequence<float> FloatS; +sequence<double> DoubleS; +sequence<string> StringS; +sequence<MyEnum> MyEnumS; +sequence<MyClass*> MyClassS; + +sequence<ByteS> ByteSS; +sequence<BoolS> BoolSS; +sequence<ShortS> ShortSS; +sequence<IntS> IntSS; +sequence<LongS> LongSS; +sequence<FloatS> FloatSS; +sequence<DoubleS> DoubleSS; +sequence<StringS> StringSS; +sequence<MyEnumS> MyEnumSS; +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<MyEnum, string> MyEnumStringD; +dictionary<MyStruct, MyEnum> MyStructMyEnumD; + +["amd"] class MyClass +{ + void shutdown(); + + void delay(int ms); + + void opVoid(); + + byte opByte(byte p1, byte p2, + out byte p3); + + bool opBool(bool p1, bool p2, + out bool p3); + + long opShortIntLong(short p1, int p2, long p3, + out short p4, out int p5, out long p6); + + double opFloatDouble(float p1, double p2, + out float p3, out double p4); + + string opString(string p1, string p2, + out string p3); + + MyEnum opMyEnum(MyEnum p1, out MyEnum p2); + + MyClass* opMyClass(MyClass* p1, out MyClass* p2, out MyClass* p3); + + Structure opStruct(Structure p1, Structure p2, + out Structure p3); + + ByteS opByteS(ByteS p1, ByteS p2, + out ByteS p3); + + BoolS opBoolS(BoolS p1, BoolS p2, + out BoolS p3); + + LongS opShortIntLongS(Test::ShortS p1, IntS p2, LongS p3, + out ::Test::ShortS p4, out IntS p5, out LongS p6); + + DoubleS opFloatDoubleS(FloatS p1, DoubleS p2, + out FloatS p3, out DoubleS p4); + + StringS opStringS(StringS p1, StringS p2, + out StringS p3); + + ByteSS opByteSS(ByteSS p1, ByteSS p2, + out ByteSS p3); + + BoolSS opBoolSS(BoolSS p1, BoolSS p2, + out BoolSS p3); + + LongSS opShortIntLongSS(ShortSS p1, IntSS p2, LongSS p3, + out ShortSS p4, out IntSS p5, out LongSS p6); + + + DoubleSS opFloatDoubleSS(FloatSS p1, DoubleSS p2, + out FloatSS p3, out DoubleSS p4); + + StringSS opStringSS(StringSS p1, StringSS p2, + out StringSS p3); + + StringSSS opStringSSS(StringSSS p1, StringSSS p2, + out StringSSS p3); + + ByteBoolD opByteBoolD(ByteBoolD p1, ByteBoolD p2, + out ByteBoolD p3); + + ShortIntD opShortIntD(ShortIntD p1, ShortIntD p2, + out ShortIntD p3); + + LongFloatD opLongFloatD(LongFloatD p1, LongFloatD p2, + out LongFloatD p3); + + StringStringD opStringStringD(StringStringD p1, StringStringD p2, + out StringStringD p3); + + StringMyEnumD opStringMyEnumD(StringMyEnumD p1, StringMyEnumD p2, + out StringMyEnumD p3); + + MyEnumStringD opMyEnumStringD(MyEnumStringD p1, MyEnumStringD p2, + out MyEnumStringD p3); + + MyStructMyEnumD opMyStructMyEnumD(MyStructMyEnumD p1, MyStructMyEnumD p2, + out MyStructMyEnumD p3); + + IntS opIntS(IntS s); + + void opByteSOneway(ByteS s); + + Ice::Context opContext(); + + void opDoubleMarshaling(double p1, DoubleS p2); + + idempotent void opIdempotent(); + + ["nonmutating"] idempotent void opNonmutating(); +}; + +["amd"] class MyDerivedClass extends MyClass +{ + void opDerived(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/operations/TieMyDerivedClassI.java b/java/test/src/main/java/test/Ice/operations/TieMyDerivedClassI.java new file mode 100644 index 00000000000..cbd7a833f15 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/TieMyDerivedClassI.java @@ -0,0 +1,511 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +import test.Ice.operations.Test.BoolSHolder; +import test.Ice.operations.Test.BoolSSHolder; +import test.Ice.operations.Test.ByteBoolDHolder; +import test.Ice.operations.Test.ByteSHolder; +import test.Ice.operations.Test.ByteSSHolder; +import test.Ice.operations.Test.DoubleSHolder; +import test.Ice.operations.Test.DoubleSSHolder; +import test.Ice.operations.Test.FloatSHolder; +import test.Ice.operations.Test.FloatSSHolder; +import test.Ice.operations.Test.IntSHolder; +import test.Ice.operations.Test.IntSSHolder; +import test.Ice.operations.Test.LongFloatDHolder; +import test.Ice.operations.Test.LongSHolder; +import test.Ice.operations.Test.LongSSHolder; +import test.Ice.operations.Test.MyClassPrx; +import test.Ice.operations.Test.MyClassPrxHelper; +import test.Ice.operations.Test.MyClassPrxHolder; +import test.Ice.operations.Test._MyDerivedClassOperations; +import test.Ice.operations.Test.MyEnum; +import test.Ice.operations.Test.MyEnumHolder; +import test.Ice.operations.Test.MyStruct; +import test.Ice.operations.Test.MyStructMyEnumDHolder; +import test.Ice.operations.Test.ShortIntDHolder; +import test.Ice.operations.Test.ShortSHolder; +import test.Ice.operations.Test.ShortSSHolder; +import test.Ice.operations.Test.StringMyEnumDHolder; +import test.Ice.operations.Test.MyEnumStringDHolder; +import test.Ice.operations.Test.StringSHolder; +import test.Ice.operations.Test.StringSSHolder; +import test.Ice.operations.Test.StringSSSHolder; +import test.Ice.operations.Test.StringStringDHolder; +import test.Ice.operations.Test.Structure; +import test.Ice.operations.Test.StructureHolder; + +public final class TieMyDerivedClassI implements _MyDerivedClassOperations +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + @Override + public void + delay(int ms, Ice.Current current) + { + try + { + Thread.sleep(ms); + } + catch(InterruptedException ex) + { + } + } + + @Override + public void + opVoid(Ice.Current current) + { + test(current.mode == Ice.OperationMode.Normal); + } + + @Override + public boolean + opBool(boolean p1, boolean p2, + Ice.BooleanHolder p3, + Ice.Current current) + { + p3.value = p1; + return p2; + } + + @Override + public boolean[] + opBoolS(boolean[] p1, boolean[] p2, + BoolSHolder p3, + Ice.Current current) + { + p3.value = new boolean[p1.length + p2.length]; + System.arraycopy(p1, 0, p3.value, 0, p1.length); + System.arraycopy(p2, 0, p3.value, p1.length, p2.length); + + boolean[] r = new boolean[p1.length]; + for(int i = 0; i < p1.length; i++) + { + r[i] = p1[p1.length - (i + 1)]; + } + return r; + } + + @Override + public boolean[][] + opBoolSS(boolean[][] p1, boolean[][] p2, + BoolSSHolder p3, + Ice.Current current) + { + p3.value = new boolean[p1.length + p2.length][]; + System.arraycopy(p1, 0, p3.value, 0, p1.length); + System.arraycopy(p2, 0, p3.value, p1.length, p2.length); + + boolean[][] r = new boolean[p1.length][]; + for(int i = 0; i < p1.length; i++) + { + r[i] = p1[p1.length - (i + 1)]; + } + return r; + } + + @Override + public byte + opByte(byte p1, byte p2, + Ice.ByteHolder p3, + Ice.Current current) + { + p3.value = (byte)(p1 ^ p2); + return p1; + } + + @Override + public java.util.Map<Byte, Boolean> + opByteBoolD(java.util.Map<Byte, Boolean> p1, java.util.Map<Byte, Boolean> p2, ByteBoolDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<Byte, Boolean> r = new java.util.HashMap<Byte, Boolean>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public byte[] + opByteS(byte[] p1, byte[] p2, + ByteSHolder p3, + Ice.Current current) + { + p3.value = new byte[p1.length]; + for(int i = 0; i < p1.length; i++) + { + p3.value[i] = p1[p1.length - (i + 1)]; + } + + byte[] r = new byte[p1.length + p2.length]; + System.arraycopy(p1, 0, r, 0, p1.length); + System.arraycopy(p2, 0, r, p1.length, p2.length); + return r; + } + + @Override + public byte[][] + opByteSS(byte[][] p1, byte[][] p2, + ByteSSHolder p3, + Ice.Current current) + { + p3.value = new byte[p1.length][]; + for(int i = 0; i < p1.length; i++) + { + p3.value[i] = p1[p1.length - (i + 1)]; + } + + byte[][] r = new byte[p1.length + p2.length][]; + System.arraycopy(p1, 0, r, 0, p1.length); + System.arraycopy(p2, 0, r, p1.length, p2.length); + return r; + } + + @Override + public double + opFloatDouble(float p1, double p2, + Ice.FloatHolder p3, Ice.DoubleHolder p4, + Ice.Current current) + { + p3.value = p1; + p4.value = p2; + return p2; + } + + @Override + public double[] + opFloatDoubleS(float[] p1, double[] p2, + FloatSHolder p3, DoubleSHolder p4, + Ice.Current current) + { + p3.value = p1; + p4.value = new double[p2.length]; + for(int i = 0; i < p2.length; i++) + { + p4.value[i] = p2[p2.length - (i + 1)]; + } + double[] r = new double[p2.length + p1.length]; + System.arraycopy(p2, 0, r, 0, p2.length); + for(int i = 0; i < p1.length; i++) + { + r[p2.length + i] = p1[i]; + } + return r; + } + + @Override + public double[][] + opFloatDoubleSS(float[][] p1, double[][] p2, + FloatSSHolder p3, DoubleSSHolder p4, + Ice.Current current) + { + p3.value = p1; + p4.value = new double[p2.length][]; + for(int i = 0; i < p2.length; i++) + { + p4.value[i] = p2[p2.length - (i + 1)]; + } + double[][] r = new double[p2.length * 2][]; + System.arraycopy(p2, 0, r, 0, p2.length); + System.arraycopy(p2, 0, r, p2.length, p2.length); + return r; + } + + @Override + public java.util.Map<Long, Float> + opLongFloatD(java.util.Map<Long, Float> p1, java.util.Map<Long, Float> p2, LongFloatDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<Long, Float> r = new java.util.HashMap<Long, Float>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public MyClassPrx + opMyClass(MyClassPrx p1, + MyClassPrxHolder p2, MyClassPrxHolder p3, + Ice.Current current) + { + p2.value = p1; + p3.value = MyClassPrxHelper.uncheckedCast( + current.adapter.createProxy(current.adapter.getCommunicator().stringToIdentity("noSuchIdentity"))); + return MyClassPrxHelper.uncheckedCast(current.adapter.createProxy(current.id)); + } + + @Override + public MyEnum + opMyEnum(MyEnum p1, + MyEnumHolder p2, + Ice.Current current) + { + p2.value = p1; + return MyEnum.enum3; + } + + @Override + public java.util.Map<Short, Integer> + opShortIntD(java.util.Map<Short, Integer> p1, java.util.Map<Short, Integer> p2, ShortIntDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<Short, Integer> r = new java.util.HashMap<Short, Integer>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public long + opShortIntLong(short p1, int p2, long p3, + Ice.ShortHolder p4, Ice.IntHolder p5, Ice.LongHolder p6, + Ice.Current current) + { + p4.value = p1; + p5.value = p2; + p6.value = p3; + return p3; + } + + @Override + public long[] + opShortIntLongS(short[] p1, int[] p2, long[] p3, + ShortSHolder p4, IntSHolder p5, LongSHolder p6, + Ice.Current current) + { + p4.value = p1; + p5.value = new int[p2.length]; + for(int i = 0; i < p2.length; i++) + { + p5.value[i] = p2[p2.length - (i + 1)]; + } + p6.value = new long[p3.length * 2]; + System.arraycopy(p3, 0, p6.value, 0, p3.length); + System.arraycopy(p3, 0, p6.value, p3.length, p3.length); + return p3; + } + + @Override + public long[][] + opShortIntLongSS(short[][] p1, int[][] p2, long[][] p3, + ShortSSHolder p4, IntSSHolder p5, LongSSHolder p6, + Ice.Current current) + { + p4.value = p1; + p5.value = new int[p2.length][]; + for(int i = 0; i < p2.length; i++) + { + p5.value[i] = p2[p2.length - (i + 1)]; + } + p6.value = new long[p3.length * 2][]; + System.arraycopy(p3, 0, p6.value, 0, p3.length); + System.arraycopy(p3, 0, p6.value, p3.length, p3.length); + return p3; + } + + @Override + public String + opString(String p1, String p2, + Ice.StringHolder p3, + Ice.Current current) + { + p3.value = p2 + " " + p1; + return p1 + " " + p2; + } + + @Override + public java.util.Map<String, MyEnum> + opStringMyEnumD(java.util.Map<String, MyEnum> p1, java.util.Map<String, MyEnum> p2, StringMyEnumDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<String, MyEnum> r = new java.util.HashMap<String, MyEnum>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public java.util.Map<MyEnum, String> + opMyEnumStringD(java.util.Map<MyEnum, String> p1, java.util.Map<MyEnum, String> p2, MyEnumStringDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<MyEnum, String> r = new java.util.HashMap<MyEnum, String>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public java.util.Map<MyStruct, MyEnum> + opMyStructMyEnumD(java.util.Map<MyStruct, MyEnum> p1, java.util.Map<MyStruct, MyEnum> p2, MyStructMyEnumDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<MyStruct, MyEnum> r = new java.util.HashMap<MyStruct, MyEnum>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public int[] + opIntS(int[] s, Ice.Current current) + { + int[] r = new int[s.length]; + for(int i = 0; i < r.length; ++i) + { + r[i] = -s[i]; + } + return r; + } + + @Override + public void + opByteSOneway(byte[] s, Ice.Current current) + { + } + + @Override + public java.util.Map<String, String> + opContext(Ice.Current current) + { + return current.ctx; + } + + @Override + public void + opDoubleMarshaling(double p1, double[] p2, Ice.Current current) + { + double d = 1278312346.0 / 13.0; + test(p1 == d); + for(int i = 0; i < p2.length; ++i) + { + test(p2[i] == d); + } + } + + @Override + public String[] + opStringS(String[] p1, String[] p2, + StringSHolder p3, + Ice.Current current) + { + p3.value = new String[p1.length + p2.length]; + System.arraycopy(p1, 0, p3.value, 0, p1.length); + System.arraycopy(p2, 0, p3.value, p1.length, p2.length); + + String[] r = new String[p1.length]; + for(int i = 0; i < p1.length; i++) + { + r[i] = p1[p1.length - (i + 1)]; + } + return r; + } + + @Override + public String[][] + opStringSS(String[][] p1, String[][] p2, + StringSSHolder p3, + Ice.Current current) + { + p3.value = new String[p1.length + p2.length][]; + System.arraycopy(p1, 0, p3.value, 0, p1.length); + System.arraycopy(p2, 0, p3.value, p1.length, p2.length); + + String[][] r = new String[p2.length][]; + for(int i = 0; i < p2.length; i++) + { + r[i] = p2[p2.length - (i + 1)]; + } + return r; + } + + @Override + public String[][][] + opStringSSS(String[][][] p1, String[][][] p2, + StringSSSHolder p3, + Ice.Current current) + { + p3.value = new String[p1.length + p2.length][][]; + System.arraycopy(p1, 0, p3.value, 0, p1.length); + System.arraycopy(p2, 0, p3.value, p1.length, p2.length); + + String[][][] r = new String[p2.length][][]; + for(int i = 0; i < p2.length; i++) + { + r[i] = p2[p2.length - (i + 1)]; + } + return r; + } + + @Override + public java.util.Map<String, String> + opStringStringD(java.util.Map<String, String> p1, java.util.Map<String, String> p2, StringStringDHolder p3, + Ice.Current current) + { + p3.value = p1; + java.util.Map<String, String> r = new java.util.HashMap<String, String>(); + r.putAll(p1); + r.putAll(p2); + return r; + } + + @Override + public Structure + opStruct(Structure p1, Structure p2, + StructureHolder p3, + Ice.Current current) + { + p3.value = p1; + p3.value.s.s = "a new string"; + return p2; + } + + @Override + public void + opIdempotent(Ice.Current current) + { + test(current.mode == Ice.OperationMode.Idempotent); + } + + @Override + public void + opNonmutating(Ice.Current current) + { + test(current.mode == Ice.OperationMode.Nonmutating); + } + + @Override + public void + opDerived(Ice.Current current) + { + } +} diff --git a/java/test/src/main/java/test/Ice/operations/TieServer.java b/java/test/src/main/java/test/Ice/operations/TieServer.java new file mode 100644 index 00000000000..26bbdc7b7b5 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/TieServer.java @@ -0,0 +1,49 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +import test.Ice.operations.Test._MyDerivedClassTie; + +public class TieServer extends test.Util.Application +{ + @Override + public int run(String[] args) + { + communicator().getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.add(new _MyDerivedClassTie(new TieMyDerivedClassI()), communicator().stringToIdentity("test")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + // + // It's possible to have batch oneway requests dispatched + // after the adapter is deactivated due to thread + // scheduling so we suppress this warning. + // + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.operations"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/operations/Twoways.java b/java/test/src/main/java/test/Ice/operations/Twoways.java new file mode 100644 index 00000000000..c148edddb0e --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/Twoways.java @@ -0,0 +1,920 @@ + +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +import test.Ice.operations.Test.AnotherStruct; +import test.Ice.operations.Test.BoolSHolder; +import test.Ice.operations.Test.BoolSSHolder; +import test.Ice.operations.Test.ByteBoolDHolder; +import test.Ice.operations.Test.ByteSHolder; +import test.Ice.operations.Test.ByteSSHolder; +import test.Ice.operations.Test.DoubleSHolder; +import test.Ice.operations.Test.DoubleSSHolder; +import test.Ice.operations.Test.FloatSHolder; +import test.Ice.operations.Test.FloatSSHolder; +import test.Ice.operations.Test.IntSHolder; +import test.Ice.operations.Test.IntSSHolder; +import test.Ice.operations.Test.LongFloatDHolder; +import test.Ice.operations.Test.LongSHolder; +import test.Ice.operations.Test.LongSSHolder; +import test.Ice.operations.Test.MyClass; +import test.Ice.operations.Test.MyClassPrx; +import test.Ice.operations.Test.MyClassPrxHelper; +import test.Ice.operations.Test.MyClassPrxHolder; +import test.Ice.operations.Test.MyDerivedClass; +import test.Ice.operations.Test.MyDerivedClassPrxHelper; +import test.Ice.operations.Test.MyEnum; +import test.Ice.operations.Test.MyStruct; +import test.Ice.operations.Test.MyEnumHolder; +import test.Ice.operations.Test.MyStructMyEnumDHolder; +import test.Ice.operations.Test.ShortIntDHolder; +import test.Ice.operations.Test.ShortSHolder; +import test.Ice.operations.Test.ShortSSHolder; +import test.Ice.operations.Test.StringMyEnumDHolder; +import test.Ice.operations.Test.MyEnumStringDHolder; +import test.Ice.operations.Test.StringSHolder; +import test.Ice.operations.Test.StringSSHolder; +import test.Ice.operations.Test.StringSSSHolder; +import test.Ice.operations.Test.StringStringDHolder; +import test.Ice.operations.Test.Structure; +import test.Ice.operations.Test.StructureHolder; + +class Twoways +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static class PerThreadContextInvokeThread extends Thread + { + public PerThreadContextInvokeThread(MyClassPrx proxy) + { + _proxy = proxy; + } + + @Override + public void + run() + { + java.util.Map<String, String> ctx = _proxy.ice_getCommunicator().getImplicitContext().getContext(); + test(ctx.isEmpty()); + ctx.put("one", "ONE"); + _proxy.ice_getCommunicator().getImplicitContext().setContext(ctx); + test(_proxy.opContext().equals(ctx)); + } + + final private MyClassPrx _proxy; + } + + static void + twoways(test.Util.Application app, MyClassPrx p) + { + Ice.Communicator communicator = app.communicator(); + + p.ice_ping(); + + test(p.ice_isA(MyClass.ice_staticId())); + + test(p.ice_id().equals(MyDerivedClass.ice_staticId())); + + test(MyDerivedClassPrxHelper.ice_staticId().equals(MyDerivedClass.ice_staticId())); + test(Ice.ObjectPrxHelper.ice_staticId().equals(Ice.Object.ice_staticId)); + test(Ice.LocatorPrxHelper.ice_staticId().equals(Ice.Locator.ice_staticId)); + + { + String[] ids = p.ice_ids(); + test(ids.length == 3); + test(ids[0].equals("::Ice::Object")); + test(ids[1].equals("::Test::MyClass")); + test(ids[2].equals("::Test::MyDerivedClass")); + } + + { + p.opVoid(); + } + + { + Ice.ByteHolder b = new Ice.ByteHolder(); + byte r; + + r = p.opByte((byte)0xff, (byte)0x0f, b); + test(b.value == (byte)0xf0); + test(r == (byte)0xff); + } + + { + Ice.BooleanHolder b = new Ice.BooleanHolder(); + boolean r; + + r = p.opBool(true, false, b); + test(b.value); + test(!r); + } + + { + Ice.ShortHolder s = new Ice.ShortHolder(); + Ice.IntHolder i = new Ice.IntHolder(); + Ice.LongHolder l = new Ice.LongHolder(); + long r; + + r = p.opShortIntLong((short)10, 11, 12L, s, i, l); + test(s.value == 10); + test(i.value == 11); + test(l.value == 12); + test(r == 12L); + + r = p.opShortIntLong(Short.MIN_VALUE, Integer.MIN_VALUE, + Long.MIN_VALUE, s, i, l); + test(s.value == Short.MIN_VALUE); + test(i.value == Integer.MIN_VALUE); + test(l.value == Long.MIN_VALUE); + test(r == Long.MIN_VALUE); + + r = p.opShortIntLong(Short.MAX_VALUE, Integer.MAX_VALUE, + Long.MAX_VALUE, s, i, l); + test(s.value == Short.MAX_VALUE); + test(i.value == Integer.MAX_VALUE); + test(l.value == Long.MAX_VALUE); + test(r == Long.MAX_VALUE); + } + + { + Ice.FloatHolder f = new Ice.FloatHolder(); + Ice.DoubleHolder d = new Ice.DoubleHolder(); + double r; + + r = p.opFloatDouble(3.14f, 1.1E10, f, d); + test(f.value == 3.14f); + test(d.value == 1.1E10); + test(r == 1.1E10); + + r = p.opFloatDouble(Float.MIN_VALUE, Double.MIN_VALUE, f, d); + test(f.value == Float.MIN_VALUE); + test(d.value == Double.MIN_VALUE); + test(r == Double.MIN_VALUE); + + r = p.opFloatDouble(Float.MAX_VALUE, Double.MAX_VALUE, f, d); + test(f.value == Float.MAX_VALUE); + test(d.value == Double.MAX_VALUE); + test(r == Double.MAX_VALUE); + } + + { + Ice.StringHolder s = new Ice.StringHolder(); + String r; + + r = p.opString("hello", "world", s); + test(s.value.equals("world hello")); + test(r.equals("hello world")); + } + + { + MyEnumHolder e = new MyEnumHolder(); + MyEnum r; + + r = p.opMyEnum(MyEnum.enum2, e); + test(e.value == MyEnum.enum2); + test(r == MyEnum.enum3); + } + + { + MyClassPrxHolder c1 = new MyClassPrxHolder(); + MyClassPrxHolder c2 = new MyClassPrxHolder(); + MyClassPrx r; + + r = p.opMyClass(p, c1, c2); + test(Ice.Util.proxyIdentityAndFacetCompare(c1.value, p) == 0); + test(Ice.Util.proxyIdentityAndFacetCompare(c2.value, p) != 0); + test(Ice.Util.proxyIdentityAndFacetCompare(r, p) == 0); + test(c1.value.ice_getIdentity().equals(communicator.stringToIdentity("test"))); + test(c2.value.ice_getIdentity().equals(communicator.stringToIdentity("noSuchIdentity"))); + test(r.ice_getIdentity().equals(communicator.stringToIdentity("test"))); + r.opVoid(); + c1.value.opVoid(); + try + { + c2.value.opVoid(); + test(false); + } + catch(Ice.ObjectNotExistException ex) + { + } + + r = p.opMyClass(null, c1, c2); + test(c1.value == null); + test(c2.value != null); + test(Ice.Util.proxyIdentityAndFacetCompare(r, p) == 0); + r.opVoid(); + } + + { + Structure si1 = new Structure(); + si1.p = p; + si1.e = MyEnum.enum3; + si1.s = new AnotherStruct(); + si1.s.s = "abc"; + Structure si2 = new Structure(); + si2.p = null; + si2.e = MyEnum.enum2; + si2.s = new AnotherStruct(); + si2.s.s = "def"; + + StructureHolder so = new StructureHolder(); + Structure rso = p.opStruct(si1, si2, so); + test(rso.p == null); + test(rso.e == MyEnum.enum2); + test(rso.s.s.equals("def")); + test(so.value.p.equals(p)); + test(so.value.e == MyEnum.enum3); + test(so.value.s.s.equals("a new string")); + so.value.p.opVoid(); + } + + { + final byte[] bsi1 = + { + (byte)0x01, + (byte)0x11, + (byte)0x12, + (byte)0x22 + }; + final byte[] bsi2 = + { + (byte)0xf1, + (byte)0xf2, + (byte)0xf3, + (byte)0xf4 + }; + + ByteSHolder bso = new ByteSHolder(); + byte[] rso; + + rso = p.opByteS(bsi1, bsi2, bso); + test(bso.value.length == 4); + test(bso.value[0] == (byte)0x22); + test(bso.value[1] == (byte)0x12); + test(bso.value[2] == (byte)0x11); + test(bso.value[3] == (byte)0x01); + test(rso.length == 8); + test(rso[0] == (byte)0x01); + test(rso[1] == (byte)0x11); + test(rso[2] == (byte)0x12); + test(rso[3] == (byte)0x22); + test(rso[4] == (byte)0xf1); + test(rso[5] == (byte)0xf2); + test(rso[6] == (byte)0xf3); + test(rso[7] == (byte)0xf4); + } + + { + final boolean[] bsi1 = { true, true, false }; + final boolean[] bsi2 = { false }; + + BoolSHolder bso = new BoolSHolder(); + boolean[] rso; + + rso = p.opBoolS(bsi1, bsi2, bso); + test(bso.value.length == 4); + test(bso.value[0]); + test(bso.value[1]); + test(!bso.value[2]); + test(!bso.value[3]); + test(rso.length == 3); + test(!rso[0]); + test(rso[1]); + test(rso[2]); + } + + { + final short[] ssi = { 1, 2, 3 }; + final int[] isi = { 5, 6, 7, 8 }; + final long[] lsi = { 10, 30, 20 }; + + ShortSHolder sso = new ShortSHolder(); + IntSHolder iso = new IntSHolder(); + LongSHolder lso = new LongSHolder(); + long[] rso; + + rso = p.opShortIntLongS(ssi, isi, lsi, sso, iso, lso); + test(sso.value.length == 3); + test(sso.value[0] == 1); + test(sso.value[1] == 2); + test(sso.value[2] == 3); + test(iso.value.length == 4); + test(iso.value[0] == 8); + test(iso.value[1] == 7); + test(iso.value[2] == 6); + test(iso.value[3] == 5); + test(lso.value.length == 6); + test(lso.value[0] == 10); + test(lso.value[1] == 30); + test(lso.value[2] == 20); + test(lso.value[3] == 10); + test(lso.value[4] == 30); + test(lso.value[5] == 20); + test(rso.length == 3); + test(rso[0] == 10); + test(rso[1] == 30); + test(rso[2] == 20); + } + + { + final float[] fsi = { 3.14f, 1.11f }; + final double[] dsi = { 1.1E10, 1.2E10, 1.3E10 }; + + FloatSHolder fso = new FloatSHolder(); + DoubleSHolder dso = new DoubleSHolder(); + double[] rso; + + rso = p.opFloatDoubleS(fsi, dsi, fso, dso); + test(fso.value.length == 2); + test(fso.value[0] == 3.14f); + test(fso.value[1] == 1.11f); + test(dso.value.length == 3); + test(dso.value[0] == 1.3E10); + test(dso.value[1] == 1.2E10); + test(dso.value[2] == 1.1E10); + test(rso.length == 5); + test(rso[0] == 1.1E10); + test(rso[1] == 1.2E10); + test(rso[2] == 1.3E10); + test((float)rso[3] == 3.14f); + test((float)rso[4] == 1.11f); + } + + { + final String[] ssi1 = { "abc", "de", "fghi" }; + final String[] ssi2 = { "xyz" }; + + StringSHolder sso = new StringSHolder(); + String[] rso; + + rso = p.opStringS(ssi1, ssi2, sso); + test(sso.value.length == 4); + test(sso.value[0].equals("abc")); + test(sso.value[1].equals("de")); + test(sso.value[2].equals("fghi")); + test(sso.value[3].equals("xyz")); + test(rso.length == 3); + test(rso[0].equals("fghi")); + test(rso[1].equals("de")); + test(rso[2].equals("abc")); + } + + { + final byte[][] bsi1 = + { + { (byte)0x01, (byte)0x11, (byte)0x12 }, + { (byte)0xff } + }; + final byte[][] bsi2 = + { + { (byte)0x0e }, + { (byte)0xf2, (byte)0xf1 } + }; + + ByteSSHolder bso = new ByteSSHolder(); + byte[][] rso; + + rso = p.opByteSS(bsi1, bsi2, bso); + test(bso.value.length == 2); + test(bso.value[0].length == 1); + test(bso.value[0][0] == (byte)0xff); + test(bso.value[1].length == 3); + test(bso.value[1][0] == (byte)0x01); + test(bso.value[1][1] == (byte)0x11); + test(bso.value[1][2] == (byte)0x12); + test(rso.length == 4); + test(rso[0].length == 3); + test(rso[0][0] == (byte)0x01); + test(rso[0][1] == (byte)0x11); + test(rso[0][2] == (byte)0x12); + test(rso[1].length == 1); + test(rso[1][0] == (byte)0xff); + test(rso[2].length == 1); + test(rso[2][0] == (byte)0x0e); + test(rso[3].length == 2); + test(rso[3][0] == (byte)0xf2); + test(rso[3][1] == (byte)0xf1); + } + + { + final boolean[][] bsi1 = + { + { true }, + { false }, + { true, true} + }; + + final boolean[][] bsi2 = + { + { false, false, true } + }; + + BoolSSHolder bso = new BoolSSHolder(); + boolean [][] rso; + + rso = p.opBoolSS(bsi1, bsi2, bso); + test(bso.value.length == 4); + test(bso.value[0].length == 1); + test(bso.value[0][0]); + test(bso.value[1].length == 1); + test(!bso.value[1][0]); + test(bso.value[2].length == 2); + test(bso.value[2][0]); + test(bso.value[2][1]); + test(bso.value[3].length == 3); + test(!bso.value[3][0]); + test(!bso.value[3][1]); + test(bso.value[3][2]); + test(rso.length == 3); + test(rso[0].length == 2); + test(rso[0][0]); + test(rso[0][1]); + test(rso[1].length == 1); + test(!rso[1][0]); + test(rso[2].length == 1); + test(rso[2][0]); + } + + { + final short[][] ssi= + { + {1, 2, 5}, + {13}, + {} + }; + final int[][] isi = + { + {24, 98}, + {42} + }; + final long[][] lsi = + { + {496, 1729}, + }; + + ShortSSHolder sso = new ShortSSHolder(); + IntSSHolder iso = new IntSSHolder(); + LongSSHolder lso = new LongSSHolder(); + long[][] rso; + + rso = p.opShortIntLongSS(ssi, isi, lsi, sso, iso, lso); + test(rso.length == 1); + test(rso[0].length == 2); + test(rso[0][0] == 496); + test(rso[0][1] == 1729); + test(sso.value.length == 3); + test(sso.value[0].length == 3); + test(sso.value[0][0] == 1); + test(sso.value[0][1] == 2); + test(sso.value[0][2] == 5); + test(sso.value[1].length == 1); + test(sso.value[1][0] == 13); + test(sso.value[2].length == 0); + test(iso.value.length == 2); + test(iso.value[0].length == 1); + test(iso.value[0][0] == 42); + test(iso.value[1].length == 2); + test(iso.value[1][0] == 24); + test(iso.value[1][1] == 98); + test(lso.value.length == 2); + test(lso.value[0].length == 2); + test(lso.value[0][0] == 496); + test(lso.value[0][1] == 1729); + test(lso.value[1].length == 2); + test(lso.value[1][0] == 496); + test(lso.value[1][1] == 1729); + } + + { + final float[][] fsi = + { + { 3.14f }, + { 1.11f }, + { }, + }; + final double[][] dsi = + { + { 1.1E10, 1.2E10, 1.3E10 } + }; + + FloatSSHolder fso = new FloatSSHolder(); + DoubleSSHolder dso = new DoubleSSHolder(); + double[][] rso; + + rso = p.opFloatDoubleSS(fsi, dsi, fso, dso); + test(fso.value.length == 3); + test(fso.value[0].length == 1); + test(fso.value[0][0] == 3.14f); + test(fso.value[1].length == 1); + test(fso.value[1][0] == 1.11f); + test(fso.value[2].length == 0); + test(dso.value.length == 1); + test(dso.value[0].length == 3); + test(dso.value[0][0] == 1.1E10); + test(dso.value[0][1] == 1.2E10); + test(dso.value[0][2] == 1.3E10); + test(rso.length == 2); + test(rso[0].length == 3); + test(rso[0][0] == 1.1E10); + test(rso[0][1] == 1.2E10); + test(rso[0][2] == 1.3E10); + test(rso[1].length == 3); + test(rso[1][0] == 1.1E10); + test(rso[1][1] == 1.2E10); + test(rso[1][2] == 1.3E10); + } + + { + final String[][] ssi1 = + { + { "abc" }, + { "de", "fghi" } + }; + final String[][] ssi2 = + { + { }, + { }, + { "xyz" } + }; + + StringSSHolder sso = new StringSSHolder(); + String[][] rso; + + rso = p.opStringSS(ssi1, ssi2, sso); + test(sso.value.length == 5); + test(sso.value[0].length == 1); + test(sso.value[0][0].equals("abc")); + test(sso.value[1].length == 2); + test(sso.value[1][0].equals("de")); + test(sso.value[1][1].equals("fghi")); + test(sso.value[2].length == 0); + test(sso.value[3].length == 0); + test(sso.value[4].length == 1); + test(sso.value[4][0].equals("xyz")); + test(rso.length == 3); + test(rso[0].length == 1); + test(rso[0][0].equals("xyz")); + test(rso[1].length == 0); + test(rso[2].length == 0); + } + + { + final String[][][] sssi1 = + { + { + { + "abc", "de" + }, + { + "xyz" + } + }, + { + { + "hello" + } + } + }; + + final String[][][] sssi2 = + { + { + { + "", "" + }, + { + "abcd" + } + }, + { + { + "" + } + }, + { + } + }; + + StringSSSHolder ssso = new StringSSSHolder(); + String rsso[][][]; + + rsso = p.opStringSSS(sssi1, sssi2, ssso); + test(ssso.value.length == 5); + test(ssso.value[0].length == 2); + test(ssso.value[0][0].length == 2); + test(ssso.value[0][1].length == 1); + test(ssso.value[1].length == 1); + test(ssso.value[1][0].length == 1); + test(ssso.value[2].length == 2); + test(ssso.value[2][0].length == 2); + test(ssso.value[2][1].length == 1); + test(ssso.value[3].length == 1); + test(ssso.value[3][0].length == 1); + test(ssso.value[4].length == 0); + test(ssso.value[0][0][0].equals("abc")); + test(ssso.value[0][0][1].equals("de")); + test(ssso.value[0][1][0].equals("xyz")); + test(ssso.value[1][0][0].equals("hello")); + test(ssso.value[2][0][0].equals("")); + test(ssso.value[2][0][1].equals("")); + test(ssso.value[2][1][0].equals("abcd")); + test(ssso.value[3][0][0].equals("")); + + test(rsso.length == 3); + test(rsso[0].length == 0); + test(rsso[1].length == 1); + test(rsso[1][0].length == 1); + test(rsso[2].length == 2); + test(rsso[2][0].length == 2); + test(rsso[2][1].length == 1); + test(rsso[1][0][0].equals("")); + test(rsso[2][0][0].equals("")); + test(rsso[2][0][1].equals("")); + test(rsso[2][1][0].equals("abcd")); + } + + { + java.util.Map<Byte, Boolean> di1 = new java.util.HashMap<Byte, Boolean>(); + di1.put((byte)10, Boolean.TRUE); + di1.put((byte)100, Boolean.FALSE); + java.util.Map<Byte, Boolean> di2 = new java.util.HashMap<Byte, Boolean>(); + di2.put((byte)10, Boolean.TRUE); + di2.put((byte)11, Boolean.FALSE); + di2.put((byte)101, Boolean.TRUE); + + ByteBoolDHolder _do = new ByteBoolDHolder(); + java.util.Map<Byte, Boolean> ro = p.opByteBoolD(di1, di2, _do); + + test(_do.value.equals(di1)); + test(ro.size() == 4); + test(ro.get((byte)10).booleanValue() == true); + test(ro.get((byte)11).booleanValue() == false); + test(ro.get((byte)100).booleanValue() == false); + test(ro.get((byte)101).booleanValue() == true); + } + + { + java.util.Map<Short, Integer> di1 = new java.util.HashMap<Short, Integer>(); + di1.put((short)110, -1); + di1.put((short)1100, 123123); + java.util.Map<Short, Integer> di2 = new java.util.HashMap<Short, Integer>(); + di2.put((short)110, -1); + di2.put((short)111, -100); + di2.put((short)1101, 0); + + ShortIntDHolder _do = new ShortIntDHolder(); + java.util.Map<Short, Integer> ro = p.opShortIntD(di1, di2, _do); + + test(_do.value.equals(di1)); + test(ro.size() == 4); + test(ro.get((short)110).intValue() == -1); + test(ro.get((short)111).intValue() == -100); + test(ro.get((short)1100).intValue() == 123123); + test(ro.get((short)1101).intValue() == 0); + } + + { + java.util.Map<Long, Float> di1 = new java.util.HashMap<Long, Float>(); + di1.put(999999110L, new Float(-1.1f)); + di1.put(999999111L, new Float(123123.2f)); + java.util.Map<Long, Float> di2 = new java.util.HashMap<Long, Float>(); + di2.put(999999110L, new Float(-1.1f)); + di2.put(999999120L, new Float(-100.4f)); + di2.put(999999130L, new Float(0.5f)); + + LongFloatDHolder _do = new LongFloatDHolder(); + java.util.Map<Long, Float> ro = p.opLongFloatD(di1, di2, _do); + + test(_do.value.equals(di1)); + test(ro.size() == 4); + test(ro.get(999999110L).floatValue() == -1.1f); + test(ro.get(999999120L).floatValue() == -100.4f); + test(ro.get(999999111L).floatValue() == 123123.2f); + test(ro.get(999999130L).floatValue() == 0.5f); + } + + { + java.util.Map<String, String> di1 = new java.util.HashMap<String, String>(); + di1.put("foo", "abc -1.1"); + di1.put("bar", "abc 123123.2"); + java.util.Map<String, String> di2 = new java.util.HashMap<String, String>(); + di2.put("foo", "abc -1.1"); + di2.put("FOO", "abc -100.4"); + di2.put("BAR", "abc 0.5"); + + StringStringDHolder _do = new StringStringDHolder(); + java.util.Map<String, String> ro = p.opStringStringD(di1, di2, _do); + + test(_do.value.equals(di1)); + test(ro.size() == 4); + test(ro.get("foo").equals("abc -1.1")); + test(ro.get("FOO").equals("abc -100.4")); + test(ro.get("bar").equals("abc 123123.2")); + test(ro.get("BAR").equals("abc 0.5")); + } + + { + java.util.Map<String, MyEnum> di1 = new java.util.HashMap<String, MyEnum>(); + di1.put("abc", MyEnum.enum1); + di1.put("", MyEnum.enum2); + java.util.Map<String, MyEnum> di2 = new java.util.HashMap<String, MyEnum>(); + di2.put("abc", MyEnum.enum1); + di2.put("qwerty", MyEnum.enum3); + di2.put("Hello!!", MyEnum.enum2); + + StringMyEnumDHolder _do = new StringMyEnumDHolder(); + java.util.Map<String, MyEnum> ro = p.opStringMyEnumD(di1, di2, _do); + + test(_do.value.equals(di1)); + test(ro.size() == 4); + test(ro.get("abc") == MyEnum.enum1); + test(ro.get("qwerty") == MyEnum.enum3); + test(ro.get("") == MyEnum.enum2); + test(ro.get("Hello!!") == MyEnum.enum2); + } + + { + java.util.Map<MyEnum, String> di1 = new java.util.HashMap<MyEnum, String>(); + di1.put(MyEnum.enum1, "abc"); + java.util.Map<MyEnum, String> di2 = new java.util.HashMap<MyEnum, String>(); + di2.put(MyEnum.enum2, "Hello!!"); + di2.put(MyEnum.enum3, "qwerty"); + + MyEnumStringDHolder _do = new MyEnumStringDHolder(); + java.util.Map<MyEnum, String> ro = p.opMyEnumStringD(di1, di2, _do); + + test(_do.value.equals(di1)); + test(ro.size() == 3); + test(ro.get(MyEnum.enum1).equals("abc")); + test(ro.get(MyEnum.enum2).equals("Hello!!")); + test(ro.get(MyEnum.enum3).equals("qwerty")); + } + + { + MyStruct s11 = new MyStruct(1, 1); + MyStruct s12 = new MyStruct(1, 2); + java.util.Map<MyStruct, MyEnum> di1 = new java.util.HashMap<MyStruct, MyEnum>(); + di1.put(s11, MyEnum.enum1); + di1.put(s12, MyEnum.enum2); + + MyStruct s22 = new MyStruct(2, 2); + MyStruct s23 = new MyStruct(2, 3); + java.util.Map<MyStruct, MyEnum> di2 = new java.util.HashMap<MyStruct, MyEnum>(); + di2.put(s11, MyEnum.enum1); + di2.put(s22, MyEnum.enum3); + di2.put(s23, MyEnum.enum2); + + MyStructMyEnumDHolder _do = new MyStructMyEnumDHolder(); + java.util.Map<MyStruct, MyEnum> ro = p.opMyStructMyEnumD(di1, di2, _do); + + test(_do.value.equals(di1)); + test(ro.size() == 4); + test(ro.get(s11) == MyEnum.enum1); + test(ro.get(s12) == MyEnum.enum2); + test(ro.get(s22) == MyEnum.enum3); + test(ro.get(s23) == MyEnum.enum2); + } + + { + int[] lengths = { 0, 1, 2, 126, 127, 128, 129, 253, 254, 255, 256, 257, 1000 }; + + for(int l : lengths) + { + int[] s = new int[l]; + for(int i = 0; i < l; ++i) + { + s[i] = i; + } + int[] r = p.opIntS(s); + test(r.length == l); + for(int j = 0; j < r.length; ++j) + { + test(r[j] == -j); + } + } + } + + { + java.util.Map<String, String> ctx = new java.util.HashMap<String, String>(); + ctx.put("one", "ONE"); + ctx.put("two", "TWO"); + ctx.put("three", "THREE"); + { + test(p.ice_getContext().isEmpty()); + java.util.Map<String, String> r = p.opContext(); + test(!r.equals(ctx)); + } + { + java.util.Map<String, String> r = p.opContext(ctx); + test(p.ice_getContext().isEmpty()); + test(r.equals(ctx)); + } + { + MyClassPrx p2 = MyClassPrxHelper.checkedCast(p.ice_context(ctx)); + test(p2.ice_getContext().equals(ctx)); + java.util.Map<String, String> r = p2.opContext(); + test(r.equals(ctx)); + r = p2.opContext(ctx); + test(r.equals(ctx)); + } + } + { + // + // Test implicit context propagation + // + + String[] impls = {"Shared", "PerThread"}; + for(int i = 0; i < 2; i++) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + initData.properties.setProperty("Ice.ImplicitContext", impls[i]); + + Ice.Communicator ic = app.initialize(initData); + + java.util.Map<String, String> ctx = new java.util.HashMap<String, String>(); + ctx.put("one", "ONE"); + ctx.put("two", "TWO"); + ctx.put("three", "THREE"); + + MyClassPrx p3 = MyClassPrxHelper.uncheckedCast(ic.stringToProxy("test:default -p 12010")); + + ic.getImplicitContext().setContext(ctx); + test(ic.getImplicitContext().getContext().equals(ctx)); + test(p3.opContext().equals(ctx)); + + test(ic.getImplicitContext().containsKey("zero") == false); + String r = ic.getImplicitContext().put("zero", "ZERO"); + test(r.equals("")); + test(ic.getImplicitContext().containsKey("zero") == true); + test(ic.getImplicitContext().get("zero").equals("ZERO")); + + ctx = ic.getImplicitContext().getContext(); + test(p3.opContext().equals(ctx)); + + java.util.Map<String, String> prxContext = new java.util.HashMap<String, String>(); + prxContext.put("one", "UN"); + prxContext.put("four", "QUATRE"); + + java.util.Map<String, String> combined = new java.util.HashMap<String, String>(ctx); + combined.putAll(prxContext); + test(combined.get("one").equals("UN")); + + p3 = MyClassPrxHelper.uncheckedCast(p3.ice_context(prxContext)); + + ic.getImplicitContext().setContext(null); + test(p3.opContext().equals(prxContext)); + + ic.getImplicitContext().setContext(ctx); + test(p3.opContext().equals(combined)); + + test(ic.getImplicitContext().remove("one").equals("ONE")); + + if(impls[i].equals("PerThread")) + { + Thread thread = new PerThreadContextInvokeThread( + MyClassPrxHelper.uncheckedCast(p3.ice_context(null))); + thread.start(); + try + { + thread.join(); + } + catch(InterruptedException ex) + { + } + } + + ic.destroy(); + } + } + + { + double d = 1278312346.0 / 13.0; + double[] ds = new double[5]; + for(int i = 0; i < 5; i++) + { + ds[i] = d; + } + p.opDoubleMarshaling(d, ds); + } + + p.opIdempotent(); + + p.opNonmutating(); + } +} diff --git a/java/test/src/main/java/test/Ice/operations/TwowaysAMI.java b/java/test/src/main/java/test/Ice/operations/TwowaysAMI.java new file mode 100644 index 00000000000..70e1a6566a0 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/TwowaysAMI.java @@ -0,0 +1,1770 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations; + +import test.Ice.operations.Test.Callback_MyClass_opVoid; +import test.Ice.operations.Test.Callback_MyClass_opBool; +import test.Ice.operations.Test.Callback_MyClass_opBoolS; +import test.Ice.operations.Test.Callback_MyClass_opBoolSS; +import test.Ice.operations.Test.Callback_MyClass_opByte; +import test.Ice.operations.Test.Callback_MyClass_opByteBoolD; +import test.Ice.operations.Test.Callback_MyClass_opByteS; +import test.Ice.operations.Test.Callback_MyClass_opByteSS; +import test.Ice.operations.Test.Callback_MyClass_opFloatDouble; +import test.Ice.operations.Test.Callback_MyClass_opFloatDoubleS; +import test.Ice.operations.Test.Callback_MyClass_opFloatDoubleSS; +import test.Ice.operations.Test.Callback_MyClass_opIdempotent; +import test.Ice.operations.Test.Callback_MyClass_opIntS; +import test.Ice.operations.Test.Callback_MyClass_opLongFloatD; +import test.Ice.operations.Test.Callback_MyClass_opMyClass; +import test.Ice.operations.Test.Callback_MyClass_opMyEnum; +import test.Ice.operations.Test.Callback_MyClass_opNonmutating; +import test.Ice.operations.Test.Callback_MyClass_opShortIntD; +import test.Ice.operations.Test.Callback_MyClass_opShortIntLong; +import test.Ice.operations.Test.Callback_MyClass_opShortIntLongS; +import test.Ice.operations.Test.Callback_MyClass_opShortIntLongSS; +import test.Ice.operations.Test.Callback_MyClass_opString; +import test.Ice.operations.Test.Callback_MyClass_opStringMyEnumD; +import test.Ice.operations.Test.Callback_MyClass_opMyEnumStringD; +import test.Ice.operations.Test.Callback_MyClass_opStringS; +import test.Ice.operations.Test.Callback_MyClass_opStringSS; +import test.Ice.operations.Test.Callback_MyClass_opStringSSS; +import test.Ice.operations.Test.Callback_MyClass_opStringStringD; +import test.Ice.operations.Test.Callback_MyClass_opStruct; +import test.Ice.operations.Test.Callback_MyClass_opMyStructMyEnumD; +import test.Ice.operations.Test.Callback_MyClass_opDoubleMarshaling; +import test.Ice.operations.Test.Callback_MyDerivedClass_opDerived; +import test.Ice.operations.Test.AnotherStruct; +import test.Ice.operations.Test.MyClass; +import test.Ice.operations.Test.MyClassPrx; +import test.Ice.operations.Test.MyClassPrxHelper; +import test.Ice.operations.Test.MyDerivedClass; +import test.Ice.operations.Test.MyDerivedClassPrx; +import test.Ice.operations.Test.MyDerivedClassPrxHelper; +import test.Ice.operations.Test.MyEnum; +import test.Ice.operations.Test.Structure; +import test.Ice.operations.Test.MyStruct; + +class TwowaysAMI +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static class pingI extends Ice.Callback_Object_ice_ping + { + @Override + public void response() + { + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class isAI extends Ice.Callback_Object_ice_isA + { + @Override + public void response(boolean r) + { + test(r); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class idI extends Ice.Callback_Object_ice_id + { + @Override + public void response(String id) + { + test(id.equals(MyDerivedClass.ice_staticId())); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class idsI extends Ice.Callback_Object_ice_ids + { + @Override + public void response(String[] ids) + { + test(ids.length == 3); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opVoidI extends Callback_MyClass_opVoid + { + @Override + public void response() + { + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opByteI extends Callback_MyClass_opByte + { + @Override + public void response(byte r, byte b) + { + test(b == (byte)0xf0); + test(r == (byte)0xff); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opBoolI extends Callback_MyClass_opBool + { + @Override + public void response(boolean r, boolean b) + { + test(b); + test(!r); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opShortIntLongI extends Callback_MyClass_opShortIntLong + { + @Override + public void response(long r, short s, int i, long l) + { + test(s == 10); + test(i == 11); + test(l == 12); + test(r == 12); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opFloatDoubleI extends Callback_MyClass_opFloatDouble + { + @Override + public void response(double r, float f, double d) + { + test(f == 3.14f); + test(d == 1.1E10); + test(r == 1.1E10); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opStringI extends Callback_MyClass_opString + { + @Override + public void response(String r, String s) + { + test(s.equals("world hello")); + test(r.equals("hello world")); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opMyEnumI extends Callback_MyClass_opMyEnum + { + @Override + public void response(MyEnum r, MyEnum e) + { + test(e == MyEnum.enum2); + test(r == MyEnum.enum3); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opMyClassI extends Callback_MyClass_opMyClass + { + opMyClassI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + @Override + public void response(MyClassPrx r, MyClassPrx c1, MyClassPrx c2) + { + test(c1.ice_getIdentity().equals(_communicator.stringToIdentity("test"))); + test(c2.ice_getIdentity().equals(_communicator.stringToIdentity("noSuchIdentity"))); + test(r.ice_getIdentity().equals(_communicator.stringToIdentity("test"))); + // We can't do the callbacks below in connection serialization mode. + if(_communicator.getProperties().getPropertyAsInt("Ice.ThreadPool.Client.Serialize") == 0) + { + r.opVoid(); + c1.opVoid(); + try + { + c2.opVoid(); + test(false); + } + catch(Ice.ObjectNotExistException ex) + { + } + } + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + private Ice.Communicator _communicator; + } + + private static class opStructI extends Callback_MyClass_opStruct + { + opStructI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + @Override + public void response(Structure rso, Structure so) + { + test(rso.p == null); + test(rso.e == MyEnum.enum2); + test(rso.s.s.equals("def")); + test(so.e == MyEnum.enum3); + test(so.s.s.equals("a new string")); + // We can't do the callbacks below in connection serialization mode. + if(_communicator.getProperties().getPropertyAsInt("Ice.ThreadPool.Client.Serialize") == 0) + { + so.p.opVoid(); + } + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + private Ice.Communicator _communicator; + } + + private static class opByteSI extends Callback_MyClass_opByteS + { + @Override + public void response(byte[] rso, byte[] bso) + { + test(bso.length == 4); + test(bso[0] == (byte)0x22); + test(bso[1] == (byte)0x12); + test(bso[2] == (byte)0x11); + test(bso[3] == (byte)0x01); + test(rso.length == 8); + test(rso[0] == (byte)0x01); + test(rso[1] == (byte)0x11); + test(rso[2] == (byte)0x12); + test(rso[3] == (byte)0x22); + test(rso[4] == (byte)0xf1); + test(rso[5] == (byte)0xf2); + test(rso[6] == (byte)0xf3); + test(rso[7] == (byte)0xf4); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opBoolSI extends Callback_MyClass_opBoolS + { + @Override + public void response(boolean[] rso, boolean[] bso) + { + test(bso.length == 4); + test(bso[0]); + test(bso[1]); + test(!bso[2]); + test(!bso[3]); + test(rso.length == 3); + test(!rso[0]); + test(rso[1]); + test(rso[2]); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opShortIntLongSI extends Callback_MyClass_opShortIntLongS + { + @Override + public void response(long[] rso, short[] sso, int[] iso, long[] lso) + { + test(sso.length == 3); + test(sso[0] == 1); + test(sso[1] == 2); + test(sso[2] == 3); + test(iso.length == 4); + test(iso[0] == 8); + test(iso[1] == 7); + test(iso[2] == 6); + test(iso[3] == 5); + test(lso.length == 6); + test(lso[0] == 10); + test(lso[1] == 30); + test(lso[2] == 20); + test(lso[3] == 10); + test(lso[4] == 30); + test(lso[5] == 20); + test(rso.length == 3); + test(rso[0] == 10); + test(rso[1] == 30); + test(rso[2] == 20); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opFloatDoubleSI extends Callback_MyClass_opFloatDoubleS + { + @Override + public void response(double[] rso, float[] fso, double[] dso) + { + test(fso.length == 2); + test(fso[0] == 3.14f); + test(fso[1] == 1.11f); + test(dso.length == 3); + test(dso[0] == 1.3E10); + test(dso[1] == 1.2E10); + test(dso[2] == 1.1E10); + test(rso.length == 5); + test(rso[0] == 1.1E10); + test(rso[1] == 1.2E10); + test(rso[2] == 1.3E10); + test((float)rso[3] == 3.14f); + test((float)rso[4] == 1.11f); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opStringSI extends Callback_MyClass_opStringS + { + @Override + public void response(String[] rso, String[] sso) + { + test(sso.length == 4); + test(sso[0].equals("abc")); + test(sso[1].equals("de")); + test(sso[2].equals("fghi")); + test(sso[3].equals("xyz")); + test(rso.length == 3); + test(rso[0].equals("fghi")); + test(rso[1].equals("de")); + test(rso[2].equals("abc")); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opByteSSI extends Callback_MyClass_opByteSS + { + @Override + public void response(byte[][] rso, byte[][] bso) + { + test(bso.length == 2); + test(bso[0].length == 1); + test(bso[0][0] == (byte)0xff); + test(bso[1].length == 3); + test(bso[1][0] == (byte)0x01); + test(bso[1][1] == (byte)0x11); + test(bso[1][2] == (byte)0x12); + test(rso.length == 4); + test(rso[0].length == 3); + test(rso[0][0] == (byte)0x01); + test(rso[0][1] == (byte)0x11); + test(rso[0][2] == (byte)0x12); + test(rso[1].length == 1); + test(rso[1][0] == (byte)0xff); + test(rso[2].length == 1); + test(rso[2][0] == (byte)0x0e); + test(rso[3].length == 2); + test(rso[3][0] == (byte)0xf2); + test(rso[3][1] == (byte)0xf1); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opBoolSSI extends Callback_MyClass_opBoolSS + { + @Override + public void + response(boolean[][] rso, boolean[][] bso) + { + test(bso.length == 4); + test(bso[0].length == 1); + test(bso[0][0]); + test(bso[1].length == 1); + test(!bso[1][0]); + test(bso[2].length == 2); + test(bso[2][0]); + test(bso[2][1]); + test(bso[3].length == 3); + test(!bso[3][0]); + test(!bso[3][1]); + test(bso[3][2]); + test(rso.length == 3); + test(rso[0].length == 2); + test(rso[0][0]); + test(rso[0][1]); + test(rso[1].length == 1); + test(!rso[1][0]); + test(rso[2].length == 1); + test(rso[2][0]); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opShortIntLongSSI extends Callback_MyClass_opShortIntLongSS + { + @Override + public void + response(long[][] rso, short[][] sso, int[][] iso, long[][] lso) + { + test(rso.length == 1); + test(rso[0].length == 2); + test(rso[0][0] == 496); + test(rso[0][1] == 1729); + test(sso.length == 3); + test(sso[0].length == 3); + test(sso[0][0] == 1); + test(sso[0][1] == 2); + test(sso[0][2] == 5); + test(sso[1].length == 1); + test(sso[1][0] == 13); + test(sso[2].length == 0); + test(iso.length == 2); + test(iso[0].length == 1); + test(iso[0][0] == 42); + test(iso[1].length == 2); + test(iso[1][0] == 24); + test(iso[1][1] == 98); + test(lso.length == 2); + test(lso[0].length == 2); + test(lso[0][0] == 496); + test(lso[0][1] == 1729); + test(lso[1].length == 2); + test(lso[1][0] == 496); + test(lso[1][1] == 1729); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opFloatDoubleSSI extends Callback_MyClass_opFloatDoubleSS + { + @Override + public void response(double[][] rso, float[][] fso, double[][] dso) + { + test(fso.length == 3); + test(fso[0].length == 1); + test(fso[0][0] == 3.14f); + test(fso[1].length == 1); + test(fso[1][0] == 1.11f); + test(fso[2].length == 0); + test(dso.length == 1); + test(dso[0].length == 3); + test(dso[0][0] == 1.1E10); + test(dso[0][1] == 1.2E10); + test(dso[0][2] == 1.3E10); + test(rso.length == 2); + test(rso[0].length == 3); + test(rso[0][0] == 1.1E10); + test(rso[0][1] == 1.2E10); + test(rso[0][2] == 1.3E10); + test(rso[1].length == 3); + test(rso[1][0] == 1.1E10); + test(rso[1][1] == 1.2E10); + test(rso[1][2] == 1.3E10); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opStringSSI extends Callback_MyClass_opStringSS + { + @Override + public void response(String[][] rso, String[][] sso) + { + test(sso.length == 5); + test(sso[0].length == 1); + test(sso[0][0].equals("abc")); + test(sso[1].length == 2); + test(sso[1][0].equals("de")); + test(sso[1][1].equals("fghi")); + test(sso[2].length == 0); + test(sso[3].length == 0); + test(sso[4].length == 1); + test(sso[4][0].equals("xyz")); + test(rso.length == 3); + test(rso[0].length == 1); + test(rso[0][0].equals("xyz")); + test(rso[1].length == 0); + test(rso[2].length == 0); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opStringSSSI extends Callback_MyClass_opStringSSS + { + @Override + public void response(String[][][] rsso, String[][][] ssso) + { + test(ssso.length == 5); + test(ssso[0].length == 2); + test(ssso[0][0].length == 2); + test(ssso[0][1].length == 1); + test(ssso[1].length == 1); + test(ssso[1][0].length == 1); + test(ssso[2].length == 2); + test(ssso[2][0].length == 2); + test(ssso[2][1].length == 1); + test(ssso[3].length == 1); + test(ssso[3][0].length == 1); + test(ssso[4].length == 0); + test(ssso[0][0][0].equals("abc")); + test(ssso[0][0][1].equals("de")); + test(ssso[0][1][0].equals("xyz")); + test(ssso[1][0][0].equals("hello")); + test(ssso[2][0][0].equals("")); + test(ssso[2][0][1].equals("")); + test(ssso[2][1][0].equals("abcd")); + test(ssso[3][0][0].equals("")); + + test(rsso.length == 3); + test(rsso[0].length == 0); + test(rsso[1].length == 1); + test(rsso[1][0].length == 1); + test(rsso[2].length == 2); + test(rsso[2][0].length == 2); + test(rsso[2][1].length == 1); + test(rsso[1][0][0].equals("")); + test(rsso[2][0][0].equals("")); + test(rsso[2][0][1].equals("")); + test(rsso[2][1][0].equals("abcd")); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opByteBoolDI extends Callback_MyClass_opByteBoolD + { + @Override + public void response(java.util.Map<Byte, Boolean> ro, java.util.Map<Byte, Boolean> _do) + { + java.util.Map<Byte, Boolean> di1 = new java.util.HashMap<Byte, Boolean>(); + di1.put((byte)10, Boolean.TRUE); + di1.put((byte)100, Boolean.FALSE); + test(_do.equals(di1)); + test(ro.size() == 4); + test(ro.get((byte)10).booleanValue() == true); + test(ro.get((byte)11).booleanValue() == false); + test(ro.get((byte)100).booleanValue() == false); + test(ro.get((byte)101).booleanValue() == true); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opShortIntDI extends Callback_MyClass_opShortIntD + { + @Override + public void response(java.util.Map<Short, Integer> ro, java.util.Map<Short, Integer> _do) + { + java.util.Map<Short, Integer> di1 = new java.util.HashMap<Short, Integer>(); + di1.put((short)110, -1); + di1.put((short)1100, 123123); + test(_do.equals(di1)); + test(ro.size() == 4); + test(ro.get((short)110).intValue() == -1); + test(ro.get((short)111).intValue() == -100); + test(ro.get((short)1100).intValue() == 123123); + test(ro.get((short)1101).intValue() == 0); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opLongFloatDI extends Callback_MyClass_opLongFloatD + { + @Override + public void response(java.util.Map<Long, Float> ro, java.util.Map<Long, Float> _do) + { + java.util.Map<Long, Float> di1 = new java.util.HashMap<Long, Float>(); + di1.put(999999110L, new Float(-1.1f)); + di1.put(999999111L, new Float(123123.2f)); + test(_do.equals(di1)); + test(ro.size() == 4); + test(ro.get(999999110L).floatValue() == -1.1f); + test(ro.get(999999120L).floatValue() == -100.4f); + test(ro.get(999999111L).floatValue() == 123123.2f); + test(ro.get(999999130L).floatValue() == 0.5f); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opStringStringDI extends Callback_MyClass_opStringStringD + { + @Override + public void response(java.util.Map<String, String> ro, java.util.Map<String, String> _do) + { + java.util.Map<String, String> di1 = new java.util.HashMap<String, String>(); + di1.put("foo", "abc -1.1"); + di1.put("bar", "abc 123123.2"); + test(_do.equals(di1)); + test(ro.size() == 4); + test(ro.get("foo").equals("abc -1.1")); + test(ro.get("FOO").equals("abc -100.4")); + test(ro.get("bar").equals("abc 123123.2")); + test(ro.get("BAR").equals("abc 0.5")); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opStringMyEnumDI extends Callback_MyClass_opStringMyEnumD + { + @Override + public void response(java.util.Map<String, MyEnum> ro, java.util.Map<String, MyEnum> _do) + { + java.util.Map<String, MyEnum> di1 = new java.util.HashMap<String, MyEnum>(); + di1.put("abc", MyEnum.enum1); + di1.put("", MyEnum.enum2); + test(_do.equals(di1)); + test(ro.size() == 4); + test(ro.get("abc") == MyEnum.enum1); + test(ro.get("qwerty") == MyEnum.enum3); + test(ro.get("") == MyEnum.enum2); + test(ro.get("Hello!!") == MyEnum.enum2); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opMyEnumStringDI extends Callback_MyClass_opMyEnumStringD + { + @Override + public void response(java.util.Map<MyEnum, String> ro, java.util.Map<MyEnum, String> _do) + { + java.util.Map<MyEnum, String> di1 = new java.util.HashMap<MyEnum, String>(); + di1.put(MyEnum.enum1, "abc"); + test(_do.equals(di1)); + test(ro.size() == 3); + test(ro.get(MyEnum.enum1).equals("abc")); + test(ro.get(MyEnum.enum2).equals("Hello!!")); + test(ro.get(MyEnum.enum3).equals("qwerty")); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opMyStructMyEnumDI extends Callback_MyClass_opMyStructMyEnumD + { + @Override + public void response(java.util.Map<MyStruct, MyEnum> ro, java.util.Map<MyStruct, MyEnum> _do) + { + MyStruct s11 = new MyStruct(1, 1); + MyStruct s12 = new MyStruct(1, 2); + java.util.Map<MyStruct, MyEnum> di1 = new java.util.HashMap<MyStruct, MyEnum>(); + di1.put(s11, MyEnum.enum1); + di1.put(s12, MyEnum.enum2); + test(_do.equals(di1)); + MyStruct s22 = new MyStruct(2, 2); + MyStruct s23 = new MyStruct(2, 3); + test(ro.size() == 4); + test(ro.get(s11) == MyEnum.enum1); + test(ro.get(s12) == MyEnum.enum2); + test(ro.get(s22) == MyEnum.enum3); + test(ro.get(s23) == MyEnum.enum2); + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opIntSI extends Callback_MyClass_opIntS + { + opIntSI(int l) + { + _l = l; + } + + @Override + public void response(int[] r) + { + test(r.length == _l); + for(int j = 0; j < r.length; ++j) + { + test(r[j] == -j); + } + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private int _l; + private Callback callback = new Callback(); + } + + private static class opDerivedI extends Callback_MyDerivedClass_opDerived + { + @Override + public void response() + { + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opDoubleMarshalingI extends Callback_MyClass_opDoubleMarshaling + { + @Override + public void response() + { + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opIdempotentI extends Callback_MyClass_opIdempotent + { + @Override + public void response() + { + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opNonmutatingI extends Callback_MyClass_opNonmutating + { + @Override + public void response() + { + callback.called(); + } + + @Override + public void exception(Ice.LocalException ex) + { + test(false); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + static void + twowaysAMI(test.Util.Application app, MyClassPrx p) + { + Ice.Communicator communicator = app.communicator(); + + { + pingI cb = new pingI(); + p.begin_ice_ping(cb); + cb.check(); + } + + { + isAI cb = new isAI(); + p.begin_ice_isA(MyClass.ice_staticId(), cb); + cb.check(); + } + + { + idI cb = new idI(); + p.begin_ice_id(cb); + cb.check(); + } + + { + idsI cb = new idsI(); + p.begin_ice_ids(cb); + cb.check(); + } + + { + Ice.AsyncResult r = p.begin_opVoid(); + p.end_opVoid(r); + } + + { + opVoidI cb = new opVoidI(); + p.begin_opVoid(cb); + cb.check(); + } + + { + Ice.AsyncResult r = p.begin_opByte((byte)0xff, (byte)0x0f); + Ice.ByteHolder p3 = new Ice.ByteHolder(); + byte ret = p.end_opByte(p3, r); + test(p3.value == (byte)0xf0); + test(ret == (byte)0xff); + } + + { + opByteI cb = new opByteI(); + p.begin_opByte((byte)0xff, (byte)0x0f, cb); + cb.check(); + } + + { + opBoolI cb = new opBoolI(); + p.begin_opBool(true, false, cb); + cb.check(); + } + + { + opShortIntLongI cb = new opShortIntLongI(); + p.begin_opShortIntLong((short)10, 11, 12L, cb); + cb.check(); + } + + { + opFloatDoubleI cb = new opFloatDoubleI(); + p.begin_opFloatDouble(3.14f, 1.1E10, cb); + cb.check(); + } + + { + opStringI cb = new opStringI(); + p.begin_opString("hello", "world", cb); + cb.check(); + } + + { + opMyEnumI cb = new opMyEnumI(); + p.begin_opMyEnum(MyEnum.enum2, cb); + cb.check(); + } + + { + opMyClassI cb = new opMyClassI(communicator); + p.begin_opMyClass(p, cb); + cb.check(); + } + + { + Structure si1 = new Structure(); + si1.p = p; + si1.e = MyEnum.enum3; + si1.s = new AnotherStruct(); + si1.s.s = "abc"; + Structure si2 = new Structure(); + si2.p = null; + si2.e = MyEnum.enum2; + si2.s = new AnotherStruct(); + si2.s.s = "def"; + + opStructI cb = new opStructI(communicator); + p.begin_opStruct(si1, si2, cb); + cb.check(); + } + + { + final byte[] bsi1 = + { + (byte)0x01, + (byte)0x11, + (byte)0x12, + (byte)0x22 + }; + final byte[] bsi2 = + { + (byte)0xf1, + (byte)0xf2, + (byte)0xf3, + (byte)0xf4 + }; + + opByteSI cb = new opByteSI(); + p.begin_opByteS(bsi1, bsi2, cb); + cb.check(); + } + + { + final boolean[] bsi1 = { true, true, false }; + final boolean[] bsi2 = { false }; + + opBoolSI cb = new opBoolSI(); + p.begin_opBoolS(bsi1, bsi2, cb); + cb.check(); + } + + { + final short[] ssi = { 1, 2, 3 }; + final int[] isi = { 5, 6, 7, 8 }; + final long[] lsi = { 10, 30, 20 }; + + opShortIntLongSI cb = new opShortIntLongSI(); + p.begin_opShortIntLongS(ssi, isi, lsi, cb); + cb.check(); + } + + { + final float[] fsi = { 3.14f, 1.11f }; + final double[] dsi = { 1.1E10, 1.2E10, 1.3E10 }; + + opFloatDoubleSI cb = new opFloatDoubleSI(); + p.begin_opFloatDoubleS(fsi, dsi, cb); + cb.check(); + } + + { + final String[] ssi1 = { "abc", "de", "fghi" }; + final String[] ssi2 = { "xyz" }; + + opStringSI cb = new opStringSI(); + p.begin_opStringS(ssi1, ssi2, cb); + cb.check(); + } + + { + final byte[][] bsi1 = + { + { (byte)0x01, (byte)0x11, (byte)0x12 }, + { (byte)0xff } + }; + final byte[][] bsi2 = + { + { (byte)0x0e }, + { (byte)0xf2, (byte)0xf1 } + }; + + opByteSSI cb = new opByteSSI(); + p.begin_opByteSS(bsi1, bsi2, cb); + cb.check(); + } + + { + final boolean[][] bsi1 = + { + { true }, + { false }, + { true, true} + }; + + final boolean[][] bsi2 = + { + { false, false, true } + }; + + opBoolSSI cb = new opBoolSSI(); + p.begin_opBoolSS(bsi1, bsi2, cb); + cb.check(); + } + + { + final short[][] ssi= + { + {1, 2, 5}, + {13}, + {} + }; + final int[][] isi = + { + {24, 98}, + {42} + }; + final long[][] lsi = + { + {496, 1729}, + }; + + opShortIntLongSSI cb = new opShortIntLongSSI(); + p.begin_opShortIntLongSS(ssi, isi, lsi, cb); + cb.check(); + } + + { + final float[][] fsi = + { + { 3.14f }, + { 1.11f }, + { }, + }; + final double[][] dsi = + { + { 1.1E10, 1.2E10, 1.3E10 } + }; + + opFloatDoubleSSI cb = new opFloatDoubleSSI(); + p.begin_opFloatDoubleSS(fsi, dsi, cb); + cb.check(); + } + + { + final String[][] ssi1 = + { + { "abc" }, + { "de", "fghi" } + }; + final String[][] ssi2 = + { + { }, + { }, + { "xyz" } + }; + + opStringSSI cb = new opStringSSI(); + p.begin_opStringSS(ssi1, ssi2, cb); + cb.check(); + } + + { + final String[][][] sssi1 = + { + { + { + "abc", "de" + }, + { + "xyz" + } + }, + { + { + "hello" + } + } + }; + + final String[][][] sssi2 = + { + { + { + "", "" + }, + { + "abcd" + } + }, + { + { + "" + } + }, + { + } + }; + + opStringSSSI cb = new opStringSSSI(); + p.begin_opStringSSS(sssi1, sssi2, cb); + cb.check(); + } + + { + java.util.Map<Byte, Boolean> di1 = new java.util.HashMap<Byte, Boolean>(); + di1.put((byte)10, Boolean.TRUE); + di1.put((byte)100, Boolean.FALSE); + java.util.Map<Byte, Boolean> di2 = new java.util.HashMap<Byte, Boolean>(); + di2.put((byte)10, Boolean.TRUE); + di2.put((byte)11, Boolean.FALSE); + di2.put((byte)101, Boolean.TRUE); + + opByteBoolDI cb = new opByteBoolDI(); + p.begin_opByteBoolD(di1, di2, cb); + cb.check(); + } + + { + java.util.Map<Short, Integer> di1 = new java.util.HashMap<Short, Integer>(); + di1.put((short)110, -1); + di1.put((short)1100, 123123); + java.util.Map<Short, Integer> di2 = new java.util.HashMap<Short, Integer>(); + di2.put((short)110, -1); + di2.put((short)111, -100); + di2.put((short)1101, 0); + + opShortIntDI cb = new opShortIntDI(); + p.begin_opShortIntD(di1, di2, cb); + cb.check(); + } + + { + java.util.Map<Long, Float> di1 = new java.util.HashMap<Long, Float>(); + di1.put(999999110L, new Float(-1.1f)); + di1.put(999999111L, new Float(123123.2f)); + java.util.Map<Long, Float> di2 = new java.util.HashMap<Long, Float>(); + di2.put(999999110L, new Float(-1.1f)); + di2.put(999999120L, new Float(-100.4f)); + di2.put(999999130L, new Float(0.5f)); + + opLongFloatDI cb = new opLongFloatDI(); + p.begin_opLongFloatD(di1, di2, cb); + cb.check(); + } + + { + java.util.Map<String, String> di1 = new java.util.HashMap<String, String>(); + di1.put("foo", "abc -1.1"); + di1.put("bar", "abc 123123.2"); + java.util.Map<String, String> di2 = new java.util.HashMap<String, String>(); + di2.put("foo", "abc -1.1"); + di2.put("FOO", "abc -100.4"); + di2.put("BAR", "abc 0.5"); + + opStringStringDI cb = new opStringStringDI(); + p.begin_opStringStringD(di1, di2, cb); + cb.check(); + } + + { + java.util.Map<String, MyEnum> di1 = new java.util.HashMap<String, MyEnum>(); + di1.put("abc", MyEnum.enum1); + di1.put("", MyEnum.enum2); + java.util.Map<String, MyEnum> di2 = new java.util.HashMap<String, MyEnum>(); + di2.put("abc", MyEnum.enum1); + di2.put("qwerty", MyEnum.enum3); + di2.put("Hello!!", MyEnum.enum2); + + opStringMyEnumDI cb = new opStringMyEnumDI(); + p.begin_opStringMyEnumD(di1, di2, cb); + cb.check(); + } + + { + java.util.Map<MyEnum, String> di1 = new java.util.HashMap<MyEnum, String>(); + di1.put(MyEnum.enum1, "abc"); + java.util.Map<MyEnum, String> di2 = new java.util.HashMap<MyEnum, String>(); + di2.put(MyEnum.enum2, "Hello!!"); + di2.put(MyEnum.enum3, "qwerty"); + + opMyEnumStringDI cb = new opMyEnumStringDI(); + p.begin_opMyEnumStringD(di1, di2, cb); + cb.check(); + } + + { + MyStruct s11 = new MyStruct(1, 1); + MyStruct s12 = new MyStruct(1, 2); + java.util.Map<MyStruct, MyEnum> di1 = new java.util.HashMap<MyStruct, MyEnum>(); + di1.put(s11, MyEnum.enum1); + di1.put(s12, MyEnum.enum2); + MyStruct s22 = new MyStruct(2, 2); + MyStruct s23 = new MyStruct(2, 3); + java.util.Map<MyStruct, MyEnum> di2 = new java.util.HashMap<MyStruct, MyEnum>(); + di2.put(s11, MyEnum.enum1); + di2.put(s22, MyEnum.enum3); + di2.put(s23, MyEnum.enum2); + + opMyStructMyEnumDI cb = new opMyStructMyEnumDI(); + p.begin_opMyStructMyEnumD(di1, di2, cb); + cb.check(); + } + + { + int[] lengths = { 0, 1, 2, 126, 127, 128, 129, 253, 254, 255, 256, 257, 1000 }; + + for(int l : lengths) + { + int[] s = new int[l]; + for(int i = 0; i < s.length; ++i) + { + s[i] = i; + } + opIntSI cb = new opIntSI(l); + p.begin_opIntS(s, cb); + cb.check(); + } + } + + { + java.util.Map<String, String> ctx = new java.util.HashMap<String, String>(); + ctx.put("one", "ONE"); + ctx.put("two", "TWO"); + ctx.put("three", "THREE"); + { + test(p.ice_getContext().isEmpty()); + Ice.AsyncResult r = p.begin_opContext(); + java.util.Map<String, String> c = p.end_opContext(r); + test(!c.equals(ctx)); + } + { + test(p.ice_getContext().isEmpty()); + Ice.AsyncResult r = p.begin_opContext(ctx); + java.util.Map<String, String> c = p.end_opContext(r); + test(c.equals(ctx)); + } + MyClassPrx p2 = MyClassPrxHelper.checkedCast(p.ice_context(ctx)); + test(p2.ice_getContext().equals(ctx)); + { + Ice.AsyncResult r = p2.begin_opContext(); + java.util.Map<String, String> c = p2.end_opContext(r); + test(c.equals(ctx)); + } + { + Ice.AsyncResult r = p2.begin_opContext(ctx); + java.util.Map<String, String> c = p2.end_opContext(r); + test(c.equals(ctx)); + } + } + + { + // + // Test implicit context propagation + // + + String[] impls = {"Shared", "PerThread"}; + for(int i = 0; i < 2; i++) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + initData.properties.setProperty("Ice.ImplicitContext", impls[i]); + + Ice.Communicator ic = app.initialize(initData); + + java.util.Map<String, String> ctx = new java.util.HashMap<String, String>(); + ctx.put("one", "ONE"); + ctx.put("two", "TWO"); + ctx.put("three", "THREE"); + + MyClassPrx p3 = MyClassPrxHelper.uncheckedCast(ic.stringToProxy("test:default -p 12010")); + + ic.getImplicitContext().setContext(ctx); + test(ic.getImplicitContext().getContext().equals(ctx)); + { + Ice.AsyncResult r = p3.begin_opContext(); + java.util.Map<String, String> c = p3.end_opContext(r); + test(c.equals(ctx)); + } + + ic.getImplicitContext().put("zero", "ZERO"); + + ctx = ic.getImplicitContext().getContext(); + { + Ice.AsyncResult r = p3.begin_opContext(); + java.util.Map<String, String> c = p3.end_opContext(r); + test(c.equals(ctx)); + } + + java.util.Map<String, String> prxContext = new java.util.HashMap<String, String>(); + prxContext.put("one", "UN"); + prxContext.put("four", "QUATRE"); + + java.util.Map<String, String> combined = new java.util.HashMap<String, String>(ctx); + combined.putAll(prxContext); + test(combined.get("one").equals("UN")); + + p3 = MyClassPrxHelper.uncheckedCast(p3.ice_context(prxContext)); + + ic.getImplicitContext().setContext(null); + { + Ice.AsyncResult r = p3.begin_opContext(); + java.util.Map<String, String> c = p3.end_opContext(r); + test(c.equals(prxContext)); + } + + ic.getImplicitContext().setContext(ctx); + { + Ice.AsyncResult r = p3.begin_opContext(); + java.util.Map<String, String> c = p3.end_opContext(r); + test(c.equals(combined)); + } + + ic.destroy(); + } + } + + { + double d = 1278312346.0 / 13.0; + double[] ds = new double[5]; + for(int i = 0; i < 5; i++) + { + ds[i] = d; + } + opDoubleMarshalingI cb = new opDoubleMarshalingI(); + p.begin_opDoubleMarshaling(d, ds, cb); + cb.check(); + } + + { + opIdempotentI cb = new opIdempotentI(); + p.begin_opIdempotent(cb); + cb.check(); + } + + { + opNonmutatingI cb = new opNonmutatingI(); + p.begin_opNonmutating(cb); + cb.check(); + } + + { + MyDerivedClassPrx derived = MyDerivedClassPrxHelper.checkedCast(p); + test(derived != null); + opDerivedI cb = new opDerivedI(); + derived.begin_opDerived(cb); + cb.check(); + } + } +} diff --git a/java/test/src/main/java/test/Ice/operations/lambda/OnewaysLambdaAMI.java b/java/test/src/main/java/test/Ice/operations/lambda/OnewaysLambdaAMI.java new file mode 100644 index 00000000000..d5885bb2b31 --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/lambda/OnewaysLambdaAMI.java @@ -0,0 +1,158 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations.lambda; + +import test.Ice.operations.Test.MyClassPrx; + +public class OnewaysLambdaAMI +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void called() + { + assert(!_called); + _called = true; + notify(); + } + + public void + sent(boolean sentSynchronously) + { + called(); + } + + void noException(Ice.Exception ex) + { + test(false); + } + + private boolean _called; + } + + public static void + onewaysLambdaAMI(test.Util.Application app, MyClassPrx proxy) + { + MyClassPrx p = (MyClassPrx)proxy.ice_oneway(); + + { + final Callback cb = new Callback(); + p.begin_ice_ping( + () -> test(false), + (Ice.Exception ex) -> cb.noException(ex), + (boolean sent) -> cb.sent(sent) + ); + cb.check(); + } + + { + try + { + p.begin_ice_isA("::Test::MyClass"); + test(false); + } + catch(java.lang.IllegalArgumentException ex) + { + } + } + + { + try + { + p.begin_ice_id(); + test(false); + } + catch(java.lang.IllegalArgumentException ex) + { + } + } + + { + try + { + p.begin_ice_ids(); + test(false); + } + catch(java.lang.IllegalArgumentException ex) + { + } + } + + { + final Callback cb = new Callback(); + p.begin_opVoid( + () -> test(false), + (Ice.Exception ex) -> cb.noException(ex), + (boolean sent) -> cb.sent(sent) + ); + cb.check(); + } + + { + final Callback cb = new Callback(); + p.begin_opIdempotent( + () -> test(false), + (Ice.Exception ex) -> cb.noException(ex), + (boolean sent) -> cb.sent(sent) + ); + cb.check(); + } + + { + final Callback cb = new Callback(); + p.begin_opNonmutating( + () -> test(false), + (Ice.Exception ex) -> cb.noException(ex), + (boolean sent) -> cb.sent(sent) + ); + cb.check(); + } + + { + try + { + p.begin_opByte((byte)0xff, (byte)0x0f); + test(false); + } + catch(java.lang.IllegalArgumentException ex) + { + } + } + } +} diff --git a/java/test/src/main/java/test/Ice/operations/lambda/TwowaysLambdaAMI.java b/java/test/src/main/java/test/Ice/operations/lambda/TwowaysLambdaAMI.java new file mode 100644 index 00000000000..81f4dcb321e --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/lambda/TwowaysLambdaAMI.java @@ -0,0 +1,1433 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.operations.lambda; + +import test.Ice.operations.Test.AnotherStruct; +import test.Ice.operations.Test.MyClass; +import test.Ice.operations.Test.MyClassPrx; +import test.Ice.operations.Test.MyDerivedClass; +import test.Ice.operations.Test.MyDerivedClassPrx; +import test.Ice.operations.Test.MyDerivedClassPrxHelper; +import test.Ice.operations.Test.MyEnum; +import test.Ice.operations.Test.Structure; +import test.Ice.operations.Test.MyStruct; + +import java.util.Map; + +public class TwowaysLambdaAMI +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static class pingI + { + public void response() + { + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class isAI + { + public void response(boolean r) + { + test(r); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class idI + { + public void response(String id) + { + test(id.equals(MyDerivedClass.ice_staticId())); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class idsI + { + public void response(String[] ids) + { + test(ids.length == 3); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opVoidI + { + public void response() + { + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opByteI + { + public void response(byte r, byte b) + { + test(b == (byte)0xf0); + test(r == (byte)0xff); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opBoolI + { + public void response(boolean r, boolean b) + { + test(b); + test(!r); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opShortIntLongI + { + public void response(long r, short s, int i, long l) + { + test(s == 10); + test(i == 11); + test(l == 12); + test(r == 12); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opFloatDoubleI + { + public void response(double r, float f, double d) + { + test(f == 3.14f); + test(d == 1.1E10); + test(r == 1.1E10); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opStringI + { + public void response(String r, String s) + { + test(s.equals("world hello")); + test(r.equals("hello world")); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opMyEnumI + { + public void response(MyEnum r, MyEnum e) + { + test(e == MyEnum.enum2); + test(r == MyEnum.enum3); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opMyClassI + { + opMyClassI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + public void response(MyClassPrx r, MyClassPrx c1, MyClassPrx c2) + { + test(c1.ice_getIdentity().equals(_communicator.stringToIdentity("test"))); + test(c2.ice_getIdentity().equals(_communicator.stringToIdentity("noSuchIdentity"))); + test(r.ice_getIdentity().equals(_communicator.stringToIdentity("test"))); + // We can't do the callbacks below in connection serialization mode. + if(_communicator.getProperties().getPropertyAsInt("Ice.ThreadPool.Client.Serialize") == 0) + { + r.opVoid(); + c1.opVoid(); + try + { + c2.opVoid(); + test(false); + } + catch(Ice.ObjectNotExistException ex) + { + } + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + private Ice.Communicator _communicator; + } + + private static class opStructI + { + opStructI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + public void response(Structure rso, Structure so) + { + test(rso.p == null); + test(rso.e == MyEnum.enum2); + test(rso.s.s.equals("def")); + test(so.e == MyEnum.enum3); + test(so.s.s.equals("a new string")); + // We can't do the callbacks below in connection serialization mode. + if(_communicator.getProperties().getPropertyAsInt("Ice.ThreadPool.Client.Serialize") == 0) + { + so.p.opVoid(); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + private Ice.Communicator _communicator; + } + + private static class opByteSI + { + public void response(byte[] rso, byte[] bso) + { + test(bso.length == 4); + test(bso[0] == (byte)0x22); + test(bso[1] == (byte)0x12); + test(bso[2] == (byte)0x11); + test(bso[3] == (byte)0x01); + test(rso.length == 8); + test(rso[0] == (byte)0x01); + test(rso[1] == (byte)0x11); + test(rso[2] == (byte)0x12); + test(rso[3] == (byte)0x22); + test(rso[4] == (byte)0xf1); + test(rso[5] == (byte)0xf2); + test(rso[6] == (byte)0xf3); + test(rso[7] == (byte)0xf4); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opBoolSI + { + public void response(boolean[] rso, boolean[] bso) + { + test(bso.length == 4); + test(bso[0]); + test(bso[1]); + test(!bso[2]); + test(!bso[3]); + test(rso.length == 3); + test(!rso[0]); + test(rso[1]); + test(rso[2]); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opShortIntLongSI + { + public void response(long[] rso, short[] sso, int[] iso, long[] lso) + { + test(sso.length == 3); + test(sso[0] == 1); + test(sso[1] == 2); + test(sso[2] == 3); + test(iso.length == 4); + test(iso[0] == 8); + test(iso[1] == 7); + test(iso[2] == 6); + test(iso[3] == 5); + test(lso.length == 6); + test(lso[0] == 10); + test(lso[1] == 30); + test(lso[2] == 20); + test(lso[3] == 10); + test(lso[4] == 30); + test(lso[5] == 20); + test(rso.length == 3); + test(rso[0] == 10); + test(rso[1] == 30); + test(rso[2] == 20); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opFloatDoubleSI + { + public void response(double[] rso, float[] fso, double[] dso) + { + test(fso.length == 2); + test(fso[0] == 3.14f); + test(fso[1] == 1.11f); + test(dso.length == 3); + test(dso[0] == 1.3E10); + test(dso[1] == 1.2E10); + test(dso[2] == 1.1E10); + test(rso.length == 5); + test(rso[0] == 1.1E10); + test(rso[1] == 1.2E10); + test(rso[2] == 1.3E10); + test((float)rso[3] == 3.14f); + test((float)rso[4] == 1.11f); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opStringSI + { + public void response(String[] rso, String[] sso) + { + test(sso.length == 4); + test(sso[0].equals("abc")); + test(sso[1].equals("de")); + test(sso[2].equals("fghi")); + test(sso[3].equals("xyz")); + test(rso.length == 3); + test(rso[0].equals("fghi")); + test(rso[1].equals("de")); + test(rso[2].equals("abc")); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opByteSSI + { + public void response(byte[][] rso, byte[][] bso) + { + test(bso.length == 2); + test(bso[0].length == 1); + test(bso[0][0] == (byte)0xff); + test(bso[1].length == 3); + test(bso[1][0] == (byte)0x01); + test(bso[1][1] == (byte)0x11); + test(bso[1][2] == (byte)0x12); + test(rso.length == 4); + test(rso[0].length == 3); + test(rso[0][0] == (byte)0x01); + test(rso[0][1] == (byte)0x11); + test(rso[0][2] == (byte)0x12); + test(rso[1].length == 1); + test(rso[1][0] == (byte)0xff); + test(rso[2].length == 1); + test(rso[2][0] == (byte)0x0e); + test(rso[3].length == 2); + test(rso[3][0] == (byte)0xf2); + test(rso[3][1] == (byte)0xf1); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opBoolSSI + { + public void response(boolean[][] rso, boolean[][] bso) + { + test(bso.length == 4); + test(bso[0].length == 1); + test(bso[0][0]); + test(bso[1].length == 1); + test(!bso[1][0]); + test(bso[2].length == 2); + test(bso[2][0]); + test(bso[2][1]); + test(bso[3].length == 3); + test(!bso[3][0]); + test(!bso[3][1]); + test(bso[3][2]); + test(rso.length == 3); + test(rso[0].length == 2); + test(rso[0][0]); + test(rso[0][1]); + test(rso[1].length == 1); + test(!rso[1][0]); + test(rso[2].length == 1); + test(rso[2][0]); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opShortIntLongSSI + { + public void response(long[][] rso, short[][] sso, int[][] iso, long[][] lso) + { + test(rso.length == 1); + test(rso[0].length == 2); + test(rso[0][0] == 496); + test(rso[0][1] == 1729); + test(sso.length == 3); + test(sso[0].length == 3); + test(sso[0][0] == 1); + test(sso[0][1] == 2); + test(sso[0][2] == 5); + test(sso[1].length == 1); + test(sso[1][0] == 13); + test(sso[2].length == 0); + test(iso.length == 2); + test(iso[0].length == 1); + test(iso[0][0] == 42); + test(iso[1].length == 2); + test(iso[1][0] == 24); + test(iso[1][1] == 98); + test(lso.length == 2); + test(lso[0].length == 2); + test(lso[0][0] == 496); + test(lso[0][1] == 1729); + test(lso[1].length == 2); + test(lso[1][0] == 496); + test(lso[1][1] == 1729); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opFloatDoubleSSI + { + public void response(double[][] rso, float[][] fso, double[][] dso) + { + test(fso.length == 3); + test(fso[0].length == 1); + test(fso[0][0] == 3.14f); + test(fso[1].length == 1); + test(fso[1][0] == 1.11f); + test(fso[2].length == 0); + test(dso.length == 1); + test(dso[0].length == 3); + test(dso[0][0] == 1.1E10); + test(dso[0][1] == 1.2E10); + test(dso[0][2] == 1.3E10); + test(rso.length == 2); + test(rso[0].length == 3); + test(rso[0][0] == 1.1E10); + test(rso[0][1] == 1.2E10); + test(rso[0][2] == 1.3E10); + test(rso[1].length == 3); + test(rso[1][0] == 1.1E10); + test(rso[1][1] == 1.2E10); + test(rso[1][2] == 1.3E10); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opStringSSI + { + public void response(String[][] rso, String[][] sso) + { + test(sso.length == 5); + test(sso[0].length == 1); + test(sso[0][0].equals("abc")); + test(sso[1].length == 2); + test(sso[1][0].equals("de")); + test(sso[1][1].equals("fghi")); + test(sso[2].length == 0); + test(sso[3].length == 0); + test(sso[4].length == 1); + test(sso[4][0].equals("xyz")); + test(rso.length == 3); + test(rso[0].length == 1); + test(rso[0][0].equals("xyz")); + test(rso[1].length == 0); + test(rso[2].length == 0); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opStringSSSI + { + public void response(String[][][] rsso, String[][][] ssso) + { + test(ssso.length == 5); + test(ssso[0].length == 2); + test(ssso[0][0].length == 2); + test(ssso[0][1].length == 1); + test(ssso[1].length == 1); + test(ssso[1][0].length == 1); + test(ssso[2].length == 2); + test(ssso[2][0].length == 2); + test(ssso[2][1].length == 1); + test(ssso[3].length == 1); + test(ssso[3][0].length == 1); + test(ssso[4].length == 0); + test(ssso[0][0][0].equals("abc")); + test(ssso[0][0][1].equals("de")); + test(ssso[0][1][0].equals("xyz")); + test(ssso[1][0][0].equals("hello")); + test(ssso[2][0][0].equals("")); + test(ssso[2][0][1].equals("")); + test(ssso[2][1][0].equals("abcd")); + test(ssso[3][0][0].equals("")); + + test(rsso.length == 3); + test(rsso[0].length == 0); + test(rsso[1].length == 1); + test(rsso[1][0].length == 1); + test(rsso[2].length == 2); + test(rsso[2][0].length == 2); + test(rsso[2][1].length == 1); + test(rsso[1][0][0].equals("")); + test(rsso[2][0][0].equals("")); + test(rsso[2][0][1].equals("")); + test(rsso[2][1][0].equals("abcd")); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opByteBoolDI + { + public void response(java.util.Map<Byte, Boolean> ro, java.util.Map<Byte, Boolean> _do) + { + java.util.Map<Byte, Boolean> di1 = new java.util.HashMap<Byte, Boolean>(); + di1.put((byte)10, Boolean.TRUE); + di1.put((byte)100, Boolean.FALSE); + test(_do.equals(di1)); + test(ro.size() == 4); + test(ro.get((byte)10).booleanValue() == true); + test(ro.get((byte)11).booleanValue() == false); + test(ro.get((byte)100).booleanValue() == false); + test(ro.get((byte)101).booleanValue() == true); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opShortIntDI + { + public void response(java.util.Map<Short, Integer> ro, java.util.Map<Short, Integer> _do) + { + java.util.Map<Short, Integer> di1 = new java.util.HashMap<Short, Integer>(); + di1.put((short)110, -1); + di1.put((short)1100, 123123); + test(_do.equals(di1)); + test(ro.size() == 4); + test(ro.get((short)110).intValue() == -1); + test(ro.get((short)111).intValue() == -100); + test(ro.get((short)1100).intValue() == 123123); + test(ro.get((short)1101).intValue() == 0); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opLongFloatDI + { + public void response(java.util.Map<Long, Float> ro, java.util.Map<Long, Float> _do) + { + java.util.Map<Long, Float> di1 = new java.util.HashMap<Long, Float>(); + di1.put(999999110L, new Float(-1.1f)); + di1.put(999999111L, new Float(123123.2f)); + test(_do.equals(di1)); + test(ro.size() == 4); + test(ro.get(999999110L).floatValue() == -1.1f); + test(ro.get(999999120L).floatValue() == -100.4f); + test(ro.get(999999111L).floatValue() == 123123.2f); + test(ro.get(999999130L).floatValue() == 0.5f); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opStringStringDI + { + public void response(java.util.Map<String, String> ro, java.util.Map<String, String> _do) + { + java.util.Map<String, String> di1 = new java.util.HashMap<String, String>(); + di1.put("foo", "abc -1.1"); + di1.put("bar", "abc 123123.2"); + test(_do.equals(di1)); + test(ro.size() == 4); + test(ro.get("foo").equals("abc -1.1")); + test(ro.get("FOO").equals("abc -100.4")); + test(ro.get("bar").equals("abc 123123.2")); + test(ro.get("BAR").equals("abc 0.5")); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opStringMyEnumDI + { + public void response(java.util.Map<String, MyEnum> ro, java.util.Map<String, MyEnum> _do) + { + java.util.Map<String, MyEnum> di1 = new java.util.HashMap<String, MyEnum>(); + di1.put("abc", MyEnum.enum1); + di1.put("", MyEnum.enum2); + test(_do.equals(di1)); + test(ro.size() == 4); + test(ro.get("abc") == MyEnum.enum1); + test(ro.get("qwerty") == MyEnum.enum3); + test(ro.get("") == MyEnum.enum2); + test(ro.get("Hello!!") == MyEnum.enum2); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opMyEnumStringDI + { + public void response(java.util.Map<MyEnum, String> ro, java.util.Map<MyEnum, String> _do) + { + java.util.Map<MyEnum, String> di1 = new java.util.HashMap<MyEnum, String>(); + di1.put(MyEnum.enum1, "abc"); + test(_do.equals(di1)); + test(ro.size() == 3); + test(ro.get(MyEnum.enum1).equals("abc")); + test(ro.get(MyEnum.enum2).equals("Hello!!")); + test(ro.get(MyEnum.enum3).equals("qwerty")); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opMyStructMyEnumDI + { + public void response(java.util.Map<MyStruct, MyEnum> ro, java.util.Map<MyStruct, MyEnum> _do) + { + MyStruct s11 = new MyStruct(1, 1); + MyStruct s12 = new MyStruct(1, 2); + java.util.Map<MyStruct, MyEnum> di1 = new java.util.HashMap<MyStruct, MyEnum>(); + di1.put(s11, MyEnum.enum1); + di1.put(s12, MyEnum.enum2); + test(_do.equals(di1)); + MyStruct s22 = new MyStruct(2, 2); + MyStruct s23 = new MyStruct(2, 3); + test(ro.size() == 4); + test(ro.get(s11) == MyEnum.enum1); + test(ro.get(s12) == MyEnum.enum2); + test(ro.get(s22) == MyEnum.enum3); + test(ro.get(s23) == MyEnum.enum2); + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opIntSI + { + opIntSI(int l) + { + _l = l; + } + + public void response(int[] r) + { + test(r.length == _l); + for(int j = 0; j < r.length; ++j) + { + test(r[j] == -j); + } + callback.called(); + } + + public void check() + { + callback.check(); + } + + private int _l; + private Callback callback = new Callback(); + } + + private static class opDerivedI + { + public void response() + { + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opDoubleMarshalingI + { + public void response() + { + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opIdempotentI + { + public void response() + { + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class opNonmutatingI + { + public void response() + { + callback.called(); + } + + public void check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + public static void + twowaysLambdaAMI(test.Util.Application app, MyClassPrx p) + { + Ice.Communicator communicator = app.communicator(); + + { + pingI cb = new pingI(); + p.begin_ice_ping(() -> cb.response(), (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + isAI cb = new isAI(); + p.begin_ice_isA(MyClass.ice_staticId(), (boolean r) -> cb.response(r), (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + idI cb = new idI(); + p.begin_ice_id((String id) -> cb.response(id), (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + idsI cb = new idsI(); + p.begin_ice_ids((String[] ids) -> cb.response(ids), (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + opVoidI cb = new opVoidI(); + p.begin_opVoid(() -> cb.response(), (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + opByteI cb = new opByteI(); + p.begin_opByte((byte)0xff, (byte)0x0f, + (byte p1, byte p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + opBoolI cb = new opBoolI(); + p.begin_opBool(true, false, + (boolean p1, boolean p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + opShortIntLongI cb = new opShortIntLongI(); + p.begin_opShortIntLong((short)10, 11, 12L, + (long p1, short p2, int p3, long p4) -> cb.response(p1, p2, p3, p4), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + opFloatDoubleI cb = new opFloatDoubleI(); + p.begin_opFloatDouble(3.14f, 1.1E10, + (double p1, float p2, double p3) -> cb.response(p1, p2, p3), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + opStringI cb = new opStringI(); + p.begin_opString("hello", "world", + (String p1, String p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + opMyEnumI cb = new opMyEnumI(); + p.begin_opMyEnum(MyEnum.enum2, + (MyEnum p1, MyEnum p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + opMyClassI cb = new opMyClassI(communicator); + p.begin_opMyClass(p, + (MyClassPrx p1, MyClassPrx p2, MyClassPrx p3) -> cb.response(p1, p2, p3), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + Structure si1 = new Structure(); + si1.p = p; + si1.e = MyEnum.enum3; + si1.s = new AnotherStruct(); + si1.s.s = "abc"; + Structure si2 = new Structure(); + si2.p = null; + si2.e = MyEnum.enum2; + si2.s = new AnotherStruct(); + si2.s.s = "def"; + + opStructI cb = new opStructI(communicator); + p.begin_opStruct(si1, si2, + (Structure p1, Structure p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + final byte[] bsi1 = + { + (byte)0x01, + (byte)0x11, + (byte)0x12, + (byte)0x22 + }; + final byte[] bsi2 = + { + (byte)0xf1, + (byte)0xf2, + (byte)0xf3, + (byte)0xf4 + }; + + opByteSI cb = new opByteSI(); + p.begin_opByteS(bsi1, bsi2, + (byte[] p1, byte[] p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + final boolean[] bsi1 = { true, true, false }; + final boolean[] bsi2 = { false }; + + opBoolSI cb = new opBoolSI(); + p.begin_opBoolS(bsi1, bsi2, + (boolean[] p1, boolean[] p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + final short[] ssi = { 1, 2, 3 }; + final int[] isi = { 5, 6, 7, 8 }; + final long[] lsi = { 10, 30, 20 }; + + opShortIntLongSI cb = new opShortIntLongSI(); + p.begin_opShortIntLongS(ssi, isi, lsi, + (long[] p1, short[] p2, int[] p3, long[] p4) -> cb.response(p1, p2, p3, p4), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + final float[] fsi = { 3.14f, 1.11f }; + final double[] dsi = { 1.1E10, 1.2E10, 1.3E10 }; + + opFloatDoubleSI cb = new opFloatDoubleSI(); + p.begin_opFloatDoubleS(fsi, dsi, + (double[] p1, float[] p2, double[] p3) -> cb.response(p1, p2, p3), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + final String[] ssi1 = { "abc", "de", "fghi" }; + final String[] ssi2 = { "xyz" }; + + opStringSI cb = new opStringSI(); + p.begin_opStringS(ssi1, ssi2, + (String[] p1, String[] p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + final byte[][] bsi1 = + { + { (byte)0x01, (byte)0x11, (byte)0x12 }, + { (byte)0xff } + }; + final byte[][] bsi2 = + { + { (byte)0x0e }, + { (byte)0xf2, (byte)0xf1 } + }; + + opByteSSI cb = new opByteSSI(); + p.begin_opByteSS(bsi1, bsi2, + (byte[][] p1, byte[][] p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + final boolean[][] bsi1 = + { + { true }, + { false }, + { true, true} + }; + + final boolean[][] bsi2 = + { + { false, false, true } + }; + + opBoolSSI cb = new opBoolSSI(); + p.begin_opBoolSS(bsi1, bsi2, + (boolean[][] rso, boolean[][] bso) -> cb.response(rso, bso), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + final short[][] ssi= + { + {1, 2, 5}, + {13}, + {} + }; + final int[][] isi = + { + {24, 98}, + {42} + }; + final long[][] lsi = + { + {496, 1729}, + }; + + opShortIntLongSSI cb = new opShortIntLongSSI(); + p.begin_opShortIntLongSS(ssi, isi, lsi, + (long[][] rso, short[][] sso, int[][] iso, long lso[][]) -> cb.response(rso, sso, iso, lso), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + final float[][] fsi = + { + { 3.14f }, + { 1.11f }, + { }, + }; + final double[][] dsi = + { + { 1.1E10, 1.2E10, 1.3E10 } + }; + + opFloatDoubleSSI cb = new opFloatDoubleSSI(); + p.begin_opFloatDoubleSS(fsi, dsi, + (double[][] p1, float[][] p2, double[][] p3) -> cb.response(p1, p2, p3), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + final String[][] ssi1 = + { + { "abc" }, + { "de", "fghi" } + }; + final String[][] ssi2 = + { + { }, + { }, + { "xyz" } + }; + + opStringSSI cb = new opStringSSI(); + p.begin_opStringSS(ssi1, ssi2, + (String[][] p1, String[][] p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + final String[][][] sssi1 = + { + { + { + "abc", "de" + }, + { + "xyz" + } + }, + { + { + "hello" + } + } + }; + + final String[][][] sssi2 = + { + { + { + "", "" + }, + { + "abcd" + } + }, + { + { + "" + } + }, + { + } + }; + + opStringSSSI cb = new opStringSSSI(); + p.begin_opStringSSS(sssi1, sssi2, + (String[][][] p1, String[][][] p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + java.util.Map<Byte, Boolean> di1 = new java.util.HashMap<Byte, Boolean>(); + di1.put((byte)10, Boolean.TRUE); + di1.put((byte)100, Boolean.FALSE); + java.util.Map<Byte, Boolean> di2 = new java.util.HashMap<Byte, Boolean>(); + di2.put((byte)10, Boolean.TRUE); + di2.put((byte)11, Boolean.FALSE); + di2.put((byte)101, Boolean.TRUE); + + opByteBoolDI cb = new opByteBoolDI(); + p.begin_opByteBoolD(di1, di2, + (Map<Byte, Boolean> p1, Map<Byte, Boolean> p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + java.util.Map<Short, Integer> di1 = new java.util.HashMap<Short, Integer>(); + di1.put((short)110, -1); + di1.put((short)1100, 123123); + java.util.Map<Short, Integer> di2 = new java.util.HashMap<Short, Integer>(); + di2.put((short)110, -1); + di2.put((short)111, -100); + di2.put((short)1101, 0); + + opShortIntDI cb = new opShortIntDI(); + p.begin_opShortIntD(di1, di2, + (Map<Short, Integer> p1, Map<Short, Integer> p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + java.util.Map<Long, Float> di1 = new java.util.HashMap<Long, Float>(); + di1.put(999999110L, new Float(-1.1f)); + di1.put(999999111L, new Float(123123.2f)); + java.util.Map<Long, Float> di2 = new java.util.HashMap<Long, Float>(); + di2.put(999999110L, new Float(-1.1f)); + di2.put(999999120L, new Float(-100.4f)); + di2.put(999999130L, new Float(0.5f)); + + opLongFloatDI cb = new opLongFloatDI(); + p.begin_opLongFloatD(di1, di2, + (Map<Long, Float> p1, Map<Long, Float> p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + java.util.Map<String, String> di1 = new java.util.HashMap<String, String>(); + di1.put("foo", "abc -1.1"); + di1.put("bar", "abc 123123.2"); + java.util.Map<String, String> di2 = new java.util.HashMap<String, String>(); + di2.put("foo", "abc -1.1"); + di2.put("FOO", "abc -100.4"); + di2.put("BAR", "abc 0.5"); + + opStringStringDI cb = new opStringStringDI(); + p.begin_opStringStringD(di1, di2, + (Map<String, String> p1, Map<String, String> p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + java.util.Map<String, MyEnum> di1 = new java.util.HashMap<String, MyEnum>(); + di1.put("abc", MyEnum.enum1); + di1.put("", MyEnum.enum2); + java.util.Map<String, MyEnum> di2 = new java.util.HashMap<String, MyEnum>(); + di2.put("abc", MyEnum.enum1); + di2.put("qwerty", MyEnum.enum3); + di2.put("Hello!!", MyEnum.enum2); + + opStringMyEnumDI cb = new opStringMyEnumDI(); + p.begin_opStringMyEnumD(di1, di2, + (Map<String, MyEnum> p1, Map<String, MyEnum> p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + java.util.Map<MyEnum, String> di1 = new java.util.HashMap<MyEnum, String>(); + di1.put(MyEnum.enum1, "abc"); + java.util.Map<MyEnum, String> di2 = new java.util.HashMap<MyEnum, String>(); + di2.put(MyEnum.enum2, "Hello!!"); + di2.put(MyEnum.enum3, "qwerty"); + + opMyEnumStringDI cb = new opMyEnumStringDI(); + p.begin_opMyEnumStringD(di1, di2, + (Map<MyEnum, String> p1, Map<MyEnum, String> p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + MyStruct s11 = new MyStruct(1, 1); + MyStruct s12 = new MyStruct(1, 2); + java.util.Map<MyStruct, MyEnum> di1 = new java.util.HashMap<MyStruct, MyEnum>(); + di1.put(s11, MyEnum.enum1); + di1.put(s12, MyEnum.enum2); + MyStruct s22 = new MyStruct(2, 2); + MyStruct s23 = new MyStruct(2, 3); + java.util.Map<MyStruct, MyEnum> di2 = new java.util.HashMap<MyStruct, MyEnum>(); + di2.put(s11, MyEnum.enum1); + di2.put(s22, MyEnum.enum3); + di2.put(s23, MyEnum.enum2); + + opMyStructMyEnumDI cb = new opMyStructMyEnumDI(); + p.begin_opMyStructMyEnumD(di1, di2, + (Map<MyStruct, MyEnum> p1, Map<MyStruct, MyEnum> p2) -> cb.response(p1, p2), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + int[] lengths = { 0, 1, 2, 126, 127, 128, 129, 253, 254, 255, 256, 257, 1000 }; + + for(int l : lengths) + { + int[] s = new int[l]; + for(int i = 0; i < s.length; ++i) + { + s[i] = i; + } + opIntSI cb = new opIntSI(l); + p.begin_opIntS(s, + (int[] p1) -> cb.response(p1), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + } + + { + double d = 1278312346.0 / 13.0; + double[] ds = new double[5]; + for(int i = 0; i < 5; i++) + { + ds[i] = d; + } + opDoubleMarshalingI cb = new opDoubleMarshalingI(); + p.begin_opDoubleMarshaling(d, ds, + () -> cb.response(), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + opIdempotentI cb = new opIdempotentI(); + p.begin_opIdempotent( + () -> cb.response(), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + opNonmutatingI cb = new opNonmutatingI(); + p.begin_opNonmutating( + () -> cb.response(), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + + { + MyDerivedClassPrx derived = MyDerivedClassPrxHelper.checkedCast(p); + test(derived != null); + opDerivedI cb = new opDerivedI(); + derived.begin_opDerived( + () -> cb.response(), + (Ice.Exception ex) -> test(false)); + cb.check(); + } + } +} diff --git a/java/test/src/main/java/test/Ice/operations/run.py b/java/test/src/main/java/test/Ice/operations/run.py new file mode 100755 index 00000000000..4a622e6a75e --- /dev/null +++ b/java/test/src/main/java/test/Ice/operations/run.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("tests with regular server.") +TestUtil.clientServerTest(additionalClientOptions = "--Ice.Warn.AMICallback=0") + +print("tests with AMD server.") +TestUtil.clientServerTest(additionalClientOptions = "--Ice.Warn.AMICallback=0", server="test.Ice.operations.AMDServer") + +print("tests with TIE server.") +TestUtil.clientServerTest(additionalClientOptions = "--Ice.Warn.AMICallback=0", server="test.Ice.operations.TieServer") + +print("tests with AMD TIE server.") +TestUtil.clientServerTest(additionalClientOptions = "--Ice.Warn.AMICallback=0", server="test.Ice.operations.AMDTieServer") + +print("tests with collocated server.") +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/optional/AMDInitialI.java b/java/test/src/main/java/test/Ice/optional/AMDInitialI.java new file mode 100644 index 00000000000..d47104d792d --- /dev/null +++ b/java/test/src/main/java/test/Ice/optional/AMDInitialI.java @@ -0,0 +1,595 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.optional; + +import test.Ice.optional.AMD.Test.*; + +public final class AMDInitialI extends Initial +{ + @Override + public void + shutdown_async(AMD_Initial_shutdown cb, Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + cb.ice_response(); + } + + @Override + public void + pingPong_async(AMD_Initial_pingPong cb, Ice.Object obj, Ice.Current current) + { + cb.ice_response(obj); + } + + @Override + public void + opOptionalException_async(AMD_Initial_opOptionalException cb, Ice.IntOptional a, Ice.Optional<String> b, + Ice.Optional<OneOptional> o, Ice.Current current) + throws OptionalException + { + OptionalException ex = new OptionalException(); + if(a.isSet()) + { + ex.setA(a.get()); + } + else + { + ex.clearA(); // The member "a" has a default value. + } + if(b.isSet()) + { + ex.setB(b.get()); + } + if(o.isSet()) + { + ex.setO(o.get()); + } + cb.ice_exception(ex); + } + + @Override + public void + opDerivedException_async(AMD_Initial_opDerivedException cb, Ice.IntOptional a, Ice.Optional<String> b, + Ice.Optional<OneOptional> o, Ice.Current current) + throws OptionalException + { + DerivedException ex = new DerivedException(); + if(a.isSet()) + { + ex.setA(a.get()); + } + else + { + ex.clearA(); // The member "a" has a default value. + } + if(b.isSet()) + { + ex.setB(b.get()); + ex.setSs(b.get()); + } + else + { + ex.clearSs(); // The member "ss" has a default value. + } + if(o.isSet()) + { + ex.setO(o.get()); + ex.setO2(o.get()); + } + cb.ice_exception(ex); + } + + @Override + public void + opRequiredException_async(AMD_Initial_opRequiredException cb, Ice.IntOptional a, Ice.Optional<String> b, + Ice.Optional<OneOptional> o, Ice.Current current) + throws OptionalException + { + RequiredException ex = new RequiredException(); + if(a.isSet()) + { + ex.setA(a.get()); + } + else + { + ex.clearA(); // The member "a" has a default value. + } + if(b.isSet()) + { + ex.setB(b.get()); + ex.ss = b.get(); + } + if(o.isSet()) + { + ex.setO(o.get()); + ex.o2 = o.get(); + } + cb.ice_exception(ex); + } + + @Override + public void + opByte_async(AMD_Initial_opByte cb, Ice.ByteOptional p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opByteReq_async(AMD_Initial_opByteReq cb, Ice.ByteOptional p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opBool_async(AMD_Initial_opBool cb, Ice.BooleanOptional p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opBoolReq_async(AMD_Initial_opBoolReq cb, Ice.BooleanOptional p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opShort_async(AMD_Initial_opShort cb, Ice.ShortOptional p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opShortReq_async(AMD_Initial_opShortReq cb, Ice.ShortOptional p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opInt_async(AMD_Initial_opInt cb, Ice.IntOptional p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opIntReq_async(AMD_Initial_opIntReq cb, Ice.IntOptional p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opLong_async(AMD_Initial_opLong cb, Ice.LongOptional p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opLongReq_async(AMD_Initial_opLongReq cb, Ice.LongOptional p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opFloat_async(AMD_Initial_opFloat cb, Ice.FloatOptional p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opFloatReq_async(AMD_Initial_opFloatReq cb, Ice.FloatOptional p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opDouble_async(AMD_Initial_opDouble cb, Ice.DoubleOptional p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opDoubleReq_async(AMD_Initial_opDoubleReq cb, Ice.DoubleOptional p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opString_async(AMD_Initial_opString cb, Ice.Optional<String> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opStringReq_async(AMD_Initial_opStringReq cb, Ice.Optional<String> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opMyEnum_async(AMD_Initial_opMyEnum cb, Ice.Optional<MyEnum> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opMyEnumReq_async(AMD_Initial_opMyEnumReq cb, Ice.Optional<MyEnum> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opSmallStruct_async(AMD_Initial_opSmallStruct cb, Ice.Optional<SmallStruct> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opSmallStructReq_async(AMD_Initial_opSmallStructReq cb, Ice.Optional<SmallStruct> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opFixedStruct_async(AMD_Initial_opFixedStruct cb, Ice.Optional<FixedStruct> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opFixedStructReq_async(AMD_Initial_opFixedStructReq cb, Ice.Optional<FixedStruct> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opVarStruct_async(AMD_Initial_opVarStruct cb, Ice.Optional<VarStruct> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opVarStructReq_async(AMD_Initial_opVarStructReq cb, Ice.Optional<VarStruct> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opOneOptional_async(AMD_Initial_opOneOptional cb, Ice.Optional<OneOptional> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opOneOptionalReq_async(AMD_Initial_opOneOptionalReq cb, Ice.Optional<OneOptional> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opOneOptionalProxy_async(AMD_Initial_opOneOptionalProxy cb, Ice.Optional<OneOptionalPrx> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opOneOptionalProxyReq_async(AMD_Initial_opOneOptionalProxyReq cb, Ice.Optional<OneOptionalPrx> p1, + Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opByteSeq_async(AMD_Initial_opByteSeq cb, Ice.Optional<byte[]> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opByteSeqReq_async(AMD_Initial_opByteSeqReq cb, Ice.Optional<byte[]> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opBoolSeq_async(AMD_Initial_opBoolSeq cb, Ice.Optional<boolean[]> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opBoolSeqReq_async(AMD_Initial_opBoolSeqReq cb, Ice.Optional<boolean[]> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opShortSeq_async(AMD_Initial_opShortSeq cb, Ice.Optional<short[]> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opShortSeqReq_async(AMD_Initial_opShortSeqReq cb, Ice.Optional<short[]> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opIntSeq_async(AMD_Initial_opIntSeq cb, Ice.Optional<int[]> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opIntSeqReq_async(AMD_Initial_opIntSeqReq cb, Ice.Optional<int[]> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opLongSeq_async(AMD_Initial_opLongSeq cb, Ice.Optional<long[]> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opLongSeqReq_async(AMD_Initial_opLongSeqReq cb, Ice.Optional<long[]> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opFloatSeq_async(AMD_Initial_opFloatSeq cb, Ice.Optional<float[]> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opFloatSeqReq_async(AMD_Initial_opFloatSeqReq cb, Ice.Optional<float[]> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opDoubleSeq_async(AMD_Initial_opDoubleSeq cb, Ice.Optional<double[]> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opDoubleSeqReq_async(AMD_Initial_opDoubleSeqReq cb, Ice.Optional<double[]> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opStringSeq_async(AMD_Initial_opStringSeq cb, Ice.Optional<String[]> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opStringSeqReq_async(AMD_Initial_opStringSeqReq cb, Ice.Optional<String[]> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opSmallStructSeq_async(AMD_Initial_opSmallStructSeq cb, Ice.Optional<SmallStruct[]> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opSmallStructSeqReq_async(AMD_Initial_opSmallStructSeqReq cb, Ice.Optional<SmallStruct[]> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opSmallStructList_async(AMD_Initial_opSmallStructList cb, Ice.Optional<java.util.List<SmallStruct>> p1, + Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opSmallStructListReq_async(AMD_Initial_opSmallStructListReq cb, Ice.Optional<java.util.List<SmallStruct>> p1, + Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opFixedStructSeq_async(AMD_Initial_opFixedStructSeq cb, Ice.Optional<FixedStruct[]> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opFixedStructSeqReq_async(AMD_Initial_opFixedStructSeqReq cb, Ice.Optional<FixedStruct[]> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opFixedStructList_async(AMD_Initial_opFixedStructList cb, Ice.Optional<java.util.List<FixedStruct>> p1, + Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opFixedStructListReq_async(AMD_Initial_opFixedStructListReq cb, Ice.Optional<java.util.List<FixedStruct>> p1, + Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opVarStructSeq_async(AMD_Initial_opVarStructSeq cb, Ice.Optional<VarStruct[]> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opVarStructSeqReq_async(AMD_Initial_opVarStructSeqReq cb, Ice.Optional<VarStruct[]> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opSerializable_async(AMD_Initial_opSerializable cb, Ice.Optional<SerializableClass> p1, Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opSerializableReq_async(AMD_Initial_opSerializableReq cb, Ice.Optional<SerializableClass> p1, Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opIntIntDict_async(AMD_Initial_opIntIntDict cb, Ice.Optional<java.util.Map<Integer, Integer>> p1, + Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opIntIntDictReq_async(AMD_Initial_opIntIntDictReq cb, Ice.Optional<java.util.Map<Integer, Integer>> p1, + Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opStringIntDict_async(AMD_Initial_opStringIntDict cb, Ice.Optional<java.util.Map<String, Integer>> p1, + Ice.Current current) + { + cb.ice_response(p1, p1); + } + + @Override + public void + opStringIntDictReq_async(AMD_Initial_opStringIntDictReq cb, Ice.Optional<java.util.Map<String, Integer>> p1, + Ice.Current current) + { + cb.ice_response(p1.get(), p1.get()); + } + + @Override + public void + opClassAndUnknownOptional_async(AMD_Initial_opClassAndUnknownOptional cb, A p, Ice.Current current) + { + cb.ice_response(); + } + + @Override + public void + sendOptionalClass_async(AMD_Initial_sendOptionalClass cb, boolean req, Ice.Optional<OneOptional> o, + Ice.Current current) + { + cb.ice_response(); + } + + @Override + public void + returnOptionalClass_async(AMD_Initial_returnOptionalClass cb, boolean req, Ice.Current current) + { + cb.ice_response(new Ice.Optional<OneOptional>(new OneOptional(53))); + } + + @Override + public void + supportsRequiredParams_async(AMD_Initial_supportsRequiredParams cb, Ice.Current current) + { + cb.ice_response(true); + } + + @Override + public void + supportsJavaSerializable_async(AMD_Initial_supportsJavaSerializable cb, Ice.Current current) + { + cb.ice_response(true); + } + + @Override + public void + supportsCsharpSerializable_async(AMD_Initial_supportsCsharpSerializable cb, Ice.Current current) + { + cb.ice_response(false); + } + + @Override + public void + supportsCppStringView_async(AMD_Initial_supportsCppStringView cb, Ice.Current current) + { + cb.ice_response(false); + } +} diff --git a/java/test/src/main/java/test/Ice/optional/AMDServer.java b/java/test/src/main/java/test/Ice/optional/AMDServer.java new file mode 100644 index 00000000000..b05e5b28f3c --- /dev/null +++ b/java/test/src/main/java/test/Ice/optional/AMDServer.java @@ -0,0 +1,41 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.optional; + +public class AMDServer extends test.Util.Application +{ + @Override + public int run(String[] args) + { + communicator().getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.add(new AMDInitialI(), communicator().stringToIdentity("initial")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.optional.AMD"); + return initData; + } + + public static void main(String[] args) + { + AMDServer c = new AMDServer(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/optional/AllTests.java b/java/test/src/main/java/test/Ice/optional/AllTests.java new file mode 100644 index 00000000000..0665eec3252 --- /dev/null +++ b/java/test/src/main/java/test/Ice/optional/AllTests.java @@ -0,0 +1,2498 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.optional; +import java.io.PrintWriter; + +import test.Ice.optional.Test.*; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static InitialPrx + allTests(test.Util.Application app, boolean collocated, PrintWriter out) + { + Ice.Communicator communicator = app.communicator(); + + FactoryI factory = new FactoryI(); + communicator.addObjectFactory(factory, ""); + + out.print("testing stringToProxy... "); + out.flush(); + String ref = "initial:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + InitialPrx initial = InitialPrxHelper.checkedCast(base); + test(initial != null); + test(initial.equals(base)); + out.println("ok"); + + out.print("testing optional data members... "); + out.flush(); + + OneOptional oo1 = new OneOptional(); + test(!oo1.hasA()); + oo1.setA(15); + test(oo1.hasA() && oo1.getA() == 15); + + OneOptional oo2 = new OneOptional(16); + test(oo2.hasA() && oo2.getA() == 16); + + MultiOptional mo1 = new MultiOptional(); + mo1.setA((byte)15); + mo1.setB(true); + mo1.setC((short)19); + mo1.setD(78); + mo1.setE(99); + mo1.setF((float)5.5); + mo1.setG(1.0); + mo1.setH("test"); + mo1.setI(MyEnum.MyEnumMember); + mo1.setJ(MultiOptionalPrxHelper.uncheckedCast(communicator.stringToProxy("test"))); + mo1.setK(mo1); + mo1.setBs(new byte[] { (byte)5 }); + mo1.setSs(new String[] { "test", "test2" }); + mo1.setIid(new java.util.HashMap<Integer, Integer>()); + mo1.getIid().put(4, 3); + mo1.setSid(new java.util.HashMap<String, Integer>()); + mo1.getSid().put("test", 10); + FixedStruct fs = new FixedStruct(); + fs.m = 78; + mo1.setFs(fs); + VarStruct vs = new VarStruct(); + vs.m = "hello"; + mo1.setVs(vs); + + mo1.setShs(new short[] { (short)1 }); + mo1.setEs(new MyEnum[] { MyEnum.MyEnumMember, MyEnum.MyEnumMember }); + mo1.setFss(new FixedStruct[] { fs }); + mo1.setVss(new VarStruct[] { vs }); + mo1.setOos(new OneOptional[] { oo1 }); + mo1.setOops(new OneOptionalPrx[] { OneOptionalPrxHelper.uncheckedCast(communicator.stringToProxy("test")) }); + + mo1.setIed(new java.util.HashMap<Integer, MyEnum>()); + mo1.getIed().put(4, MyEnum.MyEnumMember); + mo1.setIfsd(new java.util.HashMap<Integer, FixedStruct>()); + mo1.getIfsd().put(4, fs); + mo1.setIvsd(new java.util.HashMap<Integer, VarStruct>()); + mo1.getIvsd().put(5, vs); + mo1.setIood(new java.util.HashMap<Integer, OneOptional>()); + mo1.getIood().put(5, new OneOptional(15)); + mo1.setIoopd(new java.util.HashMap<Integer, OneOptionalPrx>()); + mo1.getIoopd().put(5, OneOptionalPrxHelper.uncheckedCast(communicator.stringToProxy("test"))); + + mo1.setBos(new boolean[] { false, true, false }); + + mo1.setSer(new SerializableClass(58)); + + test(mo1.getA() == (byte)15); + test(mo1.getB()); + test(mo1.isB()); + test(mo1.getC() == (short)19); + test(mo1.getD() == 78); + test(mo1.getE() == 99); + test(mo1.getF() == (float)5.5); + test(mo1.getG() == 1.0); + test(mo1.getH().equals("test")); + test(mo1.getI() == MyEnum.MyEnumMember); + test(mo1.getJ().equals(MultiOptionalPrxHelper.uncheckedCast(communicator.stringToProxy("test")))); + test(mo1.getK() == mo1); + test(java.util.Arrays.equals(mo1.getBs(), new byte[] { (byte)5 })); + test(java.util.Arrays.equals(mo1.getSs(), new String[] { "test", "test2" })); + test(mo1.getIid().get(4) == 3); + test(mo1.getSid().get("test") == 10); + test(mo1.getFs().equals(new FixedStruct(78))); + test(mo1.getVs().equals(new VarStruct("hello"))); + + test(mo1.getShs()[0] == (short)1); + test(mo1.getEs()[0] == MyEnum.MyEnumMember && mo1.getEs()[1] == MyEnum.MyEnumMember); + test(mo1.getFss()[0].equals(new FixedStruct(78))); + test(mo1.getVss()[0].equals(new VarStruct("hello"))); + test(mo1.getOos()[0] == oo1); + test(mo1.getOops()[0].equals(OneOptionalPrxHelper.uncheckedCast(communicator.stringToProxy("test")))); + + test(mo1.getIed().get(4) == MyEnum.MyEnumMember); + test(mo1.getIfsd().get(4).equals(new FixedStruct(78))); + test(mo1.getIvsd().get(5).equals(new VarStruct("hello"))); + test(mo1.getIood().get(5).getA() == 15); + test(mo1.getIoopd().get(5).equals(OneOptionalPrxHelper.uncheckedCast(communicator.stringToProxy("test")))); + + test(java.util.Arrays.equals(mo1.getBos(), new boolean[] { false, true, false })); + + test(mo1.getSer().equals(new SerializableClass(58))); + + out.println("ok"); + + out.print("testing marshaling... "); + out.flush(); + + OneOptional oo4 = (OneOptional)initial.pingPong(new OneOptional()); + test(!oo4.hasA()); + + OneOptional oo5 = (OneOptional)initial.pingPong(oo1); + test(oo1.getA() == oo5.getA()); + + MultiOptional mo4 = (MultiOptional)initial.pingPong(new MultiOptional()); + test(!mo4.hasA()); + test(!mo4.hasB()); + test(!mo4.hasC()); + test(!mo4.hasD()); + test(!mo4.hasE()); + test(!mo4.hasF()); + test(!mo4.hasG()); + test(!mo4.hasH()); + test(!mo4.hasI()); + test(!mo4.hasJ()); + test(!mo4.hasK()); + test(!mo4.hasBs()); + test(!mo4.hasSs()); + test(!mo4.hasIid()); + test(!mo4.hasSid()); + test(!mo4.hasFs()); + test(!mo4.hasVs()); + + test(!mo4.hasShs()); + test(!mo4.hasEs()); + test(!mo4.hasFss()); + test(!mo4.hasVss()); + test(!mo4.hasOos()); + test(!mo4.hasOops()); + + test(!mo4.hasIed()); + test(!mo4.hasIfsd()); + test(!mo4.hasIvsd()); + test(!mo4.hasIood()); + test(!mo4.hasIoopd()); + + test(!mo4.hasBos()); + + test(!mo4.hasSer()); + + final boolean supportsJavaSerializable = initial.supportsJavaSerializable(); + if(!supportsJavaSerializable) + { + mo1.clearSer(); + } + + MultiOptional mo5 = (MultiOptional)initial.pingPong(mo1); + test(mo5.getA() == mo1.getA()); + test(mo5.getB() == mo1.getB()); + test(mo5.getC() == mo1.getC()); + test(mo5.getD() == mo1.getD()); + test(mo5.getE() == mo1.getE()); + test(mo5.getF() == mo1.getF()); + test(mo5.getG() == mo1.getG()); + test(mo5.getH().equals(mo1.getH())); + test(mo5.getI() == mo1.getI()); + test(mo5.getJ().equals(mo1.getJ())); + test(mo5.getK() == mo5); + test(java.util.Arrays.equals(mo5.getBs(), mo1.getBs())); + test(java.util.Arrays.equals(mo5.getSs(), mo1.getSs())); + test(mo5.getIid().get(4) == 3); + test(mo5.getSid().get("test") == 10); + test(mo5.getFs().equals(mo1.getFs())); + test(mo5.getVs().equals(mo1.getVs())); + test(java.util.Arrays.equals(mo5.getShs(), mo1.getShs())); + test(mo5.getEs()[0] == MyEnum.MyEnumMember && mo1.getEs()[1] == MyEnum.MyEnumMember); + test(mo5.getFss()[0].equals(new FixedStruct(78))); + test(mo5.getVss()[0].equals(new VarStruct("hello"))); + test(mo5.getOos()[0].getA() == 15); + test(mo5.getOops()[0].equals(OneOptionalPrxHelper.uncheckedCast(communicator.stringToProxy("test")))); + + test(mo5.getIed().get(4) == MyEnum.MyEnumMember); + test(mo5.getIfsd().get(4).equals(new FixedStruct(78))); + test(mo5.getIvsd().get(5).equals(new VarStruct("hello"))); + test(mo5.getIood().get(5).getA() == 15); + test(mo5.getIoopd().get(5).equals(OneOptionalPrxHelper.uncheckedCast(communicator.stringToProxy("test")))); + + test(java.util.Arrays.equals(mo5.getBos(), new boolean[] { false, true, false })); + + if(supportsJavaSerializable) + { + test(mo5.getSer().equals(mo1.getSer())); + } + + // Clear the first half of the optional parameters + MultiOptional mo6 = new MultiOptional(); + mo6.setB(mo5.getB()); + mo6.setD(mo5.getD()); + mo6.setF(mo5.getF()); + mo6.setH(mo5.getH()); + mo6.setJ(mo5.getJ()); + mo6.setBs(mo5.getBs()); + mo6.setIid(mo5.getIid()); + mo6.setFs(mo5.getFs()); + mo6.setShs(mo5.getShs()); + mo6.setFss(mo5.getFss()); + mo6.setOos(mo5.getOos()); + mo6.setIfsd(mo5.getIfsd()); + mo6.setIood(mo5.getIood()); + mo6.setBos(mo5.getBos()); + + MultiOptional mo7 = (MultiOptional)initial.pingPong(mo6); + test(!mo7.hasA()); + test(mo7.getB() == mo1.getB()); + test(!mo7.hasC()); + test(mo7.getD() == mo1.getD()); + test(!mo7.hasE()); + test(mo7.getF() == mo1.getF()); + test(!mo7.hasG()); + test(mo7.getH().equals(mo1.getH())); + test(!mo7.hasI()); + test(mo7.getJ().equals(mo1.getJ())); + test(!mo7.hasK()); + test(java.util.Arrays.equals(mo7.getBs(), mo1.getBs())); + test(!mo7.hasSs()); + test(mo7.getIid().get(4) == 3); + test(!mo7.hasSid()); + test(mo7.getFs().equals(mo1.getFs())); + test(!mo7.hasVs()); + + test(java.util.Arrays.equals(mo7.getShs(), mo1.getShs())); + test(!mo7.hasEs()); + test(mo7.getFss()[0].equals(new FixedStruct(78))); + test(!mo7.hasVss()); + test(mo7.getOos()[0].getA() == 15); + test(!mo7.hasOops()); + + test(!mo7.hasIed()); + test(mo7.getIfsd().get(4).equals(new FixedStruct(78))); + test(!mo7.hasIvsd()); + test(mo7.getIood().get(5).getA() == 15); + test(!mo7.hasIoopd()); + + test(java.util.Arrays.equals(mo7.getBos(), new boolean[] { false, true, false })); + + // Clear the second half of the optional parameters + MultiOptional mo8 = new MultiOptional(); + mo8.setA(mo5.getA()); + mo8.setC(mo5.getC()); + mo8.setE(mo5.getE()); + mo8.setG(mo5.getG()); + mo8.setI(mo5.getI()); + mo8.setK(mo8); + mo8.setSs(mo5.getSs()); + mo8.setSid(mo5.getSid()); + mo8.setVs(mo5.getVs()); + + mo8.setEs(mo5.getEs()); + mo8.setVss(mo5.getVss()); + mo8.setOops(mo5.getOops()); + + mo8.setIed(mo5.getIed()); + mo8.setIvsd(mo5.getIvsd()); + mo8.setIoopd(mo5.getIoopd()); + + MultiOptional mo9 = (MultiOptional)initial.pingPong(mo8); + test(mo9.getA() == mo1.getA()); + test(!mo9.hasB()); + test(mo9.getC() == mo1.getC()); + test(!mo9.hasD()); + test(mo9.getE() == mo1.getE()); + test(!mo9.hasF()); + test(mo9.getG() == mo1.getG()); + test(!mo9.hasH()); + test(mo9.getI() == mo1.getI()); + test(!mo9.hasJ()); + test(mo9.getK() == mo9); + test(!mo9.hasBs()); + test(java.util.Arrays.equals(mo9.getSs(), mo1.getSs())); + test(!mo9.hasIid()); + test(mo9.getSid().get("test") == 10); + test(!mo9.hasFs()); + test(mo9.getVs().equals(mo1.getVs())); + + test(!mo9.hasShs()); + test(mo9.getEs()[0] == MyEnum.MyEnumMember && mo1.getEs()[1] == MyEnum.MyEnumMember); + test(!mo9.hasFss()); + test(mo9.getVss()[0].equals(new VarStruct("hello"))); + test(!mo9.hasOos()); + test(mo9.getOops()[0].equals(OneOptionalPrxHelper.uncheckedCast(communicator.stringToProxy("test")))); + + test(mo9.getIed().get(4) == MyEnum.MyEnumMember); + test(!mo9.hasIfsd()); + test(mo9.getIvsd().get(5).equals(new VarStruct("hello"))); + test(!mo9.hasIood()); + test(mo9.getIoopd().get(5).equals(OneOptionalPrxHelper.uncheckedCast(communicator.stringToProxy("test")))); + + test(!mo9.hasBos()); + + { + OptionalWithCustom owc1 = new OptionalWithCustom(); + java.util.ArrayList<SmallStruct> l = new java.util.ArrayList<SmallStruct>(); + l.add(new SmallStruct((byte)5)); + l.add(new SmallStruct((byte)6)); + l.add(new SmallStruct((byte)7)); + owc1.setL(l); + owc1.setS(new ClassVarStruct(5)); + OptionalWithCustom owc2 = (OptionalWithCustom)initial.pingPong(owc1); + test(owc2.hasL()); + test(owc2.getL().equals(l)); + test(owc2.hasS()); + test(owc2.getS().a == 5); + } + + // + // Send a request using blobjects. Upon receival, we don't read + // any of the optional members. This ensures the optional members + // are skipped even if the receiver knows nothing about them. + // + factory.setEnabled(true); + Ice.OutputStream os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeObject(oo1); + os.endEncapsulation(); + byte[] inEncaps = os.finished(); + Ice.ByteSeqHolder outEncaps = new Ice.ByteSeqHolder(); + test(initial.ice_invoke("pingPong", Ice.OperationMode.Normal, inEncaps, outEncaps)); + Ice.InputStream in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + ReadObjectCallbackI cb = new ReadObjectCallbackI(); + in.readObject(cb); + in.endEncapsulation(); + test(cb.obj != null && cb.obj instanceof TestObjectReader); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeObject(mo1); + os.endEncapsulation(); + inEncaps = os.finished(); + test(initial.ice_invoke("pingPong", Ice.OperationMode.Normal, inEncaps, outEncaps)); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.readObject(cb); + in.endEncapsulation(); + test(cb.obj != null && cb.obj instanceof TestObjectReader); + factory.setEnabled(false); + + // + // Use the 1.0 encoding with operations whose only class parameters are optional. + // + Ice.Optional<OneOptional> oo = new Ice.Optional<OneOptional>(new OneOptional(53)); + initial.sendOptionalClass(true, oo); + InitialPrx initial2 = (InitialPrx)initial.ice_encodingVersion(Ice.Util.Encoding_1_0); + initial2.sendOptionalClass(true, oo); + + initial.returnOptionalClass(true, oo); + test(oo.isSet()); + initial2.returnOptionalClass(true, oo); + test(!oo.isSet()); + + Recursive[] recursive1 = new Recursive[1]; + recursive1[0] = new Recursive(); + Recursive[] recursive2 = new Recursive[1]; + recursive2[0] = new Recursive(); + recursive1[0].setValue(recursive2); + Recursive outer = new Recursive(); + outer.setValue(recursive1); + initial.pingPong(outer); + + out.println("ok"); + + out.print("testing marshaling of large containers with fixed size elements... "); + out.flush(); + MultiOptional mc = new MultiOptional(); + + mc.setBs(new byte[1000]); + mc.setShs(new short[300]); + + mc.setFss(new FixedStruct[300]); + for(int i = 0; i < 300; ++i) + { + mc.getFss()[i] = new FixedStruct(); + } + + mc.setIfsd(new java.util.HashMap<Integer, FixedStruct>()); + for(int i = 0; i < 300; ++i) + { + mc.getIfsd().put(i, new FixedStruct()); + } + + mc = (MultiOptional)initial.pingPong(mc); + test(mc.getBs().length == 1000); + test(mc.getShs().length == 300); + test(mc.getFss().length == 300); + test(mc.getIfsd().size() == 300); + + factory.setEnabled(true); + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeObject(mc); + os.endEncapsulation(); + inEncaps = os.finished(); + outEncaps = new Ice.ByteSeqHolder(); + test(initial.ice_invoke("pingPong", Ice.OperationMode.Normal, inEncaps, outEncaps)); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.readObject(cb); + in.endEncapsulation(); + test(cb.obj != null && cb.obj instanceof TestObjectReader); + factory.setEnabled(false); + + out.println("ok"); + + out.print("testing tag marshaling... "); + out.flush(); + { + B b = new B(); + B b2 = (B)initial.pingPong(b); + test(!b2.hasMa()); + test(!b2.hasMb()); + test(!b2.hasMc()); + + b.setMa(10); + b.setMb(11); + b.setMc(12); + b.setMd(13); + + b2 = (B)initial.pingPong(b); + test(b2.getMa() == 10); + test(b2.getMb() == 11); + test(b2.getMc() == 12); + test(b2.getMd() == 13); + + factory.setEnabled(true); + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeObject(b); + os.endEncapsulation(); + inEncaps = os.finished(); + outEncaps = new Ice.ByteSeqHolder(); + test(initial.ice_invoke("pingPong", Ice.OperationMode.Normal, inEncaps, outEncaps)); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.readObject(cb); + in.endEncapsulation(); + test(cb.obj != null); + factory.setEnabled(false); + } + out.println("ok"); + + out.print("testing marshalling of objects with optional objects..."); + out.flush(); + { + F f = new F(); + + f.setAf(new A()); + f.ae = f.getAf(); + + F rf = (F)initial.pingPong(f); + test(rf.ae == rf.getAf()); + + factory.setEnabled(true); + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeObject(f); + os.endEncapsulation(); + inEncaps = os.finished(); + in = Ice.Util.createInputStream(communicator, inEncaps); + in.startEncapsulation(); + final FHolder fholder = new FHolder(); + in.readObject(new Ice.ReadObjectCallback() + { + @Override + public void invoke(Ice.Object obj) + { + fholder.value = ((FObjectReader)obj).getF(); + } + }); + in.endEncapsulation(); + factory.setEnabled(false); + rf = fholder.value; + test(rf.ae != null && !rf.hasAf()); + } + out.println("ok"); + + out.print("testing optional with default values... "); + out.flush(); + { + WD wd = (WD)initial.pingPong(new WD()); + test(wd.getA() == 5); + test(wd.getS().equals("test")); + wd.clearA(); + wd.clearS(); + wd = (WD)initial.pingPong(wd); + test(!wd.hasA()); + test(!wd.hasS()); + } + out.println("ok"); + + if(communicator.getProperties().getPropertyAsInt("Ice.Default.SlicedFormat") > 0) + { + out.print("testing marshaling with unknown class slices... "); + out.flush(); + { + C c = new C(); + c.ss = "test"; + c.setMs("testms"); + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeObject(c); + os.endEncapsulation(); + inEncaps = os.finished(); + factory.setEnabled(true); + test(initial.ice_invoke("pingPong", Ice.OperationMode.Normal, inEncaps, outEncaps)); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.readObject(cb); + in.endEncapsulation(); + test(cb.obj instanceof CObjectReader); + factory.setEnabled(false); + + factory.setEnabled(true); + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + Ice.Object d = new DObjectWriter(); + os.writeObject(d); + os.endEncapsulation(); + inEncaps = os.finished(); + test(initial.ice_invoke("pingPong", Ice.OperationMode.Normal, inEncaps, outEncaps)); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.readObject(cb); + in.endEncapsulation(); + test(cb.obj != null && cb.obj instanceof DObjectReader); + ((DObjectReader)cb.obj).check(); + factory.setEnabled(false); + } + out.println("ok"); + + out.print("testing optionals with unknown classes..."); + out.flush(); + { + A a = new A(); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeObject(a); + os.writeOptional(1, Ice.OptionalFormat.Class); + os.writeObject(new DObjectWriter()); + os.endEncapsulation(); + inEncaps = os.finished(); + test(initial.ice_invoke("opClassAndUnknownOptional", Ice.OperationMode.Normal, inEncaps, outEncaps)); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + out.println("ok"); + } + + out.print("testing optional parameters... "); + out.flush(); + final boolean reqParams = initial.supportsRequiredParams(); + + { + + Ice.ByteOptional p1 = new Ice.ByteOptional(); + Ice.ByteOptional p3 = new Ice.ByteOptional(); + Ice.ByteOptional p2 = initial.opByte(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set((byte)56); + p2 = initial.opByte(p1, p3); + test(p2.get() == (byte)56 && p3.get() == (byte)56); + Ice.AsyncResult r = initial.begin_opByte(p1); + p2 = initial.end_opByte(p3, r); + test(p2.get() == (byte)56 && p3.get() == (byte)56); + p2 = initial.opByte(new Ice.ByteOptional(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opByteReq(p1.get(), p3); + test(p2.get() == (byte)56 && p3.get() == (byte)56); + r = initial.begin_opByteReq(p1.get()); + p2 = initial.end_opByteReq(p3, r); + test(p2.get() == (byte)56 && p3.get() == (byte)56); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.F1); + os.writeByte(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opByteReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.F1)); + test(in.readByte() == (byte)56); + test(in.readOptional(3, Ice.OptionalFormat.F1)); + test(in.readByte() == (byte)56); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.BooleanOptional p1 = new Ice.BooleanOptional(); + Ice.BooleanOptional p3 = new Ice.BooleanOptional(); + Ice.BooleanOptional p2 = initial.opBool(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(true); + p2 = initial.opBool(p1, p3); + test(p2.get() == true && p3.get() == true); + Ice.AsyncResult r = initial.begin_opBool(p1); + p2 = initial.end_opBool(p3, r); + test(p2.get() == true && p3.get() == true); + p2 = initial.opBool(new Ice.BooleanOptional(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opBoolReq(true, p3); + test(p2.get() == true && p3.get() == true); + r = initial.begin_opBoolReq(true); + p2 = initial.end_opBoolReq(p3, r); + test(p2.get() == true && p3.get() == true); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.F1); + os.writeBool(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opBoolReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.F1)); + test(in.readBool() == true); + test(in.readOptional(3, Ice.OptionalFormat.F1)); + test(in.readBool() == true); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.ShortOptional p1 = new Ice.ShortOptional(); + Ice.ShortOptional p3 = new Ice.ShortOptional(); + Ice.ShortOptional p2 = initial.opShort(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set((short)56); + p2 = initial.opShort(p1, p3); + test(p2.get() == 56 && p3.get() == 56); + Ice.AsyncResult r = initial.begin_opShort(p1); + p2 = initial.end_opShort(p3, r); + test(p2.get() == 56 && p3.get() == 56); + p2 = initial.opShort(new Ice.ShortOptional(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opShortReq(p1.get(), p3); + test(p2.get() == 56 && p3.get() == 56); + r = initial.begin_opShortReq(p1.get()); + p2 = initial.end_opShortReq(p3, r); + test(p2.get() == 56 && p3.get() == 56); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.F2); + os.writeShort(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opShortReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.F2)); + test(in.readShort() == 56); + test(in.readOptional(3, Ice.OptionalFormat.F2)); + test(in.readShort() == 56); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.IntOptional p1 = new Ice.IntOptional(); + Ice.IntOptional p3 = new Ice.IntOptional(); + Ice.IntOptional p2 = initial.opInt(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(56); + p2 = initial.opInt(p1, p3); + test(p2.get() == 56 && p3.get() == 56); + Ice.AsyncResult r = initial.begin_opInt(p1); + p2 = initial.end_opInt(p3, r); + test(p2.get() == 56 && p3.get() == 56); + p2 = initial.opInt(new Ice.IntOptional(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opIntReq(p1.get(), p3); + test(p2.get() == 56 && p3.get() == 56); + r = initial.begin_opIntReq(p1.get()); + p2 = initial.end_opIntReq(p3, r); + test(p2.get() == 56 && p3.get() == 56); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.F4); + os.writeInt(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opIntReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.F4)); + test(in.readInt() == 56); + test(in.readOptional(3, Ice.OptionalFormat.F4)); + test(in.readInt() == 56); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.LongOptional p1 = new Ice.LongOptional(); + Ice.LongOptional p3 = new Ice.LongOptional(); + Ice.LongOptional p2 = initial.opLong(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(56); + p2 = initial.opLong(p1, p3); + test(p2.get() == 56 && p3.get() == 56); + Ice.AsyncResult r = initial.begin_opLong(p1); + p2 = initial.end_opLong(p3, r); + test(p2.get() == 56 && p3.get() == 56); + p2 = initial.opLong(new Ice.LongOptional(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opLongReq(p1.get(), p3); + test(p2.get() == 56 && p3.get() == 56); + r = initial.begin_opLongReq(p1.get()); + p2 = initial.end_opLongReq(p3, r); + test(p2.get() == 56 && p3.get() == 56); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(1, Ice.OptionalFormat.F8); + os.writeLong(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opLongReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(2, Ice.OptionalFormat.F8)); + test(in.readLong() == 56); + test(in.readOptional(3, Ice.OptionalFormat.F8)); + test(in.readLong() == 56); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.FloatOptional p1 = new Ice.FloatOptional(); + Ice.FloatOptional p3 = new Ice.FloatOptional(); + Ice.FloatOptional p2 = initial.opFloat(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set((float)1.0); + p2 = initial.opFloat(p1, p3); + test(p2.get() == 1.0 && p3.get() == 1.0); + Ice.AsyncResult r = initial.begin_opFloat(p1); + p2 = initial.end_opFloat(p3, r); + test(p2.get() == 1.0 && p3.get() == 1.0); + p2 = initial.opFloat(new Ice.FloatOptional(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opFloatReq(p1.get(), p3); + test(p2.get() == 1.0 && p3.get() == 1.0); + r = initial.begin_opFloatReq(p1.get()); + p2 = initial.end_opFloatReq(p3, r); + test(p2.get() == 1.0 && p3.get() == 1.0); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.F4); + os.writeFloat(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opFloatReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.F4)); + test(in.readFloat() == 1.0); + test(in.readOptional(3, Ice.OptionalFormat.F4)); + test(in.readFloat() == 1.0); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.DoubleOptional p1 = new Ice.DoubleOptional(); + Ice.DoubleOptional p3 = new Ice.DoubleOptional(); + Ice.DoubleOptional p2 = initial.opDouble(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(1.0); + p2 = initial.opDouble(p1, p3); + test(p2.get() == 1.0 && p3.get() == 1.0); + Ice.AsyncResult r = initial.begin_opDouble(p1); + p2 = initial.end_opDouble(p3, r); + test(p2.get() == 1.0 && p3.get() == 1.0); + p2 = initial.opDouble(new Ice.DoubleOptional(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opDoubleReq(p1.get(), p3); + test(p2.get() == 1.0 && p3.get() == 1.0); + r = initial.begin_opDoubleReq(p1.get()); + p2 = initial.end_opDoubleReq(p3, r); + test(p2.get() == 1.0 && p3.get() == 1.0); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.F8); + os.writeDouble(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opDoubleReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.F8)); + test(in.readDouble() == 1.0); + test(in.readOptional(3, Ice.OptionalFormat.F8)); + test(in.readDouble() == 1.0); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<String> p1 = new Ice.Optional<String>(); + Ice.Optional<String> p3 = new Ice.Optional<String>(); + Ice.Optional<String> p2 = initial.opString(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set("test"); + p2 = initial.opString(p1, p3); + test(p2.get().equals("test") && p3.get().equals("test")); + Ice.AsyncResult r = initial.begin_opString(p1); + p2 = initial.end_opString(p3, r); + test(p2.get().equals("test") && p3.get().equals("test")); + p2 = initial.opString(new Ice.Optional<String>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opStringReq(p1.get(), p3); + test(p2.get().equals("test") && p3.get().equals("test")); + r = initial.begin_opStringReq(p1.get()); + p2 = initial.end_opStringReq(p3, r); + test(p2.get().equals("test") && p3.get().equals("test")); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeString(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opStringReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + test(in.readString().equals("test")); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + test(in.readString().equals("test")); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<MyEnum> p1 = new Ice.Optional<MyEnum>(); + Ice.Optional<MyEnum> p3 = new Ice.Optional<MyEnum>(); + Ice.Optional<MyEnum> p2 = initial.opMyEnum(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(MyEnum.MyEnumMember); + p2 = initial.opMyEnum(p1, p3); + test(p2.get() == MyEnum.MyEnumMember && p3.get() == MyEnum.MyEnumMember); + Ice.AsyncResult r = initial.begin_opMyEnum(p1); + p2 = initial.end_opMyEnum(p3, r); + test(p2.get() == MyEnum.MyEnumMember && p3.get() == MyEnum.MyEnumMember); + p2 = initial.opMyEnum(new Ice.Optional<MyEnum>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opMyEnumReq(p1.get(), p3); + test(p2.get() == MyEnum.MyEnumMember && p3.get() == MyEnum.MyEnumMember); + r = initial.begin_opMyEnumReq(p1.get()); + p2 = initial.end_opMyEnumReq(p3, r); + test(p2.get() == MyEnum.MyEnumMember && p3.get() == MyEnum.MyEnumMember); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.Size); + p1.get().ice_write(os); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opMyEnumReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.Size)); + test(MyEnum.ice_read(in) == MyEnum.MyEnumMember); + test(in.readOptional(3, Ice.OptionalFormat.Size)); + test(MyEnum.ice_read(in) == MyEnum.MyEnumMember); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<SmallStruct> p1 = new Ice.Optional<SmallStruct>(); + Ice.Optional<SmallStruct> p3 = new Ice.Optional<SmallStruct>(); + Ice.Optional<SmallStruct> p2 = initial.opSmallStruct(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new SmallStruct((byte)56)); + p2 = initial.opSmallStruct(p1, p3); + test(p2.get().m == (byte)56 && p3.get().m == (byte)56); + Ice.AsyncResult r = initial.begin_opSmallStruct(p1); + p2 = initial.end_opSmallStruct(p3, r); + test(p2.get().m == (byte)56 && p3.get().m == (byte)56); + p2 = initial.opSmallStruct(new Ice.Optional<SmallStruct>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opSmallStructReq(p1.get(), p3); + test(p2.get().m == (byte)56 && p3.get().m == (byte)56); + r = initial.begin_opSmallStructReq(p1.get()); + p2 = initial.end_opSmallStructReq(p3, r); + test(p2.get().m == (byte)56 && p3.get().m == (byte)56); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeSize(1); + p1.get().ice_write(os); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opSmallStructReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + in.skipSize(); + SmallStruct f = new SmallStruct(); + f.ice_read(in); + test(f.m == (byte)56); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + in.skipSize(); + f.ice_read(in); + test(f.m == (byte)56); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<FixedStruct> p1 = new Ice.Optional<FixedStruct>(); + Ice.Optional<FixedStruct> p3 = new Ice.Optional<FixedStruct>(); + Ice.Optional<FixedStruct> p2 = initial.opFixedStruct(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new FixedStruct(56)); + p2 = initial.opFixedStruct(p1, p3); + test(p2.get().m == 56 && p3.get().m == 56); + Ice.AsyncResult r = initial.begin_opFixedStruct(p1); + p2 = initial.end_opFixedStruct(p3, r); + test(p2.get().m == 56 && p3.get().m == 56); + p2 = initial.opFixedStruct(new Ice.Optional<FixedStruct>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opFixedStructReq(p1.get(), p3); + test(p2.get().m == 56 && p3.get().m == 56); + r = initial.begin_opFixedStructReq(p1.get()); + p2 = initial.end_opFixedStructReq(p3, r); + test(p2.get().m == 56 && p3.get().m == 56); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeSize(4); + p1.get().ice_write(os); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opFixedStructReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + in.skipSize(); + FixedStruct f = new FixedStruct(); + f.ice_read(in); + test(f.m == 56); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + in.skipSize(); + f.ice_read(in); + test(f.m == 56); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<VarStruct> p1 = new Ice.Optional<VarStruct>(); + Ice.Optional<VarStruct> p3 = new Ice.Optional<VarStruct>(); + Ice.Optional<VarStruct> p2 = initial.opVarStruct(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new VarStruct("test")); + p2 = initial.opVarStruct(p1, p3); + test(p2.get().m.equals("test") && p3.get().m.equals("test")); + Ice.AsyncResult r = initial.begin_opVarStruct(p1); + p2 = initial.end_opVarStruct(p3, r); + test(p2.get().m.equals("test") && p3.get().m.equals("test")); + p2 = initial.opVarStruct(new Ice.Optional<VarStruct>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opVarStructReq(p1.get(), p3); + test(p2.get().m.equals("test") && p3.get().m.equals("test")); + r = initial.begin_opVarStructReq(p1.get()); + p2 = initial.end_opVarStructReq(p3, r); + test(p2.get().m.equals("test") && p3.get().m.equals("test")); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.FSize); + int pos = os.startSize(); + p1.get().ice_write(os); + os.endSize(pos); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opVarStructReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.FSize)); + in.skip(4); + VarStruct v = new VarStruct(); + v.ice_read(in); + test(v.m.equals("test")); + test(in.readOptional(3, Ice.OptionalFormat.FSize)); + in.skip(4); + v.ice_read(in); + test(v.m.equals("test")); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<OneOptional> p1 = new Ice.Optional<OneOptional>(); + Ice.Optional<OneOptional> p3 = new Ice.Optional<OneOptional>(); + Ice.Optional<OneOptional> p2 = initial.opOneOptional(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new OneOptional(58)); + p2 = initial.opOneOptional(p1, p3); + test(p2.get().getA() == 58 && p3.get().getA() == 58); + Ice.AsyncResult r = initial.begin_opOneOptional(p1); + p2 = initial.end_opOneOptional(p3, r); + test(p2.get().getA() == 58 && p3.get().getA() == 58); + p2 = initial.opOneOptional(new Ice.Optional<OneOptional>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opOneOptionalReq(p1.get(), p3); + test(p2.get().getA() == 58 && p3.get().getA() == 58); + r = initial.begin_opOneOptionalReq(p1.get()); + p2 = initial.end_opOneOptionalReq(p3, r); + test(p2.get().getA() == 58 && p3.get().getA() == 58); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.Class); + os.writeObject(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opOneOptionalReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.Class)); + ReadObjectCallbackI p2cb = new ReadObjectCallbackI(); + in.readObject(p2cb); + test(in.readOptional(3, Ice.OptionalFormat.Class)); + ReadObjectCallbackI p3cb = new ReadObjectCallbackI(); + in.readObject(p3cb); + in.endEncapsulation(); + test(((OneOptional)p2cb.obj).getA() == 58 && ((OneOptional)p3cb.obj).getA() == 58); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<OneOptionalPrx> p1 = new Ice.Optional<OneOptionalPrx>(); + Ice.Optional<OneOptionalPrx> p3 = new Ice.Optional<OneOptionalPrx>(); + Ice.Optional<OneOptionalPrx> p2 = initial.opOneOptionalProxy(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(OneOptionalPrxHelper.uncheckedCast(communicator.stringToProxy("test"))); + p2 = initial.opOneOptionalProxy(p1, p3); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + Ice.AsyncResult r = initial.begin_opOneOptionalProxy(p1); + p2 = initial.end_opOneOptionalProxy(p3, r); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + p2 = initial.opOneOptionalProxy(new Ice.Optional<OneOptionalPrx>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opOneOptionalProxyReq(p1.get(), p3); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + r = initial.begin_opOneOptionalProxyReq(p1.get()); + p2 = initial.end_opOneOptionalProxyReq(p3, r); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.FSize); + int pos = os.startSize(); + os.writeProxy(p1.get()); + os.endSize(pos); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opOneOptionalProxyReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.FSize)); + in.skip(4); + test(in.readProxy().equals(p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.FSize)); + in.skip(4); + test(in.readProxy().equals(p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<byte[]> p1 = new Ice.Optional<byte[]>(); + Ice.Optional<byte[]> p3 = new Ice.Optional<byte[]>(); + Ice.Optional<byte[]> p2 = initial.opByteSeq(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new byte[100]); + java.util.Arrays.fill(p1.get(), (byte)56); + p2 = initial.opByteSeq(p1, p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + Ice.AsyncResult r = initial.begin_opByteSeq(p1); + p2 = initial.end_opByteSeq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + p2 = initial.opByteSeq(new Ice.Optional<byte[]>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opByteSeqReq(p1.get(), p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + r = initial.begin_opByteSeqReq(p1.get()); + p2 = initial.end_opByteSeqReq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeByteSeq(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opByteSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + test(java.util.Arrays.equals(in.readByteSeq(), p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + test(java.util.Arrays.equals(in.readByteSeq(), p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<boolean[]> p1 = new Ice.Optional<boolean[]>(); + Ice.Optional<boolean[]> p3 = new Ice.Optional<boolean[]>(); + Ice.Optional<boolean[]> p2 = initial.opBoolSeq(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new boolean[100]); + p2 = initial.opBoolSeq(p1, p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + Ice.AsyncResult r = initial.begin_opBoolSeq(p1); + p2 = initial.end_opBoolSeq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + p2 = initial.opBoolSeq(new Ice.Optional<boolean[]>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opBoolSeqReq(p1.get(), p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + r = initial.begin_opBoolSeqReq(p1.get()); + p2 = initial.end_opBoolSeqReq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeBoolSeq(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opBoolSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + test(java.util.Arrays.equals(in.readBoolSeq(), p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + test(java.util.Arrays.equals(in.readBoolSeq(), p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<short[]> p1 = new Ice.Optional<short[]>(); + Ice.Optional<short[]> p3 = new Ice.Optional<short[]>(); + Ice.Optional<short[]> p2 = initial.opShortSeq(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new short[100]); + java.util.Arrays.fill(p1.get(), (short)56); + p2 = initial.opShortSeq(p1, p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + Ice.AsyncResult r = initial.begin_opShortSeq(p1); + p2 = initial.end_opShortSeq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + p2 = initial.opShortSeq(new Ice.Optional<short[]>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opShortSeqReq(p1.get(), p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + r = initial.begin_opShortSeqReq(p1.get()); + p2 = initial.end_opShortSeqReq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeSize(p1.get().length * 2 + (p1.get().length > 254 ? 5 : 1)); + os.writeShortSeq(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opShortSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + in.skipSize(); + test(java.util.Arrays.equals(in.readShortSeq(), p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + in.skipSize(); + test(java.util.Arrays.equals(in.readShortSeq(), p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<int[]> p1 = new Ice.Optional<int[]>(); + Ice.Optional<int[]> p3 = new Ice.Optional<int[]>(); + Ice.Optional<int[]> p2 = initial.opIntSeq(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new int[100]); + java.util.Arrays.fill(p1.get(), 56); + p2 = initial.opIntSeq(p1, p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + Ice.AsyncResult r = initial.begin_opIntSeq(p1); + p2 = initial.end_opIntSeq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + p2 = initial.opIntSeq(new Ice.Optional<int[]>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opIntSeqReq(p1.get(), p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + r = initial.begin_opIntSeqReq(p1.get()); + p2 = initial.end_opIntSeqReq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeSize(p1.get().length * 4 + (p1.get().length > 254 ? 5 : 1)); + os.writeIntSeq(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opIntSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + in.skipSize(); + test(java.util.Arrays.equals(in.readIntSeq(), p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + in.skipSize(); + test(java.util.Arrays.equals(in.readIntSeq(), p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<long[]> p1 = new Ice.Optional<long[]>(); + Ice.Optional<long[]> p3 = new Ice.Optional<long[]>(); + Ice.Optional<long[]> p2 = initial.opLongSeq(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new long[100]); + java.util.Arrays.fill(p1.get(), 56); + p2 = initial.opLongSeq(p1, p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + Ice.AsyncResult r = initial.begin_opLongSeq(p1); + p2 = initial.end_opLongSeq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + p2 = initial.opLongSeq(new Ice.Optional<long[]>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opLongSeqReq(p1.get(), p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + r = initial.begin_opLongSeqReq(p1.get()); + p2 = initial.end_opLongSeqReq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeSize(p1.get().length * 8 + (p1.get().length > 254 ? 5 : 1)); + os.writeLongSeq(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opLongSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + in.skipSize(); + test(java.util.Arrays.equals(in.readLongSeq(), p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + in.skipSize(); + test(java.util.Arrays.equals(in.readLongSeq(), p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<float[]> p1 = new Ice.Optional<float[]>(); + Ice.Optional<float[]> p3 = new Ice.Optional<float[]>(); + Ice.Optional<float[]> p2 = initial.opFloatSeq(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new float[100]); + java.util.Arrays.fill(p1.get(), (float)1.0); + p2 = initial.opFloatSeq(p1, p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + Ice.AsyncResult r = initial.begin_opFloatSeq(p1); + p2 = initial.end_opFloatSeq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + p2 = initial.opFloatSeq(new Ice.Optional<float[]>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opFloatSeqReq(p1.get(), p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + r = initial.begin_opFloatSeqReq(p1.get()); + p2 = initial.end_opFloatSeqReq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeSize(p1.get().length * 4 + (p1.get().length > 254 ? 5 : 1)); + os.writeFloatSeq(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opFloatSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + in.skipSize(); + test(java.util.Arrays.equals(in.readFloatSeq(), p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + in.skipSize(); + test(java.util.Arrays.equals(in.readFloatSeq(), p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<double[]> p1 = new Ice.Optional<double[]>(); + Ice.Optional<double[]> p3 = new Ice.Optional<double[]>(); + Ice.Optional<double[]> p2 = initial.opDoubleSeq(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new double[100]); + java.util.Arrays.fill(p1.get(), 1.0); + p2 = initial.opDoubleSeq(p1, p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + Ice.AsyncResult r = initial.begin_opDoubleSeq(p1); + p2 = initial.end_opDoubleSeq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + p2 = initial.opDoubleSeq(new Ice.Optional<double[]>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opDoubleSeqReq(p1.get(), p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + r = initial.begin_opDoubleSeqReq(p1.get()); + p2 = initial.end_opDoubleSeqReq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeSize(p1.get().length * 8 + (p1.get().length > 254 ? 5 : 1)); + os.writeDoubleSeq(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opDoubleSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + in.skipSize(); + test(java.util.Arrays.equals(in.readDoubleSeq(), p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + in.skipSize(); + test(java.util.Arrays.equals(in.readDoubleSeq(), p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<String[]> p1 = new Ice.Optional<String[]>(); + Ice.Optional<String[]> p3 = new Ice.Optional<String[]>(); + Ice.Optional<String[]> p2 = initial.opStringSeq(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new String[10]); + java.util.Arrays.fill(p1.get(), "test1"); + p2 = initial.opStringSeq(p1, p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + Ice.AsyncResult r = initial.begin_opStringSeq(p1); + p2 = initial.end_opStringSeq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + p2 = initial.opStringSeq(new Ice.Optional<String[]>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opStringSeqReq(p1.get(), p3); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + r = initial.begin_opStringSeqReq(p1.get()); + p2 = initial.end_opStringSeqReq(p3, r); + test(java.util.Arrays.equals(p2.get(), p1.get()) && java.util.Arrays.equals(p3.get(), p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.FSize); + int pos = os.startSize(); + os.writeStringSeq(p1.get()); + os.endSize(pos); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opStringSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.FSize)); + in.skip(4); + test(java.util.Arrays.equals(in.readStringSeq(), p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.FSize)); + in.skip(4); + test(java.util.Arrays.equals(in.readStringSeq(), p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<SmallStruct[]> p1 = new Ice.Optional<SmallStruct[]>(); + Ice.Optional<SmallStruct[]> p3 = new Ice.Optional<SmallStruct[]>(); + Ice.Optional<SmallStruct[]> p2 = initial.opSmallStructSeq(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new SmallStruct[10]); + for(int i = 0; i < p1.get().length; ++i) + { + p1.get()[i] = new SmallStruct(); + } + p2 = initial.opSmallStructSeq(p1, p3); + for(int i = 0; i < p1.get().length; ++i) + { + test(p2.get()[i].equals(p1.get()[i])); + } + Ice.AsyncResult r = initial.begin_opSmallStructSeq(p1); + p2 = initial.end_opSmallStructSeq(p3, r); + for(int i = 0; i < p1.get().length; ++i) + { + test(p2.get()[i].equals(p1.get()[i])); + } + p2 = initial.opSmallStructSeq(new Ice.Optional<SmallStruct[]>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opSmallStructSeqReq(p1.get(), p3); + for(int i = 0; i < p1.get().length; ++i) + { + test(p2.get()[i].equals(p1.get()[i])); + } + r = initial.begin_opSmallStructSeqReq(p1.get()); + p2 = initial.end_opSmallStructSeqReq(p3, r); + for(int i = 0; i < p1.get().length; ++i) + { + test(p2.get()[i].equals(p1.get()[i])); + } + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeSize(p1.get().length + (p1.get().length > 254 ? 5 : 1)); + SmallStructSeqHelper.write(os, p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opSmallStructSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + in.skipSize(); + SmallStruct[] arr = SmallStructSeqHelper.read(in); + for(int i = 0; i < p1.get().length; ++i) + { + test(arr[i].equals(p1.get()[i])); + } + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + in.skipSize(); + arr = SmallStructSeqHelper.read(in); + for(int i = 0; i < p1.get().length; ++i) + { + test(arr[i].equals(p1.get()[i])); + } + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<java.util.List<SmallStruct>> p1 = new Ice.Optional<java.util.List<SmallStruct>>(); + Ice.Optional<java.util.List<SmallStruct>> p3 = new Ice.Optional<java.util.List<SmallStruct>>(); + Ice.Optional<java.util.List<SmallStruct>> p2 = initial.opSmallStructList(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new java.util.ArrayList<SmallStruct>()); + for(int i = 0; i < 10; ++i) + { + p1.get().add(new SmallStruct()); + } + p2 = initial.opSmallStructList(p1, p3); + test(p2.get().equals(p1.get())); + Ice.AsyncResult r = initial.begin_opSmallStructList(p1); + p2 = initial.end_opSmallStructList(p3, r); + test(p2.get().equals(p1.get())); + p2 = initial.opSmallStructList(new Ice.Optional<java.util.List<SmallStruct>>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opSmallStructListReq(p1.get(), p3); + test(p2.get().equals(p1.get())); + r = initial.begin_opSmallStructListReq(p1.get()); + p2 = initial.end_opSmallStructListReq(p3, r); + test(p2.get().equals(p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeSize(p1.get().size() + (p1.get().size() > 254 ? 5 : 1)); + SmallStructListHelper.write(os, p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opSmallStructListReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + in.skipSize(); + java.util.List<SmallStruct> arr = SmallStructListHelper.read(in); + test(arr.equals(p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + in.skipSize(); + arr = SmallStructListHelper.read(in); + test(arr.equals(p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<FixedStruct[]> p1 = new Ice.Optional<FixedStruct[]>(); + Ice.Optional<FixedStruct[]> p3 = new Ice.Optional<FixedStruct[]>(); + Ice.Optional<FixedStruct[]> p2 = initial.opFixedStructSeq(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new FixedStruct[10]); + for(int i = 0; i < p1.get().length; ++i) + { + p1.get()[i] = new FixedStruct(); + } + p2 = initial.opFixedStructSeq(p1, p3); + for(int i = 0; i < p1.get().length; ++i) + { + test(p2.get()[i].equals(p1.get()[i])); + } + Ice.AsyncResult r = initial.begin_opFixedStructSeq(p1); + p2 = initial.end_opFixedStructSeq(p3, r); + for(int i = 0; i < p1.get().length; ++i) + { + test(p2.get()[i].equals(p1.get()[i])); + } + p2 = initial.opFixedStructSeq(new Ice.Optional<FixedStruct[]>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opFixedStructSeqReq(p1.get(), p3); + for(int i = 0; i < p1.get().length; ++i) + { + test(p2.get()[i].equals(p1.get()[i])); + } + r = initial.begin_opFixedStructSeqReq(p1.get()); + p2 = initial.end_opFixedStructSeqReq(p3, r); + for(int i = 0; i < p1.get().length; ++i) + { + test(p2.get()[i].equals(p1.get()[i])); + } + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeSize(p1.get().length * 4 + (p1.get().length > 254 ? 5 : 1)); + FixedStructSeqHelper.write(os, p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opFixedStructSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + in.skipSize(); + FixedStruct[] arr = FixedStructSeqHelper.read(in); + for(int i = 0; i < p1.get().length; ++i) + { + test(arr[i].equals(p1.get()[i])); + } + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + in.skipSize(); + arr = FixedStructSeqHelper.read(in); + for(int i = 0; i < p1.get().length; ++i) + { + test(arr[i].equals(p1.get()[i])); + } + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<java.util.List<FixedStruct>> p1 = new Ice.Optional<java.util.List<FixedStruct>>(); + Ice.Optional<java.util.List<FixedStruct>> p3 = new Ice.Optional<java.util.List<FixedStruct>>(); + Ice.Optional<java.util.List<FixedStruct>> p2 = initial.opFixedStructList(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new java.util.ArrayList<FixedStruct>()); + for(int i = 0; i < 10; ++i) + { + p1.get().add(new FixedStruct()); + } + p2 = initial.opFixedStructList(p1, p3); + test(p2.get().equals(p1.get())); + Ice.AsyncResult r = initial.begin_opFixedStructList(p1); + p2 = initial.end_opFixedStructList(p3, r); + test(p2.get().equals(p1.get())); + p2 = initial.opFixedStructList(new Ice.Optional<java.util.List<FixedStruct>>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opFixedStructListReq(p1.get(), p3); + test(p2.get().equals(p1.get())); + r = initial.begin_opFixedStructListReq(p1.get()); + p2 = initial.end_opFixedStructListReq(p3, r); + test(p2.get().equals(p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeSize(p1.get().size() * 4 + (p1.get().size() > 254 ? 5 : 1)); + FixedStructListHelper.write(os, p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opFixedStructListReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + in.skipSize(); + java.util.List<FixedStruct> arr = FixedStructListHelper.read(in); + test(arr.equals(p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + in.skipSize(); + arr = FixedStructListHelper.read(in); + test(arr.equals(p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<VarStruct[]> p1 = new Ice.Optional<VarStruct[]>(); + Ice.Optional<VarStruct[]> p3 = new Ice.Optional<VarStruct[]>(); + Ice.Optional<VarStruct[]> p2 = initial.opVarStructSeq(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new VarStruct[10]); + for(int i = 0; i < p1.get().length; ++i) + { + p1.get()[i] = new VarStruct(""); + } + p2 = initial.opVarStructSeq(p1, p3); + for(int i = 0; i < p1.get().length; ++i) + { + test(p2.get()[i].equals(p1.get()[i])); + } + Ice.AsyncResult r = initial.begin_opVarStructSeq(p1); + p2 = initial.end_opVarStructSeq(p3, r); + for(int i = 0; i < p1.get().length; ++i) + { + test(p2.get()[i].equals(p1.get()[i])); + } + p2 = initial.opVarStructSeq(new Ice.Optional<VarStruct[]>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opVarStructSeqReq(p1.get(), p3); + for(int i = 0; i < p1.get().length; ++i) + { + test(p2.get()[i].equals(p1.get()[i])); + } + r = initial.begin_opVarStructSeqReq(p1.get()); + p2 = initial.end_opVarStructSeqReq(p3, r); + for(int i = 0; i < p1.get().length; ++i) + { + test(p2.get()[i].equals(p1.get()[i])); + } + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.FSize); + int pos = os.startSize(); + VarStructSeqHelper.write(os, p1.get()); + os.endSize(pos); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opVarStructSeqReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.FSize)); + in.skip(4); + VarStruct[] arr = VarStructSeqHelper.read(in); + for(int i = 0; i < p1.get().length; ++i) + { + test(arr[i].equals(p1.get()[i])); + } + test(in.readOptional(3, Ice.OptionalFormat.FSize)); + in.skip(4); + arr = VarStructSeqHelper.read(in); + for(int i = 0; i < p1.get().length; ++i) + { + test(arr[i].equals(p1.get()[i])); + } + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + if(supportsJavaSerializable) + { + Ice.Optional<SerializableClass> p1 = new Ice.Optional<SerializableClass>(); + Ice.Optional<SerializableClass> p3 = new Ice.Optional<SerializableClass>(); + Ice.Optional<SerializableClass> p2 = initial.opSerializable(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new SerializableClass(58)); + p2 = initial.opSerializable(p1, p3); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + Ice.AsyncResult r = initial.begin_opSerializable(p1); + p2 = initial.end_opSerializable(p3, r); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + p2 = initial.opSerializable(new Ice.Optional<SerializableClass>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opSerializableReq(p1.get(), p3); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + r = initial.begin_opSerializableReq(p1.get()); + p2 = initial.end_opSerializableReq(p3, r); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeSerializable(p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opSerializableReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + SerializableClass sc = SerializableHelper.read(in); + test(sc.equals(p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + sc = SerializableHelper.read(in); + test(sc.equals(p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<java.util.Map<Integer, Integer>> p1 = new Ice.Optional<java.util.Map<Integer, Integer>>(); + Ice.Optional<java.util.Map<Integer, Integer>> p3 = new Ice.Optional<java.util.Map<Integer, Integer>>(); + Ice.Optional<java.util.Map<Integer, Integer>> p2 = initial.opIntIntDict(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new java.util.HashMap<Integer, Integer>()); + p1.get().put(1, 2); + p1.get().put(2, 3); + p2 = initial.opIntIntDict(p1, p3); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + Ice.AsyncResult r = initial.begin_opIntIntDict(p1); + p2 = initial.end_opIntIntDict(p3, r); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + p2 = initial.opIntIntDict(new Ice.Optional<java.util.Map<Integer, Integer>>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opIntIntDictReq(p1.get(), p3); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + r = initial.begin_opIntIntDictReq(p1.get()); + p2 = initial.end_opIntIntDictReq(p3, r); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.VSize); + os.writeSize(p1.get().size() * 8 + (p1.get().size() > 254 ? 5 : 1)); + IntIntDictHelper.write(os, p1.get()); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opIntIntDictReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.VSize)); + in.skipSize(); + java.util.Map<Integer, Integer> m = IntIntDictHelper.read(in); + test(m.equals(p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.VSize)); + in.skipSize(); + m = IntIntDictHelper.read(in); + test(m.equals(p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + Ice.Optional<java.util.Map<String, Integer>> p1 = new Ice.Optional<java.util.Map<String, Integer>>(); + Ice.Optional<java.util.Map<String, Integer>> p3 = new Ice.Optional<java.util.Map<String, Integer>>(); + Ice.Optional<java.util.Map<String, Integer>> p2 = initial.opStringIntDict(p1, p3); + test(!p2.isSet() && !p3.isSet()); + + p1.set(new java.util.HashMap<String, Integer>()); + p1.get().put("1", 1); + p1.get().put("2", 2); + p2 = initial.opStringIntDict(p1, p3); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + Ice.AsyncResult r = initial.begin_opStringIntDict(p1); + p2 = initial.end_opStringIntDict(p3, r); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + p2 = initial.opStringIntDict(new Ice.Optional<java.util.Map<String, Integer>>(), p3); + test(!p2.isSet() && !p3.isSet()); // Ensure out parameter is cleared. + + if(reqParams) + { + p2 = initial.opStringIntDictReq(p1.get(), p3); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + r = initial.begin_opStringIntDictReq(p1.get()); + p2 = initial.end_opStringIntDictReq(p3, r); + test(p2.get().equals(p1.get()) && p3.get().equals(p1.get())); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(2, Ice.OptionalFormat.FSize); + int pos = os.startSize(); + StringIntDictHelper.write(os, p1.get()); + os.endSize(pos); + os.endEncapsulation(); + inEncaps = os.finished(); + initial.ice_invoke("opStringIntDictReq", Ice.OperationMode.Normal, inEncaps, outEncaps); + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + test(in.readOptional(1, Ice.OptionalFormat.FSize)); + in.skip(4); + java.util.Map<String, Integer> m = StringIntDictHelper.read(in); + test(m.equals(p1.get())); + test(in.readOptional(3, Ice.OptionalFormat.FSize)); + in.skip(4); + m = StringIntDictHelper.read(in); + test(m.equals(p1.get())); + in.endEncapsulation(); + + in = Ice.Util.createInputStream(communicator, outEncaps.value); + in.startEncapsulation(); + in.endEncapsulation(); + } + } + + { + F f = new F(); + f.setAf(new A()); + f.getAf().requiredA = 56; + f.ae = f.getAf(); + + os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.writeOptional(1, Ice.OptionalFormat.Class); + os.writeObject(f); + os.writeOptional(2, Ice.OptionalFormat.Class); + os.writeObject(f.ae); + os.endEncapsulation(); + inEncaps = os.finished(); + + in = Ice.Util.createInputStream(communicator, inEncaps); + in.startEncapsulation(); + test(in.readOptional(2, Ice.OptionalFormat.Class)); + final AHolder a = new AHolder(); + in.readObject(new Ice.ReadObjectCallback() + { + @Override + public void invoke(Ice.Object obj) + { + a.value = (A)obj; + } + }); + in.endEncapsulation(); + test(a.value != null && a.value.requiredA == 56); + } + out.println("ok"); + + out.print("testing exception optionals... "); + out.flush(); + { + try + { + Ice.IntOptional a = new Ice.IntOptional(); + Ice.Optional<String> b = new Ice.Optional<String>(); + Ice.Optional<OneOptional> o = new Ice.Optional<OneOptional>(); + initial.opOptionalException(a, b, o); + } + catch(OptionalException ex) + { + test(!ex.hasA()); + test(!ex.hasB()); + test(!ex.hasO()); + } + + try + { + Ice.IntOptional a = new Ice.IntOptional(30); + Ice.Optional<String> b = new Ice.Optional<String>("test"); + Ice.Optional<OneOptional> o = new Ice.Optional<OneOptional>(new OneOptional(53)); + initial.opOptionalException(a, b, o); + } + catch(OptionalException ex) + { + test(ex.getA() == 30); + test(ex.getB().equals("test")); + test(ex.getO().getA() == 53); + } + + try + { + // + // Use the 1.0 encoding with an exception whose only class members are optional. + // + Ice.IntOptional a = new Ice.IntOptional(30); + Ice.Optional<String> b = new Ice.Optional<String>("test"); + Ice.Optional<OneOptional> o = new Ice.Optional<OneOptional>(new OneOptional(53)); + initial2.opOptionalException(a, b, o); + } + catch(OptionalException ex) + { + test(!ex.hasA()); + test(!ex.hasB()); + test(!ex.hasO()); + } + + try + { + Ice.IntOptional a = new Ice.IntOptional(); + Ice.Optional<String> b = new Ice.Optional<String>(); + Ice.Optional<OneOptional> o = new Ice.Optional<OneOptional>(); + initial.opDerivedException(a, b, o); + } + catch(DerivedException ex) + { + test(!ex.hasA()); + test(!ex.hasB()); + test(!ex.hasO()); + test(!ex.hasSs()); + test(!ex.hasO2()); + } + catch(OptionalException ex) + { + test(false); + } + + try + { + Ice.IntOptional a = new Ice.IntOptional(30); + Ice.Optional<String> b = new Ice.Optional<String>("test2"); + Ice.Optional<OneOptional> o = new Ice.Optional<OneOptional>(new OneOptional(53)); + initial.opDerivedException(a, b, o); + } + catch(DerivedException ex) + { + test(ex.getA() == 30); + test(ex.getB().equals("test2")); + test(ex.getO().getA() == 53); + test(ex.getSs().equals("test2")); + test(ex.getO2().getA() == 53); + } + catch(OptionalException ex) + { + test(false); + } + + try + { + Ice.IntOptional a = new Ice.IntOptional(); + Ice.Optional<String> b = new Ice.Optional<String>(); + Ice.Optional<OneOptional> o = new Ice.Optional<OneOptional>(); + initial.opRequiredException(a, b, o); + } + catch(RequiredException ex) + { + test(!ex.hasA()); + test(!ex.hasB()); + test(!ex.hasO()); + test(ex.ss.equals("test")); + test(ex.o2 == null); + } + catch(OptionalException ex) + { + test(false); + } + + try + { + Ice.IntOptional a = new Ice.IntOptional(30); + Ice.Optional<String> b = new Ice.Optional<String>("test2"); + Ice.Optional<OneOptional> o = new Ice.Optional<OneOptional>(new OneOptional(53)); + initial.opRequiredException(a, b, o); + } + catch(RequiredException ex) + { + test(ex.getA() == 30); + test(ex.getB().equals("test2")); + test(ex.getO().getA() == 53); + test(ex.ss.equals("test2")); + test(ex.o2.getA() == 53); + } + catch(OptionalException ex) + { + test(false); + } + } + out.println("ok"); + + // + // Use reflection to load TwowaysLambdaAMI as that is only supported with Java >= 1.8 + // + try + { + Class<?> cls = IceInternal.Util.findClass("test.Ice.optional.lambda.AllTests", null); + if(cls != null) + { + java.lang.reflect.Method allTests = cls.getDeclaredMethod("allTests", + new Class<?>[]{test.Util.Application.class, java.io.PrintWriter.class}); + allTests.invoke(null, app, out); + } + } + catch(java.lang.NoSuchMethodException ex) + { + throw new RuntimeException(ex); + } + catch(java.lang.IllegalAccessException ex) + { + throw new RuntimeException(ex); + } + catch(java.lang.reflect.InvocationTargetException ex) + { + throw new RuntimeException(ex); + } + + return initial; + } + + private static class TestObjectReader extends Ice.ObjectReader + { + @Override + public void read(Ice.InputStream in) + { + in.startObject(); + in.startSlice(); + in.endSlice(); + in.endObject(false); + } + } + + private static class BObjectReader extends Ice.ObjectReader + { + @Override + public void read(Ice.InputStream in) + { + in.startObject(); + // ::Test::B + in.startSlice(); + in.readInt(); + in.endSlice(); + // ::Test::A + in.startSlice(); + in.readInt(); + in.endSlice(); + in.endObject(false); + } + } + + private static class CObjectReader extends Ice.ObjectReader + { + @Override + public void read(Ice.InputStream in) + { + in.startObject(); + // ::Test::C + in.startSlice(); + in.skipSlice(); + // ::Test::B + in.startSlice(); + in.readInt(); + in.endSlice(); + // ::Test::A + in.startSlice(); + in.readInt(); + in.endSlice(); + in.endObject(false); + } + } + + private static class DObjectWriter extends Ice.ObjectWriter + { + @Override + public void write(Ice.OutputStream out) + { + out.startObject(null); + // ::Test::D + out.startSlice("::Test::D", -1, false); + out.writeString("test"); + out.writeOptional(1, Ice.OptionalFormat.FSize); + String[] o = { "test1", "test2", "test3", "test4" }; + int pos = out.startSize(); + out.writeStringSeq(o); + out.endSize(pos); + A a = new A(); + a.setMc(18); + out.writeOptional(1000, Ice.OptionalFormat.Class); + out.writeObject(a); + out.endSlice(); + // ::Test::B + out.startSlice(B.ice_staticId(), -1, false); + int v = 14; + out.writeInt(v); + out.endSlice(); + // ::Test::A + out.startSlice(A.ice_staticId(), -1, true); + out.writeInt(v); + out.endSlice(); + out.endObject(); + } + } + + private static class DObjectReader extends Ice.ObjectReader + { + @Override + public void read(Ice.InputStream in) + { + in.startObject(); + // ::Test::D + in.startSlice(); + String s = in.readString(); + test(s.equals("test")); + test(in.readOptional(1, Ice.OptionalFormat.FSize)); + in.skip(4); + String[] o = in.readStringSeq(); + test(o.length == 4 && + o[0].equals("test1") && o[1].equals("test2") && o[2].equals("test3") && o[3].equals("test4")); + test(in.readOptional(1000, Ice.OptionalFormat.Class)); + in.readObject(a); + in.endSlice(); + // ::Test::B + in.startSlice(); + in.readInt(); + in.endSlice(); + // ::Test::A + in.startSlice(); + in.readInt(); + in.endSlice(); + in.endObject(false); + } + + void check() + { + test(((A)a.obj).getMc() == 18); + } + + private ReadObjectCallbackI a = new ReadObjectCallbackI(); + } + + private static class FObjectReader extends Ice.ObjectReader + { + @Override + public void read(Ice.InputStream in) + { + _f = new F(); + in.startObject(); + in.startSlice(); + // Don't read af on purpose + //in.read(1, _f.af); + in.endSlice(); + in.startSlice(); + in.readObject(new Ice.ReadObjectCallback() + { + @Override + public void invoke(Ice.Object obj) + { + _f.ae = (A)obj; + } + }); + in.endSlice(); + in.endObject(false); + } + + F getF() + { + return _f; + } + + private F _f; + } + + private static class FactoryI implements Ice.ObjectFactory + { + @Override + public Ice.Object create(String typeId) + { + if(!_enabled) + { + return null; + } + + if(typeId.equals(OneOptional.ice_staticId())) + { + return new TestObjectReader(); + } + else if(typeId.equals(MultiOptional.ice_staticId())) + { + return new TestObjectReader(); + } + else if(typeId.equals(B.ice_staticId())) + { + return new BObjectReader(); + } + else if(typeId.equals(C.ice_staticId())) + { + return new CObjectReader(); + } + else if(typeId.equals("::Test::D")) + { + return new DObjectReader(); + } + else if(typeId.equals("::Test::F")) + { + return new FObjectReader(); + } + + return null; + } + + @Override + public void destroy() + { + } + + void setEnabled(boolean enabled) + { + _enabled = enabled; + } + + private boolean _enabled; + } + + private static class ReadObjectCallbackI implements Ice.ReadObjectCallback + { + @Override + public void invoke(Ice.Object obj) + { + this.obj = obj; + } + + Ice.Object obj; + } +} diff --git a/java/test/src/main/java/test/Ice/optional/Client.java b/java/test/src/main/java/test/Ice/optional/Client.java new file mode 100644 index 00000000000..22f05e262bc --- /dev/null +++ b/java/test/src/main/java/test/Ice/optional/Client.java @@ -0,0 +1,42 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.optional; + +import test.Ice.optional.Test.InitialPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + java.io.PrintWriter out = getWriter(); + InitialPrx initial = AllTests.allTests(this, false, out); + initial.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.optional"); + return initData; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/optional/InitialI.java b/java/test/src/main/java/test/Ice/optional/InitialI.java new file mode 100644 index 00000000000..191575aa992 --- /dev/null +++ b/java/test/src/main/java/test/Ice/optional/InitialI.java @@ -0,0 +1,643 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.optional; + +import test.Ice.optional.Test.*; + +public final class InitialI extends Initial +{ + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + @Override + public Ice.Object + pingPong(Ice.Object obj, Ice.Current current) + { + return obj; + } + + @Override + public void + opOptionalException(Ice.IntOptional a, Ice.Optional<String> b, Ice.Optional<OneOptional> o, Ice.Current current) + throws OptionalException + { + OptionalException ex = new OptionalException(); + if(a.isSet()) + { + ex.setA(a.get()); + } + else + { + ex.clearA(); // The member "a" has a default value. + } + if(b.isSet()) + { + ex.setB(b.get()); + } + if(o.isSet()) + { + ex.setO(o.get()); + } + throw ex; + } + + @Override + public void + opDerivedException(Ice.IntOptional a, Ice.Optional<String> b, Ice.Optional<OneOptional> o, Ice.Current current) + throws OptionalException + { + DerivedException ex = new DerivedException(); + if(a.isSet()) + { + ex.setA(a.get()); + } + else + { + ex.clearA(); // The member "a" has a default value. + } + if(b.isSet()) + { + ex.setB(b.get()); + ex.setSs(b.get()); + } + else + { + ex.clearSs(); // The member "ss" has a default value. + } + if(o.isSet()) + { + ex.setO(o.get()); + ex.setO2(o.get()); + } + throw ex; + } + + @Override + public void + opRequiredException(Ice.IntOptional a, Ice.Optional<String> b, Ice.Optional<OneOptional> o, Ice.Current current) + throws OptionalException + { + RequiredException ex = new RequiredException(); + if(a.isSet()) + { + ex.setA(a.get()); + } + else + { + ex.clearA(); // The member "a" has a default value. + } + if(b.isSet()) + { + ex.setB(b.get()); + ex.ss = b.get(); + } + if(o.isSet()) + { + ex.setO(o.get()); + ex.o2 = o.get(); + } + throw ex; + } + + @Override + public Ice.ByteOptional + opByte(Ice.ByteOptional p1, Ice.ByteOptional p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public byte + opByteReq(Ice.ByteOptional p1, Ice.ByteHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.BooleanOptional + opBool(Ice.BooleanOptional p1, Ice.BooleanOptional p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public boolean + opBoolReq(Ice.BooleanOptional p1, Ice.BooleanHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.ShortOptional + opShort(Ice.ShortOptional p1, Ice.ShortOptional p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public short + opShortReq(Ice.ShortOptional p1, Ice.ShortHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.IntOptional + opInt(Ice.IntOptional p1, Ice.IntOptional p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public int + opIntReq(Ice.IntOptional p1, Ice.IntHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.LongOptional + opLong(Ice.LongOptional p1, Ice.LongOptional p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public long + opLongReq(Ice.LongOptional p1, Ice.LongHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.FloatOptional + opFloat(Ice.FloatOptional p1, Ice.FloatOptional p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public float + opFloatReq(Ice.FloatOptional p1, Ice.FloatHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.DoubleOptional + opDouble(Ice.DoubleOptional p1, Ice.DoubleOptional p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public double + opDoubleReq(Ice.DoubleOptional p1, Ice.DoubleHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<String> + opString(Ice.Optional<String> p1, Ice.Optional<String> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public String + opStringReq(Ice.Optional<String> p1, Ice.StringHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<MyEnum> + opMyEnum(Ice.Optional<MyEnum> p1, Ice.Optional<MyEnum> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public MyEnum + opMyEnumReq(Ice.Optional<MyEnum> p1, MyEnumHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<SmallStruct> + opSmallStruct(Ice.Optional<SmallStruct> p1, Ice.Optional<SmallStruct> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public SmallStruct + opSmallStructReq(Ice.Optional<SmallStruct> p1, SmallStructHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<FixedStruct> + opFixedStruct(Ice.Optional<FixedStruct> p1, Ice.Optional<FixedStruct> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public FixedStruct + opFixedStructReq(Ice.Optional<FixedStruct> p1, FixedStructHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<VarStruct> + opVarStruct(Ice.Optional<VarStruct> p1, Ice.Optional<VarStruct> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public VarStruct + opVarStructReq(Ice.Optional<VarStruct> p1, VarStructHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<OneOptional> + opOneOptional(Ice.Optional<OneOptional> p1, Ice.Optional<OneOptional> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public OneOptional + opOneOptionalReq(Ice.Optional<OneOptional> p1, OneOptionalHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<OneOptionalPrx> + opOneOptionalProxy(Ice.Optional<OneOptionalPrx> p1, Ice.Optional<OneOptionalPrx> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public OneOptionalPrx + opOneOptionalProxyReq(Ice.Optional<OneOptionalPrx> p1, OneOptionalPrxHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<byte[]> + opByteSeq(Ice.Optional<byte[]> p1, Ice.Optional<byte[]> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public byte[] + opByteSeqReq(Ice.Optional<byte[]> p1, ByteSeqHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<boolean[]> + opBoolSeq(Ice.Optional<boolean[]> p1, Ice.Optional<boolean[]> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public boolean[] + opBoolSeqReq(Ice.Optional<boolean[]> p1, BoolSeqHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<short[]> + opShortSeq(Ice.Optional<short[]> p1, Ice.Optional<short[]> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public short[] + opShortSeqReq(Ice.Optional<short[]> p1, ShortSeqHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<int[]> + opIntSeq(Ice.Optional<int[]> p1, Ice.Optional<int[]> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public int[] + opIntSeqReq(Ice.Optional<int[]> p1, IntSeqHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<long[]> + opLongSeq(Ice.Optional<long[]> p1, Ice.Optional<long[]> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public long[] + opLongSeqReq(Ice.Optional<long[]> p1, LongSeqHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<float[]> + opFloatSeq(Ice.Optional<float[]> p1, Ice.Optional<float[]> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public float[] + opFloatSeqReq(Ice.Optional<float[]> p1, FloatSeqHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<double[]> + opDoubleSeq(Ice.Optional<double[]> p1, Ice.Optional<double[]> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public double[] + opDoubleSeqReq(Ice.Optional<double[]> p1, DoubleSeqHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<String[]> + opStringSeq(Ice.Optional<String[]> p1, Ice.Optional<String[]> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public String[] + opStringSeqReq(Ice.Optional<String[]> p1, StringSeqHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<SmallStruct[]> + opSmallStructSeq(Ice.Optional<SmallStruct[]> p1, Ice.Optional<SmallStruct[]> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public SmallStruct[] + opSmallStructSeqReq(Ice.Optional<SmallStruct[]> p1, SmallStructSeqHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<java.util.List<SmallStruct>> + opSmallStructList(Ice.Optional<java.util.List<SmallStruct>> p1, + Ice.Optional<java.util.List<SmallStruct>> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public java.util.List<SmallStruct> + opSmallStructListReq(Ice.Optional<java.util.List<SmallStruct>> p1, SmallStructListHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<FixedStruct[]> + opFixedStructSeq(Ice.Optional<FixedStruct[]> p1, Ice.Optional<FixedStruct[]> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public FixedStruct[] + opFixedStructSeqReq(Ice.Optional<FixedStruct[]> p1, FixedStructSeqHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<java.util.List<FixedStruct>> + opFixedStructList(Ice.Optional<java.util.List<FixedStruct>> p1, + Ice.Optional<java.util.List<FixedStruct>> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public java.util.List<FixedStruct> + opFixedStructListReq(Ice.Optional<java.util.List<FixedStruct>> p1, FixedStructListHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<VarStruct[]> + opVarStructSeq(Ice.Optional<VarStruct[]> p1, Ice.Optional<VarStruct[]> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public VarStruct[] + opVarStructSeqReq(Ice.Optional<VarStruct[]> p1, VarStructSeqHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<SerializableClass> + opSerializable(Ice.Optional<SerializableClass> p1, Ice.Optional<SerializableClass> p3, Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public SerializableClass + opSerializableReq(Ice.Optional<SerializableClass> p1, Ice.Holder<SerializableClass> p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<java.util.Map<Integer, Integer>> + opIntIntDict(Ice.Optional<java.util.Map<Integer, Integer>> p1, Ice.Optional<java.util.Map<Integer, Integer>> p3, + Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public java.util.Map<Integer, Integer> + opIntIntDictReq(Ice.Optional<java.util.Map<Integer, Integer>> p1, IntIntDictHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public Ice.Optional<java.util.Map<String, Integer>> + opStringIntDict(Ice.Optional<java.util.Map<String, Integer>> p1, Ice.Optional<java.util.Map<String, Integer>> p3, + Ice.Current current) + { + p3.set(p1); + return p1; + } + + @Override + public java.util.Map<String, Integer> + opStringIntDictReq(Ice.Optional<java.util.Map<String, Integer>> p1, StringIntDictHolder p3, Ice.Current current) + { + p3.value = p1.get(); + return p1.get(); + } + + @Override + public void + opClassAndUnknownOptional(A p, Ice.Current current) + { + } + + @Override + public void + sendOptionalClass(boolean req, Ice.Optional<OneOptional> o, Ice.Current current) + { + } + + @Override + public void + returnOptionalClass(boolean req, Ice.Optional<OneOptional> o, Ice.Current current) + { + o.set(new OneOptional(53)); + } + + @Override + public boolean + supportsRequiredParams(Ice.Current current) + { + return true; + } + + @Override + public boolean + supportsJavaSerializable(Ice.Current current) + { + return true; + } + + @Override + public boolean + supportsCsharpSerializable(Ice.Current current) + { + return false; + } + + @Override + public boolean + supportsCppStringView(Ice.Current current) + { + return false; + } +} diff --git a/java/test/src/main/java/test/Ice/optional/SerializableClass.java b/java/test/src/main/java/test/Ice/optional/SerializableClass.java new file mode 100644 index 00000000000..1d29516c246 --- /dev/null +++ b/java/test/src/main/java/test/Ice/optional/SerializableClass.java @@ -0,0 +1,32 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.optional; + +public class SerializableClass implements java.io.Serializable +{ + public SerializableClass(int v) + { + _v = v; + } + + @Override + public boolean equals(Object obj) + { + if(obj instanceof SerializableClass) + { + return _v == ((SerializableClass)obj)._v; + } + + return false; + } + + private int _v; + public static final long serialVersionUID = 1; +} diff --git a/java/test/src/main/java/test/Ice/optional/Server.java b/java/test/src/main/java/test/Ice/optional/Server.java new file mode 100644 index 00000000000..15446ac47b5 --- /dev/null +++ b/java/test/src/main/java/test/Ice/optional/Server.java @@ -0,0 +1,41 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.optional; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + communicator().getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.add(new InitialI(), communicator().stringToIdentity("initial")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.optional"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/optional/Test.ice b/java/test/src/main/java/test/Ice/optional/Test.ice new file mode 100644 index 00000000000..96078ca538a --- /dev/null +++ b/java/test/src/main/java/test/Ice/optional/Test.ice @@ -0,0 +1,313 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.optional"]] +module Test +{ + +class OneOptional +{ + optional(1) int a; +}; + +enum MyEnum +{ + MyEnumMember +}; + +struct SmallStruct +{ + byte m; +}; + +struct FixedStruct +{ + int m; +}; + +struct VarStruct +{ + string m; +}; + +struct ClassVarStruct +{ + int a; +}; + +sequence<byte> ByteSeq; +sequence<bool> BoolSeq; +sequence<short> ShortSeq; +sequence<int> IntSeq; +sequence<long> LongSeq; +sequence<float> FloatSeq; +sequence<double> DoubleSeq; +sequence<string> StringSeq; +sequence<MyEnum> MyEnumSeq; +sequence<SmallStruct> SmallStructSeq; +["java:type:java.util.ArrayList<SmallStruct>"] sequence<SmallStruct> SmallStructList; +sequence<FixedStruct> FixedStructSeq; +["java:type:java.util.ArrayList<FixedStruct>"] sequence<FixedStruct> FixedStructList; +sequence<VarStruct> VarStructSeq; +sequence<OneOptional> OneOptionalSeq; +sequence<OneOptional*> OneOptionalPrxSeq; + +["java:serializable:test.Ice.optional.SerializableClass"] sequence<byte> Serializable; + +dictionary<int, int> IntIntDict; +dictionary<string, int> StringIntDict; +dictionary<int, MyEnum> IntEnumDict; +dictionary<int, FixedStruct> IntFixedStructDict; +dictionary<int, VarStruct> IntVarStructDict; +dictionary<int, OneOptional> IntOneOptionalDict; +dictionary<int, OneOptional*> IntOneOptionalPrxDict; + +class MultiOptional +{ + optional(1) byte a; + optional(2) bool b; + optional(3) short c; + optional(4) int d; + optional(5) long e; + optional(6) float f; + optional(7) double g; + optional(8) string h; + optional(9) MyEnum i; + optional(10) MultiOptional* j; + optional(11) MultiOptional k; + optional(12) ByteSeq bs; + optional(13) StringSeq ss; + optional(14) IntIntDict iid; + optional(15) StringIntDict sid; + optional(16) FixedStruct fs; + optional(17) VarStruct vs; + + optional(18) ShortSeq shs; + optional(19) MyEnumSeq es; + optional(20) FixedStructSeq fss; + optional(21) VarStructSeq vss; + optional(22) OneOptionalSeq oos; + optional(23) OneOptionalPrxSeq oops; + + optional(24) IntEnumDict ied; + optional(25) IntFixedStructDict ifsd; + optional(26) IntVarStructDict ivsd; + optional(27) IntOneOptionalDict iood; + optional(28) IntOneOptionalPrxDict ioopd; + + optional(29) BoolSeq bos; + + optional(30) Serializable ser; +}; + +class A +{ + int requiredA; + optional(1) int ma; + optional(50) int mb; + optional(500) int mc; +}; + +["preserve-slice"] +class B extends A +{ + int requiredB; + optional(10) int md; +}; + +class C extends B +{ + string ss; + optional(890) string ms; +}; + +class WD +{ + optional(1) int a = 5; + optional(2) string s = "test"; +}; + +exception OptionalException +{ + bool req = false; + optional(1) int a = 5; + optional(2) string b; + optional(50) OneOptional o; +}; + +exception DerivedException extends OptionalException +{ + optional(600) string ss = "test"; + optional(601) OneOptional o2; +}; + +exception RequiredException extends OptionalException +{ + string ss = "test"; + OneOptional o2; +}; + +class OptionalWithCustom +{ + optional(1) SmallStructList l; + ["protected"] optional(2) SmallStructList lp; + optional(3) ClassVarStruct s; +}; + +class E +{ + A ae; +}; + +class F extends E +{ + optional(1) A af; +}; + +class Recursive; +sequence<Recursive> RecursiveSeq; + +class Recursive { + optional(0) RecursiveSeq value; +}; + +class Initial +{ + void shutdown(); + + Object pingPong(Object o); + + void opOptionalException(optional(1) int a, optional(2) string b, optional(3) OneOptional o) + throws OptionalException; + + void opDerivedException(optional(1) int a, optional(2) string b, optional(3) OneOptional o) + throws OptionalException; + + void opRequiredException(optional(1) int a, optional(2) string b, optional(3) OneOptional o) + throws OptionalException; + + ["java:optional"] optional(1) byte opByte(optional(2) byte p1, out optional(3) byte p3); + optional(1) byte opByteReq(optional(2) byte p1, out optional(3) byte p3); + + ["java:optional"] optional(1) bool opBool(optional(2) bool p1, out optional(3) bool p3); + optional(1) bool opBoolReq(optional(2) bool p1, out optional(3) bool p3); + + ["java:optional"] optional(1) short opShort(optional(2) short p1, out optional(3) short p3); + optional(1) short opShortReq(optional(2) short p1, out optional(3) short p3); + + ["java:optional"] optional(1) int opInt(optional(2) int p1, out optional(3) int p3); + optional(1) int opIntReq(optional(2) int p1, out optional(3) int p3); + + ["java:optional"] optional(3) long opLong(optional(1) long p1, out optional(2) long p3); + optional(3) long opLongReq(optional(1) long p1, out optional(2) long p3); + + ["java:optional"] optional(1) float opFloat(optional(2) float p1, out optional(3) float p3); + optional(1) float opFloatReq(optional(2) float p1, out optional(3) float p3); + + ["java:optional"] optional(1) double opDouble(optional(2) double p1, out optional(3) double p3); + optional(1) double opDoubleReq(optional(2) double p1, out optional(3) double p3); + + ["java:optional"] optional(1) string opString(optional(2) string p1, out optional(3) string p3); + optional(1) string opStringReq(optional(2) string p1, out optional(3) string p3); + + ["java:optional"] optional(1) MyEnum opMyEnum(optional(2) MyEnum p1, out optional(3) MyEnum p3); + optional(1) MyEnum opMyEnumReq(optional(2) MyEnum p1, out optional(3) MyEnum p3); + + ["java:optional"] optional(1) SmallStruct opSmallStruct(optional(2) SmallStruct p1, out optional(3) SmallStruct p3); + optional(1) SmallStruct opSmallStructReq(optional(2) SmallStruct p1, out optional(3) SmallStruct p3); + + ["java:optional"] optional(1) FixedStruct opFixedStruct(optional(2) FixedStruct p1, out optional(3) FixedStruct p3); + optional(1) FixedStruct opFixedStructReq(optional(2) FixedStruct p1, out optional(3) FixedStruct p3); + + ["java:optional"] optional(1) VarStruct opVarStruct(optional(2) VarStruct p1, out optional(3) VarStruct p3); + optional(1) VarStruct opVarStructReq(optional(2) VarStruct p1, out optional(3) VarStruct p3); + + ["java:optional"] optional(1) OneOptional opOneOptional(optional(2) OneOptional p1, out optional(3) OneOptional p3); + optional(1) OneOptional opOneOptionalReq(optional(2) OneOptional p1, out optional(3) OneOptional p3); + + ["java:optional"] optional(1) OneOptional* opOneOptionalProxy(optional(2) OneOptional* p1, + out optional(3) OneOptional* p3); + optional(1) OneOptional* opOneOptionalProxyReq(optional(2) OneOptional* p1, out optional(3) OneOptional* p3); + + ["java:optional"] optional(1) ByteSeq opByteSeq(optional(2) ByteSeq p1, out optional(3) ByteSeq p3); + optional(1) ByteSeq opByteSeqReq(optional(2) ByteSeq p1, out optional(3) ByteSeq p3); + + ["java:optional"] optional(1) BoolSeq opBoolSeq(optional(2) BoolSeq p1, out optional(3) BoolSeq p3); + optional(1) BoolSeq opBoolSeqReq(optional(2) BoolSeq p1, out optional(3) BoolSeq p3); + + ["java:optional"] optional(1) ShortSeq opShortSeq(optional(2) ShortSeq p1, out optional(3) ShortSeq p3); + optional(1) ShortSeq opShortSeqReq(optional(2) ShortSeq p1, out optional(3) ShortSeq p3); + + ["java:optional"] optional(1) IntSeq opIntSeq(optional(2) IntSeq p1, out optional(3) IntSeq p3); + optional(1) IntSeq opIntSeqReq(optional(2) IntSeq p1, out optional(3) IntSeq p3); + + ["java:optional"] optional(1) LongSeq opLongSeq(optional(2) LongSeq p1, out optional(3) LongSeq p3); + optional(1) LongSeq opLongSeqReq(optional(2) LongSeq p1, out optional(3) LongSeq p3); + + ["java:optional"] optional(1) FloatSeq opFloatSeq(optional(2) FloatSeq p1, out optional(3) FloatSeq p3); + optional(1) FloatSeq opFloatSeqReq(optional(2) FloatSeq p1, out optional(3) FloatSeq p3); + + ["java:optional"] optional(1) DoubleSeq opDoubleSeq(optional(2) DoubleSeq p1, out optional(3) DoubleSeq p3); + optional(1) DoubleSeq opDoubleSeqReq(optional(2) DoubleSeq p1, out optional(3) DoubleSeq p3); + + ["java:optional"] optional(1) StringSeq opStringSeq(optional(2) StringSeq p1, out optional(3) StringSeq p3); + optional(1) StringSeq opStringSeqReq(optional(2) StringSeq p1, out optional(3) StringSeq p3); + + ["java:optional"] optional(1) SmallStructSeq opSmallStructSeq(optional(2) SmallStructSeq p1, + out optional(3) SmallStructSeq p3); + optional(1) SmallStructSeq opSmallStructSeqReq(optional(2) SmallStructSeq p1, out optional(3) SmallStructSeq p3); + + ["java:optional"] optional(1) SmallStructList opSmallStructList(optional(2) SmallStructList p1, + out optional(3) SmallStructList p3); + optional(1) SmallStructList opSmallStructListReq(optional(2) SmallStructList p1, + out optional(3) SmallStructList p3); + + ["java:optional"] optional(1) FixedStructSeq opFixedStructSeq(optional(2) FixedStructSeq p1, + out optional(3) FixedStructSeq p3); + optional(1) FixedStructSeq opFixedStructSeqReq(optional(2) FixedStructSeq p1, out optional(3) FixedStructSeq p3); + + ["java:optional"] optional(1) FixedStructList opFixedStructList(optional(2) FixedStructList p1, + out optional(3) FixedStructList p3); + optional(1) FixedStructList opFixedStructListReq(optional(2) FixedStructList p1, + out optional(3) FixedStructList p3); + + ["java:optional"] optional(1) VarStructSeq opVarStructSeq(optional(2) VarStructSeq p1, + out optional(3) VarStructSeq p3); + optional(1) VarStructSeq opVarStructSeqReq(optional(2) VarStructSeq p1, out optional(3) VarStructSeq p3); + + ["java:optional"] optional(1) Serializable opSerializable(optional(2) Serializable p1, + out optional(3) Serializable p3); + optional(1) Serializable opSerializableReq(optional(2) Serializable p1, out optional(3) Serializable p3); + + ["java:optional"] optional(1) IntIntDict opIntIntDict(optional(2) IntIntDict p1, out optional(3) IntIntDict p3); + optional(1) IntIntDict opIntIntDictReq(optional(2) IntIntDict p1, out optional(3) IntIntDict p3); + + ["java:optional"] optional(1) StringIntDict opStringIntDict(optional(2) StringIntDict p1, + out optional(3) StringIntDict p3); + optional(1) StringIntDict opStringIntDictReq(optional(2) StringIntDict p1, out optional(3) StringIntDict p3); + + void opClassAndUnknownOptional(A p); + + void sendOptionalClass(bool req, optional(1) OneOptional o); + + ["java:optional"] + void returnOptionalClass(bool req, out optional(1) OneOptional o); + + bool supportsRequiredParams(); + + bool supportsJavaSerializable(); + + bool supportsCsharpSerializable(); + + bool supportsCppStringView(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/optional/TestAMD.ice b/java/test/src/main/java/test/Ice/optional/TestAMD.ice new file mode 100644 index 00000000000..95a283116dd --- /dev/null +++ b/java/test/src/main/java/test/Ice/optional/TestAMD.ice @@ -0,0 +1,314 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.optional.AMD"]] +module Test +{ + +class OneOptional +{ + optional(1) int a; +}; + +enum MyEnum +{ + MyEnumMember +}; + +struct SmallStruct +{ + byte m; +}; + +struct FixedStruct +{ + int m; +}; + +struct VarStruct +{ + string m; +}; + +struct ClassVarStruct +{ + int a; +}; + +sequence<byte> ByteSeq; +sequence<bool> BoolSeq; +sequence<short> ShortSeq; +sequence<int> IntSeq; +sequence<long> LongSeq; +sequence<float> FloatSeq; +sequence<double> DoubleSeq; +sequence<string> StringSeq; +sequence<MyEnum> MyEnumSeq; +sequence<SmallStruct> SmallStructSeq; +["java:type:java.util.ArrayList<SmallStruct>"] sequence<SmallStruct> SmallStructList; +sequence<FixedStruct> FixedStructSeq; +["java:type:java.util.ArrayList<FixedStruct>"] sequence<FixedStruct> FixedStructList; +sequence<VarStruct> VarStructSeq; +sequence<OneOptional> OneOptionalSeq; +sequence<OneOptional*> OneOptionalPrxSeq; + +["java:serializable:test.Ice.optional.SerializableClass"] sequence<byte> Serializable; + +dictionary<int, int> IntIntDict; +dictionary<string, int> StringIntDict; +dictionary<int, MyEnum> IntEnumDict; +dictionary<int, FixedStruct> IntFixedStructDict; +dictionary<int, VarStruct> IntVarStructDict; +dictionary<int, OneOptional> IntOneOptionalDict; +dictionary<int, OneOptional*> IntOneOptionalPrxDict; + +class MultiOptional +{ + optional(1) byte a; + optional(2) bool b; + optional(3) short c; + optional(4) int d; + optional(5) long e; + optional(6) float f; + optional(7) double g; + optional(8) string h; + optional(9) MyEnum i; + optional(10) MultiOptional* j; + optional(11) MultiOptional k; + optional(12) ByteSeq bs; + optional(13) StringSeq ss; + optional(14) IntIntDict iid; + optional(15) StringIntDict sid; + optional(16) FixedStruct fs; + optional(17) VarStruct vs; + + optional(18) ShortSeq shs; + optional(19) MyEnumSeq es; + optional(20) FixedStructSeq fss; + optional(21) VarStructSeq vss; + optional(22) OneOptionalSeq oos; + optional(23) OneOptionalPrxSeq oops; + + optional(24) IntEnumDict ied; + optional(25) IntFixedStructDict ifsd; + optional(26) IntVarStructDict ivsd; + optional(27) IntOneOptionalDict iood; + optional(28) IntOneOptionalPrxDict ioopd; + + optional(29) BoolSeq bos; + + optional(30) Serializable ser; +}; + +class A +{ + int requiredA; + optional(1) int ma; + optional(50) int mb; + optional(500) int mc; +}; + +["preserve-slice"] +class B extends A +{ + int requiredB; + optional(10) int md; +}; + +class C extends B +{ + string ss; + optional(890) string ms; +}; + +class WD +{ + optional(1) int a = 5; + optional(2) string s = "test"; +}; + +exception OptionalException +{ + bool req = false; + optional(1) int a = 5; + optional(2) string b; + optional(50) OneOptional o; +}; + +exception DerivedException extends OptionalException +{ + optional(600) string ss = "test"; + optional(601) OneOptional o2; +}; + +exception RequiredException extends OptionalException +{ + string ss = "test"; + OneOptional o2; +}; + +class OptionalWithCustom +{ + optional(1) SmallStructList l; + ["protected"] optional(2) SmallStructList lp; + optional(3) ClassVarStruct s; +}; + +class E +{ + A ae; +}; + +class F extends E +{ + optional(1) A af; +}; + +class Recursive; +sequence<Recursive> RecursiveSeq; + +class Recursive { + optional(0) RecursiveSeq value; +}; + +["amd"] +class Initial +{ + void shutdown(); + + Object pingPong(Object o); + + void opOptionalException(optional(1) int a, optional(2) string b, optional(3) OneOptional o) + throws OptionalException; + + void opDerivedException(optional(1) int a, optional(2) string b, optional(3) OneOptional o) + throws OptionalException; + + void opRequiredException(optional(1) int a, optional(2) string b, optional(3) OneOptional o) + throws OptionalException; + + ["java:optional"] optional(1) byte opByte(optional(2) byte p1, out optional(3) byte p3); + optional(1) byte opByteReq(optional(2) byte p1, out optional(3) byte p3); + + ["java:optional"] optional(1) bool opBool(optional(2) bool p1, out optional(3) bool p3); + optional(1) bool opBoolReq(optional(2) bool p1, out optional(3) bool p3); + + ["java:optional"] optional(1) short opShort(optional(2) short p1, out optional(3) short p3); + optional(1) short opShortReq(optional(2) short p1, out optional(3) short p3); + + ["java:optional"] optional(1) int opInt(optional(2) int p1, out optional(3) int p3); + optional(1) int opIntReq(optional(2) int p1, out optional(3) int p3); + + ["java:optional"] optional(3) long opLong(optional(1) long p1, out optional(2) long p3); + optional(3) long opLongReq(optional(1) long p1, out optional(2) long p3); + + ["java:optional"] optional(1) float opFloat(optional(2) float p1, out optional(3) float p3); + optional(1) float opFloatReq(optional(2) float p1, out optional(3) float p3); + + ["java:optional"] optional(1) double opDouble(optional(2) double p1, out optional(3) double p3); + optional(1) double opDoubleReq(optional(2) double p1, out optional(3) double p3); + + ["java:optional"] optional(1) string opString(optional(2) string p1, out optional(3) string p3); + optional(1) string opStringReq(optional(2) string p1, out optional(3) string p3); + + ["java:optional"] optional(1) MyEnum opMyEnum(optional(2) MyEnum p1, out optional(3) MyEnum p3); + optional(1) MyEnum opMyEnumReq(optional(2) MyEnum p1, out optional(3) MyEnum p3); + + ["java:optional"] optional(1) SmallStruct opSmallStruct(optional(2) SmallStruct p1, out optional(3) SmallStruct p3); + optional(1) SmallStruct opSmallStructReq(optional(2) SmallStruct p1, out optional(3) SmallStruct p3); + + ["java:optional"] optional(1) FixedStruct opFixedStruct(optional(2) FixedStruct p1, out optional(3) FixedStruct p3); + optional(1) FixedStruct opFixedStructReq(optional(2) FixedStruct p1, out optional(3) FixedStruct p3); + + ["java:optional"] optional(1) VarStruct opVarStruct(optional(2) VarStruct p1, out optional(3) VarStruct p3); + optional(1) VarStruct opVarStructReq(optional(2) VarStruct p1, out optional(3) VarStruct p3); + + ["java:optional"] optional(1) OneOptional opOneOptional(optional(2) OneOptional p1, out optional(3) OneOptional p3); + optional(1) OneOptional opOneOptionalReq(optional(2) OneOptional p1, out optional(3) OneOptional p3); + + ["java:optional"] optional(1) OneOptional* opOneOptionalProxy(optional(2) OneOptional* p1, + out optional(3) OneOptional* p3); + optional(1) OneOptional* opOneOptionalProxyReq(optional(2) OneOptional* p1, out optional(3) OneOptional* p3); + + ["java:optional"] optional(1) ByteSeq opByteSeq(optional(2) ByteSeq p1, out optional(3) ByteSeq p3); + optional(1) ByteSeq opByteSeqReq(optional(2) ByteSeq p1, out optional(3) ByteSeq p3); + + ["java:optional"] optional(1) BoolSeq opBoolSeq(optional(2) BoolSeq p1, out optional(3) BoolSeq p3); + optional(1) BoolSeq opBoolSeqReq(optional(2) BoolSeq p1, out optional(3) BoolSeq p3); + + ["java:optional"] optional(1) ShortSeq opShortSeq(optional(2) ShortSeq p1, out optional(3) ShortSeq p3); + optional(1) ShortSeq opShortSeqReq(optional(2) ShortSeq p1, out optional(3) ShortSeq p3); + + ["java:optional"] optional(1) IntSeq opIntSeq(optional(2) IntSeq p1, out optional(3) IntSeq p3); + optional(1) IntSeq opIntSeqReq(optional(2) IntSeq p1, out optional(3) IntSeq p3); + + ["java:optional"] optional(1) LongSeq opLongSeq(optional(2) LongSeq p1, out optional(3) LongSeq p3); + optional(1) LongSeq opLongSeqReq(optional(2) LongSeq p1, out optional(3) LongSeq p3); + + ["java:optional"] optional(1) FloatSeq opFloatSeq(optional(2) FloatSeq p1, out optional(3) FloatSeq p3); + optional(1) FloatSeq opFloatSeqReq(optional(2) FloatSeq p1, out optional(3) FloatSeq p3); + + ["java:optional"] optional(1) DoubleSeq opDoubleSeq(optional(2) DoubleSeq p1, out optional(3) DoubleSeq p3); + optional(1) DoubleSeq opDoubleSeqReq(optional(2) DoubleSeq p1, out optional(3) DoubleSeq p3); + + ["java:optional"] optional(1) StringSeq opStringSeq(optional(2) StringSeq p1, out optional(3) StringSeq p3); + optional(1) StringSeq opStringSeqReq(optional(2) StringSeq p1, out optional(3) StringSeq p3); + + ["java:optional"] optional(1) SmallStructSeq opSmallStructSeq(optional(2) SmallStructSeq p1, + out optional(3) SmallStructSeq p3); + optional(1) SmallStructSeq opSmallStructSeqReq(optional(2) SmallStructSeq p1, out optional(3) SmallStructSeq p3); + + ["java:optional"] optional(1) SmallStructList opSmallStructList(optional(2) SmallStructList p1, + out optional(3) SmallStructList p3); + optional(1) SmallStructList opSmallStructListReq(optional(2) SmallStructList p1, + out optional(3) SmallStructList p3); + + ["java:optional"] optional(1) FixedStructSeq opFixedStructSeq(optional(2) FixedStructSeq p1, + out optional(3) FixedStructSeq p3); + optional(1) FixedStructSeq opFixedStructSeqReq(optional(2) FixedStructSeq p1, out optional(3) FixedStructSeq p3); + + ["java:optional"] optional(1) FixedStructList opFixedStructList(optional(2) FixedStructList p1, + out optional(3) FixedStructList p3); + optional(1) FixedStructList opFixedStructListReq(optional(2) FixedStructList p1, + out optional(3) FixedStructList p3); + + ["java:optional"] optional(1) VarStructSeq opVarStructSeq(optional(2) VarStructSeq p1, + out optional(3) VarStructSeq p3); + optional(1) VarStructSeq opVarStructSeqReq(optional(2) VarStructSeq p1, out optional(3) VarStructSeq p3); + + ["java:optional"] optional(1) Serializable opSerializable(optional(2) Serializable p1, + out optional(3) Serializable p3); + optional(1) Serializable opSerializableReq(optional(2) Serializable p1, out optional(3) Serializable p3); + + ["java:optional"] optional(1) IntIntDict opIntIntDict(optional(2) IntIntDict p1, out optional(3) IntIntDict p3); + optional(1) IntIntDict opIntIntDictReq(optional(2) IntIntDict p1, out optional(3) IntIntDict p3); + + ["java:optional"] optional(1) StringIntDict opStringIntDict(optional(2) StringIntDict p1, + out optional(3) StringIntDict p3); + optional(1) StringIntDict opStringIntDictReq(optional(2) StringIntDict p1, out optional(3) StringIntDict p3); + + void opClassAndUnknownOptional(A p); + + void sendOptionalClass(bool req, optional(1) OneOptional o); + + ["java:optional"] + void returnOptionalClass(bool req, out optional(1) OneOptional o); + + bool supportsRequiredParams(); + + bool supportsJavaSerializable(); + + bool supportsCsharpSerializable(); + + bool supportsCppStringView(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/optional/lambda/AllTests.java b/java/test/src/main/java/test/Ice/optional/lambda/AllTests.java new file mode 100644 index 00000000000..db9fce3f89d --- /dev/null +++ b/java/test/src/main/java/test/Ice/optional/lambda/AllTests.java @@ -0,0 +1,790 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.optional.lambda; +import java.io.PrintWriter; + +import test.Ice.optional.Test.*; +import test.Ice.optional.SerializableClass; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class CallbackBase + { + CallbackBase() + { + _called = false; + } + + public synchronized void check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + test(_value); + _value = false; + } + + public synchronized void called(boolean value) + { + assert(!_called); + _value = value; + _called = true; + notify(); + } + + private boolean _value; + private boolean _called; + } + + public static InitialPrx + allTests(test.Util.Application app, PrintWriter out) + { + Ice.Communicator communicator = app.communicator(); + + String ref = "initial:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + + InitialPrx initial = InitialPrxHelper.uncheckedCast(base); + + out.print("testing optional parameters with async lambda callbacks... "); + out.flush(); + final boolean reqParams = initial.supportsRequiredParams(); + + final boolean supportsJavaSerializable = initial.supportsJavaSerializable(); + + { + Ice.ByteOptional p1 = new Ice.ByteOptional((byte)56); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opByte(p1.get(), + (Ice.ByteOptional ret, Ice.ByteOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opByte(p1, + (Ice.ByteOptional ret, Ice.ByteOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.BooleanOptional p1 = new Ice.BooleanOptional(true); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opBool(p1.get(), + (Ice.BooleanOptional ret, Ice.BooleanOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opBool(p1, + (Ice.BooleanOptional ret, Ice.BooleanOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.ShortOptional p1 = new Ice.ShortOptional((short)56); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opShort(p1.get(), + (Ice.ShortOptional ret, Ice.ShortOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opShort(p1, + (Ice.ShortOptional ret, Ice.ShortOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.IntOptional p1 = new Ice.IntOptional(56); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opInt(p1.get(), + (Ice.IntOptional ret, Ice.IntOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opInt(p1, + (Ice.IntOptional ret, Ice.IntOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.LongOptional p1 = new Ice.LongOptional(56); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opLong(p1.get(), + (Ice.LongOptional ret, Ice.LongOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opLong(p1, + (Ice.LongOptional ret, Ice.LongOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.FloatOptional p1 = new Ice.FloatOptional(1.0f); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opFloat(p1.get(), + (Ice.FloatOptional ret, Ice.FloatOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opFloat(p1, + (Ice.FloatOptional ret, Ice.FloatOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.DoubleOptional p1 = new Ice.DoubleOptional(1.0); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opDouble(p1.get(), + (Ice.DoubleOptional ret, Ice.DoubleOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opDouble(p1, + (Ice.DoubleOptional ret, Ice.DoubleOptional p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<String> p1 = new Ice.Optional<String>("test"); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opString(p1.get(), + (Ice.Optional<String> ret, Ice.Optional<String> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opString(p1, + (Ice.Optional<String> ret, Ice.Optional<String> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<MyEnum> p1 = new Ice.Optional<MyEnum>(MyEnum.MyEnumMember); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opMyEnum(p1.get(), + (Ice.Optional<MyEnum> ret, Ice.Optional<MyEnum> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opMyEnum(p1, + (Ice.Optional<MyEnum> ret, Ice.Optional<MyEnum> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get() == p2.get() && ret.get() == p1.get()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<SmallStruct> p1 = new Ice.Optional<SmallStruct>(new SmallStruct((byte)56)); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opSmallStruct(p1.get(), + (Ice.Optional<SmallStruct> ret, Ice.Optional<SmallStruct> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opSmallStruct(p1, + (Ice.Optional<SmallStruct> ret, Ice.Optional<SmallStruct> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<FixedStruct> p1 = new Ice.Optional<FixedStruct>(new FixedStruct((byte)56)); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opFixedStruct(p1.get(), + (Ice.Optional<FixedStruct> ret, Ice.Optional<FixedStruct> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opFixedStruct(p1, + (Ice.Optional<FixedStruct> ret, Ice.Optional<FixedStruct> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<VarStruct> p1 = new Ice.Optional<VarStruct>(new VarStruct("test")); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opVarStruct(p1.get(), + (Ice.Optional<VarStruct> ret, Ice.Optional<VarStruct> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opVarStruct(p1, + (Ice.Optional<VarStruct> ret, Ice.Optional<VarStruct> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<OneOptional> p1 = new Ice.Optional<OneOptional>(new OneOptional(58)); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opOneOptional(p1.get(), + (Ice.Optional<OneOptional> ret, Ice.Optional<OneOptional> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().getA() == p2.get().getA() && + ret.get().getA() == p1.get().getA()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opOneOptional(p1, + (Ice.Optional<OneOptional> ret, Ice.Optional<OneOptional> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().getA() == p2.get().getA() && + ret.get().getA() == p1.get().getA()), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<OneOptionalPrx> p1 = new Ice.Optional<OneOptionalPrx>( + OneOptionalPrxHelper.uncheckedCast(communicator.stringToProxy("test"))); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opOneOptionalProxy(p1.get(), + (Ice.Optional<OneOptionalPrx> ret, Ice.Optional<OneOptionalPrx> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opOneOptionalProxy(p1, + (Ice.Optional<OneOptionalPrx> ret, Ice.Optional<OneOptionalPrx> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<byte[]> p1 = new Ice.Optional<byte[]>(new byte[100]); + java.util.Arrays.fill(p1.get(), (byte)56); + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opByteSeq(p1.get(), + (Ice.Optional<byte[]> ret, Ice.Optional<byte[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opByteSeq(p1, + (Ice.Optional<byte[]> ret, Ice.Optional<byte[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<boolean[]> p1 = new Ice.Optional<boolean[]>(new boolean[100]); + java.util.Arrays.fill(p1.get(), true); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opBoolSeq(p1.get(), + (Ice.Optional<boolean[]> ret, Ice.Optional<boolean[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opBoolSeq(p1, + (Ice.Optional<boolean[]> ret, Ice.Optional<boolean[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<short[]> p1 = new Ice.Optional<short[]>(new short[100]); + java.util.Arrays.fill(p1.get(), (short)56); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opShortSeq(p1.get(), + (Ice.Optional<short[]> ret, Ice.Optional<short[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opShortSeq(p1, + (Ice.Optional<short[]> ret, Ice.Optional<short[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<int[]> p1 = new Ice.Optional<int[]>(new int[100]); + java.util.Arrays.fill(p1.get(), 56); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opIntSeq(p1.get(), + (Ice.Optional<int[]> ret, Ice.Optional<int[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opIntSeq(p1, + (Ice.Optional<int[]> ret, Ice.Optional<int[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<long[]> p1 = new Ice.Optional<long[]>(new long[100]); + java.util.Arrays.fill(p1.get(), 56); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opLongSeq(p1.get(), + (Ice.Optional<long[]> ret, Ice.Optional<long[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opLongSeq(p1, + (Ice.Optional<long[]> ret, Ice.Optional<long[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<float[]> p1 = new Ice.Optional<float[]>(new float[100]); + java.util.Arrays.fill(p1.get(), 1.0f); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opFloatSeq(p1.get(), + (Ice.Optional<float[]> ret, Ice.Optional<float[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + CallbackBase cb = new CallbackBase(); + initial.begin_opFloatSeq(p1, + (Ice.Optional<float[]> ret, Ice.Optional<float[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<double[]> p1 = new Ice.Optional<double[]>(new double[100]); + java.util.Arrays.fill(p1.get(), 1.0); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opDoubleSeq(p1.get(), + (Ice.Optional<double[]> ret, Ice.Optional<double[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + CallbackBase cb = new CallbackBase(); + initial.begin_opDoubleSeq(p1, + (Ice.Optional<double[]> ret, Ice.Optional<double[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<String[]> p1 = new Ice.Optional<String[]>(new String[10]); + java.util.Arrays.fill(p1.get(), "test"); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opStringSeq(p1.get(), + (Ice.Optional<String[]> ret, Ice.Optional<String[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opStringSeq(p1, + (Ice.Optional<String[]> ret, Ice.Optional<String[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<SmallStruct[]> p1 = new Ice.Optional<SmallStruct[]>(); + p1.set(new SmallStruct[10]); + for(int i = 0; i < p1.get().length; ++i) + { + p1.get()[i] = new SmallStruct(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opSmallStructSeq(p1.get(), + (Ice.Optional<SmallStruct[]> ret, Ice.Optional<SmallStruct[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opSmallStructSeq(p1, + (Ice.Optional<SmallStruct[]> ret, Ice.Optional<SmallStruct[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<java.util.List<SmallStruct>> p1 = new Ice.Optional<java.util.List<SmallStruct>>(); + p1.set(new java.util.ArrayList<SmallStruct>()); + for(int i = 0; i < 10; ++i) + { + p1.get().add(new SmallStruct()); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opSmallStructList(p1.get(), + (Ice.Optional<java.util.List<SmallStruct>> ret, Ice.Optional<java.util.List<SmallStruct>> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + CallbackBase cb = new CallbackBase(); + initial.begin_opSmallStructList(p1, + (Ice.Optional<java.util.List<SmallStruct>> ret, Ice.Optional<java.util.List<SmallStruct>> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<FixedStruct[]> p1 = new Ice.Optional<FixedStruct[]>(); + p1.set(new FixedStruct[10]); + for(int i = 0; i < p1.get().length; ++i) + { + p1.get()[i] = new FixedStruct(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opFixedStructSeq(p1.get(), + (Ice.Optional<FixedStruct[]> ret, Ice.Optional<FixedStruct[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opFixedStructSeq(p1, + (Ice.Optional<FixedStruct[]> ret, Ice.Optional<FixedStruct[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<java.util.List<FixedStruct>> p1 = new Ice.Optional<java.util.List<FixedStruct>>(); + p1.set(new java.util.ArrayList<FixedStruct>()); + for(int i = 0; i < 10; ++i) + { + p1.get().add(new FixedStruct()); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opFixedStructList(p1.get(), + (Ice.Optional<java.util.List<FixedStruct>> ret, Ice.Optional<java.util.List<FixedStruct>> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opFixedStructList(p1, + (Ice.Optional<java.util.List<FixedStruct>> ret, Ice.Optional<java.util.List<FixedStruct>> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<VarStruct[]> p1 = new Ice.Optional<VarStruct[]>(); + p1.set(new VarStruct[10]); + for(int i = 0; i < p1.get().length; ++i) + { + p1.get()[i] = new VarStruct(""); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opVarStructSeq(p1.get(), + (Ice.Optional<VarStruct[]> ret, Ice.Optional<VarStruct[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opVarStructSeq(p1, + (Ice.Optional<VarStruct[]> ret, Ice.Optional<VarStruct[]> p2) -> + cb.called(ret.isSet() && p2.isSet() && java.util.Arrays.equals(ret.get(), p2.get()) && + java.util.Arrays.equals(ret.get(), p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + if(supportsJavaSerializable) + { + Ice.Optional<SerializableClass> p1 = new Ice.Optional<SerializableClass>(new SerializableClass(58)); + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opSerializable(p1.get(), + (Ice.Optional<SerializableClass> ret, Ice.Optional<SerializableClass> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opSerializable(p1, + (Ice.Optional<SerializableClass> ret, Ice.Optional<SerializableClass> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<java.util.Map<Integer, Integer>> p1 = new Ice.Optional<java.util.Map<Integer, Integer>>(); + p1.set(new java.util.HashMap<Integer, Integer>()); + p1.get().put(1, 2); + p1.get().put(2, 3); + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opIntIntDict(p1.get(), + (Ice.Optional<java.util.Map<Integer, Integer>> ret, + Ice.Optional<java.util.Map<Integer, Integer>> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opIntIntDict(p1, + (Ice.Optional<java.util.Map<Integer, Integer>> ret, + Ice.Optional<java.util.Map<Integer, Integer>> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + { + Ice.Optional<java.util.Map<String, Integer>> p1 = new Ice.Optional<java.util.Map<String, Integer>>(); + p1.set(new java.util.HashMap<String, Integer>()); + p1.get().put("1", 1); + p1.get().put("2", 2); + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opStringIntDict(p1.get(), + (Ice.Optional<java.util.Map<String, Integer>> ret, + Ice.Optional<java.util.Map<String, Integer>> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + + { + final CallbackBase cb = new CallbackBase(); + initial.begin_opStringIntDict(p1, + (Ice.Optional<java.util.Map<String, Integer>> ret, + Ice.Optional<java.util.Map<String, Integer>> p2) -> + cb.called(ret.isSet() && p2.isSet() && ret.get().equals(p2.get()) && ret.get().equals(p1.get())), + (Ice.Exception ex) -> cb.called(false)); + cb.check(); + } + } + + out.println("ok"); + + return initial; + } +} diff --git a/java/test/src/main/java/test/Ice/optional/run.py b/java/test/src/main/java/test/Ice/optional/run.py new file mode 100755 index 00000000000..db4121d4784 --- /dev/null +++ b/java/test/src/main/java/test/Ice/optional/run.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("Running test with compact (default) format.") +TestUtil.clientServerTest() +print("Running test with sliced format.") +TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.SlicedFormat", additionalServerOptions="--Ice.Default.SlicedFormat") +print("Running test with AMD server.") +TestUtil.clientServerTest(server="test.Ice.optional.AMDServer") diff --git a/java/test/src/main/java/test/Ice/packagemd/AllTests.java b/java/test/src/main/java/test/Ice/packagemd/AllTests.java new file mode 100644 index 00000000000..564bbebbded --- /dev/null +++ b/java/test/src/main/java/test/Ice/packagemd/AllTests.java @@ -0,0 +1,196 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.packagemd; + +import java.io.PrintWriter; + +import test.Ice.packagemd.Test.InitialPrx; +import test.Ice.packagemd.Test.InitialPrxHelper; +import test.Ice.packagemd.Test1.C1; +import test.Ice.packagemd.Test1.C2; +import test.Ice.packagemd.Test1.E1; +import test.Ice.packagemd.Test1.E2; +import test.Ice.packagemd.Test1._notify; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static InitialPrx + allTests(Ice.Communicator communicator, PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + String ref = "initial:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + InitialPrx initial = InitialPrxHelper.checkedCast(base); + test(initial != null); + test(initial.equals(base)); + out.println("ok"); + + { + out.print("testing types without package... "); + out.flush(); + C1 c1 = initial.getTest1C2AsC1(); + test(c1 != null); + test(c1 instanceof C2); + C2 c2 = initial.getTest1C2AsC2(); + test(c2 != null); + try + { + initial.throwTest1E2AsE1(); + test(false); + } + catch(E1 ex) + { + test(ex instanceof E2); + } + try + { + initial.throwTest1E2AsE2(); + test(false); + } + catch(E2 ex) + { + // Expected + } + try + { + initial.throwTest1Notify(); + test(false); + } + catch(_notify ex) + { + // Expected + } + out.println("ok"); + } + + { + out.print("testing types with package... "); + out.flush(); + + { + try + { + initial.throwTest2E2AsE1(); + test(false); + } + catch(Ice.UnknownUserException ex) + { + // Expected + } + catch(Ice.MarshalException ex) + { + // Expected + } + catch(test.Ice.packagemd.testpkg.Test2.E1 ex) + { + test(false); + } + try + { + initial.throwTest2E2AsE2(); + test(false); + } + catch(Ice.UnknownUserException ex) + { + // Expected + } + catch(Ice.MarshalException ex) + { + // Expected + } + catch(test.Ice.packagemd.testpkg.Test2.E1 ex) + { + test(false); + } + } + + { + // + // Define Ice.Package.Test2=testpkg and try again. + // + communicator.getProperties().setProperty("Ice.Package.Test2", "test.Ice.packagemd.testpkg"); + test.Ice.packagemd.testpkg.Test2.C1 c1 = initial.getTest2C2AsC1(); + test(c1 != null); + test(c1 instanceof test.Ice.packagemd.testpkg.Test2.C2); + test.Ice.packagemd.testpkg.Test2.C2 c2 = initial.getTest2C2AsC2(); + test(c2 != null); + try + { + initial.throwTest2E2AsE1(); + test(false); + } + catch(test.Ice.packagemd.testpkg.Test2.E1 ex) + { + test(ex instanceof test.Ice.packagemd.testpkg.Test2.E2); + } + try + { + initial.throwTest2E2AsE2(); + test(false); + } + catch(test.Ice.packagemd.testpkg.Test2.E2 ex) + { + // Expected + } + } + + { + // + // Define Ice.Default.Package=testpkg and try again. We can't retrieve + // the Test2.* types again (with this communicator) because factories + // have already been cached for them, so now we use the Test3.* types. + // + communicator.getProperties().setProperty("Ice.Default.Package", "test.Ice.packagemd.testpkg"); + test.Ice.packagemd.testpkg.Test3.C1 c1 = initial.getTest3C2AsC1(); + test(c1 != null); + test(c1 instanceof test.Ice.packagemd.testpkg.Test3.C2); + test.Ice.packagemd.testpkg.Test3.C2 c2 = initial.getTest3C2AsC2(); + test(c2 != null); + try + { + initial.throwTest3E2AsE1(); + test(false); + } + catch(test.Ice.packagemd.testpkg.Test3.E1 ex) + { + test(ex instanceof test.Ice.packagemd.testpkg.Test3.E2); + } + try + { + initial.throwTest3E2AsE2(); + test(false); + } + catch(test.Ice.packagemd.testpkg.Test3.E2 ex) + { + // Expected + } + } + + out.println("ok"); + } + + return initial; + } +} diff --git a/java/test/src/main/java/test/Ice/packagemd/Client.java b/java/test/src/main/java/test/Ice/packagemd/Client.java new file mode 100644 index 00000000000..8081a790e76 --- /dev/null +++ b/java/test/src/main/java/test/Ice/packagemd/Client.java @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.packagemd; + +import test.Ice.packagemd.Test.InitialPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + InitialPrx initial = AllTests.allTests(communicator(), getWriter()); + initial.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.packagemd"); + initData.properties.setProperty("Ice.Package.Test1", "test.Ice.packagemd"); + return initData; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/packagemd/InitialI.java b/java/test/src/main/java/test/Ice/packagemd/InitialI.java new file mode 100644 index 00000000000..6d4d4fbaf96 --- /dev/null +++ b/java/test/src/main/java/test/Ice/packagemd/InitialI.java @@ -0,0 +1,143 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.packagemd; + +import test.Ice.packagemd.Test._InitialDisp; +import test.Ice.packagemd.Test1.C1; +import test.Ice.packagemd.Test1.C2; +import test.Ice.packagemd.Test1.E1; +import test.Ice.packagemd.Test1.E2; +import test.Ice.packagemd.Test1._notify; + +public final class InitialI extends _InitialDisp +{ + public Ice.Object + getTest1C2AsObject(Ice.Current __current) + { + return new C2(); + } + + @Override + public C1 + getTest1C2AsC1(Ice.Current __current) + { + return new C2(); + } + + @Override + public C2 + getTest1C2AsC2(Ice.Current __current) + { + return new C2(); + } + + @Override + public void + throwTest1E2AsE1(Ice.Current __current) + throws E1 + { + throw new E2(); + } + + @Override + public void + throwTest1E2AsE2(Ice.Current __current) + throws E2 + { + throw new E2(); + } + + @Override + public void + throwTest1Notify(Ice.Current __current) + throws _notify + { + throw new _notify(); + } + + public Ice.Object + getTest2C2AsObject(Ice.Current __current) + { + return new test.Ice.packagemd.testpkg.Test2.C2(); + } + + @Override + public test.Ice.packagemd.testpkg.Test2.C1 + getTest2C2AsC1(Ice.Current __current) + { + return new test.Ice.packagemd.testpkg.Test2.C2(); + } + + @Override + public test.Ice.packagemd.testpkg.Test2.C2 + getTest2C2AsC2(Ice.Current __current) + { + return new test.Ice.packagemd.testpkg.Test2.C2(); + } + + @Override + public void + throwTest2E2AsE1(Ice.Current __current) + throws test.Ice.packagemd.testpkg.Test2.E1 + { + throw new test.Ice.packagemd.testpkg.Test2.E2(); + } + + @Override + public void + throwTest2E2AsE2(Ice.Current __current) + throws test.Ice.packagemd.testpkg.Test2.E2 + { + throw new test.Ice.packagemd.testpkg.Test2.E2(); + } + + public Ice.Object + getTest3C2AsObject(Ice.Current __current) + { + return new test.Ice.packagemd.testpkg.Test3.C2(); + } + + @Override + public test.Ice.packagemd.testpkg.Test3.C1 + getTest3C2AsC1(Ice.Current __current) + { + return new test.Ice.packagemd.testpkg.Test3.C2(); + } + + @Override + public test.Ice.packagemd.testpkg.Test3.C2 + getTest3C2AsC2(Ice.Current __current) + { + return new test.Ice.packagemd.testpkg.Test3.C2(); + } + + @Override + public void + throwTest3E2AsE1(Ice.Current __current) + throws test.Ice.packagemd.testpkg.Test3.E1 + { + throw new test.Ice.packagemd.testpkg.Test3.E2(); + } + + @Override + public void + throwTest3E2AsE2(Ice.Current __current) + throws test.Ice.packagemd.testpkg.Test3.E2 + { + throw new test.Ice.packagemd.testpkg.Test3.E2(); + } + + @Override + public void + shutdown(Ice.Current __current) + { + __current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/packagemd/NoPackage.ice b/java/test/src/main/java/test/Ice/packagemd/NoPackage.ice new file mode 100644 index 00000000000..aa870ce5814 --- /dev/null +++ b/java/test/src/main/java/test/Ice/packagemd/NoPackage.ice @@ -0,0 +1,39 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.packagemd"]] +module Test1 +{ +class C1 +{ + int i; +}; + +class C2 extends C1 +{ + long l; +}; + +exception E1 +{ + int i; +}; + +exception E2 extends E1 +{ + long l; +}; + +exception notify /* Test keyword escape. */ +{ + int i; +}; +}; diff --git a/java/test/src/main/java/test/Ice/packagemd/Package.ice b/java/test/src/main/java/test/Ice/packagemd/Package.ice new file mode 100644 index 00000000000..e962c55aea7 --- /dev/null +++ b/java/test/src/main/java/test/Ice/packagemd/Package.ice @@ -0,0 +1,57 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.packagemd.testpkg"]] +module Test2 +{ +class C1 +{ + int i; +}; + +class C2 extends C1 +{ + long l; +}; + +exception E1 +{ + int i; +}; + +exception E2 extends E1 +{ + long l; +}; +}; + +module Test3 +{ +class C1 +{ + int i; +}; + +class C2 extends C1 +{ + long l; +}; + +exception E1 +{ + int i; +}; + +exception E2 extends E1 +{ + long l; +}; +}; diff --git a/java/test/src/main/java/test/Ice/packagemd/Server.java b/java/test/src/main/java/test/Ice/packagemd/Server.java new file mode 100644 index 00000000000..61bbb0dd2c6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/packagemd/Server.java @@ -0,0 +1,44 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.packagemd; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object object = new InitialI(); + adapter.add(object, communicator.stringToIdentity("initial")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.packagemd"); + initData.properties.setProperty("Ice.Package.Test1", "test.Ice.packagemd"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/packagemd/Test.ice b/java/test/src/main/java/test/Ice/packagemd/Test.ice new file mode 100644 index 00000000000..c90179c6b11 --- /dev/null +++ b/java/test/src/main/java/test/Ice/packagemd/Test.ice @@ -0,0 +1,40 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Package.ice> +#include <NoPackage.ice> + +[["java:package:test.Ice.packagemd"]] +module Test +{ + +interface Initial +{ + Test1::C1 getTest1C2AsC1(); + Test1::C2 getTest1C2AsC2(); + void throwTest1E2AsE1() throws Test1::E1; + void throwTest1E2AsE2() throws Test1::E2; + void throwTest1Notify() throws Test1::notify; + + Test2::C1 getTest2C2AsC1(); + Test2::C2 getTest2C2AsC2(); + void throwTest2E2AsE1() throws Test2::E1; + void throwTest2E2AsE2() throws Test2::E2; + + Test3::C1 getTest3C2AsC1(); + Test3::C2 getTest3C2AsC2(); + void throwTest3E2AsE1() throws Test3::E1; + void throwTest3E2AsE2() throws Test3::E2; + + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/packagemd/run.py b/java/test/src/main/java/test/Ice/packagemd/run.py new file mode 100755 index 00000000000..d5fe04787c9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/packagemd/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/plugin/Client.java b/java/test/src/main/java/test/Ice/plugin/Client.java new file mode 100644 index 00000000000..096f8d18a35 --- /dev/null +++ b/java/test/src/main/java/test/Ice/plugin/Client.java @@ -0,0 +1,201 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.plugin; + +import java.io.PrintWriter; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + PrintWriter printWriter = getWriter(); + printWriter.print("testing a simple plug-in... "); + printWriter.flush(); + try + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(); + initData.properties.setProperty("Ice.Plugin.Test", + "../../../lib/IceTestPlugins.jar:test.Ice.plugin.plugins.PluginFactory " + + "'C:\\Program Files\\' --DatabasePath 'C:\\Program Files\\Application\\db'"); + communicator = Ice.Util.initialize(args, initData); + communicator.destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + printWriter.println("ok"); + + printWriter.print("testing a simple plug-in that fails to initialize... "); + printWriter.flush(); + communicator = null; + try + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(); + initData.properties.setProperty("Ice.Plugin.Test", + "../../../lib/:test.Ice.plugin.plugins.PluginInitializeFailFactory"); + communicator = Ice.Util.initialize(args, initData); + test(false); + } + catch(RuntimeException ex) + { + test(ex.getMessage().equals("PluginInitializeFailException")); + } + test(communicator == null); + printWriter.println("ok"); + + printWriter.print("testing plug-in load order... "); + printWriter.flush(); + try + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(); + initData.properties.setProperty("Ice.Plugin.PluginOne", + "../../../lib/:test.Ice.plugin.plugins.PluginOneFactory"); + initData.properties.setProperty("Ice.Plugin.PluginTwo", + "../../../lib/:test.Ice.plugin.plugins.PluginTwoFactory"); + initData.properties.setProperty("Ice.Plugin.PluginThree", + "../../../lib/:test.Ice.plugin.plugins.PluginThreeFactory"); + initData.properties.setProperty("Ice.PluginLoadOrder", "PluginOne, PluginTwo"); // Exclude PluginThree + communicator = Ice.Util.initialize(args, initData); + communicator.destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + printWriter.println("ok"); + + printWriter.print("testing plug-in manager... "); + printWriter.flush(); + try + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(); + initData.properties.setProperty("Ice.Plugin.PluginOne", + "../../../lib/:test.Ice.plugin.plugins.PluginOneFactory"); + initData.properties.setProperty("Ice.Plugin.PluginTwo", + "../../../lib/:test.Ice.plugin.plugins.PluginTwoFactory"); + initData.properties.setProperty("Ice.Plugin.PluginThree", + "../../../lib/:test.Ice.plugin.plugins.PluginThreeFactory"); + initData.properties.setProperty("Ice.PluginLoadOrder", "PluginOne, PluginTwo"); + initData.properties.setProperty("Ice.InitPlugins", "0"); + communicator = Ice.Util.initialize(args, initData); + + Ice.PluginManager pm = communicator.getPluginManager(); + test(pm.getPlugin("PluginOne") != null); + test(pm.getPlugin("PluginTwo") != null); + test(pm.getPlugin("PluginThree") != null); + + MyPlugin p4 = new MyPlugin(); + pm.addPlugin("PluginFour", p4); + test(pm.getPlugin("PluginFour") != null); + + pm.initializePlugins(); + + test(p4.isInitialized()); + + communicator.destroy(); + + test(p4.isDestroyed()); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + test(false); + } + printWriter.println("ok"); + + printWriter.print("testing destroy when a plug-in fails to initialize... "); + printWriter.flush(); + communicator = null; + try + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(); + initData.properties.setProperty("Ice.Plugin.PluginOneFail", + "../../../lib/:test.Ice.plugin.plugins.PluginOneFailFactory"); + initData.properties.setProperty("Ice.Plugin.PluginTwoFail", + "../../../lib/:test.Ice.plugin.plugins.PluginTwoFailFactory"); + initData.properties.setProperty("Ice.Plugin.PluginThreeFail", + "../../../lib/:test.Ice.plugin.plugins.PluginThreeFailFactory"); + initData.properties.setProperty("Ice.PluginLoadOrder", "PluginOneFail, PluginTwoFail, PluginThreeFail"); + communicator = Ice.Util.initialize(args, initData); + } + catch(RuntimeException ex) + { + test(ex.getMessage().equals("PluginInitializeFailException")); + } + test(communicator == null); + printWriter.println("ok"); + + System.gc(); + System.runFinalization(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + return initData; + } + + private static void test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } + + static class MyPlugin implements Ice.Plugin + { + public boolean isInitialized() + { + return _initialized; + } + + public boolean isDestroyed() + { + return _destroyed; + } + + @Override + public void initialize() + { + _initialized = true; + } + + @Override + public void destroy() + { + _destroyed = true; + } + + private boolean _initialized = false; + private boolean _destroyed = false; + } +} diff --git a/java/test/src/main/java/test/Ice/plugin/plugins/BasePlugin.java b/java/test/src/main/java/test/Ice/plugin/plugins/BasePlugin.java new file mode 100644 index 00000000000..9ca8dbf3830 --- /dev/null +++ b/java/test/src/main/java/test/Ice/plugin/plugins/BasePlugin.java @@ -0,0 +1,41 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.plugin.plugins; + +public abstract class BasePlugin implements Ice.Plugin +{ + public BasePlugin(Ice.Communicator communicator) + { + _communicator = communicator; + } + + public boolean isInitialized() + { + return _initialized; + } + + public boolean isDestroyed() + { + return _destroyed; + } + + protected static void test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + protected Ice.Communicator _communicator; + protected boolean _initialized = false; + protected boolean _destroyed = false; + protected BasePlugin _other = null; +} diff --git a/java/test/src/main/java/test/Ice/plugin/plugins/BasePluginFail.java b/java/test/src/main/java/test/Ice/plugin/plugins/BasePluginFail.java new file mode 100644 index 00000000000..863214bf8ab --- /dev/null +++ b/java/test/src/main/java/test/Ice/plugin/plugins/BasePluginFail.java @@ -0,0 +1,45 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.plugin.plugins; + +public abstract class BasePluginFail implements Ice.Plugin +{ + public BasePluginFail(Ice.Communicator communicator) + { + _communicator = communicator; + _initialized = false; + _destroyed = false; + } + + public boolean isInitialized() + { + return _initialized; + } + + public boolean isDestroyed() + { + return _destroyed; + } + + protected static void test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + protected Ice.Communicator _communicator; + protected boolean _initialized; + protected boolean _destroyed; + protected BasePluginFail _one; + protected BasePluginFail _two; + protected BasePluginFail _three; +} diff --git a/java/test/src/main/java/test/Ice/plugin/plugins/PluginFactory.java b/java/test/src/main/java/test/Ice/plugin/plugins/PluginFactory.java new file mode 100644 index 00000000000..02e8ad76d7e --- /dev/null +++ b/java/test/src/main/java/test/Ice/plugin/plugins/PluginFactory.java @@ -0,0 +1,75 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.plugin.plugins; + +public class PluginFactory implements Ice.PluginFactory +{ + @Override + public Ice.Plugin create(Ice.Communicator communicator, String name, String[] args) + { + return new Plugin(args); + } + + static class Plugin implements Ice.Plugin + { + public Plugin(String[] args) + { + _args = args; + } + + @Override + public void initialize() + { + _initialized = true; + test(_args.length == 3); + test(_args[0].equals("C:\\Program Files\\")); + test(_args[1].equals("--DatabasePath")); + test(_args[2].equals("C:\\Program Files\\Application\\db")); + } + + @Override + public void destroy() + { + _destroyed = true; + } + + @Override + protected void finalize() throws Throwable + { + try + { + if(!_initialized) + { + System.out.println("test.Ice.plugin.plugins.Plugin not initialized"); + } + if(!_destroyed) + { + System.out.println("test.Ice.plugin.plugins.Plugin not destroyed"); + } + } + finally + { + super.finalize(); + } + } + + private static void test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private String[] _args; + private boolean _initialized = false; + private boolean _destroyed = false; + } +} diff --git a/java/test/src/main/java/test/Ice/plugin/plugins/PluginInitializeFailException.java b/java/test/src/main/java/test/Ice/plugin/plugins/PluginInitializeFailException.java new file mode 100644 index 00000000000..d5bc41ca5d0 --- /dev/null +++ b/java/test/src/main/java/test/Ice/plugin/plugins/PluginInitializeFailException.java @@ -0,0 +1,18 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.plugin.plugins; + +public class PluginInitializeFailException extends java.lang.RuntimeException +{ + public PluginInitializeFailException() + { + super("PluginInitializeFailException"); + } +} diff --git a/java/test/src/main/java/test/Ice/plugin/plugins/PluginInitializeFailFactory.java b/java/test/src/main/java/test/Ice/plugin/plugins/PluginInitializeFailFactory.java new file mode 100644 index 00000000000..a2f419ebecb --- /dev/null +++ b/java/test/src/main/java/test/Ice/plugin/plugins/PluginInitializeFailFactory.java @@ -0,0 +1,42 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.plugin.plugins; + +public class PluginInitializeFailFactory implements Ice.PluginFactory +{ + @Override + public Ice.Plugin create(Ice.Communicator communicator, String name, String[] args) + { + return new PluginInitializeFail(); + } + + static class PluginInitializeFail implements Ice.Plugin + { + @Override + public void initialize() + { + throw new PluginInitializeFailException(); + } + + @Override + public void destroy() + { + test(false); + } + + private static void test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + } +} diff --git a/java/test/src/main/java/test/Ice/plugin/plugins/PluginOneFactory.java b/java/test/src/main/java/test/Ice/plugin/plugins/PluginOneFactory.java new file mode 100644 index 00000000000..b4895874772 --- /dev/null +++ b/java/test/src/main/java/test/Ice/plugin/plugins/PluginOneFactory.java @@ -0,0 +1,42 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.plugin.plugins; + +public class PluginOneFactory implements Ice.PluginFactory +{ + @Override + public Ice.Plugin create(Ice.Communicator communicator, String name, String[] args) + { + return new PluginOne(communicator); + } + + static class PluginOne extends BasePlugin + { + public PluginOne(Ice.Communicator communicator) + { + super(communicator); + } + + @Override + public void initialize() + { + _other = (BasePlugin)_communicator.getPluginManager().getPlugin("PluginTwo"); + test(!_other.isInitialized()); + _initialized = true; + } + + @Override + public void destroy() + { + _destroyed = true; + test(_other.isDestroyed()); + } + } +} diff --git a/java/test/src/main/java/test/Ice/plugin/plugins/PluginOneFailFactory.java b/java/test/src/main/java/test/Ice/plugin/plugins/PluginOneFailFactory.java new file mode 100644 index 00000000000..5fd118de41e --- /dev/null +++ b/java/test/src/main/java/test/Ice/plugin/plugins/PluginOneFailFactory.java @@ -0,0 +1,68 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.plugin.plugins; + +public class PluginOneFailFactory implements Ice.PluginFactory +{ + @Override + public Ice.Plugin create(Ice.Communicator communicator, String name, String[] args) + { + return new PluginOneFail(communicator); + } + + static class PluginOneFail extends BasePluginFail + { + public PluginOneFail(Ice.Communicator communicator) + { + super(communicator); + } + + @Override + public void initialize() + { + _two = (BasePluginFail)_communicator.getPluginManager().getPlugin("PluginTwoFail"); + test(!_two.isInitialized()); + _three = (BasePluginFail)_communicator.getPluginManager().getPlugin("PluginThreeFail"); + test(!_three.isInitialized()); + _initialized = true; + } + + @Override + public void destroy() + { + test(_two.isDestroyed()); + // + // Not destroyed because initialize fails. + // + test(!_three.isDestroyed()); + _destroyed = true; + } + + @Override + protected void finalize() throws Throwable + { + try + { + if(!_initialized) + { + System.out.println(getClass().getName() + " not initialized"); + } + if(!_destroyed) + { + System.out.println(getClass().getName() + " not destroyed"); + } + } + finally + { + super.finalize(); + } + } + } +} diff --git a/java/test/src/main/java/test/Ice/plugin/plugins/PluginThreeFactory.java b/java/test/src/main/java/test/Ice/plugin/plugins/PluginThreeFactory.java new file mode 100644 index 00000000000..6fa993b414f --- /dev/null +++ b/java/test/src/main/java/test/Ice/plugin/plugins/PluginThreeFactory.java @@ -0,0 +1,42 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.plugin.plugins; + +public class PluginThreeFactory implements Ice.PluginFactory +{ + @Override + public Ice.Plugin create(Ice.Communicator communicator, String name, String[] args) + { + return new PluginThree(communicator); + } + + static class PluginThree extends BasePlugin + { + public PluginThree(Ice.Communicator communicator) + { + super(communicator); + } + + @Override + public void initialize() + { + _other = (BasePlugin)_communicator.getPluginManager().getPlugin("PluginTwo"); + test(_other.isInitialized()); + _initialized = true; + } + + @Override + public void destroy() + { + _destroyed = true; + test(!_other.isDestroyed()); + } + } +} diff --git a/java/test/src/main/java/test/Ice/plugin/plugins/PluginThreeFailFactory.java b/java/test/src/main/java/test/Ice/plugin/plugins/PluginThreeFailFactory.java new file mode 100644 index 00000000000..bc5e4cc0be1 --- /dev/null +++ b/java/test/src/main/java/test/Ice/plugin/plugins/PluginThreeFailFactory.java @@ -0,0 +1,59 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.plugin.plugins; + +public class PluginThreeFailFactory implements Ice.PluginFactory +{ + @Override + public Ice.Plugin create(Ice.Communicator communicator, String name, String[] args) + { + return new PluginThreeFail(communicator); + } + + public class PluginThreeFail extends BasePluginFail + { + public PluginThreeFail(Ice.Communicator communicator) + { + super(communicator); + } + + @Override + public void initialize() + { + throw new PluginInitializeFailException(); + } + + @Override + public void destroy() + { + test(false); + } + + @Override + protected void finalize() throws Throwable + { + try + { + if(_initialized) + { + System.out.println(getClass().getName() + " was initialized"); + } + if(_destroyed) + { + System.out.println(getClass().getName() + " was destroyed"); + } + } + finally + { + super.finalize(); + } + } + } +} diff --git a/java/test/src/main/java/test/Ice/plugin/plugins/PluginTwoFactory.java b/java/test/src/main/java/test/Ice/plugin/plugins/PluginTwoFactory.java new file mode 100644 index 00000000000..ecab2ba5222 --- /dev/null +++ b/java/test/src/main/java/test/Ice/plugin/plugins/PluginTwoFactory.java @@ -0,0 +1,42 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.plugin.plugins; + +public class PluginTwoFactory implements Ice.PluginFactory +{ + @Override + public Ice.Plugin create(Ice.Communicator communicator, String name, String[] args) + { + return new PluginTwo(communicator); + } + + static class PluginTwo extends BasePlugin + { + public PluginTwo(Ice.Communicator communicator) + { + super(communicator); + } + + @Override + public void initialize() + { + _other = (BasePlugin)_communicator.getPluginManager().getPlugin("PluginOne"); + test(_other.isInitialized()); + _initialized = true; + } + + @Override + public void destroy() + { + _destroyed = true; + test(!_other.isDestroyed()); + } + } +} diff --git a/java/test/src/main/java/test/Ice/plugin/plugins/PluginTwoFailFactory.java b/java/test/src/main/java/test/Ice/plugin/plugins/PluginTwoFailFactory.java new file mode 100644 index 00000000000..1b5ee8fb4af --- /dev/null +++ b/java/test/src/main/java/test/Ice/plugin/plugins/PluginTwoFailFactory.java @@ -0,0 +1,68 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.plugin.plugins; + +public class PluginTwoFailFactory implements Ice.PluginFactory +{ + @Override + public Ice.Plugin create(Ice.Communicator communicator, String name, String[] args) + { + return new PluginTwoFail(communicator); + } + + static class PluginTwoFail extends BasePluginFail + { + public PluginTwoFail(Ice.Communicator communicator) + { + super(communicator); + } + + @Override + public void initialize() + { + _one = (BasePluginFail)_communicator.getPluginManager().getPlugin("PluginOneFail"); + test(_one.isInitialized()); + _three = (BasePluginFail)_communicator.getPluginManager().getPlugin("PluginThreeFail"); + test(!_three.isInitialized()); + _initialized = true; + } + + @Override + public void destroy() + { + test(!_one.isDestroyed()); + // + // Not destroyed because initialize fails. + // + test(!_three.isDestroyed()); + _destroyed = true; + } + + @Override + protected void finalize() throws Throwable + { + try + { + if(!_initialized) + { + System.out.println(getClass().getName() + " not initialized"); + } + if(!_destroyed) + { + System.out.println(getClass().getName() + " not destroyed"); + } + } + finally + { + super.finalize(); + } + } + } +} diff --git a/java/test/src/main/java/test/Ice/plugin/run.py b/java/test/src/main/java/test/Ice/plugin/run.py new file mode 100755 index 00000000000..2b0bccd6c23 --- /dev/null +++ b/java/test/src/main/java/test/Ice/plugin/run.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +sys.stdout.write("starting test... ") +sys.stdout.flush() +clientProc = TestUtil.startClient("test.Ice.plugin.Client",startReader=False) +print("ok") +clientProc.startReader() + +clientProc.waitTestSuccess() + diff --git a/java/test/src/main/java/test/Ice/properties/Client.java b/java/test/src/main/java/test/Ice/properties/Client.java new file mode 100644 index 00000000000..4b2571e185c --- /dev/null +++ b/java/test/src/main/java/test/Ice/properties/Client.java @@ -0,0 +1,116 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.properties; + +public class Client extends test.Util.Application +{ + public static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + class PropertiesClient extends Ice.Application + { + @Override + public int + run(String[] args) + { + Ice.Properties properties = communicator().getProperties(); + test(properties.getProperty("Ice.Trace.Network").equals("1")); + test(properties.getProperty("Ice.Trace.Protocol").equals("1")); + test(properties.getProperty("Config.Path").equals(configPath)); + test(properties.getProperty("Ice.ProgramName").equals("PropertiesClient")); + test(appName().equals(properties.getProperty("Ice.ProgramName"))); + return 0; + }; + }; + + @Override + public int run(String[] args) + { + { + System.out.print("testing load properties from UTF-8 path... "); + Ice.Properties properties = Ice.Util.createProperties(); + properties.load(configPath); + test(properties.getProperty("Ice.Trace.Network").equals("1")); + test(properties.getProperty("Ice.Trace.Protocol").equals("1")); + test(properties.getProperty("Config.Path").equals(configPath)); + test(properties.getProperty("Ice.ProgramName").equals("PropertiesClient")); + System.out.println("ok"); + System.out.print("testing load properties from UTF-8 path using Ice::Application... "); + PropertiesClient c = new PropertiesClient(); + c.main("", args, configPath); + System.out.println("ok"); + } + { + // + // Try to load multiple config files. + // + System.out.print("testing using Ice.Config with multiple config files... "); + String[] args1 = new String[]{"--Ice.Config=config/config.1, config/config.2, config/config.3"}; + Ice.Properties properties = Ice.Util.createProperties(args1); + test(properties.getProperty("Config1").equals("Config1")); + test(properties.getProperty("Config2").equals("Config2")); + test(properties.getProperty("Config3").equals("Config3")); + System.out.println("ok"); + } + + { + System.out.print("testing configuration file escapes... "); + String[] args1 = new String[]{"--Ice.Config=config/escapes.cfg"}; + Ice.Properties properties = Ice.Util.createProperties(args1); + + String[] props = new String[]{"Foo\tBar", "3", + "Foo\\tBar", "4", + "Escape\\ Space", "2", + "Prop1", "1", + "Prop2", "2", + "Prop3", "3", + "My Prop1", "1", + "My Prop2", "2", + "My.Prop1", "a property", + "My.Prop2", "a property", + "My.Prop3", " a property ", + "My.Prop4", " a property ", + "My.Prop5", "a \\ property", + "foo=bar", "1", + "foo#bar", "2", + "foo bar", "3", + "A", "1", + "B", "2 3 4", + "C", "5=#6", + "AServer", "\\\\server\\dir", + "BServer", "\\server\\dir", + ""}; + + for(int i = 0; !props[i].isEmpty(); i += 2) + { + test(properties.getProperty(props[i]).equals(props[i + 1])); + } + System.out.println("ok"); + } + + return 0; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + System.gc(); + System.exit(status); + } + + private static String configPath = "./config/\u4E2D\u56FD_client.config"; +} diff --git a/java/test/src/main/java/test/Ice/properties/config/.gitignore b/java/test/src/main/java/test/Ice/properties/config/.gitignore new file mode 100644 index 00000000000..143c64680f3 --- /dev/null +++ b/java/test/src/main/java/test/Ice/properties/config/.gitignore @@ -0,0 +1 @@ +*.config diff --git a/java/test/src/main/java/test/Ice/properties/config/config.1 b/java/test/src/main/java/test/Ice/properties/config/config.1 new file mode 100644 index 00000000000..2a20653e4c5 --- /dev/null +++ b/java/test/src/main/java/test/Ice/properties/config/config.1 @@ -0,0 +1 @@ +Config1=Config1
\ No newline at end of file diff --git a/java/test/src/main/java/test/Ice/properties/config/config.2 b/java/test/src/main/java/test/Ice/properties/config/config.2 new file mode 100644 index 00000000000..be276df6602 --- /dev/null +++ b/java/test/src/main/java/test/Ice/properties/config/config.2 @@ -0,0 +1 @@ +Config2=Config2
\ No newline at end of file diff --git a/java/test/src/main/java/test/Ice/properties/config/config.3 b/java/test/src/main/java/test/Ice/properties/config/config.3 new file mode 100644 index 00000000000..55c1e1123f6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/properties/config/config.3 @@ -0,0 +1 @@ +Config3=Config3
\ No newline at end of file diff --git a/java/test/src/main/java/test/Ice/properties/config/escapes.cfg b/java/test/src/main/java/test/Ice/properties/config/escapes.cfg new file mode 100644 index 00000000000..f438d2b59c8 --- /dev/null +++ b/java/test/src/main/java/test/Ice/properties/config/escapes.cfg @@ -0,0 +1,35 @@ +Foo Bar=3 #tab +Foo\tBar=4 # embedded\t +Escape\\ Space=2 + +# +# From Ice manual: +# + +Prop1 = 1 # Key is "Prop1" + Prop2 = 2 # Key is "Prop2" +\ Prop3 \ = 3 # Key is "Prop3" +My Prop1 = 1 # Key is "My Prop1" +My\ Prop2 = 2 # Key is "My Prop2" + +My.Prop1 = a property # Value is "a property" +My.Prop2 = a property # Value is "a property" +My.Prop3 = \ \ a property\ \ # Value is " a property " +My.Prop4 = \ \ a \ \ property\ \ # Value is " a property " +My.Prop5 = a \\ property # Value is "a \ property" + +foo\=bar=1 # Name is "foo=bar", value is "1" +foo\#bar = 2 # Name is "foo#bar", value is "2" +foo bar =3 # Name is "foo bar", value is "3" + + +A=1 # Name is "A", value is "1" +B= 2 3 4 # Name is "B", value is "2 3 4" +C=5=\#6 # 7 # Name is "C", value is "5=#6" + +AServer=\\\\server\dir # Value is "\\server\dir" +BServer=\\server\\dir # Value is "\server\dir" + + + + diff --git a/java/test/src/main/java/test/Ice/properties/run.py b/java/test/src/main/java/test/Ice/properties/run.py new file mode 100755 index 00000000000..034d0abef9d --- /dev/null +++ b/java/test/src/main/java/test/Ice/properties/run.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +# +# Write config +# +if sys.version_info[0] == 2: + configPath = "./config/\xe4\xb8\xad\xe5\x9b\xbd_client.config" +else: + configPath = "./config/\u4e2d\u56fd_client.config" + +TestUtil.createConfig(configPath, + ["# Automatically generated by Ice test driver.", + "Ice.Trace.Protocol=1", + "Ice.Trace.Network=1", + "Ice.ProgramName=PropertiesClient", + "Config.Path=" + configPath], + "utf-8") + +sys.stdout.write("starting client... ") +sys.stdout.flush() +clientProc = TestUtil.startClient("test.Ice.properties.Client",startReader=False) +print("ok") +clientProc.startReader() +clientProc.waitTestSuccess() + +if os.path.exists(configPath): + os.remove(configPath) diff --git a/java/test/src/main/java/test/Ice/proxy/AMDMyDerivedClassI.java b/java/test/src/main/java/test/Ice/proxy/AMDMyDerivedClassI.java new file mode 100644 index 00000000000..5cf41db2870 --- /dev/null +++ b/java/test/src/main/java/test/Ice/proxy/AMDMyDerivedClassI.java @@ -0,0 +1,57 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.proxy; +import test.Ice.proxy.AMD.Test.AMD_MyClass_getContext; +import test.Ice.proxy.AMD.Test.AMD_MyClass_shutdown; +import test.Ice.proxy.AMD.Test.AMD_MyDerivedClass_echo; +import test.Ice.proxy.AMD.Test.MyDerivedClass; + +public final class AMDMyDerivedClassI extends MyDerivedClass +{ + public + AMDMyDerivedClassI() + { + } + + @Override + public void + echo_async(AMD_MyDerivedClass_echo cb, + Ice.ObjectPrx obj, + Ice.Current c) + { + cb.ice_response(obj); + } + + @Override + public void + shutdown_async(AMD_MyClass_shutdown cb, + Ice.Current c) + { + c.adapter.getCommunicator().shutdown(); + cb.ice_response(); + } + + @Override + public void + getContext_async(AMD_MyClass_getContext cb, Ice.Current current) + { + cb.ice_response(_ctx); + } + + @Override + public boolean + ice_isA(String s, Ice.Current current) + { + _ctx = current.ctx; + return super.ice_isA(s, current); + } + + private java.util.Map<String, String> _ctx; +} diff --git a/java/test/src/main/java/test/Ice/proxy/AMDServer.java b/java/test/src/main/java/test/Ice/proxy/AMDServer.java new file mode 100644 index 00000000000..3629cf905b0 --- /dev/null +++ b/java/test/src/main/java/test/Ice/proxy/AMDServer.java @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.proxy; + +public class AMDServer extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new AMDMyDerivedClassI(), communicator.stringToIdentity("test")); + adapter.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.proxy.AMD"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + return initData; + } + + public static void main(String[] args) + { + AMDServer app = new AMDServer(); + int result = app.main("AMDServer", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/proxy/AllTests.java b/java/test/src/main/java/test/Ice/proxy/AllTests.java new file mode 100644 index 00000000000..98e3c124fbb --- /dev/null +++ b/java/test/src/main/java/test/Ice/proxy/AllTests.java @@ -0,0 +1,981 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.proxy; +import java.io.PrintWriter; + +import test.Ice.proxy.Test.MyClassPrx; +import test.Ice.proxy.Test.MyClassPrxHelper; +import test.Ice.proxy.Test.MyDerivedClassPrx; +import test.Ice.proxy.Test.MyDerivedClassPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static MyClassPrx + allTests(Ice.Communicator communicator, PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + String ref = "test:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + + Ice.ObjectPrx b1 = communicator.stringToProxy("test"); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getAdapterId().length() == 0 && b1.ice_getFacet().length() == 0); + b1 = communicator.stringToProxy("test "); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().length() == 0); + b1 = communicator.stringToProxy(" test "); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().length() == 0); + b1 = communicator.stringToProxy(" test"); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().length() == 0); + b1 = communicator.stringToProxy("'test -f facet'"); + test(b1.ice_getIdentity().name.equals("test -f facet") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().length() == 0); + try + { + b1 = communicator.stringToProxy("\"test -f facet'"); + test(false); + } + catch(Ice.ProxyParseException ex) + { + } + b1 = communicator.stringToProxy("\"test -f facet\""); + test(b1.ice_getIdentity().name.equals("test -f facet") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().length() == 0); + b1 = communicator.stringToProxy("\"test -f facet@test\""); + test(b1.ice_getIdentity().name.equals("test -f facet@test") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().length() == 0); + b1 = communicator.stringToProxy("\"test -f facet@test @test\""); + test(b1.ice_getIdentity().name.equals("test -f facet@test @test") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().length() == 0); + try + { + b1 = communicator.stringToProxy("test test"); + test(false); + } + catch(Ice.ProxyParseException ex) + { + } + b1 = communicator.stringToProxy("test\\040test"); + test(b1.ice_getIdentity().name.equals("test test") && b1.ice_getIdentity().category.length() == 0); + try + { + b1 = communicator.stringToProxy("test\\777"); + test(false); + } + catch(Ice.IdentityParseException ex) + { + } + b1 = communicator.stringToProxy("test\\40test"); + test(b1.ice_getIdentity().name.equals("test test")); + + // Test some octal and hex corner cases. + b1 = communicator.stringToProxy("test\\4test"); + test(b1.ice_getIdentity().name.equals("test\4test")); + b1 = communicator.stringToProxy("test\\04test"); + test(b1.ice_getIdentity().name.equals("test\4test")); + b1 = communicator.stringToProxy("test\\004test"); + test(b1.ice_getIdentity().name.equals("test\4test")); + b1 = communicator.stringToProxy("test\\1114test"); + test(b1.ice_getIdentity().name.equals("test\1114test")); + + b1 = communicator.stringToProxy("test\\b\\f\\n\\r\\t\\'\\\"\\\\test"); + test(b1.ice_getIdentity().name.equals("test\b\f\n\r\t\'\"\\test") && + b1.ice_getIdentity().category.length() == 0); + + b1 = communicator.stringToProxy("category/test"); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.equals("category") && + b1.ice_getAdapterId().length() == 0); + + b1 = communicator.stringToProxy(""); + test(b1 == null); + b1 = communicator.stringToProxy("\"\""); + test(b1 == null); + try + { + b1 = communicator.stringToProxy("\"\" test"); // Invalid trailing characters. + test(false); + } + catch(Ice.ProxyParseException ex) + { + } + try + { + b1 = communicator.stringToProxy("test:"); // Missing endpoint. + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + + b1 = communicator.stringToProxy("test@adapter"); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getAdapterId().equals("adapter")); + try + { + b1 = communicator.stringToProxy("id@adapter test"); + test(false); + } + catch(Ice.ProxyParseException ex) + { + } + b1 = communicator.stringToProxy("category/test@adapter"); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.equals("category") && + b1.ice_getAdapterId().equals("adapter")); + b1 = communicator.stringToProxy("category/test@adapter:tcp"); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.equals("category") && + b1.ice_getAdapterId().equals("adapter:tcp")); + b1 = communicator.stringToProxy("'category 1/test'@adapter"); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.equals("category 1") && + b1.ice_getAdapterId().equals("adapter")); + b1 = communicator.stringToProxy("'category/test 1'@adapter"); + test(b1.ice_getIdentity().name.equals("test 1") && b1.ice_getIdentity().category.equals("category") && + b1.ice_getAdapterId().equals("adapter")); + b1 = communicator.stringToProxy("'category/test'@'adapter 1'"); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.equals("category") && + b1.ice_getAdapterId().equals("adapter 1")); + b1 = communicator.stringToProxy("\"category \\/test@foo/test\"@adapter"); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.equals("category /test@foo") && + b1.ice_getAdapterId().equals("adapter")); + b1 = communicator.stringToProxy("\"category \\/test@foo/test\"@\"adapter:tcp\""); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.equals("category /test@foo") && + b1.ice_getAdapterId().equals("adapter:tcp")); + + b1 = communicator.stringToProxy("id -f facet"); + test(b1.ice_getIdentity().name.equals("id") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().equals("facet")); + b1 = communicator.stringToProxy("id -f 'facet x'"); + test(b1.ice_getIdentity().name.equals("id") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().equals("facet x")); + b1 = communicator.stringToProxy("id -f \"facet x\""); + test(b1.ice_getIdentity().name.equals("id") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().equals("facet x")); + try + { + b1 = communicator.stringToProxy("id -f \"facet x"); + test(false); + } + catch(Ice.ProxyParseException ex) + { + } + try + { + b1 = communicator.stringToProxy("id -f \'facet x"); + test(false); + } + catch(Ice.ProxyParseException ex) + { + } + b1 = communicator.stringToProxy("test -f facet:tcp"); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().equals("facet") && b1.ice_getAdapterId().length() == 0); + b1 = communicator.stringToProxy("test -f \"facet:tcp\""); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().equals("facet:tcp") && b1.ice_getAdapterId().length() == 0); + b1 = communicator.stringToProxy("test -f facet@test"); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().equals("facet") && b1.ice_getAdapterId().equals("test")); + b1 = communicator.stringToProxy("test -f 'facet@test'"); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().equals("facet@test") && b1.ice_getAdapterId().length() == 0); + b1 = communicator.stringToProxy("test -f 'facet@test'@test"); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getFacet().equals("facet@test") && b1.ice_getAdapterId().equals("test")); + try + { + b1 = communicator.stringToProxy("test -f facet@test @test"); + test(false); + } + catch(Ice.ProxyParseException ex) + { + } + b1 = communicator.stringToProxy("test"); + test(b1.ice_isTwoway()); + b1 = communicator.stringToProxy("test -t"); + test(b1.ice_isTwoway()); + b1 = communicator.stringToProxy("test -o"); + test(b1.ice_isOneway()); + b1 = communicator.stringToProxy("test -O"); + test(b1.ice_isBatchOneway()); + b1 = communicator.stringToProxy("test -d"); + test(b1.ice_isDatagram()); + b1 = communicator.stringToProxy("test -D"); + test(b1.ice_isBatchDatagram()); + b1 = communicator.stringToProxy("test"); + test(!b1.ice_isSecure()); + b1 = communicator.stringToProxy("test -s"); + test(b1.ice_isSecure()); + + test(b1.ice_getEncodingVersion().equals(Ice.Util.currentEncoding())); + + b1 = communicator.stringToProxy("test -e 1.0"); + test(b1.ice_getEncodingVersion().major == 1 && b1.ice_getEncodingVersion().minor == 0); + + b1 = communicator.stringToProxy("test -e 6.5"); + test(b1.ice_getEncodingVersion().major == 6 && b1.ice_getEncodingVersion().minor == 5); + + b1 = communicator.stringToProxy("test -p 1.0 -e 1.0"); + test(b1.toString().equals("test -t -e 1.0")); + + b1 = communicator.stringToProxy("test -p 6.5 -e 1.0"); + test(b1.toString().equals("test -t -p 6.5 -e 1.0")); + + try + { + b1 = communicator.stringToProxy("test:tcp@adapterId"); + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + // This is an unknown endpoint warning, not a parse exception. + // + //try + //{ + // b1 = communicator.stringToProxy("test -f the:facet:tcp"); + // test(false); + //} + //catch(Ice.EndpointParseException ex) + //{ + //} + try + { + b1 = communicator.stringToProxy("test::tcp"); + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + + // + // Test for bug ICE-5543: escaped escapes in stringToIdentity + // + Ice.Identity id = new Ice.Identity("test", ",X2QNUAzSBcJ_e$AV;E\\"); + Ice.Identity id2 = communicator.stringToIdentity(communicator.identityToString(id)); + test(id.equals(id2)); + + id = new Ice.Identity("test", ",X2QNUAz\\SB\\/cJ_e$AV;E\\\\"); + id2 = communicator.stringToIdentity(communicator.identityToString(id)); + test(id.equals(id2)); + + out.println("ok"); + + out.print("testing propertyToProxy... "); + out.flush(); + Ice.Properties prop = communicator.getProperties(); + String propertyPrefix = "Foo.Proxy"; + prop.setProperty(propertyPrefix, "test:default -p 12010"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(b1.ice_getIdentity().name.equals("test") && b1.ice_getIdentity().category.length() == 0 && + b1.ice_getAdapterId().length() == 0 && b1.ice_getFacet().length() == 0); + + String property; + + property = propertyPrefix + ".Locator"; + test(b1.ice_getLocator() == null); + prop.setProperty(property, "locator:default -p 10000"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(b1.ice_getLocator() != null && b1.ice_getLocator().ice_getIdentity().name.equals("locator")); + prop.setProperty(property, ""); + + property = propertyPrefix + ".LocatorCacheTimeout"; + test(b1.ice_getLocatorCacheTimeout() == -1); + prop.setProperty(property, "1"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(b1.ice_getLocatorCacheTimeout() == 1); + prop.setProperty(property, ""); + + // Now retest with an indirect proxy. + prop.setProperty(propertyPrefix, "test"); + property = propertyPrefix + ".Locator"; + prop.setProperty(property, "locator:default -p 10000"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(b1.ice_getLocator() != null && b1.ice_getLocator().ice_getIdentity().name.equals("locator")); + prop.setProperty(property, ""); + + property = propertyPrefix + ".LocatorCacheTimeout"; + test(b1.ice_getLocatorCacheTimeout() == -1); + prop.setProperty(property, "1"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(b1.ice_getLocatorCacheTimeout() == 1); + prop.setProperty(property, ""); + + // This cannot be tested so easily because the property is cached + // on communicator initialization. + // + //prop.setProperty("Ice.Default.LocatorCacheTimeout", "60"); + //b1 = communicator.propertyToProxy(propertyPrefix); + //test(b1.ice_getLocatorCacheTimeout() == 60); + //prop.setProperty("Ice.Default.LocatorCacheTimeout", ""); + + prop.setProperty(propertyPrefix, "test:default -p 12010"); + + property = propertyPrefix + ".Router"; + test(b1.ice_getRouter() == null); + prop.setProperty(property, "router:default -p 10000"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(b1.ice_getRouter() != null && b1.ice_getRouter().ice_getIdentity().name.equals("router")); + prop.setProperty(property, ""); + + property = propertyPrefix + ".PreferSecure"; + test(!b1.ice_isPreferSecure()); + prop.setProperty(property, "1"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(b1.ice_isPreferSecure()); + prop.setProperty(property, ""); + + property = propertyPrefix + ".ConnectionCached"; + test(b1.ice_isConnectionCached()); + prop.setProperty(property, "0"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(!b1.ice_isConnectionCached()); + prop.setProperty(property, ""); + + property = propertyPrefix + ".InvocationTimeout"; + test(b1.ice_getInvocationTimeout() == -1); + prop.setProperty(property, "1000"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(b1.ice_getInvocationTimeout() == 1000); + prop.setProperty(property, ""); + + property = propertyPrefix + ".EndpointSelection"; + test(b1.ice_getEndpointSelection() == Ice.EndpointSelectionType.Random); + prop.setProperty(property, "Random"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(b1.ice_getEndpointSelection() == Ice.EndpointSelectionType.Random); + prop.setProperty(property, "Ordered"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(b1.ice_getEndpointSelection() == Ice.EndpointSelectionType.Ordered); + prop.setProperty(property, ""); + + property = propertyPrefix + ".CollocationOptimized"; + test(b1.ice_isCollocationOptimized()); + prop.setProperty(property, "0"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(!b1.ice_isCollocationOptimized()); + prop.setProperty(property, ""); + + property = propertyPrefix + ".Context.c1"; + test(b1.ice_getContext().get("c1") == null); + prop.setProperty(property, "TEST"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(b1.ice_getContext().get("c1").equals("TEST")); + + property = propertyPrefix + ".Context.c2"; + test(b1.ice_getContext().get("c2") == null); + prop.setProperty(property, "TEST"); + b1 = communicator.propertyToProxy(propertyPrefix); + test(b1.ice_getContext().get("c2").equals("TEST")); + + prop.setProperty(propertyPrefix + ".Context.c1", ""); + prop.setProperty(propertyPrefix + ".Context.c2", ""); + + out.println("ok"); + + out.print("testing proxyToProperty... "); + out.flush(); + + b1 = communicator.stringToProxy("test"); + b1 = b1.ice_collocationOptimized(true); + b1 = b1.ice_connectionCached(true); + b1 = b1.ice_preferSecure(false); + b1 = b1.ice_endpointSelection(Ice.EndpointSelectionType.Ordered); + b1 = b1.ice_locatorCacheTimeout(100); + b1 = b1.ice_invocationTimeout(1234); + b1 = b1.ice_encodingVersion(new Ice.EncodingVersion((byte)1, (byte)0)); + + Ice.ObjectPrx router = communicator.stringToProxy("router"); + router = router.ice_collocationOptimized(false); + router = router.ice_connectionCached(true); + router = router.ice_preferSecure(true); + router = router.ice_endpointSelection(Ice.EndpointSelectionType.Random); + router = router.ice_locatorCacheTimeout(200); + router = router.ice_invocationTimeout(1500); + + Ice.ObjectPrx locator = communicator.stringToProxy("locator"); + locator = locator.ice_collocationOptimized(true); + locator = locator.ice_connectionCached(false); + locator = locator.ice_preferSecure(true); + locator = locator.ice_endpointSelection(Ice.EndpointSelectionType.Random); + locator = locator.ice_locatorCacheTimeout(300); + locator = locator.ice_invocationTimeout(1500); + + locator = locator.ice_router(Ice.RouterPrxHelper.uncheckedCast(router)); + b1 = b1.ice_locator(Ice.LocatorPrxHelper.uncheckedCast(locator)); + + java.util.Map<String, String> proxyProps = communicator.proxyToProperty(b1, "Test"); + test(proxyProps.size() == 21); + + test(proxyProps.get("Test").equals("test -t -e 1.0")); + test(proxyProps.get("Test.CollocationOptimized").equals("1")); + test(proxyProps.get("Test.ConnectionCached").equals("1")); + test(proxyProps.get("Test.PreferSecure").equals("0")); + test(proxyProps.get("Test.EndpointSelection").equals("Ordered")); + test(proxyProps.get("Test.LocatorCacheTimeout").equals("100")); + test(proxyProps.get("Test.InvocationTimeout").equals("1234")); + + test(proxyProps.get("Test.Locator").equals( + "locator -t -e " + Ice.Util.encodingVersionToString(Ice.Util.currentEncoding()))); + // Locator collocation optimization is always disabled. + //test(proxyProps.get("Test.Locator.CollocationOptimized").equals("1")); + test(proxyProps.get("Test.Locator.ConnectionCached").equals("0")); + test(proxyProps.get("Test.Locator.PreferSecure").equals("1")); + test(proxyProps.get("Test.Locator.EndpointSelection").equals("Random")); + test(proxyProps.get("Test.Locator.LocatorCacheTimeout").equals("300")); + test(proxyProps.get("Test.Locator.InvocationTimeout").equals("1500")); + + test(proxyProps.get("Test.Locator.Router").equals( + "router -t -e " + Ice.Util.encodingVersionToString(Ice.Util.currentEncoding()))); + test(proxyProps.get("Test.Locator.Router.CollocationOptimized").equals("0")); + test(proxyProps.get("Test.Locator.Router.ConnectionCached").equals("1")); + test(proxyProps.get("Test.Locator.Router.PreferSecure").equals("1")); + test(proxyProps.get("Test.Locator.Router.EndpointSelection").equals("Random")); + test(proxyProps.get("Test.Locator.Router.LocatorCacheTimeout").equals("200")); + test(proxyProps.get("Test.Locator.Router.InvocationTimeout").equals("1500")); + + out.println("ok"); + + out.print("testing ice_getCommunicator... "); + out.flush(); + test(base.ice_getCommunicator() == communicator); + out.println("ok"); + + out.print("testing proxy methods... "); + out.flush(); + test(communicator.identityToString( + base.ice_identity(communicator.stringToIdentity("other")).ice_getIdentity()).equals("other")); + test(base.ice_facet("facet").ice_getFacet().equals("facet")); + test(base.ice_adapterId("id").ice_getAdapterId().equals("id")); + test(base.ice_twoway().ice_isTwoway()); + test(base.ice_oneway().ice_isOneway()); + test(base.ice_batchOneway().ice_isBatchOneway()); + test(base.ice_datagram().ice_isDatagram()); + test(base.ice_batchDatagram().ice_isBatchDatagram()); + test(base.ice_secure(true).ice_isSecure()); + test(!base.ice_secure(false).ice_isSecure()); + test(base.ice_collocationOptimized(true).ice_isCollocationOptimized()); + test(!base.ice_collocationOptimized(false).ice_isCollocationOptimized()); + test(base.ice_preferSecure(true).ice_isPreferSecure()); + test(!base.ice_preferSecure(false).ice_isPreferSecure()); + test(base.ice_encodingVersion(Ice.Util.Encoding_1_0).ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)); + test(base.ice_encodingVersion(Ice.Util.Encoding_1_1).ice_getEncodingVersion().equals(Ice.Util.Encoding_1_1)); + test(!base.ice_encodingVersion(Ice.Util.Encoding_1_0).ice_getEncodingVersion().equals(Ice.Util.Encoding_1_1)); + + try + { + base.ice_timeout(0); + test(false); + } + catch(IllegalArgumentException e) + { + } + + try + { + base.ice_timeout(-1); + } + catch(IllegalArgumentException e) + { + test(false); + } + + try + { + base.ice_timeout(-2); + test(false); + } + catch(IllegalArgumentException e) + { + } + + try + { + base.ice_invocationTimeout(0); + test(false); + } + catch(IllegalArgumentException e) + { + } + + try + { + base.ice_invocationTimeout(-1); + base.ice_invocationTimeout(-2); + } + catch(IllegalArgumentException e) + { + test(false); + } + + try + { + base.ice_invocationTimeout(-3); + test(false); + } + catch(IllegalArgumentException e) + { + } + + try + { + base.ice_locatorCacheTimeout(0); + } + catch(IllegalArgumentException e) + { + test(false); + } + + try + { + base.ice_locatorCacheTimeout(-1); + } + catch(IllegalArgumentException e) + { + test(false); + } + + try + { + base.ice_locatorCacheTimeout(-2); + test(false); + } + catch(IllegalArgumentException e) + { + } + + out.println("ok"); + + out.print("testing proxy comparison... "); + out.flush(); + + test(communicator.stringToProxy("foo").equals(communicator.stringToProxy("foo"))); + test(!communicator.stringToProxy("foo").equals(communicator.stringToProxy("foo2"))); + + Ice.ObjectPrx compObj = communicator.stringToProxy("foo"); + + test(compObj.ice_facet("facet").equals(compObj.ice_facet("facet"))); + test(!compObj.ice_facet("facet").equals(compObj.ice_facet("facet1"))); + + test(compObj.ice_oneway().equals(compObj.ice_oneway())); + test(!compObj.ice_oneway().equals(compObj.ice_twoway())); + + test(compObj.ice_secure(true).equals(compObj.ice_secure(true))); + test(!compObj.ice_secure(false).equals(compObj.ice_secure(true))); + + test(compObj.ice_collocationOptimized(true).equals(compObj.ice_collocationOptimized(true))); + test(!compObj.ice_collocationOptimized(false).equals(compObj.ice_collocationOptimized(true))); + + test(compObj.ice_connectionCached(true).equals(compObj.ice_connectionCached(true))); + test(!compObj.ice_connectionCached(false).equals(compObj.ice_connectionCached(true))); + + test(compObj.ice_endpointSelection(Ice.EndpointSelectionType.Random).equals( + compObj.ice_endpointSelection(Ice.EndpointSelectionType.Random))); + test(!compObj.ice_endpointSelection(Ice.EndpointSelectionType.Random).equals( + compObj.ice_endpointSelection(Ice.EndpointSelectionType.Ordered))); + + test(compObj.ice_connectionId("id2").equals(compObj.ice_connectionId("id2"))); + test(!compObj.ice_connectionId("id1").equals(compObj.ice_connectionId("id2"))); + + test(compObj.ice_connectionId("id1").ice_getConnectionId().equals("id1")); + test(compObj.ice_connectionId("id2").ice_getConnectionId().equals("id2")); + + test(compObj.ice_compress(true).equals(compObj.ice_compress(true))); + test(!compObj.ice_compress(false).equals(compObj.ice_compress(true))); + + test(compObj.ice_timeout(20).equals(compObj.ice_timeout(20))); + test(!compObj.ice_timeout(10).equals(compObj.ice_timeout(20))); + + Ice.LocatorPrx loc1 = Ice.LocatorPrxHelper.uncheckedCast(communicator.stringToProxy("loc1:default -p 10000")); + Ice.LocatorPrx loc2 = Ice.LocatorPrxHelper.uncheckedCast(communicator.stringToProxy("loc2:default -p 10000")); + test(compObj.ice_locator(null).equals(compObj.ice_locator(null))); + test(compObj.ice_locator(loc1).equals(compObj.ice_locator(loc1))); + test(!compObj.ice_locator(loc1).equals(compObj.ice_locator(null))); + test(!compObj.ice_locator(null).equals(compObj.ice_locator(loc2))); + test(!compObj.ice_locator(loc1).equals(compObj.ice_locator(loc2))); + + Ice.RouterPrx rtr1 = Ice.RouterPrxHelper.uncheckedCast(communicator.stringToProxy("rtr1:default -p 10000")); + Ice.RouterPrx rtr2 = Ice.RouterPrxHelper.uncheckedCast(communicator.stringToProxy("rtr2:default -p 10000")); + test(compObj.ice_router(null).equals(compObj.ice_router(null))); + test(compObj.ice_router(rtr1).equals(compObj.ice_router(rtr1))); + test(!compObj.ice_router(rtr1).equals(compObj.ice_router(null))); + test(!compObj.ice_router(null).equals(compObj.ice_router(rtr2))); + test(!compObj.ice_router(rtr1).equals(compObj.ice_router(rtr2))); + + java.util.Map<String, String> ctx1 = new java.util.HashMap<String, String>(); + ctx1.put("ctx1", "v1"); + java.util.Map<String, String> ctx2 = new java.util.HashMap<String, String>(); + ctx2.put("ctx2", "v2"); + test(compObj.ice_context(null).equals(compObj.ice_context(null))); + test(compObj.ice_context(ctx1).equals(compObj.ice_context(ctx1))); + test(!compObj.ice_context(ctx1).equals(compObj.ice_context(null))); + test(!compObj.ice_context(null).equals(compObj.ice_context(ctx2))); + test(!compObj.ice_context(ctx1).equals(compObj.ice_context(ctx2))); + + test(compObj.ice_preferSecure(true).equals(compObj.ice_preferSecure(true))); + test(!compObj.ice_preferSecure(true).equals(compObj.ice_preferSecure(false))); + + Ice.ObjectPrx compObj1 = communicator.stringToProxy("foo:tcp -h 127.0.0.1 -p 10000"); + Ice.ObjectPrx compObj2 = communicator.stringToProxy("foo:tcp -h 127.0.0.1 -p 10001"); + test(!compObj1.equals(compObj2)); + + compObj1 = communicator.stringToProxy("foo@MyAdapter1"); + compObj2 = communicator.stringToProxy("foo@MyAdapter2"); + test(!compObj1.equals(compObj2)); + + test(compObj1.ice_locatorCacheTimeout(20).equals(compObj1.ice_locatorCacheTimeout(20))); + test(!compObj1.ice_locatorCacheTimeout(10).equals(compObj1.ice_locatorCacheTimeout(20))); + + test(compObj1.ice_invocationTimeout(20).equals(compObj1.ice_invocationTimeout(20))); + test(!compObj1.ice_invocationTimeout(10).equals(compObj1.ice_invocationTimeout(20))); + + compObj1 = communicator.stringToProxy("foo:tcp -h 127.0.0.1 -p 1000"); + compObj2 = communicator.stringToProxy("foo@MyAdapter1"); + test(!compObj1.equals(compObj2)); + + Ice.Endpoint[] endpts1 = communicator.stringToProxy("foo:tcp -h 127.0.0.1 -p 10000").ice_getEndpoints(); + Ice.Endpoint[] endpts2 = communicator.stringToProxy("foo:tcp -h 127.0.0.1 -p 10001").ice_getEndpoints(); + test(!endpts1[0].equals(endpts2[0])); + test(endpts1[0].equals(communicator.stringToProxy("foo:tcp -h 127.0.0.1 -p 10000").ice_getEndpoints()[0])); + + test(compObj1.ice_encodingVersion(Ice.Util.Encoding_1_0).equals( + compObj1.ice_encodingVersion(Ice.Util.Encoding_1_0))); + test(!compObj1.ice_encodingVersion(Ice.Util.Encoding_1_0).equals( + compObj1.ice_encodingVersion(Ice.Util.Encoding_1_1))); + + // + // TODO: Ideally we should also test comparison of fixed proxies. + // + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + MyClassPrx cl = MyClassPrxHelper.checkedCast(base); + test(cl != null); + MyDerivedClassPrx derived = MyDerivedClassPrxHelper.checkedCast(cl); + test(derived != null); + test(cl.equals(base)); + test(derived.equals(base)); + test(cl.equals(derived)); + out.println("ok"); + + out.print("testing checked cast with context... "); + out.flush(); + + java.util.Map<String, String> c = cl.getContext(); + test(c == null || c.size() == 0); + + c = new java.util.HashMap<String, String>(); + c.put("one", "hello"); + c.put("two", "world"); + cl = MyClassPrxHelper.checkedCast(base, c); + java.util.Map<String, String> c2 = cl.getContext(); + test(c.equals(c2)); + out.println("ok"); + + out.print("testing encoding versioning... "); + out.flush(); + String ref20 = "test -e 2.0:default -p 12010"; + MyClassPrx cl20 = MyClassPrxHelper.uncheckedCast(communicator.stringToProxy(ref20)); + try + { + cl20.ice_collocationOptimized(false).ice_ping(); + test(false); + } + catch(Ice.UnsupportedEncodingException ex) + { + // Server 2.0 endpoint doesn't support 1.1 version. + } + + String ref10 = "test -e 1.0:default -p 12010"; + MyClassPrx cl10 = MyClassPrxHelper.uncheckedCast(communicator.stringToProxy(ref10)); + cl10.ice_ping(); + cl10.ice_encodingVersion(Ice.Util.Encoding_1_0).ice_ping(); + cl.ice_collocationOptimized(false).ice_encodingVersion(Ice.Util.Encoding_1_0).ice_ping(); + + // 1.3 isn't supported but since a 1.3 proxy supports 1.1, the + // call will use the 1.1 encoding + String ref13 = "test -e 1.3:default -p 12010"; + MyClassPrx cl13 = MyClassPrxHelper.uncheckedCast(communicator.stringToProxy(ref13)); + cl13.ice_ping(); + cl13.end_ice_ping(cl13.begin_ice_ping()); + + try + { + // Send request with bogus 1.2 encoding. + Ice.EncodingVersion version = new Ice.EncodingVersion((byte)1, (byte)2); + Ice.OutputStream os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.endEncapsulation(); + byte[] inEncaps = os.finished(); + inEncaps[4] = version.major; + inEncaps[5] = version.minor; + Ice.ByteSeqHolder outEncaps = new Ice.ByteSeqHolder(); + cl.ice_collocationOptimized(false).ice_invoke("ice_ping", Ice.OperationMode.Normal, inEncaps, outEncaps); + test(false); + } + catch(Ice.UnknownLocalException ex) + { + // The server thrown an UnsupportedEncodingException + test(ex.unknown.indexOf("UnsupportedEncodingException") > 0); + } + + try + { + // Send request with bogus 2.0 encoding. + Ice.EncodingVersion version = new Ice.EncodingVersion((byte)2, (byte)0); + Ice.OutputStream os = Ice.Util.createOutputStream(communicator); + os.startEncapsulation(); + os.endEncapsulation(); + byte[] inEncaps = os.finished(); + inEncaps[4] = version.major; + inEncaps[5] = version.minor; + Ice.ByteSeqHolder outEncaps = new Ice.ByteSeqHolder(); + cl.ice_collocationOptimized(false).ice_invoke("ice_ping", Ice.OperationMode.Normal, inEncaps, outEncaps); + test(false); + } + catch(Ice.UnknownLocalException ex) + { + // The server thrown an UnsupportedEncodingException + test(ex.unknown.indexOf("UnsupportedEncodingException") > 0); + } + + out.println("ok"); + + out.print("testing protocol versioning... "); + out.flush(); + ref20 = "test -p 2.0:default -p 12010"; + cl20 = MyClassPrxHelper.uncheckedCast(communicator.stringToProxy(ref20)); + try + { + cl20.ice_collocationOptimized(false).ice_ping(); + test(false); + } + catch(Ice.UnsupportedProtocolException ex) + { + // Server 2.0 proxy doesn't support 1.0 version. + } + + ref10 = "test -p 1.0:default -p 12010"; + cl10 = MyClassPrxHelper.uncheckedCast(communicator.stringToProxy(ref10)); + cl10.ice_ping(); + + // 1.3 isn't supported but since a 1.3 proxy supports 1.1, the + // call will use the 1.1 protocol + ref13 = "test -p 1.3:default -p 12010"; + cl13 = MyClassPrxHelper.uncheckedCast(communicator.stringToProxy(ref13)); + cl13.ice_ping(); + cl13.end_ice_ping(cl13.begin_ice_ping()); + out.println("ok"); + + out.print("testing opaque endpoints... "); + out.flush(); + + try + { + // Invalid -x option + communicator.stringToProxy("id:opaque -t 99 -v abc -x abc"); + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + + try + { + // Missing -t and -v + communicator.stringToProxy("id:opaque"); + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + + try + { + // Repeated -t + communicator.stringToProxy("id:opaque -t 1 -t 1 -v abc"); + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + + try + { + // Repeated -v + communicator.stringToProxy("id:opaque -t 1 -v abc -v abc"); + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + + try + { + // Missing -t + communicator.stringToProxy("id:opaque -v abc"); + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + + try + { + // Missing -v + communicator.stringToProxy("id:opaque -t 1"); + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + + try + { + // Missing arg for -t + communicator.stringToProxy("id:opaque -t -v abc"); + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + + try + { + // Missing arg for -v + communicator.stringToProxy("id:opaque -t 1 -v"); + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + + try + { + // Not a number for -t + communicator.stringToProxy("id:opaque -t x -v abc"); + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + + try + { + // < 0 for -t + communicator.stringToProxy("id:opaque -t -1 -v abc"); + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + + try + { + // Invalid char for -v + communicator.stringToProxy("id:opaque -t 99 -v x?c"); + test(false); + } + catch(Ice.EndpointParseException ex) + { + } + + // Legal TCP endpoint expressed as opaque endpoint + Ice.ObjectPrx p1 = communicator.stringToProxy("test -e 1.1:opaque -e 1.0 -t 1 -v CTEyNy4wLjAuMeouAAAQJwAAAA=="); + String pstr = communicator.proxyToString(p1); + test(pstr.equals("test -t -e 1.1:tcp -h 127.0.0.1 -p 12010 -t 10000")); + + // Opaque endpoint encoded with 1.1 encoding. + Ice.ObjectPrx p2 = communicator.stringToProxy("test:opaque -e 1.1 -t 1 -v CTEyNy4wLjAuMeouAAAQJwAAAA=="); + test(communicator.proxyToString(p2).equals("test -t -e 1.1:tcp -h 127.0.0.1 -p 12010 -t 10000")); + + if(communicator.getProperties().getPropertyAsInt("Ice.IPv6") == 0) + { + // Working? + boolean ssl = communicator.getProperties().getProperty("Ice.Default.Protocol").equals("ssl"); + boolean tcp = communicator.getProperties().getProperty("Ice.Default.Protocol").equals("tcp"); + if(tcp) + { + p1.ice_encodingVersion(Ice.Util.Encoding_1_0).ice_ping(); + } + + // Two legal TCP endpoints expressed as opaque endpoints + p1 = communicator.stringToProxy("test -e 1.0:opaque -e 1.0 -t 1 -v CTEyNy4wLjAuMeouAAAQJwAAAA==:opaque -e 1.0 -t 1 -v CTEyNy4wLjAuMusuAAAQJwAAAA=="); + pstr = communicator.proxyToString(p1); + test(pstr.equals("test -t -e 1.0:tcp -h 127.0.0.1 -p 12010 -t 10000:tcp -h 127.0.0.2 -p 12011 -t 10000")); + + // + // Test that an SSL endpoint and a nonsense endpoint get + // written back out as an opaque endpoint. + // + p1 = communicator.stringToProxy("test -e 1.0:opaque -e 1.0 -t 2 -v CTEyNy4wLjAuMREnAAD/////AA==:opaque -t 99 -e 1.0 -v abch"); + pstr = communicator.proxyToString(p1); + if(ssl) + { + test(pstr.equals("test -t -e 1.0:ssl -h 127.0.0.1 -p 10001 -t infinite:opaque -t 99 -e 1.0 -v abch")); + } + else if(tcp) + { + test(pstr.equals("test -t -e 1.0:opaque -t 2 -e 1.0 -v CTEyNy4wLjAuMREnAAD/////AA==:opaque -t 99 -e 1.0 -v abch")); + } + + // + // Try to invoke on the SSL endpoint to verify that we get a + // NoEndpointException (or ConnectFailedException when + // running with SSL). + // + if(ssl) + { + try + { + p1.ice_encodingVersion(Ice.Util.Encoding_1_0).ice_ping(); + test(false); + } + catch(Ice.ConnectFailedException ex) + { + } + } + + // + // Test that the proxy with an SSL endpoint and a nonsense + // endpoint (which the server doesn't understand either) can + // be sent over the wire and returned by the server without + // losing the opaque endpoints. + // + p2 = derived.echo(p1); + pstr = communicator.proxyToString(p2); + if(ssl) + { + test(pstr.equals("test -t -e 1.0:ssl -h 127.0.0.1 -p 10001 -t infinite:opaque -t 99 -e 1.0 -v abch")); + } + else if(tcp) + { + test(pstr.equals( + "test -t -e 1.0:opaque -t 2 -e 1.0 -v CTEyNy4wLjAuMREnAAD/////AA==:opaque -t 99 -e 1.0 -v abch")); + } + + } + out.println("ok"); + + return cl; + } +} diff --git a/java/test/src/main/java/test/Ice/proxy/Client.java b/java/test/src/main/java/test/Ice/proxy/Client.java new file mode 100644 index 00000000000..1ad397216c9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/proxy/Client.java @@ -0,0 +1,41 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.proxy; + +import test.Ice.proxy.Test.MyClassPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + MyClassPrx myClass = AllTests.allTests(communicator, getWriter()); + myClass.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.proxy"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/proxy/Collocated.java b/java/test/src/main/java/test/Ice/proxy/Collocated.java new file mode 100644 index 00000000000..26e71003545 --- /dev/null +++ b/java/test/src/main/java/test/Ice/proxy/Collocated.java @@ -0,0 +1,45 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.proxy; + +public class Collocated extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + communicator.getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new MyDerivedClassI(), communicator.stringToIdentity("test")); + adapter.activate(); + + AllTests.allTests(communicator, getWriter()); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.proxy"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + return initData; + } + + public static void main(String[] args) + { + Collocated app = new Collocated(); + int result = app.main(" extends", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/proxy/MyDerivedClassI.java b/java/test/src/main/java/test/Ice/proxy/MyDerivedClassI.java new file mode 100644 index 00000000000..35cc76794c0 --- /dev/null +++ b/java/test/src/main/java/test/Ice/proxy/MyDerivedClassI.java @@ -0,0 +1,50 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.proxy; +import test.Ice.proxy.Test.MyDerivedClass; + +public final class MyDerivedClassI extends MyDerivedClass +{ + public + MyDerivedClassI() + { + } + + @Override + public Ice.ObjectPrx + echo(Ice.ObjectPrx obj, Ice.Current c) + { + return obj; + } + + @Override + public void + shutdown(Ice.Current c) + { + c.adapter.getCommunicator().shutdown(); + } + + @Override + public java.util.Map<String, String> + getContext(Ice.Current current) + { + return _ctx; + } + + @Override + public boolean + ice_isA(String s, Ice.Current current) + { + _ctx = current.ctx; + return super.ice_isA(s, current); + } + + private java.util.Map<String, String> _ctx; +} diff --git a/java/test/src/main/java/test/Ice/proxy/Server.java b/java/test/src/main/java/test/Ice/proxy/Server.java new file mode 100644 index 00000000000..ae09627cfe5 --- /dev/null +++ b/java/test/src/main/java/test/Ice/proxy/Server.java @@ -0,0 +1,42 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.proxy; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new MyDerivedClassI(), communicator.stringToIdentity("test")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.proxy"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/proxy/Test.ice b/java/test/src/main/java/test/Ice/proxy/Test.ice new file mode 100644 index 00000000000..be3393a11a6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/proxy/Test.ice @@ -0,0 +1,30 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/Current.ice> + +[["java:package:test.Ice.proxy"]] +module Test +{ + +class MyClass +{ + void shutdown(); + + Ice::Context getContext(); +}; + +class MyDerivedClass extends MyClass +{ + Object* echo(Object* obj); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/proxy/TestAMD.ice b/java/test/src/main/java/test/Ice/proxy/TestAMD.ice new file mode 100644 index 00000000000..c95dd99bd9a --- /dev/null +++ b/java/test/src/main/java/test/Ice/proxy/TestAMD.ice @@ -0,0 +1,30 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include<Ice/Current.ice> + +[["java:package:test.Ice.proxy.AMD"]] +module Test +{ + +["amd"] class MyClass +{ + void shutdown(); + + Ice::Context getContext(); +}; + +["amd"] class MyDerivedClass extends MyClass +{ + Object* echo(Object* obj); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/proxy/run.py b/java/test/src/main/java/test/Ice/proxy/run.py new file mode 100755 index 00000000000..c013796c45b --- /dev/null +++ b/java/test/src/main/java/test/Ice/proxy/run.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("tests with regular server.") +TestUtil.clientServerTest() + +print("tests with AMD server.") +TestUtil.clientServerTest(server="test.Ice.proxy.AMDServer") + +print("tests with collocated server.") +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/retry/AllTests.java b/java/test/src/main/java/test/Ice/retry/AllTests.java new file mode 100644 index 00000000000..2552f593dd0 --- /dev/null +++ b/java/test/src/main/java/test/Ice/retry/AllTests.java @@ -0,0 +1,295 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.retry; + +import java.io.PrintWriter; + +import test.Ice.retry.Test.Callback_Retry_op; +import test.Ice.retry.Test.RetryPrx; +import test.Ice.retry.Test.RetryPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized void + check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void + called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static class AMIRegular extends Callback_Retry_op + { + @Override + public void + response() + { + callback.called(); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class AMIException extends Callback_Retry_op + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException ex) + { + test(ex instanceof Ice.ConnectionLostException || ex instanceof Ice.UnknownLocalException); + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + public static RetryPrx + allTests(Ice.Communicator communicator, PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + String ref = "retry:default -p 12010"; + Ice.ObjectPrx base1 = communicator.stringToProxy(ref); + test(base1 != null); + Ice.ObjectPrx base2 = communicator.stringToProxy(ref); + test(base2 != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + RetryPrx retry1 = RetryPrxHelper.checkedCast(base1); + test(retry1 != null); + test(retry1.equals(base1)); + RetryPrx retry2 = RetryPrxHelper.checkedCast(base2); + test(retry2 != null); + test(retry2.equals(base2)); + out.println("ok"); + + out.print("calling regular operation with first proxy... "); + out.flush(); + retry1.op(false); + out.println("ok"); + + Instrumentation.testInvocationCount(3); + + out.print("calling operation to kill connection with second proxy... "); + out.flush(); + try + { + retry2.op(true); + test(false); + } + catch(Ice.UnknownLocalException ex) + { + // Expected with collocation + } + catch(Ice.ConnectionLostException ex) + { + } + Instrumentation.testInvocationCount(1); + Instrumentation.testFailureCount(1); + Instrumentation.testRetryCount(0); + out.println("ok"); + + out.print("calling regular operation with first proxy again... "); + out.flush(); + retry1.op(false); + Instrumentation.testInvocationCount(1); + Instrumentation.testFailureCount(0); + Instrumentation.testRetryCount(0); + out.println("ok"); + + AMIRegular cb1 = new AMIRegular(); + AMIException cb2 = new AMIException(); + + out.print("calling regular AMI operation with first proxy... "); + retry1.begin_op(false, cb1); + cb1.check(); + Instrumentation.testInvocationCount(1); + Instrumentation.testFailureCount(0); + Instrumentation.testRetryCount(0); + out.println("ok"); + + out.print("calling AMI operation to kill connection with second proxy... "); + retry2.begin_op(true, cb2); + cb2.check(); + Instrumentation.testInvocationCount(1); + Instrumentation.testFailureCount(1); + Instrumentation.testRetryCount(0); + out.println("ok"); + + out.print("calling regular AMI operation with first proxy again... "); + retry1.begin_op(false, cb1); + cb1.check(); + Instrumentation.testInvocationCount(1); + Instrumentation.testFailureCount(0); + Instrumentation.testRetryCount(0); + out.println("ok"); + + out.print("testing idempotent operation... "); + test(retry1.opIdempotent(4) == 4); + Instrumentation.testInvocationCount(1); + Instrumentation.testFailureCount(0); + Instrumentation.testRetryCount(4); + test(retry1.end_opIdempotent(retry1.begin_opIdempotent(4)) == 4); + Instrumentation.testInvocationCount(1); + Instrumentation.testFailureCount(0); + Instrumentation.testRetryCount(4); + out.println("ok"); + + out.print("testing non-idempotent operation... "); + try + { + retry1.opNotIdempotent(); + test(false); + } + catch(Ice.LocalException ex) + { + } + Instrumentation.testInvocationCount(1); + Instrumentation.testFailureCount(1); + Instrumentation.testRetryCount(0); + try + { + retry1.end_opNotIdempotent(retry1.begin_opNotIdempotent()); + test(false); + } + catch(Ice.LocalException ex) + { + } + Instrumentation.testInvocationCount(1); + Instrumentation.testFailureCount(1); + Instrumentation.testRetryCount(0); + out.println("ok"); + + if(retry1.ice_getConnection() == null) + { + Instrumentation.testInvocationCount(1); + + out.print("testing system exception... "); + try + { + retry1.opSystemException(); + test(false); + } + catch(SystemFailure ex) + { + } + Instrumentation.testInvocationCount(1); + Instrumentation.testFailureCount(1); + Instrumentation.testRetryCount(0); + try + { + retry1.end_opSystemException(retry1.begin_opSystemException()); + test(false); + } + catch(SystemFailure ex) + { + } + Instrumentation.testInvocationCount(1); + Instrumentation.testFailureCount(1); + Instrumentation.testRetryCount(0); + out.println("ok"); + } + + out.print("testing invocation timeout and retries... "); + out.flush(); + try + { + // No more than 2 retries before timeout kicks-in + ((RetryPrx)retry1.ice_invocationTimeout(200)).opIdempotent(4); + test(false); + } + catch(Ice.InvocationTimeoutException ex) + { + Instrumentation.testRetryCount(2); + retry1.opIdempotent(-1); // Reset the counter + Instrumentation.testRetryCount(-1); + } + try + { + // No more than 2 retries before timeout kicks-in + RetryPrx prx = (RetryPrx)retry1.ice_invocationTimeout(200); + prx.end_opIdempotent(prx.begin_opIdempotent(4)); + test(false); + } + catch(Ice.InvocationTimeoutException ex) + { + Instrumentation.testRetryCount(2); + retry1.opIdempotent(-1); // Reset the counter + Instrumentation.testRetryCount(-1); + } + out.println("ok"); + + return retry1; + } +} diff --git a/java/test/src/main/java/test/Ice/retry/Client.java b/java/test/src/main/java/test/Ice/retry/Client.java new file mode 100644 index 00000000000..f26a2b43eca --- /dev/null +++ b/java/test/src/main/java/test/Ice/retry/Client.java @@ -0,0 +1,51 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.retry; + +import test.Ice.retry.Test.RetryPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + RetryPrx retry = AllTests.allTests(communicator, getWriter()); + retry.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.observer = Instrumentation.getObserver(); + + initData.properties.setProperty("Ice.Package.Test", "test.Ice.retry"); + + initData.properties.setProperty("Ice.RetryIntervals", "0 1 300 1"); + + // + // We don't want connection warnings because of the timeout + // + initData.properties.setProperty("Ice.Warn.Connections", "0"); + + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/retry/Collocated.java b/java/test/src/main/java/test/Ice/retry/Collocated.java new file mode 100644 index 00000000000..9a49ec6f991 --- /dev/null +++ b/java/test/src/main/java/test/Ice/retry/Collocated.java @@ -0,0 +1,59 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.retry; + +import test.Ice.retry.Test.RetryPrx; + +public class Collocated extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new RetryI(), communicator.stringToIdentity("retry")); + //adapter.activate(); + + RetryPrx retry = AllTests.allTests(communicator, getWriter()); + retry.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.observer = Instrumentation.getObserver(); + + initData.properties.setProperty("Ice.Package.Test", "test.Ice.retry"); + + initData.properties.setProperty("Ice.RetryIntervals", "0 1 300 1"); + + // + // We don't want connection warnings because of the timeout + // + initData.properties.setProperty("Ice.Warn.Connections", "0"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + + return initData; + } + + public static void main(String[] args) + { + Collocated app = new Collocated(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} + diff --git a/java/test/src/main/java/test/Ice/retry/Instrumentation.java b/java/test/src/main/java/test/Ice/retry/Instrumentation.java new file mode 100644 index 00000000000..609a8225ef2 --- /dev/null +++ b/java/test/src/main/java/test/Ice/retry/Instrumentation.java @@ -0,0 +1,205 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.retry; + +public class Instrumentation +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static class InvocationObserverI implements Ice.Instrumentation.InvocationObserver + { + @Override + public void + attach() + { + } + + @Override + public void + detach() + { + synchronized(Instrumentation.class) + { + ++nInvocation.value; + } + } + + @Override + public void + failed(String msg) + { + synchronized(Instrumentation.class) + { + ++nFailure.value; + } + } + + @Override + public void + retried() + { + synchronized(Instrumentation.class) + { + ++nRetry.value; + } + } + + @Override + public void + userException() + { + } + + @Override + public Ice.Instrumentation.RemoteObserver + getRemoteObserver(Ice.ConnectionInfo ci, Ice.Endpoint ei, int i, int j) + { + return null; + } + + @Override + public Ice.Instrumentation.CollocatedObserver + getCollocatedObserver(Ice.ObjectAdapter adapter, int i , int j) + { + return null; + } + + }; + static private Ice.Instrumentation.InvocationObserver invocationObserver = new InvocationObserverI(); + + static class CommunicatorObserverI implements Ice.Instrumentation.CommunicatorObserver + { + @Override + public Ice.Instrumentation.Observer + getConnectionEstablishmentObserver(Ice.Endpoint e, String s) + { + return null; + } + + @Override + public Ice.Instrumentation.Observer + getEndpointLookupObserver(Ice.Endpoint e) + { + return null; + } + + @Override + public Ice.Instrumentation.ConnectionObserver + getConnectionObserver(Ice.ConnectionInfo ci, + Ice.Endpoint ei, + Ice.Instrumentation.ConnectionState s, + Ice.Instrumentation.ConnectionObserver o) + { + return null; + } + + @Override + public Ice.Instrumentation.ThreadObserver + getThreadObserver(String p, + String n, + Ice.Instrumentation.ThreadState s, + Ice.Instrumentation.ThreadObserver o) + { + return null; + } + + @Override + public Ice.Instrumentation.InvocationObserver + getInvocationObserver(Ice.ObjectPrx p, String o, java.util.Map<String, String> c) + { + return invocationObserver; + } + + @Override + public Ice.Instrumentation.DispatchObserver + getDispatchObserver(Ice.Current c, int i) + { + return null; + } + + @Override + public void + setObserverUpdater(Ice.Instrumentation.ObserverUpdater u) + { + } + }; + + static private Ice.Instrumentation.CommunicatorObserver communicatorObserver = new CommunicatorObserverI(); + + static public Ice.Instrumentation.CommunicatorObserver + getObserver() + { + return communicatorObserver; + } + + static private void + testEqual(Ice.IntHolder value, int expected) + { + if(expected < 0) + { + value.value = 0; + return; + } + + int retry = 0; + while(++retry < 100) + { + synchronized(Instrumentation.class) + { + if(value.value == expected) + { + break; + } + } + try + { + Thread.sleep(10); + } + catch(java.lang.InterruptedException ex) + { + } + } + if(value.value != expected) + { + System.err.println("value = " + value.value + ", expected = " + expected); + test(false); + } + value.value = 0; + } + + static public void + testRetryCount(int expected) + { + testEqual(nRetry, expected); + } + + static public void + testFailureCount(int expected) + { + testEqual(nFailure, expected); + } + + static public void + testInvocationCount(int expected) + { + testEqual(nInvocation, expected); + } + + static private Ice.IntHolder nRetry = new Ice.IntHolder(0); + static private Ice.IntHolder nFailure = new Ice.IntHolder(0); + static private Ice.IntHolder nInvocation = new Ice.IntHolder(0); +}; diff --git a/java/test/src/main/java/test/Ice/retry/RetryI.java b/java/test/src/main/java/test/Ice/retry/RetryI.java new file mode 100644 index 00000000000..f2afcc881dd --- /dev/null +++ b/java/test/src/main/java/test/Ice/retry/RetryI.java @@ -0,0 +1,95 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.retry; +import test.Ice.retry.Test._RetryDisp; + +public final class RetryI extends _RetryDisp +{ + public + RetryI() + { + } + + @Override + public void + op(boolean kill, Ice.Current current) + { + if(kill) + { + if(current.con != null) + { + current.con.close(true); + } + else + { + throw new Ice.ConnectionLostException(); + } + } + } + + @Override + public int + opIdempotent(int nRetry, Ice.Current current) + { + if(nRetry < 0) + { + _counter = 0; + return 0; + } + + if(nRetry > _counter) + { + ++_counter; + if(current.con != null) + { + current.con.close(true); + } + else + { + throw new Ice.ConnectionLostException(); + } + return 0; + } + + int counter = _counter; + _counter = 0; + return counter; + } + + @Override + public void + opNotIdempotent(Ice.Current current) + { + if(current.con != null) + { + current.con.close(true); + } + else + { + throw new Ice.ConnectionLostException(); + } + } + + @Override + public void + opSystemException(Ice.Current c) + { + throw new SystemFailure(); + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + private int _counter; +} diff --git a/java/test/src/main/java/test/Ice/retry/Server.java b/java/test/src/main/java/test/Ice/retry/Server.java new file mode 100644 index 00000000000..678839b36a5 --- /dev/null +++ b/java/test/src/main/java/test/Ice/retry/Server.java @@ -0,0 +1,41 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.retry; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new RetryI(), communicator.stringToIdentity("retry")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.retry"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/retry/SystemFailure.java b/java/test/src/main/java/test/Ice/retry/SystemFailure.java new file mode 100644 index 00000000000..fc03b8e6f82 --- /dev/null +++ b/java/test/src/main/java/test/Ice/retry/SystemFailure.java @@ -0,0 +1,20 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.retry; + +class SystemFailure extends Ice.SystemException +{ + @Override + public String + ice_name() + { + return "SystemFailure"; + } +}; diff --git a/java/test/src/main/java/test/Ice/retry/Test.ice b/java/test/src/main/java/test/Ice/retry/Test.ice new file mode 100644 index 00000000000..0e1be095f41 --- /dev/null +++ b/java/test/src/main/java/test/Ice/retry/Test.ice @@ -0,0 +1,27 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.retry"]] +module Test +{ + +interface Retry +{ + void op(bool kill); + + idempotent int opIdempotent(int c); + void opNotIdempotent(); + void opSystemException(); + + idempotent void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/retry/run.py b/java/test/src/main/java/test/Ice/retry/run.py new file mode 100755 index 00000000000..6444a527f9a --- /dev/null +++ b/java/test/src/main/java/test/Ice/retry/run.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("tests with regular server.") +TestUtil.clientServerTest() +print("tests with collocated server.") +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/seqMapping/AMDMyClassI.java b/java/test/src/main/java/test/Ice/seqMapping/AMDMyClassI.java new file mode 100644 index 00000000000..49ee338fc1d --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/AMDMyClassI.java @@ -0,0 +1,44 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping; + +import test.Ice.seqMapping.AMD.Test.*; +import test.Ice.seqMapping.Serialize.*; + +public final class AMDMyClassI extends MyClass +{ + @Override + public void + shutdown_async(AMD_MyClass_shutdown cb, Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + cb.ice_response(); + } + + @Override + public void + opSerialSmallJava_async(AMD_MyClass_opSerialSmallJava cb, Small i, Ice.Current current) + { + cb.ice_response(i, i); + } + + @Override + public void + opSerialLargeJava_async(AMD_MyClass_opSerialLargeJava cb, Large i, Ice.Current current) + { + cb.ice_response(i, i); + } + + @Override + public void opSerialStructJava_async(AMD_MyClass_opSerialStructJava cb, Struct i, Ice.Current current) + { + cb.ice_response(i, i); + } +} diff --git a/java/test/src/main/java/test/Ice/seqMapping/AMDServer.java b/java/test/src/main/java/test/Ice/seqMapping/AMDServer.java new file mode 100644 index 00000000000..5c3e9bc5fc0 --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/AMDServer.java @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping; + +public class AMDServer extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.add(new AMDMyClassI(), communicator().stringToIdentity("test")); + adapter.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.seqMapping.AMD"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + return initData; + } + + public static void main(String[] args) + { + AMDServer c = new AMDServer(); + int status = c.main("AMDServer", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/seqMapping/AllTests.java b/java/test/src/main/java/test/Ice/seqMapping/AllTests.java new file mode 100644 index 00000000000..546de84ae74 --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/AllTests.java @@ -0,0 +1,40 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping; + +import java.io.PrintWriter; + +import test.Ice.seqMapping.Test.*; + +public class AllTests +{ + public static MyClassPrx + allTests(Ice.Communicator communicator, boolean collocated, PrintWriter out) + { + String ref = "test:default -p 12010"; + Ice.ObjectPrx baseProxy = communicator.stringToProxy(ref); + MyClassPrx cl = MyClassPrxHelper.checkedCast(baseProxy); + + out.print("testing twoway operations... "); + out.flush(); + Twoways.twoways(cl); + out.println("ok"); + + if(!collocated) + { + out.print("testing twoway operations with AMI... "); + out.flush(); + TwowaysAMI.twowaysAMI(cl); + out.println("ok"); + } + + return cl; + } +} diff --git a/java/test/src/main/java/test/Ice/seqMapping/Client.java b/java/test/src/main/java/test/Ice/seqMapping/Client.java new file mode 100644 index 00000000000..2124aefda4d --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/Client.java @@ -0,0 +1,49 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping; + +import test.Ice.seqMapping.Test.*; + +public class Client extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + java.io.PrintWriter out = getWriter(); + + MyClassPrx myClass = AllTests.allTests(communicator(), false, out); + + out.print("shutting down server... "); + out.flush(); + myClass.shutdown(); + out.println("ok"); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.seqMapping"); + return initData; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/seqMapping/Collocated.java b/java/test/src/main/java/test/Ice/seqMapping/Collocated.java new file mode 100644 index 00000000000..bafcdce6b20 --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/Collocated.java @@ -0,0 +1,46 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping; + +public class Collocated extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + java.io.PrintWriter out = getWriter(); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.add(new MyClassI(), communicator().stringToIdentity("test")); + adapter.activate(); + + AllTests.allTests(communicator(), true, out); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.seqMapping"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + return initData; + } + + public static void main(String[] args) + { + Collocated c = new Collocated(); + int status = c.main("Collocated", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/seqMapping/MyClassI.java b/java/test/src/main/java/test/Ice/seqMapping/MyClassI.java new file mode 100644 index 00000000000..f0a2505be21 --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/MyClassI.java @@ -0,0 +1,44 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping; + +import test.Ice.seqMapping.Test.*; +import test.Ice.seqMapping.Serialize.*; + +public final class MyClassI extends MyClass +{ + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + @Override + public Small opSerialSmallJava(Small i, Ice.Holder<Small> o, Ice.Current current) + { + o.value = i; + return i; + } + + @Override + public Large opSerialLargeJava(Large i, Ice.Holder<Large> o, Ice.Current current) + { + o.value = i; + return i; + } + + @Override + public Struct opSerialStructJava(Struct i, Ice.Holder<Struct> o, Ice.Current current) + { + o.value = i; + return i; + } +} diff --git a/java/test/src/main/java/test/Ice/seqMapping/Serialize/Large.java b/java/test/src/main/java/test/Ice/seqMapping/Serialize/Large.java new file mode 100644 index 00000000000..3b6e3edd327 --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/Serialize/Large.java @@ -0,0 +1,24 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping.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/src/main/java/test/Ice/seqMapping/Serialize/Small.java b/java/test/src/main/java/test/Ice/seqMapping/Serialize/Small.java new file mode 100644 index 00000000000..3503c5415b5 --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/Serialize/Small.java @@ -0,0 +1,15 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping.Serialize; + +public class Small implements java.io.Serializable // Fewer than 254 bytes when serialized. +{ + public int i; +} diff --git a/java/test/src/main/java/test/Ice/seqMapping/Serialize/SmallHolder.java b/java/test/src/main/java/test/Ice/seqMapping/Serialize/SmallHolder.java new file mode 100644 index 00000000000..f2f01a4805c --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/Serialize/SmallHolder.java @@ -0,0 +1,15 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping.Serialize; + +public class SmallHolder +{ + public Small value; +} diff --git a/java/test/src/main/java/test/Ice/seqMapping/Serialize/Struct.java b/java/test/src/main/java/test/Ice/seqMapping/Serialize/Struct.java new file mode 100644 index 00000000000..30c80c752e6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/Serialize/Struct.java @@ -0,0 +1,18 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping.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/src/main/java/test/Ice/seqMapping/Serialize/StructHolder.java b/java/test/src/main/java/test/Ice/seqMapping/Serialize/StructHolder.java new file mode 100644 index 00000000000..9768382d0e7 --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/Serialize/StructHolder.java @@ -0,0 +1,15 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping.Serialize; + +public class StructHolder +{ + public Struct value; +} diff --git a/java/test/src/main/java/test/Ice/seqMapping/Server.java b/java/test/src/main/java/test/Ice/seqMapping/Server.java new file mode 100644 index 00000000000..eea5e6536dd --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/Server.java @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping; + +public class Server extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.add(new MyClassI(), communicator().stringToIdentity("test")); + adapter.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.seqMapping"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/seqMapping/Test.ice b/java/test/src/main/java/test/Ice/seqMapping/Test.ice new file mode 100644 index 00000000000..15dfffb884b --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/Test.ice @@ -0,0 +1,54 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.seqMapping"]] +module Test +{ + +["java:serializable:test.Ice.seqMapping.Serialize.Small"] sequence<byte> SerialSmall; +["java:serializable:test.Ice.seqMapping.Serialize.Large"] sequence<byte> SerialLarge; +["java:serializable:test.Ice.seqMapping.Serialize.Struct"] sequence<byte> SerialStruct; + +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; +}; + +}; diff --git a/java/test/src/main/java/test/Ice/seqMapping/TestAMD.ice b/java/test/src/main/java/test/Ice/seqMapping/TestAMD.ice new file mode 100644 index 00000000000..28b3aa3c434 --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/TestAMD.ice @@ -0,0 +1,54 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.seqMapping.AMD"]] +module Test +{ + +["java:serializable:test.Ice.seqMapping.Serialize.Small"] sequence<byte> SerialSmall; +["java:serializable:test.Ice.seqMapping.Serialize.Large"] sequence<byte> SerialLarge; +["java:serializable:test.Ice.seqMapping.Serialize.Struct"] sequence<byte> SerialStruct; + +["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; +}; + +}; diff --git a/java/test/src/main/java/test/Ice/seqMapping/Twoways.java b/java/test/src/main/java/test/Ice/seqMapping/Twoways.java new file mode 100644 index 00000000000..a6f50f8a327 --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/Twoways.java @@ -0,0 +1,137 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping; + +import test.Ice.seqMapping.Test.*; +import test.Ice.seqMapping.Serialize.*; + +class Twoways +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + static void + twoways(MyClassPrx p) + { + { + Small i = null; + Ice.Holder<Small> o = new Ice.Holder<Small>(); + Small r; + + r = p.opSerialSmallJava(i, o); + + test(o.value == null); + test(r == null); + } + + { + Small i = new Small(); + i.i = 99; + Ice.Holder<Small> o = new Ice.Holder<Small>(); + 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. + } + } + + { + Large i = new 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<Large> o = new Ice.Holder<Large>(); + 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. + } + } + + { + Struct i = new Struct(); + i.o = null; + i.o2 = i; + i.s = null; + i.s2 = "Hello"; + Ice.Holder<Struct> o = new Ice.Holder<Struct>(); + Struct r; + + try + { + r = p.opSerialStructJava(i, o); + + test(o.value.o == null); + test(o.value.o2 != null); + test(((Struct)(o.value.o2)).o == null); + test(((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(((Struct)(r.o2)).o == null); + test(((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/src/main/java/test/Ice/seqMapping/TwowaysAMI.java b/java/test/src/main/java/test/Ice/seqMapping/TwowaysAMI.java new file mode 100644 index 00000000000..575686dac1b --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/TwowaysAMI.java @@ -0,0 +1,248 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.seqMapping; + +import test.Ice.seqMapping.Test.*; +import test.Ice.seqMapping.Serialize.*; + +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(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + return true; + } + + public synchronized void + called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static class Callback_MyClass_opSerialSmallJavaNull extends Callback_MyClass_opSerialSmallJava + { + @Override + public void + response(Small r, Small o) + { + test(o == null); + test(r == null); + callback.called(); + } + + @Override + public void + 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 Callback_MyClass_opSerialSmallJavaI extends Callback_MyClass_opSerialSmallJava + { + @Override + public void + response(Small r, Small o) + { + test(o.i == 99); + test(r.i == 99); + callback.called(); + } + + @Override + public void + 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 Callback_MyClass_opSerialLargeJavaI extends Callback_MyClass_opSerialLargeJava + { + @Override + public void + response(Large r, 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(); + } + + @Override + public void + 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 Callback_MyClass_opSerialStructJavaI extends Callback_MyClass_opSerialStructJava + { + @Override + public void + response(Struct r, Struct o) + { + test(o.o == null); + test(o.o2 != null); + test(((Struct)(o.o2)).o == null); + test(((Struct)(o.o2)).o2 == o.o2); + test(o.s == null); + test(o.s2.equals("Hello")); + test(r.o == null); + test(r.o2 != null); + test(((Struct)(r.o2)).o == null); + test(((Struct)(r.o2)).o2 == r.o2); + test(r.s == null); + test(r.s2.equals("Hello")); + callback.called(); + } + + @Override + public void + 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(MyClassPrx p) + { + { + Small i = null; + + Callback_MyClass_opSerialSmallJavaNull cb = new Callback_MyClass_opSerialSmallJavaNull(); + p.begin_opSerialSmallJava(i, cb); + test(cb.check()); + } + + { + Small i = new Small(); + i.i = 99; + + Callback_MyClass_opSerialSmallJavaI cb = new Callback_MyClass_opSerialSmallJavaI(); + p.begin_opSerialSmallJava(i, cb); + test(cb.check()); + } + + { + Large i = new 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; + + Callback_MyClass_opSerialLargeJavaI cb = new Callback_MyClass_opSerialLargeJavaI(); + p.begin_opSerialLargeJava(i, cb); + test(cb.check()); + } + + { + Struct i = new Struct(); + i.o = null; + i.o2 = i; + i.s = null; + i.s2 = "Hello"; + + Callback_MyClass_opSerialStructJavaI cb = new Callback_MyClass_opSerialStructJavaI(); + p.begin_opSerialStructJava(i, cb); + test(cb.check()); + } + } +} diff --git a/java/test/src/main/java/test/Ice/seqMapping/run.py b/java/test/src/main/java/test/Ice/seqMapping/run.py new file mode 100755 index 00000000000..e3ca7f3e9c6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/seqMapping/run.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("tests with regular server.") +TestUtil.clientServerTest() + +print("tests with AMD server.") +TestUtil.clientServerTest(server="test.Ice.seqMapping.AMDServer") + +print("tests with collocated server.") +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/serialize/AllTests.java b/java/test/src/main/java/test/Ice/serialize/AllTests.java new file mode 100644 index 00000000000..212acc0893c --- /dev/null +++ b/java/test/src/main/java/test/Ice/serialize/AllTests.java @@ -0,0 +1,170 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.serialize; +import test.Ice.serialize.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, PrintWriter out) + { + String ref = "initial:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + InitialPrx initial = InitialPrxHelper.checkedCast(base); + + out.print("testing serialization... "); + 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); + try + { + Struct1 s = (Struct1)ois.readObject(); + checkStruct1(s); + } + finally + { + ois.close(); + } + } + 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); + try + { + Base b = (Base) ois.readObject(); + checkBase(b); + } + finally + { + ois.close(); + } + } + 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); + try + { + Ex ex = (Ex)ois.readObject(); + checkStruct1(ex.s); + checkBase(ex.b); + } + finally + { + ois.close(); + } + } + catch(Throwable ex) + { + test(false); + } + + 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/src/main/java/test/Ice/serialize/Client.java b/java/test/src/main/java/test/Ice/serialize/Client.java new file mode 100644 index 00000000000..ffa339ba2ca --- /dev/null +++ b/java/test/src/main/java/test/Ice/serialize/Client.java @@ -0,0 +1,42 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.serialize; +import test.Ice.serialize.Test.*; + +public class Client extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + java.io.PrintWriter out = getWriter(); + InitialPrx initial = AllTests.allTests(communicator(), false, out); + initial.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.serialize"); + return initData; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/serialize/InitialI.java b/java/test/src/main/java/test/Ice/serialize/InitialI.java new file mode 100644 index 00000000000..9fdd4e03c4c --- /dev/null +++ b/java/test/src/main/java/test/Ice/serialize/InitialI.java @@ -0,0 +1,119 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.serialize; +import test.Ice.serialize.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 = MyEnum.enum2; + _s.p = 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; + } + + @Override + 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; + } + } + + @Override + 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; + } + } + + @Override + 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; + } + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + private Struct1 _s; + private Derived _d; +} diff --git a/java/test/src/main/java/test/Ice/serialize/Server.java b/java/test/src/main/java/test/Ice/serialize/Server.java new file mode 100644 index 00000000000..19346017593 --- /dev/null +++ b/java/test/src/main/java/test/Ice/serialize/Server.java @@ -0,0 +1,45 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.serialize; + +public class Server extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + 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(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.serialize"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/serialize/Test.ice b/java/test/src/main/java/test/Ice/serialize/Test.ice new file mode 100644 index 00000000000..2d9a4030f63 --- /dev/null +++ b/java/test/src/main/java/test/Ice/serialize/Test.ice @@ -0,0 +1,84 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.serialize"]] +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(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/serialize/run.py b/java/test/src/main/java/test/Ice/serialize/run.py new file mode 100755 index 00000000000..d5fe04787c9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/serialize/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/servantLocator/AMDCookieI.java b/java/test/src/main/java/test/Ice/servantLocator/AMDCookieI.java new file mode 100644 index 00000000000..5f0d227ed38 --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/AMDCookieI.java @@ -0,0 +1,22 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.servantLocator; + +import test.Ice.servantLocator.AMD.Test.Cookie; + +public final class AMDCookieI extends Cookie +{ + @Override + public String + message() + { + return "blahblah"; + } +} diff --git a/java/test/src/main/java/test/Ice/servantLocator/AMDServantLocatorI.java b/java/test/src/main/java/test/Ice/servantLocator/AMDServantLocatorI.java new file mode 100644 index 00000000000..24b14d3ef39 --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/AMDServantLocatorI.java @@ -0,0 +1,184 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.servantLocator; + +import test.Ice.servantLocator.AMD.Test.Cookie; +import test.Ice.servantLocator.AMD.Test.TestImpossibleException; +import test.Ice.servantLocator.AMD.Test.TestIntfUserException; +import Ice.ObjectNotExistException; +import Ice.SocketException; +import Ice.UnknownException; +import Ice.UnknownLocalException; +import Ice.UnknownUserException; + +public final class AMDServantLocatorI implements Ice.ServantLocator +{ + public + AMDServantLocatorI(String category) + { + _category = category; + _deactivated = false; + _requestId = -1; + } + + @Override + protected synchronized void + finalize() + throws Throwable + { + test(_deactivated); + } + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + @Override + public Ice.Object + locate(Ice.Current current, Ice.LocalObjectHolder cookie) throws Ice.UserException + { + synchronized(this) + { + test(!_deactivated); + } + + test(current.id.category.equals(_category) || _category.length() == 0); + + if(current.id.name.equals("unknown")) + { + return null; + } + + test(current.id.name.equals("locate") || current.id.name.equals("finished")); + if(current.id.name.equals("locate")) + { + exception(current); + } + + // + // Ensure locate() is only called once per request. + // + test(_requestId == -1); + _requestId = current.requestId; + + cookie.value = new AMDCookieI(); + + return new AMDTestI(); + } + + @Override + public void + finished(Ice.Current current, Ice.Object servant, java.lang.Object cookie) throws Ice.UserException + { + synchronized(this) + { + test(!_deactivated); + } + + // + // Ensure finished() is only called once per request. + // + test(_requestId == current.requestId); + _requestId = -1; + + test(current.id.category.equals(_category) || _category.length() == 0); + test(current.id.name.equals("locate") || current.id.name.equals("finished")); + + if(current.id.name.equals("finished")) + { + exception(current); + } + + Cookie co = (Cookie)cookie; + test(co.message().equals("blahblah")); + } + + @Override + public synchronized void + deactivate(String category) + { + synchronized(this) + { + test(!_deactivated); + + _deactivated = true; + } + } + + private void + exception(Ice.Current current) throws Ice.UserException + { + if(current.operation.equals("ice_ids")) + { + throw new TestIntfUserException(); + } + else if(current.operation.equals("requestFailedException")) + { + throw new ObjectNotExistException(); + } + else if(current.operation.equals("unknownUserException")) + { + throw new UnknownUserException("reason"); + } + else if(current.operation.equals("unknownLocalException")) + { + throw new UnknownLocalException("reason"); + } + else if(current.operation.equals("unknownException")) + { + throw new UnknownException("reason"); + } + // + // User exceptions are checked exceptions in Java, so it's not + // possible to throw it from the servant locator. + // +// else if(current.operation.equals("userException")) +// { +// throw new TestIntfUserException(); +// } + else if(current.operation.equals("localException")) + { + throw new SocketException(0); + } + else if(current.operation.equals("javaException")) + { + throw new java.lang.RuntimeException("message"); + } + else if(current.operation.equals("unknownExceptionWithServantException")) + { + throw new UnknownException("reason"); + } + else if(current.operation.equals("impossibleException")) + { + throw new TestIntfUserException(); // Yes, it really is meant to be TestIntfUserException. + } + else if(current.operation.equals("intfUserException")) + { + throw new TestImpossibleException(); // Yes, it really is meant to be TestImpossibleException. + } + else if(current.operation.equals("asyncResponse")) + { + throw new TestImpossibleException(); + } + else if(current.operation.equals("asyncException")) + { + throw new TestImpossibleException(); + } + } + + private boolean _deactivated; + private final String _category; + private int _requestId; +} diff --git a/java/test/src/main/java/test/Ice/servantLocator/AMDServer.java b/java/test/src/main/java/test/Ice/servantLocator/AMDServer.java new file mode 100644 index 00000000000..29f8754170a --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/AMDServer.java @@ -0,0 +1,46 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.servantLocator; + +public class AMDServer extends test.Util.Application +{ + @Override + public int run(String[] args) + { + + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.addServantLocator(new AMDServantLocatorI("category"), "category"); + adapter.addServantLocator(new AMDServantLocatorI(""), ""); + adapter.add(new AMDTestI(), communicator().stringToIdentity("asm")); + adapter.add(new AMDTestActivationI(), communicator().stringToIdentity("test/activation")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.servantLocator.AMD"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + + return initData; + } + + public static void main(String[] args) + { + AMDServer app = new AMDServer(); + int result = app.main("AMDServer", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/servantLocator/AMDTestActivationI.java b/java/test/src/main/java/test/Ice/servantLocator/AMDTestActivationI.java new file mode 100644 index 00000000000..31ecfeab516 --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/AMDTestActivationI.java @@ -0,0 +1,32 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.servantLocator; + +import test.Ice.servantLocator.Test._TestActivationDisp; + +public final class AMDTestActivationI extends _TestActivationDisp +{ + @Override + public void activateServantLocator(boolean activate, Ice.Current current) + { + if(activate) + { + current.adapter.addServantLocator(new AMDServantLocatorI(""), ""); + current.adapter.addServantLocator(new AMDServantLocatorI("category"), "category"); + } + else + { + Ice.ServantLocator locator = current.adapter.removeServantLocator(""); + locator.deactivate(""); + locator = current.adapter.removeServantLocator("category"); + locator.deactivate("category"); + } + } +} diff --git a/java/test/src/main/java/test/Ice/servantLocator/AMDTestI.java b/java/test/src/main/java/test/Ice/servantLocator/AMDTestI.java new file mode 100644 index 00000000000..999b2871a89 --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/AMDTestI.java @@ -0,0 +1,145 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.servantLocator; + +import test.Ice.servantLocator.AMD.Test.AMD_TestIntf_asyncException; +import test.Ice.servantLocator.AMD.Test.AMD_TestIntf_asyncResponse; +import test.Ice.servantLocator.AMD.Test.AMD_TestIntf_impossibleException; +import test.Ice.servantLocator.AMD.Test.AMD_TestIntf_intfUserException; +import test.Ice.servantLocator.AMD.Test.AMD_TestIntf_javaException; +import test.Ice.servantLocator.AMD.Test.AMD_TestIntf_localException; +import test.Ice.servantLocator.AMD.Test.AMD_TestIntf_requestFailedException; +import test.Ice.servantLocator.AMD.Test.AMD_TestIntf_shutdown; +import test.Ice.servantLocator.AMD.Test.AMD_TestIntf_unknownException; +import test.Ice.servantLocator.AMD.Test.AMD_TestIntf_unknownLocalException; +import test.Ice.servantLocator.AMD.Test.AMD_TestIntf_unknownUserException; +import test.Ice.servantLocator.AMD.Test.AMD_TestIntf_unknownExceptionWithServantException; +import test.Ice.servantLocator.AMD.Test.TestImpossibleException; +import test.Ice.servantLocator.AMD.Test.TestIntfUserException; +import test.Ice.servantLocator.AMD.Test._TestIntfDisp; + +public final class AMDTestI extends _TestIntfDisp +{ + @Override + public void + requestFailedException_async(AMD_TestIntf_requestFailedException cb, Ice.Current current) + { + cb.ice_response(); + } + + @Override + public void + unknownUserException_async(AMD_TestIntf_unknownUserException cb, Ice.Current current) + { + cb.ice_response(); + } + + @Override + public void + unknownLocalException_async(AMD_TestIntf_unknownLocalException cb, Ice.Current current) + { + cb.ice_response(); + } + + @Override + public void + unknownException_async(AMD_TestIntf_unknownException cb, Ice.Current current) + { + cb.ice_response(); + } + + @Override + public void + localException_async(AMD_TestIntf_localException cb, Ice.Current current) + { + cb.ice_response(); + } + +// public void +// userException_async(AMD_TestIntf_userException cb, Ice.Current current) +// { +// cb.ice_response(); +// } + + @Override + public void + javaException_async(AMD_TestIntf_javaException cb, Ice.Current current) + { + cb.ice_response(); + } + + @Override + public void + unknownExceptionWithServantException_async(AMD_TestIntf_unknownExceptionWithServantException cb, + Ice.Current current) + { + cb.ice_exception(new Ice.ObjectNotExistException()); + } + + @Override + public void + impossibleException_async(AMD_TestIntf_impossibleException cb, boolean _throw, Ice.Current current) + { + if(_throw) + { + cb.ice_exception(new TestImpossibleException()); + } + else + { + // + // Return a value so we can be sure that the stream position + // is reset correctly if finished() throws. + // + cb.ice_response("Hello"); + } + } + + @Override + public void + intfUserException_async(AMD_TestIntf_intfUserException cb, boolean _throw, Ice.Current current) + { + if(_throw) + { + cb.ice_exception(new TestIntfUserException()); + } + else + { + // + // Return a value so we can be sure that the stream position + // is reset correctly if finished() throws. + // + cb.ice_response("Hello"); + } + } + + @Override + public void + asyncResponse_async(AMD_TestIntf_asyncResponse cb, Ice.Current current) + { + cb.ice_response(); + throw new Ice.ObjectNotExistException(); + } + + @Override + public void + asyncException_async(AMD_TestIntf_asyncException cb, Ice.Current current) + { + cb.ice_exception(new TestIntfUserException()); + throw new Ice.ObjectNotExistException(); + } + + @Override + public void + shutdown_async(AMD_TestIntf_shutdown cb, Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + cb.ice_response(); + } +} diff --git a/java/test/src/main/java/test/Ice/servantLocator/AllTests.java b/java/test/src/main/java/test/Ice/servantLocator/AllTests.java new file mode 100644 index 00000000000..15273a5b687 --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/AllTests.java @@ -0,0 +1,374 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.servantLocator; + +import java.io.PrintWriter; + +import test.Ice.servantLocator.Test.TestImpossibleException; +import test.Ice.servantLocator.Test.TestIntfUserException; +import test.Ice.servantLocator.Test.TestIntfPrx; +import test.Ice.servantLocator.Test.TestIntfPrxHelper; +import test.Ice.servantLocator.Test.TestActivationPrx; +import test.Ice.servantLocator.Test.TestActivationPrxHelper; + +import Ice.ObjectNotExistException; +import Ice.ObjectPrx; +import Ice.UnknownException; +import Ice.UnknownLocalException; +import Ice.UnknownUserException; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + testExceptions(TestIntfPrx obj) + { + try + { + obj.requestFailedException(); + test(false); + } + catch(ObjectNotExistException ex) + { + test(ex.id.equals(obj.ice_getIdentity())); + test(ex.facet.equals(obj.ice_getFacet())); + test(ex.operation.equals("requestFailedException")); + } + + try + { + obj.unknownUserException(); + test(false); + } + catch(UnknownUserException ex) + { + test(ex.unknown.equals("reason")); + } + + try + { + obj.unknownLocalException(); + test(false); + } + catch(UnknownLocalException ex) + { + test(ex.unknown.equals("reason")); + } + + try + { + obj.unknownException(); + test(false); + } + catch(UnknownException ex) + { + test(ex.unknown.equals("reason")); + } + + // + // User exceptions are checked exceptions + // +// try +// { +// obj.userException(); +// test(false); +// } +// catch(UnknownUserException ex) +// { +// //System.err.println(ex.unknown); +// test(!collocated); +// test(ex.unknown.equals("Test::TestIntfUserException")); +// } +// catch(TestIntfUserException ex) +// { +// test(collocated); +// } + + try + { + obj.localException(); + test(false); + } + catch(UnknownLocalException ex) + { + test(ex.unknown.indexOf("Ice::SocketException") >= 0); + } + catch(Throwable ex) + { + test(false); + } + + try + { + obj.javaException(); + test(false); + } + catch(UnknownException ex) + { + test(ex.unknown.indexOf("java.lang.RuntimeException: message") >= 0); + } + catch(Ice.OperationNotExistException ex) + { + } + catch(Throwable ex) + { + //System.err.println(ex); + test(false); + } + + try + { + obj.unknownExceptionWithServantException(); + test(false); + } + catch(UnknownException ex) + { + test(ex.unknown.equals("reason")); + } + catch(Throwable ex) + { + test(false); + } + + try + { + obj.impossibleException(false); + test(false); + } + catch(UnknownUserException ex) + { + // Operation doesn't throw, but locate() and finished() throw TestIntfUserException. + } + catch(Throwable ex) + { + //System.err.println(ex); + test(false); + } + + try + { + obj.impossibleException(true); + test(false); + } + catch(UnknownUserException ex) + { + // Operation throws TestImpossibleException, but locate() and finished() throw TestIntfUserException. + } + catch(Throwable ex) + { + //System.err.println(ex); + test(false); + } + + try + { + obj.intfUserException(false); + test(false); + } + catch(TestImpossibleException ex) + { + // Operation doesn't throw, but locate() and finished() throw TestImpossibleException. + } + catch(Throwable ex) + { + //System.err.println(ex); + test(false); + } + + try + { + obj.intfUserException(true); + test(false); + } + catch(TestImpossibleException ex) + { + // Operation throws TestIntfUserException, but locate() and finished() throw TestImpossibleException. + } + catch(Throwable ex) + { + //System.err.println(ex); + test(false); + } + } + + public static TestIntfPrx + allTests(Ice.Communicator communicator, PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + String ref = "asm:default -p 12010"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + TestIntfPrx obj = TestIntfPrxHelper.checkedCast(base); + test(obj != null); + test(obj.equals(base)); + out.println("ok"); + + out.print("testing ice_ids... "); + out.flush(); + try + { + ObjectPrx o = communicator.stringToProxy("category/locate:default -p 12010"); + o.ice_ids(); + test(false); + } + catch(UnknownUserException ex) + { + test(ex.unknown.equals("Test::TestIntfUserException")); + } + catch(Throwable ex) + { + test(false); + } + + try + { + ObjectPrx o = communicator.stringToProxy("category/finished:default -p 12010"); + o.ice_ids(); + test(false); + } + catch(UnknownUserException ex) + { + test(ex.unknown.equals("Test::TestIntfUserException")); + } + catch(Throwable ex) + { + test(false); + } + out.println("ok"); + + out.print("testing servant locator... "); + out.flush(); + base = communicator.stringToProxy("category/locate:default -p 12010"); + obj = TestIntfPrxHelper.checkedCast(base); + try + { + TestIntfPrxHelper.checkedCast(communicator.stringToProxy("category/unknown:default -p 12010")); + } + catch(ObjectNotExistException ex) + { + } + out.println("ok"); + + out.print("testing default servant locator... "); + out.flush(); + base = communicator.stringToProxy("anothercat/locate:default -p 12010"); + obj = TestIntfPrxHelper.checkedCast(base); + base = communicator.stringToProxy("locate:default -p 12010"); + obj = TestIntfPrxHelper.checkedCast(base); + try + { + TestIntfPrxHelper.checkedCast(communicator.stringToProxy("anothercat/unknown:default -p 12010")); + } + catch(ObjectNotExistException ex) + { + } + try + { + TestIntfPrxHelper.checkedCast(communicator.stringToProxy("unknown:default -p 12010")); + } + catch(ObjectNotExistException ex) + { + } + out.println("ok"); + + out.print("testing locate exceptions... "); + out.flush(); + base = communicator.stringToProxy("category/locate:default -p 12010"); + obj = TestIntfPrxHelper.checkedCast(base); + testExceptions(obj); + out.println("ok"); + + out.print("testing finished exceptions... "); + out.flush(); + base = communicator.stringToProxy("category/finished:default -p 12010"); + obj = TestIntfPrxHelper.checkedCast(base); + testExceptions(obj); + + // + // Only call these for category/finished. + // + try + { + obj.asyncResponse(); + } + catch(TestIntfUserException ex) + { + test(false); + } + catch(TestImpossibleException ex) + { + // + // Called by finished(). + // + } + + // + // Only call these for category/finished. + // + try + { + obj.asyncException(); + } + catch(TestIntfUserException ex) + { + test(false); + } + catch(TestImpossibleException ex) + { + // + // Called by finished(). + // + } + + out.println("ok"); + + out.print("testing servant locator removal... "); + out.flush(); + base = communicator.stringToProxy("test/activation:default -p 12010"); + TestActivationPrx activation = TestActivationPrxHelper.checkedCast(base); + activation.activateServantLocator(false); + try + { + obj.ice_ping(); + test(false); + } + catch(ObjectNotExistException ex) + { + out.println("ok"); + } + out.print("testing servant locator addition... "); + out.flush(); + activation.activateServantLocator(true); + try + { + obj.ice_ping(); + out.println("ok"); + } + catch(Exception ex) + { + test(false); + } + + return obj; + } +} diff --git a/java/test/src/main/java/test/Ice/servantLocator/Client.java b/java/test/src/main/java/test/Ice/servantLocator/Client.java new file mode 100644 index 00000000000..c781cb5ac50 --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/Client.java @@ -0,0 +1,40 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.servantLocator; + +import test.Ice.servantLocator.Test.TestIntfPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + TestIntfPrx obj = AllTests.allTests(communicator(), getWriter()); + obj.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.servantLocator"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/servantLocator/Collocated.java b/java/test/src/main/java/test/Ice/servantLocator/Collocated.java new file mode 100644 index 00000000000..612602d933d --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/Collocated.java @@ -0,0 +1,46 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.servantLocator; + +public class Collocated extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.addServantLocator(new ServantLocatorI("category"), "category"); + adapter.addServantLocator(new ServantLocatorI(""), ""); + adapter.add(new TestI(), communicator().stringToIdentity("asm")); + adapter.add(new TestActivationI(), communicator().stringToIdentity("test/activation")); + AllTests.allTests(communicator(), getWriter()); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.servantLocator"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + + return initData; + } + + public static void main(String[] args) + { + Collocated app = new Collocated(); + int result = app.main("Collocated", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/servantLocator/CookieI.java b/java/test/src/main/java/test/Ice/servantLocator/CookieI.java new file mode 100644 index 00000000000..52bab91e922 --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/CookieI.java @@ -0,0 +1,22 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.servantLocator; + +import test.Ice.servantLocator.Test.Cookie; + +public final class CookieI extends Cookie +{ + @Override + public String + message() + { + return "blahblah"; + } +} diff --git a/java/test/src/main/java/test/Ice/servantLocator/ServantLocatorI.java b/java/test/src/main/java/test/Ice/servantLocator/ServantLocatorI.java new file mode 100644 index 00000000000..f3fa5388634 --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/ServantLocatorI.java @@ -0,0 +1,184 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.servantLocator; + +import test.Ice.servantLocator.Test.Cookie; +import test.Ice.servantLocator.Test.TestImpossibleException; +import test.Ice.servantLocator.Test.TestIntfUserException; +import Ice.ObjectNotExistException; +import Ice.SocketException; +import Ice.UnknownException; +import Ice.UnknownLocalException; +import Ice.UnknownUserException; + +public final class ServantLocatorI implements Ice.ServantLocator +{ + public + ServantLocatorI(String category) + { + _category = category; + _deactivated = false; + _requestId = -1; + } + + @Override + protected synchronized void + finalize() + throws Throwable + { + test(_deactivated); + } + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + @Override + public Ice.Object + locate(Ice.Current current, Ice.LocalObjectHolder cookie) throws Ice.UserException + { + synchronized(this) + { + test(!_deactivated); + } + + test(current.id.category.equals(_category) || _category.length() == 0); + + if(current.id.name.equals("unknown")) + { + return null; + } + + test(current.id.name.equals("locate") || current.id.name.equals("finished")); + if(current.id.name.equals("locate")) + { + exception(current); + } + + // + // Ensure locate() is only called once per request. + // + test(_requestId == -1); + _requestId = current.requestId; + + cookie.value = new CookieI(); + + return new TestI(); + } + + @Override + public void + finished(Ice.Current current, Ice.Object servant, java.lang.Object cookie) throws Ice.UserException + { + synchronized(this) + { + test(!_deactivated); + } + + // + // Ensure finished() is only called once per request. + // + test(_requestId == current.requestId); + _requestId = -1; + + test(current.id.category.equals(_category) || _category.length() == 0); + test(current.id.name.equals("locate") || current.id.name.equals("finished")); + + if(current.id.name.equals("finished")) + { + exception(current); + } + + Cookie co = (Cookie)cookie; + test(co.message().equals("blahblah")); + } + + @Override + public synchronized void + deactivate(String category) + { + synchronized(this) + { + test(!_deactivated); + + _deactivated = true; + } + } + + private void + exception(Ice.Current current) throws Ice.UserException + { + if(current.operation.equals("ice_ids")) + { + throw new TestIntfUserException(); + } + else if(current.operation.equals("requestFailedException")) + { + throw new ObjectNotExistException(); + } + else if(current.operation.equals("unknownUserException")) + { + throw new UnknownUserException("reason"); + } + else if(current.operation.equals("unknownLocalException")) + { + throw new UnknownLocalException("reason"); + } + else if(current.operation.equals("unknownException")) + { + throw new UnknownException("reason"); + } + // + // User exceptions are checked exceptions in Java, so it's not + // possible to throw it from the servant locator. + // +// else if(current.operation.equals("userException")) +// { +// throw new TestIntfUserException(); +// } + else if(current.operation.equals("localException")) + { + throw new SocketException(0); + } + else if(current.operation.equals("javaException")) + { + throw new java.lang.RuntimeException("message"); + } + else if(current.operation.equals("unknownExceptionWithServantException")) + { + throw new UnknownException("reason"); + } + else if(current.operation.equals("impossibleException")) + { + throw new TestIntfUserException(); // Yes, it really is meant to be TestIntfUserException. + } + else if(current.operation.equals("intfUserException")) + { + throw new TestImpossibleException(); // Yes, it really is meant to be TestImpossibleException. + } + else if(current.operation.equals("asyncResponse")) + { + throw new TestImpossibleException(); + } + else if(current.operation.equals("asyncException")) + { + throw new TestImpossibleException(); + } + } + + private boolean _deactivated; + private final String _category; + private int _requestId; +} diff --git a/java/test/src/main/java/test/Ice/servantLocator/Server.java b/java/test/src/main/java/test/Ice/servantLocator/Server.java new file mode 100644 index 00000000000..bd3dfdc7288 --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/Server.java @@ -0,0 +1,45 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.servantLocator; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.addServantLocator(new ServantLocatorI("category"), "category"); + adapter.addServantLocator(new ServantLocatorI(""), ""); + adapter.add(new TestI(), communicator().stringToIdentity("asm")); + adapter.add(new TestActivationI(), communicator().stringToIdentity("test/activation")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.servantLocator"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/servantLocator/Test.ice b/java/test/src/main/java/test/Ice/servantLocator/Test.ice new file mode 100644 index 00000000000..1c12f4b8483 --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/Test.ice @@ -0,0 +1,55 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.servantLocator"]] +module Test +{ + +exception TestIntfUserException +{ +}; + +exception TestImpossibleException +{ +}; + +interface TestIntf +{ + void requestFailedException(); + void unknownUserException(); + void unknownLocalException(); + void unknownException(); + void localException(); + //void userException(); + void javaException(); + + void unknownExceptionWithServantException(); + + string impossibleException(bool throw) throws TestImpossibleException; + string intfUserException(bool throw) throws TestIntfUserException, TestImpossibleException; + + void asyncResponse() throws TestIntfUserException, TestImpossibleException; + void asyncException() throws TestIntfUserException, TestImpossibleException; + + void shutdown(); +}; + +interface TestActivation +{ + void activateServantLocator(bool activate); +}; + +local class Cookie +{ + ["cpp:const"] string message(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/servantLocator/TestAMD.ice b/java/test/src/main/java/test/Ice/servantLocator/TestAMD.ice new file mode 100644 index 00000000000..2a776edb658 --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/TestAMD.ice @@ -0,0 +1,55 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.servantLocator.AMD"]] +module Test +{ + +exception TestIntfUserException +{ +}; + +exception TestImpossibleException +{ +}; + +["amd"] interface TestIntf +{ + void requestFailedException(); + void unknownUserException(); + void unknownLocalException(); + void unknownException(); + void localException(); + //void userException(); + void javaException(); + + void unknownExceptionWithServantException(); + + string impossibleException(bool throw) throws TestImpossibleException; + string intfUserException(bool throw) throws TestIntfUserException, TestImpossibleException; + + void asyncResponse() throws TestIntfUserException, TestImpossibleException; + void asyncException() throws TestIntfUserException, TestImpossibleException; + + void shutdown(); +}; + +interface TestActivation +{ + void activateServantLocator(bool activate); +}; + +local class Cookie +{ + ["cpp:const"] string message(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/servantLocator/TestActivationI.java b/java/test/src/main/java/test/Ice/servantLocator/TestActivationI.java new file mode 100644 index 00000000000..3c1c6f209ad --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/TestActivationI.java @@ -0,0 +1,32 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.servantLocator; + +import test.Ice.servantLocator.Test._TestActivationDisp; + +public final class TestActivationI extends _TestActivationDisp +{ + @Override + public void activateServantLocator(boolean activate, Ice.Current current) + { + if(activate) + { + current.adapter.addServantLocator(new ServantLocatorI(""), ""); + current.adapter.addServantLocator(new ServantLocatorI("category"), "category"); + } + else + { + Ice.ServantLocator locator = current.adapter.removeServantLocator(""); + locator.deactivate(""); + locator = current.adapter.removeServantLocator("category"); + locator.deactivate("category"); + } + } +} diff --git a/java/test/src/main/java/test/Ice/servantLocator/TestI.java b/java/test/src/main/java/test/Ice/servantLocator/TestI.java new file mode 100644 index 00000000000..b0704d4f6a6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/TestI.java @@ -0,0 +1,122 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.servantLocator; + +import test.Ice.servantLocator.Test.TestImpossibleException; +import test.Ice.servantLocator.Test.TestIntfUserException; +import test.Ice.servantLocator.Test._TestIntfDisp; + +public final class TestI extends _TestIntfDisp +{ + @Override + public void + requestFailedException(Ice.Current current) + { + } + + @Override + public void + unknownUserException(Ice.Current current) + { + } + + @Override + public void + unknownLocalException(Ice.Current current) + { + } + + @Override + public void + unknownException(Ice.Current current) + { + } + + @Override + public void + localException(Ice.Current current) + { + } + +// public void +// userException(Ice.Current current) +// { +// } + + @Override + public void + javaException(Ice.Current current) + { + } + + @Override + public void + unknownExceptionWithServantException(Ice.Current current) + { + throw new Ice.ObjectNotExistException(); + } + + @Override + public String + impossibleException(boolean _throw, Ice.Current current) throws TestImpossibleException + { + if(_throw) + { + throw new TestImpossibleException(); + } + + // + // Return a value so we can be sure that the stream position + // is reset correctly if finished() throws. + // + return "Hello"; + } + + @Override + public String + intfUserException(boolean _throw, Ice.Current current) throws TestIntfUserException, TestImpossibleException + { + if(_throw) + { + throw new TestIntfUserException(); + } + + // + // Return a value so we can be sure that the stream position + // is reset correctly if finished() throws. + // + return "Hello"; + } + + @Override + public void + asyncResponse(Ice.Current current) throws TestIntfUserException, TestImpossibleException + { + // + // Only relevant for AMD. + // + } + + @Override + public void + asyncException(Ice.Current current) throws TestIntfUserException, TestImpossibleException + { + // + // Only relevant for AMD. + // + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/servantLocator/run.py b/java/test/src/main/java/test/Ice/servantLocator/run.py new file mode 100755 index 00000000000..7944176bc4a --- /dev/null +++ b/java/test/src/main/java/test/Ice/servantLocator/run.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("tests with regular server.") +TestUtil.clientServerTest() + +print("tests with AMD server.") +TestUtil.clientServerTest(server="test.Ice.servantLocator.AMDServer") + +print("tests with collocated server.") +TestUtil.collocatedTest() diff --git a/java/test/src/main/java/test/Ice/slicing/exceptions/AMDServer.java b/java/test/src/main/java/test/Ice/slicing/exceptions/AMDServer.java new file mode 100644 index 00000000000..acca7cf53e8 --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/exceptions/AMDServer.java @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.slicing.exceptions; + +public class AMDServer extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + Ice.Object object = new AMDTestI(); + adapter.add(object, communicator().stringToIdentity("Test")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.slicing.exceptions.serverAMD"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010 -t 2000"); + return initData; + } + + public static void main(String[] args) + { + AMDServer c = new AMDServer(); + int status = c.main("AMDServer", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/slicing/exceptions/AMDTestI.java b/java/test/src/main/java/test/Ice/slicing/exceptions/AMDTestI.java new file mode 100644 index 00000000000..07ca77f5dad --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/exceptions/AMDTestI.java @@ -0,0 +1,321 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.slicing.exceptions; + +import test.Ice.slicing.exceptions.serverAMD.Test.*; + +public final class AMDTestI extends _TestIntfDisp +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + @Override + public void + shutdown_async(AMD_TestIntf_shutdown cb, Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + cb.ice_response(); + } + + @Override + public void + baseAsBase_async(AMD_TestIntf_baseAsBase cb, Ice.Current current) + throws Base + { + Base b = new Base(); + b.b = "Base.b"; + cb.ice_exception(b); + } + + @Override + public void + unknownDerivedAsBase_async(AMD_TestIntf_unknownDerivedAsBase cb, Ice.Current current) + throws Base + { + UnknownDerived d = new UnknownDerived(); + d.b = "UnknownDerived.b"; + d.ud = "UnknownDerived.ud"; + cb.ice_exception(d); + } + + @Override + public void + knownDerivedAsBase_async(AMD_TestIntf_knownDerivedAsBase cb, Ice.Current current) + throws Base + { + KnownDerived d = new KnownDerived(); + d.b = "KnownDerived.b"; + d.kd = "KnownDerived.kd"; + cb.ice_exception(d); + } + + @Override + public void + knownDerivedAsKnownDerived_async(AMD_TestIntf_knownDerivedAsKnownDerived cb, Ice.Current current) + throws KnownDerived + { + KnownDerived d = new KnownDerived(); + d.b = "KnownDerived.b"; + d.kd = "KnownDerived.kd"; + cb.ice_exception(d); + } + + @Override + public void + unknownIntermediateAsBase_async(AMD_TestIntf_unknownIntermediateAsBase cb, Ice.Current current) + throws Base + { + UnknownIntermediate ui = new UnknownIntermediate(); + ui.b = "UnknownIntermediate.b"; + ui.ui = "UnknownIntermediate.ui"; + cb.ice_exception(ui); + } + + @Override + public void + knownIntermediateAsBase_async(AMD_TestIntf_knownIntermediateAsBase cb, Ice.Current current) + throws Base + { + KnownIntermediate ki = new KnownIntermediate(); + ki.b = "KnownIntermediate.b"; + ki.ki = "KnownIntermediate.ki"; + cb.ice_exception(ki); + } + + @Override + public void + knownMostDerivedAsBase_async(AMD_TestIntf_knownMostDerivedAsBase cb, Ice.Current current) + throws Base + { + KnownMostDerived kmd = new KnownMostDerived(); + kmd.b = "KnownMostDerived.b"; + kmd.ki = "KnownMostDerived.ki"; + kmd.kmd = "KnownMostDerived.kmd"; + cb.ice_exception(kmd); + } + + @Override + public void + knownIntermediateAsKnownIntermediate_async(AMD_TestIntf_knownIntermediateAsKnownIntermediate cb, + Ice.Current current) + throws KnownIntermediate + { + KnownIntermediate ki = new KnownIntermediate(); + ki.b = "KnownIntermediate.b"; + ki.ki = "KnownIntermediate.ki"; + cb.ice_exception(ki); + } + + @Override + public void + knownMostDerivedAsKnownIntermediate_async(AMD_TestIntf_knownMostDerivedAsKnownIntermediate cb, + Ice.Current current) + throws KnownIntermediate + { + KnownMostDerived kmd = new KnownMostDerived(); + kmd.b = "KnownMostDerived.b"; + kmd.ki = "KnownMostDerived.ki"; + kmd.kmd = "KnownMostDerived.kmd"; + cb.ice_exception(kmd); + } + + @Override + public void + knownMostDerivedAsKnownMostDerived_async(AMD_TestIntf_knownMostDerivedAsKnownMostDerived cb, + Ice.Current current) + throws KnownMostDerived + { + KnownMostDerived kmd = new KnownMostDerived(); + kmd.b = "KnownMostDerived.b"; + kmd.ki = "KnownMostDerived.ki"; + kmd.kmd = "KnownMostDerived.kmd"; + cb.ice_exception(kmd); + } + + @Override + public void + unknownMostDerived1AsBase_async(AMD_TestIntf_unknownMostDerived1AsBase cb, Ice.Current current) + throws Base + { + UnknownMostDerived1 umd1 = new UnknownMostDerived1(); + umd1.b = "UnknownMostDerived1.b"; + umd1.ki = "UnknownMostDerived1.ki"; + umd1.umd1 = "UnknownMostDerived1.umd1"; + cb.ice_exception(umd1); + } + + @Override + public void + unknownMostDerived1AsKnownIntermediate_async(AMD_TestIntf_unknownMostDerived1AsKnownIntermediate cb, + Ice.Current current) + throws KnownIntermediate + { + UnknownMostDerived1 umd1 = new UnknownMostDerived1(); + umd1.b = "UnknownMostDerived1.b"; + umd1.ki = "UnknownMostDerived1.ki"; + umd1.umd1 = "UnknownMostDerived1.umd1"; + cb.ice_exception(umd1); + } + + @Override + public void + unknownMostDerived2AsBase_async(AMD_TestIntf_unknownMostDerived2AsBase cb, Ice.Current current) + throws Base + { + UnknownMostDerived2 umd2 = new UnknownMostDerived2(); + umd2.b = "UnknownMostDerived2.b"; + umd2.ui = "UnknownMostDerived2.ui"; + umd2.umd2 = "UnknownMostDerived2.umd2"; + cb.ice_exception(umd2); + } + + @Override + public void + unknownMostDerived2AsBaseCompact_async(AMD_TestIntf_unknownMostDerived2AsBaseCompact cb, Ice.Current current) + { + UnknownMostDerived2 umd2 = new UnknownMostDerived2(); + umd2.b = "UnknownMostDerived2.b"; + umd2.ui = "UnknownMostDerived2.ui"; + umd2.umd2 = "UnknownMostDerived2.umd2"; + cb.ice_exception(umd2); + } + + @Override + public void + knownPreservedAsBase_async(AMD_TestIntf_knownPreservedAsBase cb, Ice.Current current) + { + KnownPreservedDerived ex = new KnownPreservedDerived(); + ex.b = "base"; + ex.kp = "preserved"; + ex.kpd = "derived"; + cb.ice_exception(ex); + } + + @Override + public void + knownPreservedAsKnownPreserved_async(AMD_TestIntf_knownPreservedAsKnownPreserved cb, Ice.Current current) + { + KnownPreservedDerived ex = new KnownPreservedDerived(); + ex.b = "base"; + ex.kp = "preserved"; + ex.kpd = "derived"; + cb.ice_exception(ex); + } + + @Override + public void + relayKnownPreservedAsBase_async(AMD_TestIntf_relayKnownPreservedAsBase cb, RelayPrx r, Ice.Current current) + { + try + { + r.knownPreservedAsBase(); + test(false); + } + catch(Ice.UserException ex) + { + cb.ice_exception(ex); + } + catch(Ice.LocalException ex) + { + cb.ice_exception(ex); + } + } + + @Override + public void + relayKnownPreservedAsKnownPreserved_async(AMD_TestIntf_relayKnownPreservedAsKnownPreserved cb, + RelayPrx r, Ice.Current current) + { + try + { + r.knownPreservedAsKnownPreserved(); + test(false); + } + catch(Ice.UserException ex) + { + cb.ice_exception(ex); + } + catch(Ice.LocalException ex) + { + cb.ice_exception(ex); + } + } + + @Override + public void + unknownPreservedAsBase_async(AMD_TestIntf_unknownPreservedAsBase cb, Ice.Current current) + { + SPreserved2 ex = new SPreserved2(); + ex.b = "base"; + ex.kp = "preserved"; + ex.kpd = "derived"; + ex.p1 = new SPreservedClass("bc", "spc"); + ex.p2 = ex.p1; + cb.ice_exception(ex); + } + + @Override + public void + unknownPreservedAsKnownPreserved_async(AMD_TestIntf_unknownPreservedAsKnownPreserved cb, Ice.Current current) + { + SPreserved2 ex = new SPreserved2(); + ex.b = "base"; + ex.kp = "preserved"; + ex.kpd = "derived"; + ex.p1 = new SPreservedClass("bc", "spc"); + ex.p2 = ex.p1; + cb.ice_exception(ex); + } + + @Override + public void + relayUnknownPreservedAsBase_async(AMD_TestIntf_relayUnknownPreservedAsBase cb, RelayPrx r, Ice.Current current) + { + try + { + r.unknownPreservedAsBase(); + test(false); + } + catch(Ice.UserException ex) + { + cb.ice_exception(ex); + } + catch(Ice.LocalException ex) + { + cb.ice_exception(ex); + } + } + + @Override + public void + relayUnknownPreservedAsKnownPreserved_async(AMD_TestIntf_relayUnknownPreservedAsKnownPreserved cb, RelayPrx r, + Ice.Current current) + { + try + { + r.unknownPreservedAsKnownPreserved(); + test(false); + } + catch(Ice.UserException ex) + { + cb.ice_exception(ex); + } + catch(Ice.LocalException ex) + { + cb.ice_exception(ex); + } + } +} diff --git a/java/test/src/main/java/test/Ice/slicing/exceptions/AllTests.java b/java/test/src/main/java/test/Ice/slicing/exceptions/AllTests.java new file mode 100644 index 00000000000..cd159a9006b --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/exceptions/AllTests.java @@ -0,0 +1,1278 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.slicing.exceptions; + +import test.Ice.slicing.exceptions.client.Test.*; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized void + check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void + called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static class Callback_TestIntf_baseAsBaseI extends Callback_TestIntf_baseAsBase + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(Base b) + { + test(b.b.equals("Base.b")); + test(b.ice_name().equals("Test::Base")); + } + catch(Exception ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_unknownDerivedAsBaseI extends Callback_TestIntf_unknownDerivedAsBase + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(Base b) + { + test(b.b.equals("UnknownDerived.b")); + test(b.ice_name().equals("Test::Base")); + } + catch(Exception ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_knownDerivedAsBaseI extends Callback_TestIntf_knownDerivedAsBase + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(KnownDerived k) + { + test(k.b.equals("KnownDerived.b")); + test(k.kd.equals("KnownDerived.kd")); + test(k.ice_name().equals("Test::KnownDerived")); + } + catch(Exception ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_knownDerivedAsKnownDerivedI + extends Callback_TestIntf_knownDerivedAsKnownDerived + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(KnownDerived k) + { + test(k.b.equals("KnownDerived.b")); + test(k.kd.equals("KnownDerived.kd")); + test(k.ice_name().equals("Test::KnownDerived")); + } + catch(Exception ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_unknownIntermediateAsBaseI + extends Callback_TestIntf_unknownIntermediateAsBase + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(Base b) + { + test(b.b.equals("UnknownIntermediate.b")); + test(b.ice_name().equals("Test::Base")); + } + catch(Exception ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_knownIntermediateAsBaseI extends Callback_TestIntf_knownIntermediateAsBase + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(KnownIntermediate ki) + { + test(ki.b.equals("KnownIntermediate.b")); + test(ki.ki.equals("KnownIntermediate.ki")); + test(ki.ice_name().equals("Test::KnownIntermediate")); + } + catch(Exception ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_knownMostDerivedAsBaseI extends Callback_TestIntf_knownMostDerivedAsBase + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(KnownMostDerived kmd) + { + test(kmd.b.equals("KnownMostDerived.b")); + test(kmd.ki.equals("KnownMostDerived.ki")); + test(kmd.kmd.equals("KnownMostDerived.kmd")); + test(kmd.ice_name().equals("Test::KnownMostDerived")); + } + catch(Exception ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_knownIntermediateAsKnownIntermediateI + extends Callback_TestIntf_knownIntermediateAsKnownIntermediate + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(KnownIntermediate ki) + { + test(ki.b.equals("KnownIntermediate.b")); + test(ki.ki.equals("KnownIntermediate.ki")); + test(ki.ice_name().equals("Test::KnownIntermediate")); + } + catch(Exception ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_knownMostDerivedAsKnownIntermediateI + extends Callback_TestIntf_knownMostDerivedAsKnownIntermediate + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(KnownMostDerived kmd) + { + test(kmd.b.equals("KnownMostDerived.b")); + test(kmd.ki.equals("KnownMostDerived.ki")); + test(kmd.kmd.equals("KnownMostDerived.kmd")); + test(kmd.ice_name().equals("Test::KnownMostDerived")); + } + catch(Exception ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_knownMostDerivedAsKnownMostDerivedI + extends Callback_TestIntf_knownMostDerivedAsKnownMostDerived + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(KnownMostDerived kmd) + { + test(kmd.b.equals("KnownMostDerived.b")); + test(kmd.ki.equals("KnownMostDerived.ki")); + test(kmd.kmd.equals("KnownMostDerived.kmd")); + test(kmd.ice_name().equals("Test::KnownMostDerived")); + } + catch(Exception ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_unknownMostDerived1AsBaseI + extends Callback_TestIntf_unknownMostDerived1AsBase + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(KnownIntermediate ki) + { + test(ki.b.equals("UnknownMostDerived1.b")); + test(ki.ki.equals("UnknownMostDerived1.ki")); + test(ki.ice_name().equals("Test::KnownIntermediate")); + } + catch(Exception ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_unknownMostDerived1AsKnownIntermediateI + extends Callback_TestIntf_unknownMostDerived1AsKnownIntermediate + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(KnownIntermediate ki) + { + test(ki.b.equals("UnknownMostDerived1.b")); + test(ki.ki.equals("UnknownMostDerived1.ki")); + test(ki.ice_name().equals("Test::KnownIntermediate")); + } + catch(Exception ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_unknownMostDerived2AsBaseI + extends Callback_TestIntf_unknownMostDerived2AsBase + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + throw exc; + } + catch(Base b) + { + test(b.b.equals("UnknownMostDerived2.b")); + test(b.ice_name().equals("Test::Base")); + } + catch(Exception ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class RelayI extends _RelayDisp + { + @Override + public void knownPreservedAsBase(Ice.Current current) + throws Base + { + KnownPreservedDerived ex = new KnownPreservedDerived(); + ex.b = "base"; + ex.kp = "preserved"; + ex.kpd = "derived"; + throw ex; + } + + @Override + public void knownPreservedAsKnownPreserved(Ice.Current current) + throws KnownPreserved + { + KnownPreservedDerived ex = new KnownPreservedDerived(); + ex.b = "base"; + ex.kp = "preserved"; + ex.kpd = "derived"; + throw ex; + } + + @Override + public void unknownPreservedAsBase(Ice.Current current) + throws Base + { + Preserved2 ex = new Preserved2(); + ex.b = "base"; + ex.kp = "preserved"; + ex.kpd = "derived"; + ex.p1 = new PreservedClass("bc", "pc"); + ex.p2 = ex.p1; + throw ex; + } + + @Override + public void unknownPreservedAsKnownPreserved(Ice.Current current) + throws KnownPreserved + { + Preserved2 ex = new Preserved2(); + ex.b = "base"; + ex.kp = "preserved"; + ex.kpd = "derived"; + ex.p1 = new PreservedClass("bc", "pc"); + ex.p2 = ex.p1; + throw ex; + } + } + + public static TestIntfPrx + allTests(Ice.Communicator communicator, boolean collocated, java.io.PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + String ref = "Test:default -p 12010 -t 10000"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + TestIntfPrx test = TestIntfPrxHelper.checkedCast(base); + test(test != null); + test(test.equals(base)); + out.println("ok"); + + out.print("base... "); + out.flush(); + { + try + { + test.baseAsBase(); + test(false); + } + catch(Base b) + { + test(b.b.equals("Base.b")); + test(b.ice_name().equals("Test::Base")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("base (AMI)... "); + out.flush(); + { + Callback_TestIntf_baseAsBaseI cb = new Callback_TestIntf_baseAsBaseI(); + test.begin_baseAsBase(cb); + cb.check(); + } + out.println("ok"); + + out.print("slicing of unknown derived... "); + out.flush(); + { + try + { + test.unknownDerivedAsBase(); + test(false); + } + catch(Base b) + { + test(b.b.equals("UnknownDerived.b")); + test(b.ice_name().equals("Test::Base")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("slicing of unknown derived (AMI)... "); + out.flush(); + { + Callback_TestIntf_unknownDerivedAsBaseI cb = new Callback_TestIntf_unknownDerivedAsBaseI(); + test.begin_unknownDerivedAsBase(cb); + cb.check(); + } + out.println("ok"); + + out.print("non-slicing of known derived as base... "); + out.flush(); + { + try + { + test.knownDerivedAsBase(); + test(false); + } + catch(KnownDerived k) + { + test(k.b.equals("KnownDerived.b")); + test(k.kd.equals("KnownDerived.kd")); + test(k.ice_name().equals("Test::KnownDerived")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("non-slicing of known derived as base (AMI)... "); + out.flush(); + { + Callback_TestIntf_knownDerivedAsBaseI cb = new Callback_TestIntf_knownDerivedAsBaseI(); + test.begin_knownDerivedAsBase(cb); + cb.check(); + } + out.println("ok"); + + out.print("non-slicing of known derived as derived... "); + out.flush(); + { + try + { + test.knownDerivedAsKnownDerived(); + test(false); + } + catch(KnownDerived k) + { + test(k.b.equals("KnownDerived.b")); + test(k.kd.equals("KnownDerived.kd")); + test(k.ice_name().equals("Test::KnownDerived")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("non-slicing of known derived as derived (AMI)... "); + out.flush(); + { + Callback_TestIntf_knownDerivedAsKnownDerivedI cb = new Callback_TestIntf_knownDerivedAsKnownDerivedI(); + test.begin_knownDerivedAsKnownDerived(cb); + cb.check(); + } + out.println("ok"); + + out.print("slicing of unknown intermediate as base... "); + out.flush(); + { + try + { + test.unknownIntermediateAsBase(); + test(false); + } + catch(Base b) + { + test(b.b.equals("UnknownIntermediate.b")); + test(b.ice_name().equals("Test::Base")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("slicing of unknown intermediate as base (AMI)... "); + out.flush(); + { + Callback_TestIntf_unknownIntermediateAsBaseI cb = new Callback_TestIntf_unknownIntermediateAsBaseI(); + test.begin_unknownIntermediateAsBase(cb); + cb.check(); + } + out.println("ok"); + + out.print("slicing of known intermediate as base... "); + out.flush(); + { + try + { + test.knownIntermediateAsBase(); + test(false); + } + catch(KnownIntermediate ki) + { + test(ki.b.equals("KnownIntermediate.b")); + test(ki.ki.equals("KnownIntermediate.ki")); + test(ki.ice_name().equals("Test::KnownIntermediate")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("slicing of known intermediate as base (AMI)... "); + out.flush(); + { + Callback_TestIntf_knownIntermediateAsBaseI cb = new Callback_TestIntf_knownIntermediateAsBaseI(); + test.begin_knownIntermediateAsBase(cb); + cb.check(); + } + out.println("ok"); + + out.print("slicing of known most derived as base... "); + out.flush(); + { + try + { + test.knownMostDerivedAsBase(); + test(false); + } + catch(KnownMostDerived kmd) + { + test(kmd.b.equals("KnownMostDerived.b")); + test(kmd.ki.equals("KnownMostDerived.ki")); + test(kmd.kmd.equals("KnownMostDerived.kmd")); + test(kmd.ice_name().equals("Test::KnownMostDerived")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("slicing of known most derived as base (AMI)... "); + out.flush(); + { + Callback_TestIntf_knownMostDerivedAsBaseI cb = new Callback_TestIntf_knownMostDerivedAsBaseI(); + test.begin_knownMostDerivedAsBase(cb); + cb.check(); + } + out.println("ok"); + + out.print("non-slicing of known intermediate as intermediate... "); + out.flush(); + { + try + { + test.knownIntermediateAsKnownIntermediate(); + test(false); + } + catch(KnownIntermediate ki) + { + test(ki.b.equals("KnownIntermediate.b")); + test(ki.ki.equals("KnownIntermediate.ki")); + test(ki.ice_name().equals("Test::KnownIntermediate")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("non-slicing of known intermediate as intermediate (AMI)... "); + out.flush(); + { + Callback_TestIntf_knownIntermediateAsKnownIntermediateI cb = + new Callback_TestIntf_knownIntermediateAsKnownIntermediateI(); + test.begin_knownIntermediateAsKnownIntermediate(cb); + cb.check(); + } + out.println("ok"); + + out.print("non-slicing of known most derived as intermediate... "); + out.flush(); + { + try + { + test.knownMostDerivedAsKnownIntermediate(); + test(false); + } + catch(KnownMostDerived kmd) + { + test(kmd.b.equals("KnownMostDerived.b")); + test(kmd.ki.equals("KnownMostDerived.ki")); + test(kmd.kmd.equals("KnownMostDerived.kmd")); + test(kmd.ice_name().equals("Test::KnownMostDerived")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("non-slicing of known most derived as intermediate (AMI)... "); + out.flush(); + { + Callback_TestIntf_knownMostDerivedAsKnownIntermediateI cb = + new Callback_TestIntf_knownMostDerivedAsKnownIntermediateI(); + test.begin_knownMostDerivedAsKnownIntermediate(cb); + cb.check(); + } + out.println("ok"); + + out.print("non-slicing of known most derived as most derived... "); + out.flush(); + { + try + { + test.knownMostDerivedAsKnownMostDerived(); + test(false); + } + catch(KnownMostDerived kmd) + { + test(kmd.b.equals("KnownMostDerived.b")); + test(kmd.ki.equals("KnownMostDerived.ki")); + test(kmd.kmd.equals("KnownMostDerived.kmd")); + test(kmd.ice_name().equals("Test::KnownMostDerived")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("non-slicing of known most derived as most derived (AMI)... "); + out.flush(); + { + Callback_TestIntf_knownMostDerivedAsKnownMostDerivedI cb = + new Callback_TestIntf_knownMostDerivedAsKnownMostDerivedI(); + test.begin_knownMostDerivedAsKnownMostDerived(cb); + cb.check(); + } + out.println("ok"); + + out.print("slicing of unknown most derived, known intermediate as base... "); + out.flush(); + { + try + { + test.unknownMostDerived1AsBase(); + test(false); + } + catch(KnownIntermediate ki) + { + test(ki.b.equals("UnknownMostDerived1.b")); + test(ki.ki.equals("UnknownMostDerived1.ki")); + test(ki.ice_name().equals("Test::KnownIntermediate")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("slicing of unknown most derived, known intermediate as base (AMI)... "); + out.flush(); + { + Callback_TestIntf_unknownMostDerived1AsBaseI cb = new Callback_TestIntf_unknownMostDerived1AsBaseI(); + test.begin_unknownMostDerived1AsBase(cb); + cb.check(); + } + out.println("ok"); + + out.print("slicing of unknown most derived, known intermediate as intermediate... "); + out.flush(); + { + try + { + test.unknownMostDerived1AsKnownIntermediate(); + test(false); + } + catch(KnownIntermediate ki) + { + test(ki.b.equals("UnknownMostDerived1.b")); + test(ki.ki.equals("UnknownMostDerived1.ki")); + test(ki.ice_name().equals("Test::KnownIntermediate")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("slicing of unknown most derived, known intermediate as intermediate (AMI)... "); + out.flush(); + { + Callback_TestIntf_unknownMostDerived1AsKnownIntermediateI cb = + new Callback_TestIntf_unknownMostDerived1AsKnownIntermediateI(); + test.begin_unknownMostDerived1AsKnownIntermediate(cb); + cb.check(); + } + out.println("ok"); + + out.print("slicing of unknown most derived, unknown intermediate thrown as base... "); + out.flush(); + { + try + { + test.unknownMostDerived2AsBase(); + test(false); + } + catch(Base b) + { + test(b.b.equals("UnknownMostDerived2.b")); + test(b.ice_name().equals("Test::Base")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("slicing of unknown most derived, unknown intermediate thrown as base (AMI)... "); + out.flush(); + { + Callback_TestIntf_unknownMostDerived2AsBaseI cb = new Callback_TestIntf_unknownMostDerived2AsBaseI(); + test.begin_unknownMostDerived2AsBase(cb); + cb.check(); + } + out.println("ok"); + + out.print("unknown most derived in compact format... "); + out.flush(); + { + try + { + test.unknownMostDerived2AsBaseCompact(); + test(false); + } + catch(Base ex) + { + // + // For the 1.0 encoding, the unknown exception is sliced to Base. + // + test(test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)); + } + catch(Ice.UnknownUserException ex) + { + // + // An UnknownUserException is raised for the compact format because the + // most-derived type is unknown and the exception cannot be sliced. + // + test(!test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)); + } + catch(Ice.OperationNotExistException ex) + { + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("preserved exceptions... "); + out.flush(); + { + Ice.ObjectAdapter adapter = communicator.createObjectAdapterWithEndpoints("Relay", "default"); + RelayPrx relay = RelayPrxHelper.uncheckedCast(adapter.addWithUUID(new RelayI())); + adapter.activate(); + + try + { + test.relayKnownPreservedAsBase(relay); + test(false); + } + catch(KnownPreservedDerived ex) + { + test(ex.b.equals("base")); + test(ex.kp.equals("preserved")); + test(ex.kpd.equals("derived")); + } + catch(Ice.OperationNotExistException ex) + { + } + catch(Exception ex) + { + test(false); + } + + try + { + test.relayKnownPreservedAsKnownPreserved(relay); + test(false); + } + catch(KnownPreservedDerived ex) + { + test(ex.b.equals("base")); + test(ex.kp.equals("preserved")); + test(ex.kpd.equals("derived")); + } + catch(Ice.OperationNotExistException ex) + { + } + catch(Exception ex) + { + test(false); + } + + try + { + test.relayUnknownPreservedAsBase(relay); + test(false); + } + catch(Preserved2 ex) + { + test(ex.b.equals("base")); + test(ex.kp.equals("preserved")); + test(ex.kpd.equals("derived")); + test(ex.p1.ice_id().equals(PreservedClass.ice_staticId())); + PreservedClass pc = (PreservedClass)ex.p1; + test(pc.bc.equals("bc")); + test(pc.pc.equals("pc")); + test(ex.p2 == ex.p1); + } + catch(KnownPreservedDerived ex) + { + // + // For the 1.0 encoding, the unknown exception is sliced to KnownPreserved. + // + test(test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)); + test(ex.b.equals("base")); + test(ex.kp.equals("preserved")); + test(ex.kpd.equals("derived")); + } + catch(Ice.OperationNotExistException ex) + { + } + catch(Exception ex) + { + test(false); + } + + try + { + test.relayUnknownPreservedAsKnownPreserved(relay); + test(false); + } + catch(Preserved2 ex) + { + test(ex.b.equals("base")); + test(ex.kp.equals("preserved")); + test(ex.kpd.equals("derived")); + test(ex.p1.ice_id().equals(PreservedClass.ice_staticId())); + PreservedClass pc = (PreservedClass)ex.p1; + test(pc.bc.equals("bc")); + test(pc.pc.equals("pc")); + test(ex.p2 == ex.p1); + } + catch(KnownPreservedDerived ex) + { + // + // For the 1.0 encoding, the unknown exception is sliced to KnownPreserved. + // + test(test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)); + test(ex.b.equals("base")); + test(ex.kp.equals("preserved")); + test(ex.kpd.equals("derived")); + } + catch(Ice.OperationNotExistException ex) + { + } + catch(Exception ex) + { + test(false); + } + + adapter.destroy(); + } + out.println("ok"); + + return test; + } +} diff --git a/java/test/src/main/java/test/Ice/slicing/exceptions/Client.java b/java/test/src/main/java/test/Ice/slicing/exceptions/Client.java new file mode 100644 index 00000000000..bee392fe3b3 --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/exceptions/Client.java @@ -0,0 +1,41 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.slicing.exceptions; + +import test.Ice.slicing.exceptions.client.Test.TestIntfPrx; + +public class Client extends test.Util.Application +{ + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.slicing.exceptions.client"); + return initData; + } + + @Override + public int run(String[] args) + { + TestIntfPrx test = AllTests.allTests(communicator(), false, getWriter()); + test.shutdown(); + return 0; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/slicing/exceptions/ClientPrivate.ice b/java/test/src/main/java/test/Ice/slicing/exceptions/ClientPrivate.ice new file mode 100644 index 00000000000..703399d8502 --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/exceptions/ClientPrivate.ice @@ -0,0 +1,123 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.slicing.exceptions.client"]] +module Test +{ + +// +// Duplicate types from Test.ice. We cannot use #include since +// that will use the types from the same prefix. +// + +exception Base +{ + string b; +}; + +exception KnownDerived extends Base +{ + string kd; +}; + +exception KnownIntermediate extends Base +{ + string ki; +}; + +exception KnownMostDerived extends KnownIntermediate +{ + string kmd; +}; + +["preserve-slice"] +exception KnownPreserved extends Base +{ + string kp; +}; + +exception KnownPreservedDerived extends KnownPreserved +{ + string kpd; +}; + +["preserve-slice"] +class BaseClass +{ + string bc; +}; + +["format:sliced"] +interface Relay +{ + void knownPreservedAsBase() throws Base; + void knownPreservedAsKnownPreserved() throws KnownPreserved; + + void unknownPreservedAsBase() throws Base; + void unknownPreservedAsKnownPreserved() throws KnownPreserved; +}; + +["format:sliced"] +interface TestIntf +{ + void baseAsBase() throws Base; + void unknownDerivedAsBase() throws Base; + void knownDerivedAsBase() throws Base; + void knownDerivedAsKnownDerived() throws KnownDerived; + + void unknownIntermediateAsBase() throws Base; + void knownIntermediateAsBase() throws Base; + void knownMostDerivedAsBase() throws Base; + void knownIntermediateAsKnownIntermediate() throws KnownIntermediate; + void knownMostDerivedAsKnownIntermediate() throws KnownIntermediate; + void knownMostDerivedAsKnownMostDerived() throws KnownMostDerived; + + void unknownMostDerived1AsBase() throws Base; + void unknownMostDerived1AsKnownIntermediate() throws KnownIntermediate; + void unknownMostDerived2AsBase() throws Base; + + ["format:compact"] void unknownMostDerived2AsBaseCompact() throws Base; + + void knownPreservedAsBase() throws Base; + void knownPreservedAsKnownPreserved() throws KnownPreserved; + + void relayKnownPreservedAsBase(Relay* r) throws Base; + void relayKnownPreservedAsKnownPreserved(Relay* r) throws KnownPreserved; + + void unknownPreservedAsBase() throws Base; + void unknownPreservedAsKnownPreserved() throws KnownPreserved; + + void relayUnknownPreservedAsBase(Relay* r) throws Base; + void relayUnknownPreservedAsKnownPreserved(Relay* r) throws KnownPreserved; + + void shutdown(); +}; + +// +// Types private to the client. +// + +class PreservedClass extends BaseClass +{ + string pc; +}; + +exception Preserved1 extends KnownPreservedDerived +{ + BaseClass p1; +}; + +exception Preserved2 extends Preserved1 +{ + BaseClass p2; +}; + +}; diff --git a/java/test/src/main/java/test/Ice/slicing/exceptions/Server.java b/java/test/src/main/java/test/Ice/slicing/exceptions/Server.java new file mode 100644 index 00000000000..0844dd92275 --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/exceptions/Server.java @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.slicing.exceptions; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + Ice.Object object = new TestI(); + adapter.add(object, Ice.Util.stringToIdentity("Test")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.slicing.exceptions.server"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010 -t 2000"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/slicing/exceptions/ServerPrivate.ice b/java/test/src/main/java/test/Ice/slicing/exceptions/ServerPrivate.ice new file mode 100644 index 00000000000..d12869fb451 --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/exceptions/ServerPrivate.ice @@ -0,0 +1,143 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.slicing.exceptions.server"]] +module Test +{ + +// +// Duplicate types from Test.ice. We cannot use #include since +// that will use the types from the same prefix. +// + +exception Base +{ + string b; +}; + +exception KnownDerived extends Base +{ + string kd; +}; + +exception KnownIntermediate extends Base +{ + string ki; +}; + +exception KnownMostDerived extends KnownIntermediate +{ + string kmd; +}; + +["preserve-slice"] +exception KnownPreserved extends Base +{ + string kp; +}; + +exception KnownPreservedDerived extends KnownPreserved +{ + string kpd; +}; + +["preserve-slice"] +class BaseClass +{ + string bc; +}; + +["format:sliced"] +interface Relay +{ + void knownPreservedAsBase() throws Base; + void knownPreservedAsKnownPreserved() throws KnownPreserved; + + void unknownPreservedAsBase() throws Base; + void unknownPreservedAsKnownPreserved() throws KnownPreserved; +}; + +["format:sliced"] +interface TestIntf +{ + void baseAsBase() throws Base; + void unknownDerivedAsBase() throws Base; + void knownDerivedAsBase() throws Base; + void knownDerivedAsKnownDerived() throws KnownDerived; + + void unknownIntermediateAsBase() throws Base; + void knownIntermediateAsBase() throws Base; + void knownMostDerivedAsBase() throws Base; + void knownIntermediateAsKnownIntermediate() throws KnownIntermediate; + void knownMostDerivedAsKnownIntermediate() throws KnownIntermediate; + void knownMostDerivedAsKnownMostDerived() throws KnownMostDerived; + + void unknownMostDerived1AsBase() throws Base; + void unknownMostDerived1AsKnownIntermediate() throws KnownIntermediate; + void unknownMostDerived2AsBase() throws Base; + + ["format:compact"] void unknownMostDerived2AsBaseCompact() throws Base; + + void knownPreservedAsBase() throws Base; + void knownPreservedAsKnownPreserved() throws KnownPreserved; + + void relayKnownPreservedAsBase(Relay* r) throws Base; + void relayKnownPreservedAsKnownPreserved(Relay* r) throws KnownPreserved; + + void unknownPreservedAsBase() throws Base; + void unknownPreservedAsKnownPreserved() throws KnownPreserved; + + void relayUnknownPreservedAsBase(Relay* r) throws Base; + void relayUnknownPreservedAsKnownPreserved(Relay* r) throws KnownPreserved; + + void shutdown(); +}; + +// +// Types private to the server. +// + +exception UnknownDerived extends Base +{ + string ud; +}; + +exception UnknownIntermediate extends Base +{ + string ui; +}; + +exception UnknownMostDerived1 extends KnownIntermediate +{ + string umd1; +}; + +exception UnknownMostDerived2 extends UnknownIntermediate +{ + string umd2; +}; + +class SPreservedClass extends BaseClass +{ + string spc; +}; + +exception SPreserved1 extends KnownPreservedDerived +{ + BaseClass p1; +}; + +exception SPreserved2 extends SPreserved1 +{ + BaseClass p2; +}; + +}; diff --git a/java/test/src/main/java/test/Ice/slicing/exceptions/ServerPrivateAMD.ice b/java/test/src/main/java/test/Ice/slicing/exceptions/ServerPrivateAMD.ice new file mode 100644 index 00000000000..ff2ee33b93e --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/exceptions/ServerPrivateAMD.ice @@ -0,0 +1,143 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.slicing.exceptions.serverAMD"]] +module Test +{ + +// +// Duplicate types from Test.ice. We cannot use #include since +// that will use the types from the same prefix. +// + +exception Base +{ + string b; +}; + +exception KnownDerived extends Base +{ + string kd; +}; + +exception KnownIntermediate extends Base +{ + string ki; +}; + +exception KnownMostDerived extends KnownIntermediate +{ + string kmd; +}; + +["preserve-slice"] +exception KnownPreserved extends Base +{ + string kp; +}; + +exception KnownPreservedDerived extends KnownPreserved +{ + string kpd; +}; + +["preserve-slice"] +class BaseClass +{ + string bc; +}; + +["format:sliced"] +interface Relay +{ + void knownPreservedAsBase() throws Base; + void knownPreservedAsKnownPreserved() throws KnownPreserved; + + void unknownPreservedAsBase() throws Base; + void unknownPreservedAsKnownPreserved() throws KnownPreserved; +}; + +["amd", "format:sliced"] +interface TestIntf +{ + void baseAsBase() throws Base; + void unknownDerivedAsBase() throws Base; + void knownDerivedAsBase() throws Base; + void knownDerivedAsKnownDerived() throws KnownDerived; + + void unknownIntermediateAsBase() throws Base; + void knownIntermediateAsBase() throws Base; + void knownMostDerivedAsBase() throws Base; + void knownIntermediateAsKnownIntermediate() throws KnownIntermediate; + void knownMostDerivedAsKnownIntermediate() throws KnownIntermediate; + void knownMostDerivedAsKnownMostDerived() throws KnownMostDerived; + + void unknownMostDerived1AsBase() throws Base; + void unknownMostDerived1AsKnownIntermediate() throws KnownIntermediate; + void unknownMostDerived2AsBase() throws Base; + + ["format:compact"] void unknownMostDerived2AsBaseCompact() throws Base; + + void knownPreservedAsBase() throws Base; + void knownPreservedAsKnownPreserved() throws KnownPreserved; + + void relayKnownPreservedAsBase(Relay* r) throws Base; + void relayKnownPreservedAsKnownPreserved(Relay* r) throws KnownPreserved; + + void unknownPreservedAsBase() throws Base; + void unknownPreservedAsKnownPreserved() throws KnownPreserved; + + void relayUnknownPreservedAsBase(Relay* r) throws Base; + void relayUnknownPreservedAsKnownPreserved(Relay* r) throws KnownPreserved; + + void shutdown(); +}; + +// +// Types private to the server. +// + +exception UnknownDerived extends Base +{ + string ud; +}; + +exception UnknownIntermediate extends Base +{ + string ui; +}; + +exception UnknownMostDerived1 extends KnownIntermediate +{ + string umd1; +}; + +exception UnknownMostDerived2 extends UnknownIntermediate +{ + string umd2; +}; + +class SPreservedClass extends BaseClass +{ + string spc; +}; + +exception SPreserved1 extends KnownPreservedDerived +{ + BaseClass p1; +}; + +exception SPreserved2 extends SPreserved1 +{ + BaseClass p2; +}; + +}; diff --git a/java/test/src/main/java/test/Ice/slicing/exceptions/TestI.java b/java/test/src/main/java/test/Ice/slicing/exceptions/TestI.java new file mode 100644 index 00000000000..9cedab3b4af --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/exceptions/TestI.java @@ -0,0 +1,279 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.slicing.exceptions; + +import test.Ice.slicing.exceptions.server.Test.*; + +public final class TestI extends _TestIntfDisp +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + @Override + public void + baseAsBase(Ice.Current current) + throws Base + { + Base b = new Base(); + b.b = "Base.b"; + throw b; + } + + @Override + public void + unknownDerivedAsBase(Ice.Current current) + throws Base + { + UnknownDerived d = new UnknownDerived(); + d.b = "UnknownDerived.b"; + d.ud = "UnknownDerived.ud"; + throw d; + } + + @Override + public void + knownDerivedAsBase(Ice.Current current) + throws Base + { + KnownDerived d = new KnownDerived(); + d.b = "KnownDerived.b"; + d.kd = "KnownDerived.kd"; + throw d; + } + + @Override + public void + knownDerivedAsKnownDerived(Ice.Current current) + throws KnownDerived + { + KnownDerived d = new KnownDerived(); + d.b = "KnownDerived.b"; + d.kd = "KnownDerived.kd"; + throw d; + } + + @Override + public void + unknownIntermediateAsBase(Ice.Current current) + throws Base + { + UnknownIntermediate ui = new UnknownIntermediate(); + ui.b = "UnknownIntermediate.b"; + ui.ui = "UnknownIntermediate.ui"; + throw ui; + } + + @Override + public void + knownIntermediateAsBase(Ice.Current current) + throws Base + { + KnownIntermediate ki = new KnownIntermediate(); + ki.b = "KnownIntermediate.b"; + ki.ki = "KnownIntermediate.ki"; + throw ki; + } + + @Override + public void + knownMostDerivedAsBase(Ice.Current current) + throws Base + { + KnownMostDerived kmd = new KnownMostDerived(); + kmd.b = "KnownMostDerived.b"; + kmd.ki = "KnownMostDerived.ki"; + kmd.kmd = "KnownMostDerived.kmd"; + throw kmd; + } + + @Override + public void + knownIntermediateAsKnownIntermediate(Ice.Current current) + throws KnownIntermediate + { + KnownIntermediate ki = new KnownIntermediate(); + ki.b = "KnownIntermediate.b"; + ki.ki = "KnownIntermediate.ki"; + throw ki; + } + + @Override + public void + knownMostDerivedAsKnownIntermediate(Ice.Current current) + throws KnownIntermediate + { + KnownMostDerived kmd = new KnownMostDerived(); + kmd.b = "KnownMostDerived.b"; + kmd.ki = "KnownMostDerived.ki"; + kmd.kmd = "KnownMostDerived.kmd"; + throw kmd; + } + + @Override + public void + knownMostDerivedAsKnownMostDerived(Ice.Current current) + throws KnownMostDerived + { + KnownMostDerived kmd = new KnownMostDerived(); + kmd.b = "KnownMostDerived.b"; + kmd.ki = "KnownMostDerived.ki"; + kmd.kmd = "KnownMostDerived.kmd"; + throw kmd; + } + + @Override + public void + unknownMostDerived1AsBase(Ice.Current current) + throws Base + { + UnknownMostDerived1 umd1 = new UnknownMostDerived1(); + umd1.b = "UnknownMostDerived1.b"; + umd1.ki = "UnknownMostDerived1.ki"; + umd1.umd1 = "UnknownMostDerived1.umd1"; + throw umd1; + } + + @Override + public void + unknownMostDerived1AsKnownIntermediate(Ice.Current current) + throws KnownIntermediate + { + UnknownMostDerived1 umd1 = new UnknownMostDerived1(); + umd1.b = "UnknownMostDerived1.b"; + umd1.ki = "UnknownMostDerived1.ki"; + umd1.umd1 = "UnknownMostDerived1.umd1"; + throw umd1; + } + + @Override + public void + unknownMostDerived2AsBase(Ice.Current current) + throws Base + { + UnknownMostDerived2 umd2 = new UnknownMostDerived2(); + umd2.b = "UnknownMostDerived2.b"; + umd2.ui = "UnknownMostDerived2.ui"; + umd2.umd2 = "UnknownMostDerived2.umd2"; + throw umd2; + } + + @Override + public void + unknownMostDerived2AsBaseCompact(Ice.Current current) + throws Base + { + UnknownMostDerived2 umd2 = new UnknownMostDerived2(); + umd2.b = "UnknownMostDerived2.b"; + umd2.ui = "UnknownMostDerived2.ui"; + umd2.umd2 = "UnknownMostDerived2.umd2"; + throw umd2; + } + + @Override + public void + knownPreservedAsBase(Ice.Current current) + throws Base + { + KnownPreservedDerived ex = new KnownPreservedDerived(); + ex.b = "base"; + ex.kp = "preserved"; + ex.kpd = "derived"; + throw ex; + } + + @Override + public void + knownPreservedAsKnownPreserved(Ice.Current current) + throws KnownPreserved + { + KnownPreservedDerived ex = new KnownPreservedDerived(); + ex.b = "base"; + ex.kp = "preserved"; + ex.kpd = "derived"; + throw ex; + } + + @Override + public void + relayKnownPreservedAsBase(RelayPrx r, Ice.Current current) + throws Base + { + r.knownPreservedAsBase(); + test(false); + } + + @Override + public void + relayKnownPreservedAsKnownPreserved(RelayPrx r, Ice.Current current) + throws KnownPreserved + { + r.knownPreservedAsKnownPreserved(); + test(false); + } + + @Override + public void + unknownPreservedAsBase(Ice.Current current) + throws Base + { + SPreserved2 ex = new SPreserved2(); + ex.b = "base"; + ex.kp = "preserved"; + ex.kpd = "derived"; + ex.p1 = new SPreservedClass("bc", "spc"); + ex.p2 = ex.p1; + throw ex; + } + + @Override + public void + unknownPreservedAsKnownPreserved(Ice.Current current) + throws KnownPreserved + { + SPreserved2 ex = new SPreserved2(); + ex.b = "base"; + ex.kp = "preserved"; + ex.kpd = "derived"; + ex.p1 = new SPreservedClass("bc", "spc"); + ex.p2 = ex.p1; + throw ex; + } + + @Override + public void + relayUnknownPreservedAsBase(RelayPrx r, Ice.Current current) + throws Base + { + r.unknownPreservedAsBase(); + test(false); + } + + @Override + public void + relayUnknownPreservedAsKnownPreserved(RelayPrx r, Ice.Current current) + throws KnownPreserved + { + r.unknownPreservedAsKnownPreserved(); + test(false); + } +} diff --git a/java/test/src/main/java/test/Ice/slicing/exceptions/run.py b/java/test/src/main/java/test/Ice/slicing/exceptions/run.py new file mode 100755 index 00000000000..e4130c0b4e6 --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/exceptions/run.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("Running test with sliced format.") +TestUtil.clientServerTest() + +print("Running test with 1.0 encoding.") +TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.EncodingVersion=1.0", + additionalServerOptions="--Ice.Default.EncodingVersion=1.0") + +print("Running test with sliced format and AMD server.") +TestUtil.clientServerTest(server="test.Ice.slicing.exceptions.AMDServer") + +print("Running test with 1.0 encoding and AMD server.") +TestUtil.clientServerTest(server="test.Ice.slicing.exceptions.AMDServer", + additionalClientOptions="--Ice.Default.EncodingVersion=1.0", + additionalServerOptions="--Ice.Default.EncodingVersion=1.0") diff --git a/java/test/src/main/java/test/Ice/slicing/objects/AMDServer.java b/java/test/src/main/java/test/Ice/slicing/objects/AMDServer.java new file mode 100644 index 00000000000..c905976b193 --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/objects/AMDServer.java @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.slicing.objects; + +public class AMDServer extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object object = new AMDTestI(); + adapter.add(object, communicator.stringToIdentity("Test")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.slicing.objects.serverAMD"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010 -t 2000"); + return initData; + } + + public static void main(String[] args) + { + AMDServer app = new AMDServer(); + int result = app.main("AMDServer", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/slicing/objects/AMDTestI.java b/java/test/src/main/java/test/Ice/slicing/objects/AMDTestI.java new file mode 100644 index 00000000000..f1c9e814a9b --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/objects/AMDTestI.java @@ -0,0 +1,571 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.slicing.objects; + +import test.Ice.slicing.objects.serverAMD.Test.*; + +public final class AMDTestI extends _TestIntfDisp +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + @Override + public void + shutdown_async(AMD_TestIntf_shutdown cb, Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + cb.ice_response(); + } + + @Override + public void + SBaseAsObject_async(AMD_TestIntf_SBaseAsObject cb, Ice.Current current) + { + SBase sb = new SBase(); + sb.sb = "SBase.sb"; + cb.ice_response(sb); + } + + @Override + public void + SBaseAsSBase_async(AMD_TestIntf_SBaseAsSBase cb, Ice.Current current) + { + SBase sb = new SBase(); + sb.sb = "SBase.sb"; + cb.ice_response(sb); + } + + @Override + public void + SBSKnownDerivedAsSBase_async(AMD_TestIntf_SBSKnownDerivedAsSBase cb, Ice.Current current) + { + SBSKnownDerived sbskd = new SBSKnownDerived(); + sbskd.sb = "SBSKnownDerived.sb"; + sbskd.sbskd = "SBSKnownDerived.sbskd"; + cb.ice_response(sbskd); + } + + @Override + public void + SBSKnownDerivedAsSBSKnownDerived_async(AMD_TestIntf_SBSKnownDerivedAsSBSKnownDerived cb, Ice.Current current) + { + SBSKnownDerived sbskd = new SBSKnownDerived(); + sbskd.sb = "SBSKnownDerived.sb"; + sbskd.sbskd = "SBSKnownDerived.sbskd"; + cb.ice_response(sbskd); + } + + @Override + public void + SBSUnknownDerivedAsSBase_async(AMD_TestIntf_SBSUnknownDerivedAsSBase cb, Ice.Current current) + { + SBSUnknownDerived sbsud = new SBSUnknownDerived(); + sbsud.sb = "SBSUnknownDerived.sb"; + sbsud.sbsud = "SBSUnknownDerived.sbsud"; + cb.ice_response(sbsud); + } + + @Override + public void + SBSUnknownDerivedAsSBaseCompact_async(AMD_TestIntf_SBSUnknownDerivedAsSBaseCompact cb, Ice.Current current) + { + SBSUnknownDerived sbsud = new SBSUnknownDerived(); + sbsud.sb = "SBSUnknownDerived.sb"; + sbsud.sbsud = "SBSUnknownDerived.sbsud"; + cb.ice_response(sbsud); + } + + @Override + public void + SUnknownAsObject_async(AMD_TestIntf_SUnknownAsObject cb, Ice.Current current) + { + SUnknown su = new SUnknown(); + su.su = "SUnknown.su"; + cb.ice_response(su); + } + + @Override + public void + checkSUnknown_async(AMD_TestIntf_checkSUnknown cb, Ice.Object obj, Ice.Current current) + { + if(current.encoding.equals(Ice.Util.Encoding_1_0)) + { + test(!(obj instanceof SUnknown)); + } + else + { + SUnknown su = (SUnknown)obj; + test(su.su.equals("SUnknown.su")); + } + cb.ice_response(); + } + + @Override + public void + oneElementCycle_async(AMD_TestIntf_oneElementCycle cb, Ice.Current current) + { + B b = new B(); + b.sb = "B1.sb"; + b.pb = b; + cb.ice_response(b); + } + + @Override + public void + twoElementCycle_async(AMD_TestIntf_twoElementCycle cb, Ice.Current current) + { + B b1 = new B(); + b1.sb = "B1.sb"; + B b2 = new B(); + b2.sb = "B2.sb"; + b2.pb = b1; + b1.pb = b2; + cb.ice_response(b1); + } + + @Override + public void + D1AsB_async(AMD_TestIntf_D1AsB cb, Ice.Current current) + { + D1 d1 = new D1(); + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + D2 d2 = new D2(); + d2.pb = d1; + d2.sb = "D2.sb"; + d2.sd2 = "D2.sd2"; + d2.pd2 = d1; + d1.pb = d2; + d1.pd1 = d2; + cb.ice_response(d1); + } + + @Override + public void + D1AsD1_async(AMD_TestIntf_D1AsD1 cb, Ice.Current current) + { + D1 d1 = new D1(); + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + D2 d2 = new D2(); + d2.pb = d1; + d2.sb = "D2.sb"; + d2.sd2 = "D2.sd2"; + d2.pd2 = d1; + d1.pb = d2; + d1.pd1 = d2; + cb.ice_response(d1); + } + + @Override + public void + D2AsB_async(AMD_TestIntf_D2AsB cb, Ice.Current current) + { + D2 d2 = new D2(); + d2.sb = "D2.sb"; + d2.sd2 = "D2.sd2"; + D1 d1 = new D1(); + d1.pb = d2; + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + d1.pd1 = d2; + d2.pb = d1; + d2.pd2 = d1; + cb.ice_response(d2); + } + + @Override + public void + paramTest1_async(AMD_TestIntf_paramTest1 cb, Ice.Current current) + { + D1 d1 = new D1(); + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + D2 d2 = new D2(); + d2.pb = d1; + d2.sb = "D2.sb"; + d2.sd2 = "D2.sd2"; + d2.pd2 = d1; + d1.pb = d2; + d1.pd1 = d2; + cb.ice_response(d1, d2); + } + + @Override + public void + paramTest2_async(AMD_TestIntf_paramTest2 cb, Ice.Current current) + { + D1 d1 = new D1(); + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + D2 d2 = new D2(); + d2.pb = d1; + d2.sb = "D2.sb"; + d2.sd2 = "D2.sd2"; + d2.pd2 = d1; + d1.pb = d2; + d1.pd1 = d2; + cb.ice_response(d2, d1); + } + + @Override + public void + paramTest3_async(AMD_TestIntf_paramTest3 cb, Ice.Current current) + { + D2 d2 = new D2(); + d2.sb = "D2.sb (p1 1)"; + d2.pb = null; + d2.sd2 = "D2.sd2 (p1 1)"; + + D1 d1 = new D1(); + d1.sb = "D1.sb (p1 2)"; + d1.pb = null; + d1.sd1 = "D1.sd2 (p1 2)"; + d1.pd1 = null; + d2.pd2 = d1; + + D2 d4 = new D2(); + d4.sb = "D2.sb (p2 1)"; + d4.pb = null; + d4.sd2 = "D2.sd2 (p2 1)"; + + D1 d3 = new D1(); + d3.sb = "D1.sb (p2 2)"; + d3.pb = null; + d3.sd1 = "D1.sd2 (p2 2)"; + d3.pd1 = null; + d4.pd2 = d3; + cb.ice_response(d3, d2, d4); + } + + @Override + public void + paramTest4_async(AMD_TestIntf_paramTest4 cb, Ice.Current current) + { + D4 d4 = new D4(); + d4.sb = "D4.sb (1)"; + d4.pb = null; + d4.p1 = new B(); + d4.p1.sb = "B.sb (1)"; + d4.p2 = new B(); + d4.p2.sb = "B.sb (2)"; + cb.ice_response(d4.p2, d4); + } + + @Override + public void + returnTest1_async(AMD_TestIntf_returnTest1 cb, Ice.Current current) + { + D1 d1 = new D1(); + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + D2 d2 = new D2(); + d2.pb = d1; + d2.sb = "D2.sb"; + d2.sd2 = "D2.sd2"; + d2.pd2 = d1; + d1.pb = d2; + d1.pd1 = d2; + cb.ice_response(d2, d2, d1); + } + + @Override + public void + returnTest2_async(AMD_TestIntf_returnTest2 cb, Ice.Current current) + { + D1 d1 = new D1(); + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + D2 d2 = new D2(); + d2.pb = d1; + d2.sb = "D2.sb"; + d2.sd2 = "D2.sd2"; + d2.pd2 = d1; + d1.pb = d2; + d1.pd1 = d2; + cb.ice_response(d1, d1, d2); + } + + @Override + public void + returnTest3_async(AMD_TestIntf_returnTest3 cb, B p1, B p2, Ice.Current current) + { + cb.ice_response(p1); + } + + @Override + public void + sequenceTest_async(AMD_TestIntf_sequenceTest cb, SS1 p1, SS2 p2, Ice.Current current) + { + SS3 ss = new SS3(); + ss.c1 = p1; + ss.c2 = p2; + cb.ice_response(ss); + } + + @Override + public void + dictionaryTest_async(AMD_TestIntf_dictionaryTest cb, java.util.Map<Integer, B> bin, Ice.Current current) + { + java.util.Map<Integer, B> bout = new java.util.HashMap<Integer, B>(); + int i; + for(i = 0; i < 10; ++i) + { + B b = bin.get(i); + D2 d2 = new D2(); + d2.sb = b.sb; + d2.pb = b.pb; + d2.sd2 = "D2"; + d2.pd2 = d2; + bout.put(i * 10, d2); + } + java.util.Map<Integer, B> r = new java.util.HashMap<Integer, B>(); + for(i = 0; i < 10; ++i) + { + String s = "D1." + new Integer(i * 20).toString(); + D1 d1 = new D1(); + d1.sb = s; + d1.pb = (i == 0 ? null : r.get((i - 1) * 20)); + d1.sd1 = s; + d1.pd1 = d1; + r.put(i * 20, d1); + } + cb.ice_response(r, bout); + } + + @Override + public void + exchangePBase_async(AMD_TestIntf_exchangePBase cb, PBase pb, Ice.Current current) + { + cb.ice_response(pb); + } + + @Override + public void + PBSUnknownAsPreserved_async(AMD_TestIntf_PBSUnknownAsPreserved cb, Ice.Current current) + { + PSUnknown r = new PSUnknown(); + r.pi = 5; + r.ps = "preserved"; + r.psu = "unknown"; + r.graph = null; + if(!current.encoding.equals(Ice.Util.Encoding_1_0)) + { + // + // 1.0 encoding doesn't support unmarshaling unknown classes even if referenced + // from unread slice. + // + r.cl = new MyClass(15); + } + cb.ice_response(r); + } + + @Override + public void + checkPBSUnknown_async(AMD_TestIntf_checkPBSUnknown cb, Preserved p, Ice.Current current) + { + if(current.encoding.equals(Ice.Util.Encoding_1_0)) + { + test(!(p instanceof PSUnknown)); + test(p.pi == 5); + test(p.ps.equals("preserved")); + } + else + { + PSUnknown pu = (PSUnknown)p; + test(pu.pi == 5); + test(pu.ps.equals("preserved")); + test(pu.psu.equals("unknown")); + test(pu.graph == null); + test(pu.cl != null && pu.cl.i == 15); + } + cb.ice_response(); + } + + @Override + public void + PBSUnknownAsPreservedWithGraph_async(AMD_TestIntf_PBSUnknownAsPreservedWithGraph cb, Ice.Current current) + { + PSUnknown r = new PSUnknown(); + r.pi = 5; + r.ps = "preserved"; + r.psu = "unknown"; + r.graph = new PNode(); + r.graph.next = new PNode(); + r.graph.next.next = new PNode(); + r.graph.next.next.next = r.graph; + cb.ice_response(r); + r.graph.next.next.next = null; // Break the cycle. + } + + @Override + public void + checkPBSUnknownWithGraph_async(AMD_TestIntf_checkPBSUnknownWithGraph cb, Preserved p, Ice.Current current) + { + if(current.encoding.equals(Ice.Util.Encoding_1_0)) + { + test(!(p instanceof PSUnknown)); + test(p.pi == 5); + test(p.ps.equals("preserved")); + } + else + { + PSUnknown pu = (PSUnknown)p; + test(pu.pi == 5); + test(pu.ps.equals("preserved")); + test(pu.psu.equals("unknown")); + test(pu.graph != pu.graph.next); + test(pu.graph.next != pu.graph.next.next); + test(pu.graph.next.next.next == pu.graph); + pu.graph.next.next.next = null; // Break the cycle. + } + cb.ice_response(); + } + + @Override + public void + PBSUnknown2AsPreservedWithGraph_async(AMD_TestIntf_PBSUnknown2AsPreservedWithGraph cb, Ice.Current current) + { + PSUnknown2 r = new PSUnknown2(); + r.pi = 5; + r.ps = "preserved"; + r.pb = r; + cb.ice_response(r); + r.pb = null; // Break the cycle. + } + + @Override + public void + checkPBSUnknown2WithGraph_async(AMD_TestIntf_checkPBSUnknown2WithGraph cb, Preserved p, Ice.Current current) + { + if(current.encoding.equals(Ice.Util.Encoding_1_0)) + { + test(!(p instanceof PSUnknown2)); + test(p.pi == 5); + test(p.ps.equals("preserved")); + } + else + { + PSUnknown2 pu = (PSUnknown2)p; + test(pu.pi == 5); + test(pu.ps.equals("preserved")); + test(pu.pb == pu); + pu.pb = null; // Break the cycle. + } + cb.ice_response(); + } + + @Override + public void + exchangePNode_async(AMD_TestIntf_exchangePNode cb, PNode pn, Ice.Current current) + { + cb.ice_response(pn); + } + + @Override + public void + throwBaseAsBase_async(AMD_TestIntf_throwBaseAsBase cb, Ice.Current current) + throws BaseException + { + BaseException be = new BaseException(); + be.sbe = "sbe"; + be.pb = new B(); + be.pb.sb = "sb"; + be.pb.pb = be.pb; + cb.ice_exception(be); + } + + @Override + public void + throwDerivedAsBase_async(AMD_TestIntf_throwDerivedAsBase cb, Ice.Current current) + throws BaseException + { + DerivedException de = new DerivedException(); + de.sbe = "sbe"; + de.pb = new B(); + de.pb.sb = "sb1"; + de.pb.pb = de.pb; + de.sde = "sde1"; + de.pd1 = new D1(); + de.pd1.sb = "sb2"; + de.pd1.pb = de.pd1; + de.pd1.sd1 = "sd2"; + de.pd1.pd1 = de.pd1; + cb.ice_exception(de); + } + + @Override + public void + throwDerivedAsDerived_async(AMD_TestIntf_throwDerivedAsDerived cb, Ice.Current current) + throws DerivedException + { + DerivedException de = new DerivedException(); + de.sbe = "sbe"; + de.pb = new B(); + de.pb.sb = "sb1"; + de.pb.pb = de.pb; + de.sde = "sde1"; + de.pd1 = new D1(); + de.pd1.sb = "sb2"; + de.pd1.pb = de.pd1; + de.pd1.sd1 = "sd2"; + de.pd1.pd1 = de.pd1; + cb.ice_exception(de); + } + + @Override + public void + throwUnknownDerivedAsBase_async(AMD_TestIntf_throwUnknownDerivedAsBase cb, Ice.Current current) + throws BaseException + { + D2 d2 = new D2(); + d2.sb = "sb d2"; + d2.pb = d2; + d2.sd2 = "sd2 d2"; + d2.pd2 = d2; + + UnknownDerivedException ude = new UnknownDerivedException(); + ude.sbe = "sbe"; + ude.pb = d2; + ude.sude = "sude"; + ude.pd2 = d2; + cb.ice_exception(ude); + } + + @Override + public void + throwPreservedException_async(AMD_TestIntf_throwPreservedException cb, Ice.Current current) + { + PSUnknownException ue = new PSUnknownException(); + ue.p = new PSUnknown2(); + ue.p.pi = 5; + ue.p.ps = "preserved"; + ue.p.pb = ue.p; + cb.ice_exception(ue); + ue.p.pb = null; // Break the cycle. + } + + @Override + public void + useForward_async(AMD_TestIntf_useForward cb, Ice.Current current) + { + Forward f = new Forward(); + f = new Forward(); + f.h = new Hidden(); + f.h.f = f; + cb.ice_response(f); + } +} diff --git a/java/test/src/main/java/test/Ice/slicing/objects/AllTests.java b/java/test/src/main/java/test/Ice/slicing/objects/AllTests.java new file mode 100644 index 00000000000..be43330eae1 --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/objects/AllTests.java @@ -0,0 +1,3161 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.slicing.objects; + +import java.io.PrintWriter; + +import test.Ice.slicing.objects.client.Test.*; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized void + check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void + called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static class Callback_TestIntf_SBaseAsObjectI extends Callback_TestIntf_SBaseAsObject + { + @Override + public void + response(Ice.Object o) + { + test(o != null); + test(o.ice_id().equals("::Test::SBase")); + SBase sb = (SBase)o; + test(sb != null); + test(sb.sb.equals("SBase.sb")); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_SBaseAsSBaseI extends Callback_TestIntf_SBaseAsSBase + { + @Override + public void + response(SBase sb) + { + test(sb.sb.equals("SBase.sb")); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_SBSKnownDerivedAsSBaseI extends Callback_TestIntf_SBSKnownDerivedAsSBase + { + @Override + public void + response(SBase sb) + { + test(sb.sb.equals("SBSKnownDerived.sb")); + SBSKnownDerived sbskd = (SBSKnownDerived)sb; + test(sbskd != null); + test(sbskd.sbskd.equals("SBSKnownDerived.sbskd")); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_SBSKnownDerivedAsSBSKnownDerivedI + extends Callback_TestIntf_SBSKnownDerivedAsSBSKnownDerived + { + @Override + public void + response(SBSKnownDerived sbskd) + { + test(sbskd.sbskd.equals("SBSKnownDerived.sbskd")); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_SBSUnknownDerivedAsSBaseI extends Callback_TestIntf_SBSUnknownDerivedAsSBase + { + @Override + public void + response(SBase sb) + { + test(sb.sb.equals("SBSUnknownDerived.sb")); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_SBSUnknownDerivedAsSBaseCompactI + extends Callback_TestIntf_SBSUnknownDerivedAsSBaseCompact + { + @Override + public void + response(SBase sb) + { + test(sb.sb.equals("SBSUnknownDerived.sb")); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + if(exc instanceof Ice.OperationNotExistException) + { + callback.called(); + return; + } + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_SBSUnknownDerivedAsSBaseCompactFailI + extends Callback_TestIntf_SBSUnknownDerivedAsSBaseCompact + { + @Override + public void + response(SBase sb) + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + if(exc instanceof Ice.OperationNotExistException) + { + callback.called(); + return; + } + test(exc instanceof Ice.NoObjectFactoryException); + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_SUnknownAsObjectI1 extends Callback_TestIntf_SUnknownAsObject + { + @Override + public void + response(Ice.Object o) + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(exc.ice_name().equals("Ice::NoObjectFactoryException")); + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_SUnknownAsObjectI2 extends Callback_TestIntf_SUnknownAsObject + { + @Override + public void + response(Ice.Object o) + { + test(o instanceof Ice.UnknownSlicedObject); + test(((Ice.UnknownSlicedObject)o).getUnknownTypeId().equals("::Test::SUnknown")); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_oneElementCycleI extends Callback_TestIntf_oneElementCycle + { + @Override + public void + response(B b) + { + test(b != null); + test(b.ice_id().equals("::Test::B")); + test(b.sb.equals("B1.sb")); + test(b.pb == b); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_twoElementCycleI extends Callback_TestIntf_twoElementCycle + { + @Override + public void + response(B b1) + { + test(b1 != null); + test(b1.ice_id().equals("::Test::B")); + test(b1.sb.equals("B1.sb")); + + B b2 = b1.pb; + test(b2 != null); + test(b2.ice_id().equals("::Test::B")); + test(b2.sb.equals("B2.sb")); + test(b2.pb == b1); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_D1AsBI extends Callback_TestIntf_D1AsB + { + @Override + public void + response(B b1) + { + test(b1 != null); + test(b1.ice_id().equals("::Test::D1")); + test(b1.sb.equals("D1.sb")); + test(b1.pb != null); + test(b1.pb != b1); + D1 d1 = (D1)b1; + test(d1 != null); + test(d1.sd1.equals("D1.sd1")); + test(d1.pd1 != null); + test(d1.pd1 != b1); + test(b1.pb == d1.pd1); + + B b2 = b1.pb; + test(b2 != null); + test(b2.pb == b1); + test(b2.sb.equals("D2.sb")); + test(b2.ice_id().equals("::Test::B")); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_D1AsD1I extends Callback_TestIntf_D1AsD1 + { + @Override + public void + response(D1 d1) + { + test(d1 != null); + test(d1.ice_id().equals("::Test::D1")); + test(d1.sb.equals("D1.sb")); + test(d1.pb != null); + test(d1.pb != d1); + + B b2 = d1.pb; + test(b2 != null); + test(b2.ice_id().equals("::Test::B")); + test(b2.sb.equals("D2.sb")); + test(b2.pb == d1); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_D2AsBI extends Callback_TestIntf_D2AsB + { + @Override + public void + response(B b2) + { + test(b2 != null); + test(b2.ice_id().equals("::Test::B")); + test(b2.sb.equals("D2.sb")); + test(b2.pb != null); + test(b2.pb != b2); + + B b1 = b2.pb; + test(b1 != null); + test(b1.ice_id().equals("::Test::D1")); + test(b1.sb.equals("D1.sb")); + test(b1.pb == b2); + D1 d1 = (D1)b1; + test(d1 != null); + test(d1.sd1.equals("D1.sd1")); + test(d1.pd1 == b2); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_paramTest1I extends Callback_TestIntf_paramTest1 + { + @Override + public void + response(B b1, B b2) + { + test(b1 != null); + test(b1.ice_id().equals("::Test::D1")); + test(b1.sb.equals("D1.sb")); + test(b1.pb == b2); + D1 d1 = (D1)b1; + test(d1 != null); + test(d1.sd1.equals("D1.sd1")); + test(d1.pd1 == b2); + + test(b2 != null); + test(b2.ice_id().equals("::Test::B")); // No factory, must be sliced + test(b2.sb.equals("D2.sb")); + test(b2.pb == b1); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_paramTest2I extends Callback_TestIntf_paramTest2 + { + @Override + public void + response(B b2, B b1) + { + test(b1 != null); + test(b1.ice_id().equals("::Test::D1")); + test(b1.sb.equals("D1.sb")); + test(b1.pb == b2); + D1 d1 = (D1)b1; + test(d1 != null); + test(d1.sd1.equals("D1.sd1")); + test(d1.pd1 == b2); + + test(b2 != null); + test(b2.ice_id().equals("::Test::B")); // No factory, must be sliced + test(b2.sb.equals("D2.sb")); + test(b2.pb == b1); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_returnTest1I extends Callback_TestIntf_returnTest1 + { + @Override + public void + response(B r, B p1, B p2) + { + test(r == p1); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_returnTest2I extends Callback_TestIntf_returnTest2 + { + @Override + public void + response(B r, B p1, B p2) + { + test(r == p1); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_returnTest3I extends Callback_TestIntf_returnTest3 + { + @Override + public void + response(B b) + { + r = b; + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + + public B r; + } + + private static class Callback_TestIntf_paramTest3I extends Callback_TestIntf_paramTest3 + { + @Override + public void + response(B ret, B p1, B p2) + { + test(p1 != null); + test(p1.sb.equals("D2.sb (p1 1)")); + test(p1.pb == null); + test(p1.ice_id().equals("::Test::B")); + + test(p2 != null); + test(p2.sb.equals("D2.sb (p2 1)")); + test(p2.pb == null); + test(p2.ice_id().equals("::Test::B")); + + test(ret != null); + test(ret.sb.equals("D1.sb (p2 2)")); + test(ret.pb == null); + test(ret.ice_id().equals("::Test::D1")); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_paramTest4I extends Callback_TestIntf_paramTest4 + { + @Override + public void + response(B ret, B b) + { + test(b != null); + test(b.sb.equals("D4.sb (1)")); + test(b.pb == null); + test(b.ice_id().equals("::Test::B")); + + test(ret != null); + test(ret.sb.equals("B.sb (2)")); + test(ret.pb == null); + test(ret.ice_id().equals("::Test::B")); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_sequenceTestI extends Callback_TestIntf_sequenceTest + { + @Override + public void + response(SS3 ss) + { + r = ss; + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + + public SS3 r; + } + + private static class Callback_TestIntf_dictionaryTestI extends Callback_TestIntf_dictionaryTest + { + @Override + public void + response(java.util.Map<Integer, B> r, java.util.Map<Integer, B> bout) + { + this.r = r; + this.bout = bout; + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + + public java.util.Map<Integer, B> r; + public java.util.Map<Integer, B> bout; + } + + private static class Callback_TestIntf_throwBaseAsBaseI extends Callback_TestIntf_throwBaseAsBase + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + BaseException e = (BaseException)exc; + test(e.ice_name().equals("Test::BaseException")); + test(e.sbe.equals("sbe")); + test(e.pb != null); + test(e.pb.sb.equals("sb")); + test(e.pb.pb == e.pb); + } + catch(Exception e) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_throwDerivedAsBaseI extends Callback_TestIntf_throwDerivedAsBase + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + DerivedException e = (DerivedException)exc; + test(e.ice_name().equals("Test::DerivedException")); + test(e.sbe.equals("sbe")); + test(e.pb != null); + test(e.pb.sb.equals("sb1")); + test(e.pb.pb == e.pb); + test(e.sde.equals("sde1")); + test(e.pd1 != null); + test(e.pd1.sb.equals("sb2")); + test(e.pd1.pb == e.pd1); + test(e.pd1.sd1.equals("sd2")); + test(e.pd1.pd1 == e.pd1); + } + catch(Exception e) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_throwDerivedAsDerivedI extends Callback_TestIntf_throwDerivedAsDerived + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + DerivedException e = (DerivedException)exc; + test(e.ice_name().equals("Test::DerivedException")); + test(e.sbe.equals("sbe")); + test(e.pb != null); + test(e.pb.sb.equals("sb1")); + test(e.pb.pb == e.pb); + test(e.sde.equals("sde1")); + test(e.pd1 != null); + test(e.pd1.sb.equals("sb2")); + test(e.pd1.pb == e.pd1); + test(e.pd1.sd1.equals("sd2")); + test(e.pd1.pd1 == e.pd1); + } + catch(Exception e) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_throwUnknownDerivedAsBaseI + extends Callback_TestIntf_throwUnknownDerivedAsBase + { + @Override + public void + response() + { + test(false); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + @Override + public void + exception(Ice.UserException exc) + { + try + { + BaseException e = (BaseException)exc; + test(e.ice_name().equals("Test::BaseException")); + test(e.sbe.equals("sbe")); + test(e.pb != null); + test(e.pb.sb.equals("sb d2")); + test(e.pb.pb == e.pb); + } + catch(Exception e) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_useForwardI extends Callback_TestIntf_useForward + { + @Override + public void + response(Forward f) + { + test(f != null); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_exchangePBaseI1 extends Callback_TestIntf_exchangePBase + { + @Override + public void + response(PBase r) + { + PDerived p2 = (PDerived)r; + test(p2.pi == 3); + test(p2.ps.equals("preserved")); + test(p2.pb == p2); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + if(exc instanceof Ice.OperationNotExistException) + { + callback.called(); + return; + } + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_exchangePBaseI2 extends Callback_TestIntf_exchangePBase + { + @Override + public void + response(PBase r) + { + test(!(r instanceof PCUnknown)); + test(r.pi == 3); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + if(exc instanceof Ice.OperationNotExistException) + { + callback.called(); + return; + } + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_exchangePBaseI3 extends Callback_TestIntf_exchangePBase + { + @Override + public void + response(PBase r) + { + test(!(r instanceof PCDerived)); + test(r.pi == 3); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + if(exc instanceof Ice.OperationNotExistException) + { + callback.called(); + return; + } + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_exchangePBaseI4 extends Callback_TestIntf_exchangePBase + { + @Override + public void + response(PBase r) + { + PCDerived p2 = (PCDerived)r; + test(p2.pi == 3); + test(p2.pbs[0] == p2); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + if(exc instanceof Ice.OperationNotExistException) + { + callback.called(); + return; + } + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_exchangePBaseICompact1 extends Callback_TestIntf_exchangePBase + { + @Override + public void + response(PBase r) + { + test(!(r instanceof CompactPCDerived)); + test(r.pi == 3); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + if(exc instanceof Ice.OperationNotExistException) + { + callback.called(); + return; + } + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_exchangePBaseICompact2 extends Callback_TestIntf_exchangePBase + { + @Override + public void + response(PBase r) + { + CompactPCDerived p2 = (CompactPCDerived)r; + test(p2.pi == 3); + test(p2.pbs[0] == p2); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + if(exc instanceof Ice.OperationNotExistException) + { + callback.called(); + return; + } + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_exchangePBaseI5 extends Callback_TestIntf_exchangePBase + { + @Override + public void + response(PBase r) + { + test(!(r instanceof PCDerived3)); + test(r instanceof Preserved); + test(r.pi == 3); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + if(exc instanceof Ice.OperationNotExistException) + { + callback.called(); + return; + } + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class Callback_TestIntf_exchangePBaseI6 extends Callback_TestIntf_exchangePBase + { + @Override + public void + response(PBase r) + { + PCDerived3 p3 = (PCDerived3)r; + test(p3.pi == 3); + for(int i = 0; i < 300; ++i) + { + PCDerived2 p2 = (PCDerived2)p3.pbs[i]; + test(p2.pi == i); + test(p2.pbs.length == 1); + test(p2.pbs[0] == null); + test(p2.pcd2 == i); + } + test(p3.pcd2 == p3.pi); + test(p3.pcd3 == p3.pbs[10]); + callback.called(); + } + + @Override + public void + exception(Ice.LocalException exc) + { + if(exc instanceof Ice.OperationNotExistException) + { + callback.called(); + return; + } + test(false); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class PNodeI extends PNode + { + public PNodeI() + { + ++counter; + } + + static int counter = 0; + } + + private static class NodeFactoryI implements Ice.ObjectFactory + { + @Override + public Ice.Object create(String id) + { + if(id.equals(PNode.ice_staticId())) + { + return new PNodeI(); + } + return null; + } + + @Override + public void destroy() + { + } + } + + private static class PreservedI extends Preserved + { + public PreservedI() + { + ++counter; + } + + static int counter = 0; + } + + private static class PreservedFactoryI implements Ice.ObjectFactory + { + @Override + public Ice.Object create(String id) + { + if(id.equals(Preserved.ice_staticId())) + { + return new PreservedI(); + } + return null; + } + + @Override + public void destroy() + { + } + } + + public static TestIntfPrx + allTests(Ice.Communicator communicator, boolean collocated, PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + String ref = "Test:default -p 12010 -t 10000"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + TestIntfPrx test = TestIntfPrxHelper.checkedCast(base); + test(test != null); + test(test.equals(base)); + out.println("ok"); + + out.print("base as Object... "); + out.flush(); + { + Ice.Object o; + SBase sb = null; + try + { + o = test.SBaseAsObject(); + test(o != null); + test(o.ice_id().equals("::Test::SBase")); + sb = (SBase)o; + } + catch(Exception ex) + { + test(false); + } + test(sb != null); + test(sb.sb.equals("SBase.sb")); + } + out.println("ok"); + + out.print("base as Object (AMI)... "); + out.flush(); + { + Callback_TestIntf_SBaseAsObjectI cb = new Callback_TestIntf_SBaseAsObjectI(); + test.begin_SBaseAsObject(cb); + cb.check(); + } + out.println("ok"); + + out.print("base as base... "); + out.flush(); + { + SBase sb; + try + { + sb = test.SBaseAsSBase(); + test(sb.sb.equals("SBase.sb")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("base as base (AMI)... "); + out.flush(); + { + Callback_TestIntf_SBaseAsSBaseI cb = new Callback_TestIntf_SBaseAsSBaseI(); + test.begin_SBaseAsSBase(cb); + cb.check(); + } + out.println("ok"); + + out.print("base with known derived as base... "); + out.flush(); + { + SBase sb; + SBSKnownDerived sbskd = null; + try + { + sb = test.SBSKnownDerivedAsSBase(); + test(sb.sb.equals("SBSKnownDerived.sb")); + sbskd = (SBSKnownDerived)sb; + } + catch(Exception ex) + { + test(false); + } + test(sbskd != null); + test(sbskd.sbskd.equals("SBSKnownDerived.sbskd")); + } + out.println("ok"); + + out.print("base with known derived as base (AMI)... "); + out.flush(); + { + Callback_TestIntf_SBSKnownDerivedAsSBaseI cb = new Callback_TestIntf_SBSKnownDerivedAsSBaseI(); + test.begin_SBSKnownDerivedAsSBase(cb); + cb.check(); + } + out.println("ok"); + + out.print("base with known derived as known derived... "); + out.flush(); + { + SBSKnownDerived sbskd; + try + { + sbskd = test.SBSKnownDerivedAsSBSKnownDerived(); + test(sbskd.sbskd.equals("SBSKnownDerived.sbskd")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("base with known derived as known derived (AMI)... "); + out.flush(); + { + Callback_TestIntf_SBSKnownDerivedAsSBSKnownDerivedI cb = + new Callback_TestIntf_SBSKnownDerivedAsSBSKnownDerivedI(); + test.begin_SBSKnownDerivedAsSBSKnownDerived(cb); + cb.check(); + } + out.println("ok"); + + out.print("base with unknown derived as base... "); + out.flush(); + { + try + { + SBase sb = test.SBSUnknownDerivedAsSBase(); + test(sb.sb.equals("SBSUnknownDerived.sb")); + } + catch(Exception ex) + { + test(false); + } + } + if(test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)) + { + try + { + SBase sb = test.SBSUnknownDerivedAsSBaseCompact(); + test(sb.sb.equals("SBSUnknownDerived.sb")); + } + catch(Ice.OperationNotExistException ex) + { + } + catch(Exception ex) + { + test(false); + } + } + else + { + try + { + // + // This test fails when using the compact format because the instance cannot + // be sliced to a known type. + // + test.SBSUnknownDerivedAsSBaseCompact(); + test(false); + } + catch(Ice.NoObjectFactoryException ex) + { + // Expected. + } + catch(Ice.OperationNotExistException ex) + { + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("base with unknown derived as base (AMI)... "); + out.flush(); + { + Callback_TestIntf_SBSUnknownDerivedAsSBaseI cb = new Callback_TestIntf_SBSUnknownDerivedAsSBaseI(); + test.begin_SBSUnknownDerivedAsSBase(cb); + cb.check(); + } + if(test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)) + { + // + // This test succeeds for the 1.0 encoding. + // + Callback_TestIntf_SBSUnknownDerivedAsSBaseCompactI cb = + new Callback_TestIntf_SBSUnknownDerivedAsSBaseCompactI(); + test.begin_SBSUnknownDerivedAsSBaseCompact(cb); + cb.check(); + } + else + { + // + // This test fails when using the compact format because the instance cannot + // be sliced to a known type. + // + Callback_TestIntf_SBSUnknownDerivedAsSBaseCompactFailI cb = + new Callback_TestIntf_SBSUnknownDerivedAsSBaseCompactFailI(); + test.begin_SBSUnknownDerivedAsSBaseCompact(cb); + cb.check(); + } + out.println("ok"); + + out.print("unknown with Object as Object... "); + out.flush(); + { + Ice.Object o; + try + { + o = test.SUnknownAsObject(); + test(!test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)); + test(o instanceof Ice.UnknownSlicedObject); + test(((Ice.UnknownSlicedObject)o).getUnknownTypeId().equals("::Test::SUnknown")); + test.checkSUnknown(o); + } + catch(Ice.NoObjectFactoryException ex) + { + test(test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("unknown with Object as Object (AMI)... "); + out.flush(); + { + if(test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)) + { + Callback_TestIntf_SUnknownAsObjectI1 cb = new Callback_TestIntf_SUnknownAsObjectI1(); + test.begin_SUnknownAsObject(cb); + cb.check(); + } + else + { + Callback_TestIntf_SUnknownAsObjectI2 cb = new Callback_TestIntf_SUnknownAsObjectI2(); + test.begin_SUnknownAsObject(cb); + cb.check(); + } + } + out.println("ok"); + + out.print("one-element cycle... "); + out.flush(); + { + try + { + B b = test.oneElementCycle(); + test(b != null); + test(b.ice_id().equals("::Test::B")); + test(b.sb.equals("B1.sb")); + test(b.pb == b); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("one-element cycle (AMI)... "); + out.flush(); + { + Callback_TestIntf_oneElementCycleI cb = new Callback_TestIntf_oneElementCycleI(); + test.begin_oneElementCycle(cb); + cb.check(); + } + out.println("ok"); + + out.print("two-element cycle... "); + out.flush(); + { + try + { + B b1 = test.twoElementCycle(); + test(b1 != null); + test(b1.ice_id().equals("::Test::B")); + test(b1.sb.equals("B1.sb")); + + B b2 = b1.pb; + test(b2 != null); + test(b2.ice_id().equals("::Test::B")); + test(b2.sb.equals("B2.sb")); + test(b2.pb == b1); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("two-element cycle (AMI)... "); + out.flush(); + { + Callback_TestIntf_twoElementCycleI cb = new Callback_TestIntf_twoElementCycleI(); + test.begin_twoElementCycle(cb); + cb.check(); + } + out.println("ok"); + + out.print("known derived pointer slicing as base... "); + out.flush(); + { + try + { + B b1; + b1 = test.D1AsB(); + test(b1 != null); + test(b1.ice_id().equals("::Test::D1")); + test(b1.sb.equals("D1.sb")); + test(b1.pb != null); + test(b1.pb != b1); + D1 d1 = (D1)b1; + test(d1 != null); + test(d1.sd1.equals("D1.sd1")); + test(d1.pd1 != null); + test(d1.pd1 != b1); + test(b1.pb == d1.pd1); + + B b2 = b1.pb; + test(b2 != null); + test(b2.pb == b1); + test(b2.sb.equals("D2.sb")); + test(b2.ice_id().equals("::Test::B")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("known derived pointer slicing as base (AMI)... "); + out.flush(); + { + Callback_TestIntf_D1AsBI cb = new Callback_TestIntf_D1AsBI(); + test.begin_D1AsB(cb); + cb.check(); + } + out.println("ok"); + + out.print("known derived pointer slicing as derived... "); + out.flush(); + { + try + { + D1 d1; + d1 = test.D1AsD1(); + test(d1 != null); + test(d1.ice_id().equals("::Test::D1")); + test(d1.sb.equals("D1.sb")); + test(d1.pb != null); + test(d1.pb != d1); + + B b2 = d1.pb; + test(b2 != null); + test(b2.ice_id().equals("::Test::B")); + test(b2.sb.equals("D2.sb")); + test(b2.pb == d1); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("known derived pointer slicing as derived (AMI)... "); + out.flush(); + { + Callback_TestIntf_D1AsD1I cb = new Callback_TestIntf_D1AsD1I(); + test.begin_D1AsD1(cb); + cb.check(); + } + out.println("ok"); + + out.print("unknown derived pointer slicing as base... "); + out.flush(); + { + try + { + B b2; + b2 = test.D2AsB(); + test(b2 != null); + test(b2.ice_id().equals("::Test::B")); + test(b2.sb.equals("D2.sb")); + test(b2.pb != null); + test(b2.pb != b2); + + B b1 = b2.pb; + test(b1 != null); + test(b1.ice_id().equals("::Test::D1")); + test(b1.sb.equals("D1.sb")); + test(b1.pb == b2); + D1 d1 = (D1)b1; + test(d1 != null); + test(d1.sd1.equals("D1.sd1")); + test(d1.pd1 == b2); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("unknown derived pointer slicing as base (AMI)... "); + out.flush(); + { + Callback_TestIntf_D2AsBI cb = new Callback_TestIntf_D2AsBI(); + test.begin_D2AsB(cb); + cb.check(); + } + out.println("ok"); + + out.print("param ptr slicing with known first... "); + out.flush(); + { + try + { + BHolder b1 = new BHolder(); + BHolder b2 = new BHolder(); + test.paramTest1(b1, b2); + + test(b1.value != null); + test(b1.value.ice_id().equals("::Test::D1")); + test(b1.value.sb.equals("D1.sb")); + test(b1.value.pb == b2.value); + D1 d1 = (D1)b1.value; + test(d1 != null); + test(d1.sd1.equals("D1.sd1")); + test(d1.pd1 == b2.value); + + test(b2.value != null); + test(b2.value.ice_id().equals("::Test::B")); // No factory, must be sliced + test(b2.value.sb.equals("D2.sb")); + test(b2.value.pb == b1.value); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("param ptr slicing with known first (AMI)... "); + out.flush(); + { + Callback_TestIntf_paramTest1I cb = new Callback_TestIntf_paramTest1I(); + test.begin_paramTest1(cb); + cb.check(); + } + out.println("ok"); + + out.print("param ptr slicing with unknown first... "); + out.flush(); + { + try + { + BHolder b2 = new BHolder(); + BHolder b1 = new BHolder(); + test.paramTest2(b2, b1); + + test(b1.value != null); + test(b1.value.ice_id().equals("::Test::D1")); + test(b1.value.sb.equals("D1.sb")); + test(b1.value.pb == b2.value); + D1 d1 = (D1)b1.value; + test(d1 != null); + test(d1.sd1.equals("D1.sd1")); + test(d1.pd1 == b2.value); + + test(b2.value != null); + test(b2.value.ice_id().equals("::Test::B")); // No factory, must be sliced + test(b2.value.sb.equals("D2.sb")); + test(b2.value.pb == b1.value); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("param ptr slicing with unknown first (AMI)... "); + out.flush(); + { + Callback_TestIntf_paramTest2I cb = new Callback_TestIntf_paramTest2I(); + test.begin_paramTest2(cb); + cb.check(); + } + out.println("ok"); + + out.print("return value identity with known first... "); + out.flush(); + { + try + { + BHolder p1 = new BHolder(); + BHolder p2 = new BHolder(); + B r = test.returnTest1(p1, p2); + test(r == p1.value); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("return value identity with known first (AMI)... "); + out.flush(); + { + Callback_TestIntf_returnTest1I cb = new Callback_TestIntf_returnTest1I(); + test.begin_returnTest1(cb); + cb.check(); + } + out.println("ok"); + + out.print("return value identity with unknown first... "); + out.flush(); + { + try + { + BHolder p1 = new BHolder(); + BHolder p2 = new BHolder(); + B r = test.returnTest2(p1, p2); + test(r == p1.value); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("return value identity with unknown first (AMI)... "); + out.flush(); + { + Callback_TestIntf_returnTest2I cb = new Callback_TestIntf_returnTest2I(); + test.begin_returnTest2(cb); + cb.check(); + } + out.println("ok"); + + out.print("return value identity for input params known first... "); + out.flush(); + { + //try + //{ + D1 d1 = new D1(); + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + D3 d3 = new D3(); + d3.pb = d1; + d3.sb = "D3.sb"; + d3.sd3 = "D3.sd3"; + d3.pd3 = d1; + d1.pb = d3; + d1.pd1 = d3; + + B b1 = test.returnTest3(d1, d3); + + test(b1 != null); + test(b1.sb.equals("D1.sb")); + test(b1.ice_id().equals("::Test::D1")); + D1 p1 = (D1)b1; + test(p1 != null); + test(p1.sd1.equals("D1.sd1")); + test(p1.pd1 == b1.pb); + + B b2 = b1.pb; + test(b2 != null); + test(b2.sb.equals("D3.sb")); + test(b2.ice_id().equals("::Test::B")); // Sliced by server + test(b2.pb == b1); + try + { + D3 p3 = (D3)b2; + test(p3 != null); + test(false); + } + catch(ClassCastException ex) + { + } + + test(b1 != d1); + test(b1 != d3); + test(b2 != d1); + test(b2 != d3); + //} + //catch(Exception ex) + //{ + //test(false); + //} + } + out.println("ok"); + + out.print("return value identity for input params known first (AMI)... "); + out.flush(); + { + D1 d1 = new D1(); + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + D3 d3 = new D3(); + d3.pb = d1; + d3.sb = "D3.sb"; + d3.sd3 = "D3.sd3"; + d3.pd3 = d1; + d1.pb = d3; + d1.pd1 = d3; + + Callback_TestIntf_returnTest3I cb = new Callback_TestIntf_returnTest3I(); + test.begin_returnTest3(d1, d3, cb); + cb.check(); + B b1 = cb.r; + + test(b1 != null); + test(b1.sb.equals("D1.sb")); + test(b1.ice_id().equals("::Test::D1")); + D1 p1 = (D1)b1; + test(p1 != null); + test(p1.sd1.equals("D1.sd1")); + test(p1.pd1 == b1.pb); + + B b2 = b1.pb; + test(b2 != null); + test(b2.sb.equals("D3.sb")); + test(b2.ice_id().equals("::Test::B")); // Sliced by server + test(b2.pb == b1); + try + { + D3 p3 = (D3)b2; + test(p3 != null); + test(false); + } + catch(ClassCastException ex) + { + } + + test(b1 != d1); + test(b1 != d3); + test(b2 != d1); + test(b2 != d3); + } + out.println("ok"); + + out.print("return value identity for input params unknown first... "); + out.flush(); + { + try + { + D1 d1 = new D1(); + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + D3 d3 = new D3(); + d3.pb = d1; + d3.sb = "D3.sb"; + d3.sd3 = "D3.sd3"; + d3.pd3 = d1; + d1.pb = d3; + d1.pd1 = d3; + + B b1 = test.returnTest3(d3, d1); + + test(b1 != null); + test(b1.sb.equals("D3.sb")); + test(b1.ice_id().equals("::Test::B")); // Sliced by server + + try + { + D3 p1 = (D3)b1; + test(p1 != null); + test(false); + } + catch(ClassCastException ex) + { + } + + B b2 = b1.pb; + test(b2 != null); + test(b2.sb.equals("D1.sb")); + test(b2.ice_id().equals("::Test::D1")); + test(b2.pb == b1); + D1 p3 = (D1)b2; + test(p3 != null); + test(p3.sd1.equals("D1.sd1")); + test(p3.pd1 == b1); + + test(b1 != d1); + test(b1 != d3); + test(b2 != d1); + test(b2 != d3); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("return value identity for input params unknown first (AMI)... "); + out.flush(); + { + D1 d1 = new D1(); + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + D3 d3 = new D3(); + d3.pb = d1; + d3.sb = "D3.sb"; + d3.sd3 = "D3.sd3"; + d3.pd3 = d1; + d1.pb = d3; + d1.pd1 = d3; + + Callback_TestIntf_returnTest3I cb = new Callback_TestIntf_returnTest3I(); + test.begin_returnTest3(d3, d1, cb); + cb.check(); + B b1 = cb.r; + + test(b1 != null); + test(b1.sb.equals("D3.sb")); + test(b1.ice_id().equals("::Test::B")); // Sliced by server + + try + { + D3 p1 = (D3)b1; + test(p1 != null); + test(false); + } + catch(ClassCastException ex) + { + } + + B b2 = b1.pb; + test(b2 != null); + test(b2.sb.equals("D1.sb")); + test(b2.ice_id().equals("::Test::D1")); + test(b2.pb == b1); + D1 p3 = (D1)b2; + test(p3 != null); + test(p3.sd1.equals("D1.sd1")); + test(p3.pd1 == b1); + + test(b1 != d1); + test(b1 != d3); + test(b2 != d1); + test(b2 != d3); + } + out.println("ok"); + + out.print("remainder unmarshaling (3 instances)... "); + out.flush(); + { + try + { + BHolder p1 = new BHolder(); + BHolder p2 = new BHolder(); + B ret = test.paramTest3(p1, p2); + + test(p1.value != null); + test(p1.value.sb.equals("D2.sb (p1 1)")); + test(p1.value.pb == null); + test(p1.value.ice_id().equals("::Test::B")); + + test(p2.value != null); + test(p2.value.sb.equals("D2.sb (p2 1)")); + test(p2.value.pb == null); + test(p2.value.ice_id().equals("::Test::B")); + + test(ret != null); + test(ret.sb.equals("D1.sb (p2 2)")); + test(ret.pb == null); + test(ret.ice_id().equals("::Test::D1")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("remainder unmarshaling (3 instances) (AMI)... "); + out.flush(); + { + Callback_TestIntf_paramTest3I cb = new Callback_TestIntf_paramTest3I(); + test.begin_paramTest3(cb); + cb.check(); + } + out.println("ok"); + + out.print("remainder unmarshaling (4 instances)... "); + out.flush(); + { + try + { + BHolder b = new BHolder(); + B ret = test.paramTest4(b); + + test(b.value != null); + test(b.value.sb.equals("D4.sb (1)")); + test(b.value.pb == null); + test(b.value.ice_id().equals("::Test::B")); + + test(ret != null); + test(ret.sb.equals("B.sb (2)")); + test(ret.pb == null); + test(ret.ice_id().equals("::Test::B")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("remainder unmarshaling (4 instances) (AMI)... "); + out.flush(); + { + Callback_TestIntf_paramTest4I cb = new Callback_TestIntf_paramTest4I(); + test.begin_paramTest4(cb); + cb.check(); + } + out.println("ok"); + + out.print("param ptr slicing, instance marshaled in unknown derived as base... "); + out.flush(); + { + try + { + B b1 = new B(); + b1.sb = "B.sb(1)"; + b1.pb = b1; + + D3 d3 = new D3(); + d3.sb = "D3.sb"; + d3.pb = d3; + d3.sd3 = "D3.sd3"; + d3.pd3 = b1; + + B b2 = new B(); + b2.sb = "B.sb(2)"; + b2.pb = b1; + + B r = test.returnTest3(d3, b2); + + test(r != null); + test(r.ice_id().equals("::Test::B")); + test(r.sb.equals("D3.sb")); + test(r.pb == r); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("param ptr slicing, instance marshaled in unknown derived as base (AMI)... "); + out.flush(); + { + B b1 = new B(); + b1.sb = "B.sb(1)"; + b1.pb = b1; + + D3 d3 = new D3(); + d3.sb = "D3.sb"; + d3.pb = d3; + d3.sd3 = "D3.sd3"; + d3.pd3 = b1; + + B b2 = new B(); + b2.sb = "B.sb(2)"; + b2.pb = b1; + + Callback_TestIntf_returnTest3I cb = new Callback_TestIntf_returnTest3I(); + test.begin_returnTest3(d3, b2, cb); + cb.check(); + B r = cb.r; + + test(r != null); + test(r.ice_id().equals("::Test::B")); + test(r.sb.equals("D3.sb")); + test(r.pb == r); + } + out.println("ok"); + + out.print("param ptr slicing, instance marshaled in unknown derived as derived... "); + out.flush(); + { + try + { + D1 d11 = new D1(); + d11.sb = "D1.sb(1)"; + d11.pb = d11; + d11.sd1 = "D1.sd1(1)"; + + D3 d3 = new D3(); + d3.sb = "D3.sb"; + d3.pb = d3; + d3.sd3 = "D3.sd3"; + d3.pd3 = d11; + + D1 d12 = new D1(); + d12.sb = "D1.sb(2)"; + d12.pb = d12; + d12.sd1 = "D1.sd1(2)"; + d12.pd1 = d11; + + B r = test.returnTest3(d3, d12); + test(r != null); + test(r.ice_id().equals("::Test::B")); + test(r.sb.equals("D3.sb")); + test(r.pb == r); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("param ptr slicing, instance marshaled in unknown derived as derived (AMI)... "); + out.flush(); + { + D1 d11 = new D1(); + d11.sb = "D1.sb(1)"; + d11.pb = d11; + d11.sd1 = "D1.sd1(1)"; + + D3 d3 = new D3(); + d3.sb = "D3.sb"; + d3.pb = d3; + d3.sd3 = "D3.sd3"; + d3.pd3 = d11; + + D1 d12 = new D1(); + d12.sb = "D1.sb(2)"; + d12.pb = d12; + d12.sd1 = "D1.sd1(2)"; + d12.pd1 = d11; + + Callback_TestIntf_returnTest3I cb = new Callback_TestIntf_returnTest3I(); + test.begin_returnTest3(d3, d12, cb); + cb.check(); + B r = cb.r; + + test(r != null); + test(r.ice_id().equals("::Test::B")); + test(r.sb.equals("D3.sb")); + test(r.pb == r); + } + out.println("ok"); + + out.print("sequence slicing... "); + out.flush(); + { + try + { + SS3 ss; + { + B ss1b = new B(); + ss1b.sb = "B.sb"; + ss1b.pb = ss1b; + + D1 ss1d1 = new D1(); + ss1d1.sb = "D1.sb"; + ss1d1.sd1 = "D1.sd1"; + ss1d1.pb = ss1b; + + D3 ss1d3 = new D3(); + ss1d3.sb = "D3.sb"; + ss1d3.sd3 = "D3.sd3"; + ss1d3.pb = ss1b; + + B ss2b = new B(); + ss2b.sb = "B.sb"; + ss2b.pb = ss1b; + + D1 ss2d1 = new D1(); + ss2d1.sb = "D1.sb"; + ss2d1.sd1 = "D1.sd1"; + ss2d1.pb = ss2b; + + D3 ss2d3 = new D3(); + ss2d3.sb = "D3.sb"; + ss2d3.sd3 = "D3.sd3"; + ss2d3.pb = ss2b; + + ss1d1.pd1 = ss2b; + ss1d3.pd3 = ss2d1; + + ss2d1.pd1 = ss1d3; + ss2d3.pd3 = ss1d1; + + SS1 ss1 = new SS1(); + ss1.s = new B[3]; + ss1.s[0] = ss1b; + ss1.s[1] = ss1d1; + ss1.s[2] = ss1d3; + + SS2 ss2 = new SS2(); + ss2.s = new B[3]; + ss2.s[0] = ss2b; + ss2.s[1] = ss2d1; + ss2.s[2] = ss2d3; + + ss = test.sequenceTest(ss1, ss2); + } + + test(ss.c1 != null); + B ss1b = ss.c1.s[0]; + B ss1d1 = ss.c1.s[1]; + test(ss.c2 != null); + B ss1d3 = ss.c1.s[2]; + + test(ss.c2 != null); + B ss2b = ss.c2.s[0]; + B ss2d1 = ss.c2.s[1]; + B ss2d3 = ss.c2.s[2]; + + test(ss1b.pb == ss1b); + test(ss1d1.pb == ss1b); + test(ss1d3.pb == ss1b); + + test(ss2b.pb == ss1b); + test(ss2d1.pb == ss2b); + test(ss2d3.pb == ss2b); + + test(ss1b.ice_id().equals("::Test::B")); + test(ss1d1.ice_id().equals("::Test::D1")); + test(ss1d3.ice_id().equals("::Test::B")); + + test(ss2b.ice_id().equals("::Test::B")); + test(ss2d1.ice_id().equals("::Test::D1")); + test(ss2d3.ice_id().equals("::Test::B")); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("sequence slicing (AMI)... "); + out.flush(); + { + SS3 ss; + { + B ss1b = new B(); + ss1b.sb = "B.sb"; + ss1b.pb = ss1b; + + D1 ss1d1 = new D1(); + ss1d1.sb = "D1.sb"; + ss1d1.sd1 = "D1.sd1"; + ss1d1.pb = ss1b; + + D3 ss1d3 = new D3(); + ss1d3.sb = "D3.sb"; + ss1d3.sd3 = "D3.sd3"; + ss1d3.pb = ss1b; + + B ss2b = new B(); + ss2b.sb = "B.sb"; + ss2b.pb = ss1b; + + D1 ss2d1 = new D1(); + ss2d1.sb = "D1.sb"; + ss2d1.sd1 = "D1.sd1"; + ss2d1.pb = ss2b; + + D3 ss2d3 = new D3(); + ss2d3.sb = "D3.sb"; + ss2d3.sd3 = "D3.sd3"; + ss2d3.pb = ss2b; + + ss1d1.pd1 = ss2b; + ss1d3.pd3 = ss2d1; + + ss2d1.pd1 = ss1d3; + ss2d3.pd3 = ss1d1; + + SS1 ss1 = new SS1(); + ss1.s = new B[3]; + ss1.s[0] = ss1b; + ss1.s[1] = ss1d1; + ss1.s[2] = ss1d3; + + SS2 ss2 = new SS2(); + ss2.s = new B[3]; + ss2.s[0] = ss2b; + ss2.s[1] = ss2d1; + ss2.s[2] = ss2d3; + + Callback_TestIntf_sequenceTestI cb = new Callback_TestIntf_sequenceTestI(); + test.begin_sequenceTest(ss1, ss2, cb); + cb.check(); + ss = cb.r; + } + test(ss.c1 != null); + B ss1b = ss.c1.s[0]; + B ss1d1 = ss.c1.s[1]; + test(ss.c2 != null); + B ss1d3 = ss.c1.s[2]; + + test(ss.c2 != null); + B ss2b = ss.c2.s[0]; + B ss2d1 = ss.c2.s[1]; + B ss2d3 = ss.c2.s[2]; + + test(ss1b.pb == ss1b); + test(ss1d1.pb == ss1b); + test(ss1d3.pb == ss1b); + + test(ss2b.pb == ss1b); + test(ss2d1.pb == ss2b); + test(ss2d3.pb == ss2b); + + test(ss1b.ice_id().equals("::Test::B")); + test(ss1d1.ice_id().equals("::Test::D1")); + test(ss1d3.ice_id().equals("::Test::B")); + + test(ss2b.ice_id().equals("::Test::B")); + test(ss2d1.ice_id().equals("::Test::D1")); + test(ss2d3.ice_id().equals("::Test::B")); + } + out.println("ok"); + + out.print("dictionary slicing... "); + out.flush(); + { + try + { + java.util.IdentityHashMap<Integer, B> bin = new java.util.IdentityHashMap<Integer, B>(); + BDictHolder boutH = new BDictHolder(); + java.util.Map<Integer, B> r; + int i; + for(i = 0; i < 10; ++i) + { + String s = "D1." + new Integer(i).toString(); + D1 d1 = new D1(); + d1.sb = s; + d1.pb = d1; + d1.sd1 = s; + bin.put(i, d1); + } + + r = test.dictionaryTest(bin, boutH); + + test(boutH.value.size() == 10); + for(i = 0; i < 10; ++i) + { + B b = boutH.value.get(i * 10); + test(b != null); + String s = "D1." + new Integer(i).toString(); + test(b.sb.equals(s)); + test(b.pb != null); + test(b.pb != b); + test(b.pb.sb.equals(s)); + test(b.pb.pb == b.pb); + } + + test(r.size() == 10); + for(i = 0; i < 10; ++i) + { + B b = r.get(i * 20); + test(b != null); + String s = "D1." + new Integer(i * 20).toString(); + test(b.sb.equals(s)); + test(b.pb == (i == 0 ? null : r.get((i - 1) * 20))); + D1 d1 = (D1)b; + test(d1 != null); + test(d1.sd1.equals(s)); + test(d1.pd1 == d1); + } + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("dictionary slicing (AMI)... "); + out.flush(); + { + java.util.Map<Integer, B> bin = new java.util.HashMap<Integer, B>(); + java.util.Map<Integer, B> bout; + java.util.Map<Integer, B> r; + int i; + for(i = 0; i < 10; ++i) + { + String s = "D1." + new Integer(i).toString(); + D1 d1 = new D1(); + d1.sb = s; + d1.pb = d1; + d1.sd1 = s; + bin.put(i, d1); + } + + Callback_TestIntf_dictionaryTestI cb = new Callback_TestIntf_dictionaryTestI(); + test.begin_dictionaryTest(bin, cb); + cb.check(); + bout = cb.bout; + r = cb.r; + + test(bout.size() == 10); + for(i = 0; i < 10; ++i) + { + B b = bout.get(i * 10); + test(b != null); + String s = "D1." + new Integer(i).toString(); + test(b.sb.equals(s)); + test(b.pb != null); + test(b.pb != b); + test(b.pb.sb.equals(s)); + test(b.pb.pb == b.pb); + } + + test(r.size() == 10); + for(i = 0; i < 10; ++i) + { + B b = r.get(i * 20); + test(b != null); + String s = "D1." + new Integer(i * 20).toString(); + test(b.sb.equals(s)); + test(b.pb == (i == 0 ? null : r.get((i - 1) * 20))); + D1 d1 = (D1)b; + test(d1 != null); + test(d1.sd1.equals(s)); + test(d1.pd1 == d1); + } + } + out.println("ok"); + + out.print("base exception thrown as base exception... "); + out.flush(); + { + try + { + test.throwBaseAsBase(); + test(false); + } + catch(BaseException e) + { + test(e.ice_name().equals("Test::BaseException")); + test(e.sbe.equals("sbe")); + test(e.pb != null); + test(e.pb.sb.equals("sb")); + test(e.pb.pb == e.pb); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("base exception thrown as base exception (AMI)... "); + out.flush(); + { + Callback_TestIntf_throwBaseAsBaseI cb = new Callback_TestIntf_throwBaseAsBaseI(); + test.begin_throwBaseAsBase(cb); + cb.check(); + } + out.println("ok"); + + out.print("derived exception thrown as base exception... "); + out.flush(); + { + try + { + test.throwDerivedAsBase(); + test(false); + } + catch(DerivedException e) + { + test(e.ice_name().equals("Test::DerivedException")); + test(e.sbe.equals("sbe")); + test(e.pb != null); + test(e.pb.sb.equals("sb1")); + test(e.pb.pb == e.pb); + test(e.sde.equals("sde1")); + test(e.pd1 != null); + test(e.pd1.sb.equals("sb2")); + test(e.pd1.pb == e.pd1); + test(e.pd1.sd1.equals("sd2")); + test(e.pd1.pd1 == e.pd1); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("derived exception thrown as base exception (AMI)... "); + out.flush(); + { + Callback_TestIntf_throwDerivedAsBaseI cb = new Callback_TestIntf_throwDerivedAsBaseI(); + test.begin_throwDerivedAsBase(cb); + cb.check(); + } + out.println("ok"); + + out.print("derived exception thrown as derived exception... "); + out.flush(); + { + try + { + test.throwDerivedAsDerived(); + test(false); + } + catch(DerivedException e) + { + test(e.ice_name().equals("Test::DerivedException")); + test(e.sbe.equals("sbe")); + test(e.pb != null); + test(e.pb.sb.equals("sb1")); + test(e.pb.pb == e.pb); + test(e.sde.equals("sde1")); + test(e.pd1 != null); + test(e.pd1.sb.equals("sb2")); + test(e.pd1.pb == e.pd1); + test(e.pd1.sd1.equals("sd2")); + test(e.pd1.pd1 == e.pd1); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("derived exception thrown as derived exception (AMI)... "); + out.flush(); + { + Callback_TestIntf_throwDerivedAsDerivedI cb = new Callback_TestIntf_throwDerivedAsDerivedI(); + test.begin_throwDerivedAsDerived(cb); + cb.check(); + } + out.println("ok"); + + out.print("unknown derived exception thrown as base exception... "); + out.flush(); + { + try + { + test.throwUnknownDerivedAsBase(); + test(false); + } + catch(BaseException e) + { + test(e.ice_name().equals("Test::BaseException")); + test(e.sbe.equals("sbe")); + test(e.pb != null); + test(e.pb.sb.equals("sb d2")); + test(e.pb.pb == e.pb); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("unknown derived exception thrown as base exception (AMI)... "); + out.flush(); + { + Callback_TestIntf_throwUnknownDerivedAsBaseI cb = new Callback_TestIntf_throwUnknownDerivedAsBaseI(); + test.begin_throwUnknownDerivedAsBase(cb); + cb.check(); + } + out.println("ok"); + + out.print("forward-declared class... "); + out.flush(); + { + try + { + ForwardHolder f = new ForwardHolder(); + test.useForward(f); + test(f.value != null); + } + catch(Exception ex) + { + test(false); + } + } + out.println("ok"); + + out.print("forward-declared class (AMI)... "); + out.flush(); + { + Callback_TestIntf_useForwardI cb = new Callback_TestIntf_useForwardI(); + test.begin_useForward(cb); + cb.check(); + } + out.println("ok"); + + out.print("preserved classes... "); + out.flush(); + + // + // Register a factory in order to substitute our own subclass of Preserved. This provides + // an easy way to determine how many unmarshaled instances currently exist. + // + // TODO: We have to install this now (even though it's not necessary yet), because otherwise + // the Ice run time will install its own internal factory for Preserved upon receiving the + // first instance. + // + communicator.addObjectFactory(new PreservedFactoryI(), Preserved.ice_staticId()); + + try + { + // + // Server knows the most-derived class PDerived. + // + PDerived pd = new PDerived(); + pd.pi = 3; + pd.ps = "preserved"; + pd.pb = pd; + + PBase r = test.exchangePBase(pd); + PDerived p2 = (PDerived)r; + test(p2.pi == 3); + test(p2.ps.equals("preserved")); + test(p2.pb == p2); + } + catch(Ice.OperationNotExistException ex) + { + } + + try + { + // + // Server only knows the base (non-preserved) type, so the object is sliced. + // + PCUnknown pu = new PCUnknown(); + pu.pi = 3; + pu.pu = "preserved"; + + PBase r = test.exchangePBase(pu); + test(!(r instanceof PCUnknown)); + test(r.pi == 3); + } + catch(Ice.OperationNotExistException ex) + { + } + + try + { + // + // Server only knows the intermediate type Preserved. The object will be sliced to + // Preserved for the 1.0 encoding; otherwise it should be returned intact. + // + PCDerived pcd = new PCDerived(); + pcd.pi = 3; + pcd.pbs = new PBase[] { pcd }; + + PBase r = test.exchangePBase(pcd); + if(test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)) + { + test(!(r instanceof PCDerived)); + test(r.pi == 3); + } + else + { + PCDerived p2 = (PCDerived)r; + test(p2.pi == 3); + test(p2.pbs[0] == p2); + } + } + catch(Ice.OperationNotExistException ex) + { + } + + try + { + // + // Server only knows the intermediate type Preserved. The object will be sliced to + // Preserved for the 1.0 encoding; otherwise it should be returned intact. + // + CompactPCDerived pcd = new CompactPCDerived(); + pcd.pi = 3; + pcd.pbs = new PBase[] { pcd }; + + PBase r = test.exchangePBase(pcd); + if(test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)) + { + test(!(r instanceof CompactPCDerived)); + test(r.pi == 3); + } + else + { + CompactPCDerived p2 = (CompactPCDerived)r; + test(p2.pi == 3); + test(p2.pbs[0] == p2); + } + } + catch(Ice.OperationNotExistException ex) + { + } + + try + { + // + // Send an object that will have multiple preserved slices in the server. + // The object will be sliced to Preserved for the 1.0 encoding. + // + PCDerived3 pcd = new PCDerived3(); + pcd.pi = 3; + // + // Sending more than 254 objects exercises the encoding for object ids. + // + pcd.pbs = new PBase[300]; + int i; + for(i = 0; i < 300; ++i) + { + PCDerived2 p2 = new PCDerived2(); + p2.pi = i; + p2.pbs = new PBase[] { null }; // Nil reference. This slice should not have an indirection table. + p2.pcd2 = i; + pcd.pbs[i] = p2; + } + pcd.pcd2 = pcd.pi; + pcd.pcd3 = pcd.pbs[10]; + + PBase r = test.exchangePBase(pcd); + if(test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)) + { + test(!(r instanceof PCDerived3)); + test(r instanceof Preserved); + test(r.pi == 3); + } + else + { + PCDerived3 p3 = (PCDerived3)r; + test(p3.pi == 3); + for(i = 0; i < 300; ++i) + { + PCDerived2 p2 = (PCDerived2)p3.pbs[i]; + test(p2.pi == i); + test(p2.pbs.length == 1); + test(p2.pbs[0] == null); + test(p2.pcd2 == i); + } + test(p3.pcd2 == p3.pi); + test(p3.pcd3 == p3.pbs[10]); + } + } + catch(Ice.OperationNotExistException ex) + { + } + + try + { + // + // Obtain an object with preserved slices and send it back to the server. + // The preserved slices should be excluded for the 1.0 encoding, otherwise + // they should be included. + // + Preserved p = test.PBSUnknownAsPreserved(); + test.checkPBSUnknown(p); + if(!test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)) + { + ((TestIntfPrx)test.ice_encodingVersion(Ice.Util.Encoding_1_0)).checkPBSUnknown(p); + } + } + catch(Ice.OperationNotExistException ex) + { + } + out.println("ok"); + + out.print("preserved classes (AMI)... "); + out.flush(); + try + { + // + // Server knows the most-derived class PDerived. + // + PDerived pd = new PDerived(); + pd.pi = 3; + pd.ps = "preserved"; + pd.pb = pd; + + Callback_TestIntf_exchangePBaseI1 cb = new Callback_TestIntf_exchangePBaseI1(); + test.begin_exchangePBase(pd, cb); + cb.check(); + } + catch(Ice.OperationNotExistException ex) + { + } + + try + { + // + // Server only knows the base (non-preserved) type, so the object is sliced. + // + PCUnknown pu = new PCUnknown(); + pu.pi = 3; + pu.pu = "preserved"; + + Callback_TestIntf_exchangePBaseI2 cb = new Callback_TestIntf_exchangePBaseI2(); + test.begin_exchangePBase(pu, cb); + cb.check(); + } + catch(Ice.OperationNotExistException ex) + { + } + + try + { + // + // Server only knows the intermediate type Preserved. The object will be sliced to + // Preserved for the 1.0 encoding; otherwise it should be returned intact. + // + PCDerived pcd = new PCDerived(); + pcd.pi = 3; + pcd.pbs = new PBase[] { pcd }; + + if(test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)) + { + Callback_TestIntf_exchangePBaseI3 cb = new Callback_TestIntf_exchangePBaseI3(); + test.begin_exchangePBase(pcd, cb); + cb.check(); + } + else + { + Callback_TestIntf_exchangePBaseI4 cb = new Callback_TestIntf_exchangePBaseI4(); + test.begin_exchangePBase(pcd, cb); + cb.check(); + } + } + catch(Ice.OperationNotExistException ex) + { + } + + try + { + // + // Server only knows the intermediate type Preserved. The object will be sliced to + // Preserved for the 1.0 encoding; otherwise it should be returned intact. + // + CompactPCDerived pcd = new CompactPCDerived(); + pcd.pi = 3; + pcd.pbs = new PBase[] { pcd }; + + if(test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)) + { + Callback_TestIntf_exchangePBaseICompact1 cb = new Callback_TestIntf_exchangePBaseICompact1(); + test.begin_exchangePBase(pcd, cb); + cb.check(); + } + else + { + Callback_TestIntf_exchangePBaseICompact2 cb = new Callback_TestIntf_exchangePBaseICompact2(); + test.begin_exchangePBase(pcd, cb); + cb.check(); + } + } + catch(Ice.OperationNotExistException ex) + { + } + + try + { + // + // Send an object that will have multiple preserved slices in the server. + // The object will be sliced to Preserved for the 1.0 encoding. + // + PCDerived3 pcd = new PCDerived3(); + pcd.pi = 3; + // + // Sending more than 254 objects exercises the encoding for object ids. + // + pcd.pbs = new PBase[300]; + int i; + for(i = 0; i < 300; ++i) + { + PCDerived2 p2 = new PCDerived2(); + p2.pi = i; + p2.pbs = new PBase[] { null }; // Nil reference. This slice should not have an indirection table. + p2.pcd2 = i; + pcd.pbs[i] = p2; + } + pcd.pcd2 = pcd.pi; + pcd.pcd3 = pcd.pbs[10]; + + if(test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)) + { + Callback_TestIntf_exchangePBaseI5 cb = new Callback_TestIntf_exchangePBaseI5(); + test.begin_exchangePBase(pcd, cb); + cb.check(); + } + else + { + Callback_TestIntf_exchangePBaseI6 cb = new Callback_TestIntf_exchangePBaseI6(); + test.begin_exchangePBase(pcd, cb); + cb.check(); + } + } + catch(Ice.OperationNotExistException ex) + { + } + + try + { + // + // Obtain an object with preserved slices and send it back to the server. + // The preserved slices should be excluded for the 1.0 encoding, otherwise + // they should be included. + // + Preserved p = test.PBSUnknownAsPreserved(); + test.checkPBSUnknown(p); + if(!test.ice_getEncodingVersion().equals(Ice.Util.Encoding_1_0)) + { + ((TestIntfPrx)test.ice_encodingVersion(Ice.Util.Encoding_1_0)).checkPBSUnknown(p); + } + } + catch(Ice.OperationNotExistException ex) + { + } + + out.println("ok"); + + out.print("garbage collection for preserved classes... "); + out.flush(); + try + { + // + // Register a factory in order to substitute our own subclass of PNode. This provides + // an easy way to determine how many unmarshaled instances currently exist. + // + communicator.addObjectFactory(new NodeFactoryI(), PNode.ice_staticId()); + + // + // Relay a graph through the server. + // + { + PNode c = new PNode(); + c.next = new PNode(); + c.next.next = new PNode(); + c.next.next.next = c; + + test(PNodeI.counter == 0); + test.exchangePNode(c); + + test(PNodeI.counter == 3); + PNodeI.counter = 0; + } + + // + // Obtain a preserved object from the server where the most-derived + // type is unknown. The preserved slice refers to a graph of PNode + // objects. + // + { + test(PNodeI.counter == 0); + Preserved p = test.PBSUnknownAsPreservedWithGraph(); + test.checkPBSUnknownWithGraph(p); + test(PNodeI.counter == 3); + PNodeI.counter = 0; + } + + // + // Obtain a preserved object from the server where the most-derived + // type is unknown. A data member in the preserved slice refers to the + // outer object, so the chain of references looks like this: + // + // outer.slicedData.outer + // + { + PreservedI.counter = 0; + Preserved p = test.PBSUnknown2AsPreservedWithGraph(); + test.checkPBSUnknown2WithGraph(p); + test(PreservedI.counter == 1); + PreservedI.counter = 0; + } + + // + // Throw a preserved exception where the most-derived type is unknown. + // The preserved exception slice contains a class data member. This + // object is also preserved, and its most-derived type is also unknown. + // The preserved slice of the object contains a class data member that + // refers to itself. + // + // The chain of references looks like this: + // + // ex.slicedData.obj.slicedData.obj + // + try + { + test(PreservedI.counter == 0); + + try + { + test.throwPreservedException(); + } + catch(PreservedException ex) + { + test(PreservedI.counter == 1); + } + + PreservedI.counter = 0; + } + catch(Exception ex) + { + test(false); + } + } + catch(Ice.OperationNotExistException ex) + { + } + + out.println("ok"); + + return test; + } +} diff --git a/java/test/src/main/java/test/Ice/slicing/objects/Client.java b/java/test/src/main/java/test/Ice/slicing/objects/Client.java new file mode 100644 index 00000000000..e725c725339 --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/objects/Client.java @@ -0,0 +1,41 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.slicing.objects; + +import test.Ice.slicing.objects.client.Test.TestIntfPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + TestIntfPrx test = AllTests.allTests(communicator, false, getWriter()); + test.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.slicing.objects.client"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/slicing/objects/ClientPrivate.ice b/java/test/src/main/java/test/Ice/slicing/objects/ClientPrivate.ice new file mode 100644 index 00000000000..716147695ae --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/objects/ClientPrivate.ice @@ -0,0 +1,215 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.slicing.objects.client"]] +module Test +{ + +// +// Duplicate types from Test.ice. We cannot use #include since +// that will use the types from the same prefix. +// + +class SBase +{ + string sb; +}; + +class SBSKnownDerived extends SBase +{ + string sbskd; +}; + +class B +{ + string sb; + B pb; +}; + +class D1 extends B +{ + string sd1; + B pd1; +}; + +sequence<B> BSeq; + +class SS1 +{ + BSeq s; +}; + +class SS2 +{ + BSeq s; +}; + +struct SS3 +{ + SS1 c1; + SS2 c2; +}; + +dictionary<int, B> BDict; + +exception BaseException +{ + string sbe; + B pb; +}; + +exception DerivedException extends BaseException +{ + string sde; + D1 pd1; +}; + +class Forward; /* Forward-declared class defined in another compilation unit */ + +class PBase +{ + int pi; +}; + +sequence<PBase> PBaseSeq; + +["preserve-slice"] +class Preserved extends PBase +{ + string ps; +}; + +class PDerived extends Preserved +{ + PBase pb; +}; + +class CompactPDerived(56) extends Preserved +{ + PBase pb; +}; + +["preserve-slice"] +class PNode +{ + PNode next; +}; + +["preserve-slice"] +exception PreservedException +{ +}; + +["format:sliced"] +interface TestIntf +{ + Object SBaseAsObject(); + SBase SBaseAsSBase(); + SBase SBSKnownDerivedAsSBase(); + SBSKnownDerived SBSKnownDerivedAsSBSKnownDerived(); + + SBase SBSUnknownDerivedAsSBase(); + + ["format:compact"] SBase SBSUnknownDerivedAsSBaseCompact(); + + Object SUnknownAsObject(); + void checkSUnknown(Object o); + + B oneElementCycle(); + B twoElementCycle(); + B D1AsB(); + D1 D1AsD1(); + B D2AsB(); + + void paramTest1(out B p1, out B p2); + void paramTest2(out B p2, out B p1); + B paramTest3(out B p1, out B p2); + B paramTest4(out B p); + + B returnTest1(out B p1, out B p2); + B returnTest2(out B p2, out B p1); + B returnTest3(B p1, B p2); + + SS3 sequenceTest(SS1 p1, SS2 p2); + + BDict dictionaryTest(BDict bin, out BDict bout); + + PBase exchangePBase(PBase pb); + + Preserved PBSUnknownAsPreserved(); + void checkPBSUnknown(Preserved p); + + ["amd"] Preserved PBSUnknownAsPreservedWithGraph(); + void checkPBSUnknownWithGraph(Preserved p); + + ["amd"] Preserved PBSUnknown2AsPreservedWithGraph(); + void checkPBSUnknown2WithGraph(Preserved p); + + PNode exchangePNode(PNode pn); + + void throwBaseAsBase() throws BaseException; + void throwDerivedAsBase() throws BaseException; + void throwDerivedAsDerived() throws DerivedException; + void throwUnknownDerivedAsBase() throws BaseException; + ["amd"] void throwPreservedException() throws PreservedException; + + void useForward(out Forward f); /* Use of forward-declared class to verify that code is generated correctly. */ + + void shutdown(); +}; + +// +// Types private to the client. +// + +class D3 extends B +{ + string sd3; + B pd3; +}; + +["preserve-slice"] +class PCUnknown extends PBase +{ + string pu; +}; + +class PCDerived extends PDerived +{ + PBaseSeq pbs; +}; + +class PCDerived2 extends PCDerived +{ + int pcd2; +}; + +class PCDerived3 extends PCDerived2 +{ + Object pcd3; +}; + +class CompactPCDerived(57) extends CompactPDerived +{ + PBaseSeq pbs; +}; + +class Hidden +{ + Forward f; +}; + +class Forward +{ + Hidden h; +}; + +}; diff --git a/java/test/src/main/java/test/Ice/slicing/objects/Server.java b/java/test/src/main/java/test/Ice/slicing/objects/Server.java new file mode 100644 index 00000000000..fded6895de1 --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/objects/Server.java @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.slicing.objects; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Object object = new TestI(); + adapter.add(object, Ice.Util.stringToIdentity("Test")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.slicing.objects.server"); + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010 -t 2000"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/slicing/objects/ServerPrivate.ice b/java/test/src/main/java/test/Ice/slicing/objects/ServerPrivate.ice new file mode 100644 index 00000000000..f880521b7b1 --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/objects/ServerPrivate.ice @@ -0,0 +1,233 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.slicing.objects.server"]] +module Test +{ + +// +// Duplicate types from Test.ice. We cannot use #include since +// that will use the types from the same prefix. +// + +class SBase +{ + string sb; +}; + +class SBSKnownDerived extends SBase +{ + string sbskd; +}; + +class B +{ + string sb; + B pb; +}; + +class D1 extends B +{ + string sd1; + B pd1; +}; + +sequence<B> BSeq; + +class SS1 +{ + BSeq s; +}; + +class SS2 +{ + BSeq s; +}; + +struct SS3 +{ + SS1 c1; + SS2 c2; +}; + +dictionary<int, B> BDict; + +exception BaseException +{ + string sbe; + B pb; +}; + +exception DerivedException extends BaseException +{ + string sde; + D1 pd1; +}; + +class Forward; /* Forward-declared class defined in another compilation unit */ + +class PBase +{ + int pi; +}; + +sequence<PBase> PBaseSeq; + +["preserve-slice"] +class Preserved extends PBase +{ + string ps; +}; + +class PDerived extends Preserved +{ + PBase pb; +}; + +class CompactPDerived(56) extends Preserved +{ + PBase pb; +}; + +["preserve-slice"] +class PNode +{ + PNode next; +}; + +["preserve-slice"] +exception PreservedException +{ +}; + +["format:sliced"] +interface TestIntf +{ + Object SBaseAsObject(); + SBase SBaseAsSBase(); + SBase SBSKnownDerivedAsSBase(); + SBSKnownDerived SBSKnownDerivedAsSBSKnownDerived(); + + SBase SBSUnknownDerivedAsSBase(); + + ["format:compact"] SBase SBSUnknownDerivedAsSBaseCompact(); + + Object SUnknownAsObject(); + void checkSUnknown(Object o); + + B oneElementCycle(); + B twoElementCycle(); + B D1AsB(); + D1 D1AsD1(); + B D2AsB(); + + void paramTest1(out B p1, out B p2); + void paramTest2(out B p2, out B p1); + B paramTest3(out B p1, out B p2); + B paramTest4(out B p); + + B returnTest1(out B p1, out B p2); + B returnTest2(out B p2, out B p1); + B returnTest3(B p1, B p2); + + SS3 sequenceTest(SS1 p1, SS2 p2); + + BDict dictionaryTest(BDict bin, out BDict bout); + + PBase exchangePBase(PBase pb); + + Preserved PBSUnknownAsPreserved(); + void checkPBSUnknown(Preserved p); + + ["amd"] Preserved PBSUnknownAsPreservedWithGraph(); + void checkPBSUnknownWithGraph(Preserved p); + + ["amd"] Preserved PBSUnknown2AsPreservedWithGraph(); + void checkPBSUnknown2WithGraph(Preserved p); + + PNode exchangePNode(PNode pn); + + void throwBaseAsBase() throws BaseException; + void throwDerivedAsBase() throws BaseException; + void throwDerivedAsDerived() throws DerivedException; + void throwUnknownDerivedAsBase() throws BaseException; + ["amd"] void throwPreservedException() throws PreservedException; + + void useForward(out Forward f); /* Use of forward-declared class to verify that code is generated correctly. */ + + void shutdown(); +}; + +// +// Types private to the server. +// + +class SBSUnknownDerived extends SBase +{ + string sbsud; +}; + +class SUnknown +{ + string su; +}; + +class D2 extends B +{ + string sd2; + B pd2; +}; + +class D4 extends B +{ + B p1; + B p2; +}; + +exception UnknownDerivedException extends BaseException +{ + string sude; + D2 pd2; +}; + +class MyClass +{ + int i; +}; + +class PSUnknown extends Preserved +{ + string psu; + PNode graph; + MyClass cl; +}; + +class PSUnknown2 extends Preserved +{ + PBase pb; +}; + +exception PSUnknownException extends PreservedException +{ + PSUnknown2 p; +}; + +class Hidden +{ + Forward f; +}; + +class Forward +{ + Hidden h; +}; + +}; diff --git a/java/test/src/main/java/test/Ice/slicing/objects/ServerPrivateAMD.ice b/java/test/src/main/java/test/Ice/slicing/objects/ServerPrivateAMD.ice new file mode 100644 index 00000000000..abf0fc4ee64 --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/objects/ServerPrivateAMD.ice @@ -0,0 +1,228 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.slicing.objects.serverAMD"]] +module Test +{ + +// +// Duplicate types from Test.ice. We cannot use #include since +// that will use the types from the same prefix. +// + +class SBase +{ + string sb; +}; + +class SBSKnownDerived extends SBase +{ + string sbskd; +}; + +class B +{ + string sb; + B pb; +}; + +class D1 extends B +{ + string sd1; + B pd1; +}; + +sequence<B> BSeq; + +class SS1 +{ + BSeq s; +}; + +class SS2 +{ + BSeq s; +}; + +struct SS3 +{ + SS1 c1; + SS2 c2; +}; + +dictionary<int, B> BDict; + +exception BaseException +{ + string sbe; + B pb; +}; + +exception DerivedException extends BaseException +{ + string sde; + D1 pd1; +}; + +class Forward; // Forward-declared class defined in another compilation unit + +class PBase +{ + int pi; +}; + +sequence<PBase> PBaseSeq; + +["preserve-slice"] +class Preserved extends PBase +{ + string ps; +}; + +class PDerived extends Preserved +{ + PBase pb; +}; + +["preserve-slice"] +class PNode +{ + PNode next; +}; + +["preserve-slice"] +exception PreservedException +{ +}; + +["amd", "format:sliced"] +interface TestIntf +{ + Object SBaseAsObject(); + SBase SBaseAsSBase(); + SBase SBSKnownDerivedAsSBase(); + SBSKnownDerived SBSKnownDerivedAsSBSKnownDerived(); + + SBase SBSUnknownDerivedAsSBase(); + + ["format:compact"] SBase SBSUnknownDerivedAsSBaseCompact(); + + Object SUnknownAsObject(); + void checkSUnknown(Object o); + + B oneElementCycle(); + B twoElementCycle(); + B D1AsB(); + D1 D1AsD1(); + B D2AsB(); + + void paramTest1(out B p1, out B p2); + void paramTest2(out B p2, out B p1); + B paramTest3(out B p1, out B p2); + B paramTest4(out B p); + + B returnTest1(out B p1, out B p2); + B returnTest2(out B p2, out B p1); + B returnTest3(B p1, B p2); + + SS3 sequenceTest(SS1 p1, SS2 p2); + + BDict dictionaryTest(BDict bin, out BDict bout); + + PBase exchangePBase(PBase pb); + + Preserved PBSUnknownAsPreserved(); + void checkPBSUnknown(Preserved p); + + Preserved PBSUnknownAsPreservedWithGraph(); + void checkPBSUnknownWithGraph(Preserved p); + + Preserved PBSUnknown2AsPreservedWithGraph(); + void checkPBSUnknown2WithGraph(Preserved p); + + PNode exchangePNode(PNode pn); + + void throwBaseAsBase() throws BaseException; + void throwDerivedAsBase() throws BaseException; + void throwDerivedAsDerived() throws DerivedException; + void throwUnknownDerivedAsBase() throws BaseException; + void throwPreservedException() throws PreservedException; + + void useForward(out Forward f); /* Use of forward-declared class to verify that code is generated correctly. */ + + void shutdown(); +}; + +// +// Types private to the server. +// + +class SBSUnknownDerived extends SBase +{ + string sbsud; +}; + +class SUnknown +{ + string su; +}; + +class D2 extends B +{ + string sd2; + B pd2; +}; + +class D4 extends B +{ + B p1; + B p2; +}; + +exception UnknownDerivedException extends BaseException +{ + string sude; + D2 pd2; +}; + +class MyClass +{ + int i; +}; + +class PSUnknown extends Preserved +{ + string psu; + PNode graph; + MyClass cl; +}; + +class PSUnknown2 extends Preserved +{ + PBase pb; +}; + +exception PSUnknownException extends PreservedException +{ + PSUnknown2 p; +}; + +class Hidden +{ + Forward f; +}; + +class Forward +{ + Hidden h; +}; + +}; diff --git a/java/test/src/main/java/test/Ice/slicing/objects/TestI.java b/java/test/src/main/java/test/Ice/slicing/objects/TestI.java new file mode 100644 index 00000000000..aa199bfdcbe --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/objects/TestI.java @@ -0,0 +1,543 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.slicing.objects; + +import test.Ice.slicing.objects.server.Test.*; + +public final class TestI extends _TestIntfDisp +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + @Override + public Ice.Object + SBaseAsObject(Ice.Current current) + { + SBase sb = new SBase(); + sb.sb = "SBase.sb"; + return sb; + } + + @Override + public SBase + SBaseAsSBase(Ice.Current current) + { + SBase sb = new SBase(); + sb.sb = "SBase.sb"; + return sb; + } + + @Override + public SBase + SBSKnownDerivedAsSBase(Ice.Current current) + { + SBSKnownDerived sbskd = new SBSKnownDerived(); + sbskd.sb = "SBSKnownDerived.sb"; + sbskd.sbskd = "SBSKnownDerived.sbskd"; + return sbskd; + } + + @Override + public SBSKnownDerived + SBSKnownDerivedAsSBSKnownDerived(Ice.Current current) + { + SBSKnownDerived sbskd = new SBSKnownDerived(); + sbskd.sb = "SBSKnownDerived.sb"; + sbskd.sbskd = "SBSKnownDerived.sbskd"; + return sbskd; + } + + @Override + public SBase + SBSUnknownDerivedAsSBase(Ice.Current current) + { + SBSUnknownDerived sbsud = new SBSUnknownDerived(); + sbsud.sb = "SBSUnknownDerived.sb"; + sbsud.sbsud = "SBSUnknownDerived.sbsud"; + return sbsud; + } + + @Override + public SBase + SBSUnknownDerivedAsSBaseCompact(Ice.Current current) + { + SBSUnknownDerived sbsud = new SBSUnknownDerived(); + sbsud.sb = "SBSUnknownDerived.sb"; + sbsud.sbsud = "SBSUnknownDerived.sbsud"; + return sbsud; + } + + @Override + public Ice.Object + SUnknownAsObject(Ice.Current current) + { + SUnknown su = new SUnknown(); + su.su = "SUnknown.su"; + return su; + } + + @Override + public void + checkSUnknown(Ice.Object obj, Ice.Current current) + { + if(current.encoding.equals(Ice.Util.Encoding_1_0)) + { + test(!(obj instanceof SUnknown)); + } + else + { + SUnknown su = (SUnknown)obj; + test(su.su.equals("SUnknown.su")); + } + } + + @Override + public B + oneElementCycle(Ice.Current current) + { + B b = new B(); + b.sb = "B1.sb"; + b.pb = b; + return b; + } + + @Override + public B + twoElementCycle(Ice.Current current) + { + B b1 = new B(); + b1.sb = "B1.sb"; + B b2 = new B(); + b2.sb = "B2.sb"; + b2.pb = b1; + b1.pb = b2; + return b1; + } + + @Override + public B + D1AsB(Ice.Current current) + { + D1 d1 = new D1(); + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + D2 d2 = new D2(); + d2.pb = d1; + d2.sb = "D2.sb"; + d2.sd2 = "D2.sd2"; + d2.pd2 = d1; + d1.pb = d2; + d1.pd1 = d2; + return d1; + } + + @Override + public D1 + D1AsD1(Ice.Current current) + { + D1 d1 = new D1(); + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + D2 d2 = new D2(); + d2.pb = d1; + d2.sb = "D2.sb"; + d2.sd2 = "D2.sd2"; + d2.pd2 = d1; + d1.pb = d2; + d1.pd1 = d2; + return d1; + } + + @Override + public B + D2AsB(Ice.Current current) + { + D2 d2 = new D2(); + d2.sb = "D2.sb"; + d2.sd2 = "D2.sd2"; + D1 d1 = new D1(); + d1.pb = d2; + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + d1.pd1 = d2; + d2.pb = d1; + d2.pd2 = d1; + return d2; + } + + @Override + public void + paramTest1(BHolder p1, BHolder p2, Ice.Current current) + { + D1 d1 = new D1(); + d1.sb = "D1.sb"; + d1.sd1 = "D1.sd1"; + D2 d2 = new D2(); + d2.pb = d1; + d2.sb = "D2.sb"; + d2.sd2 = "D2.sd2"; + d2.pd2 = d1; + d1.pb = d2; + d1.pd1 = d2; + p1.value = d1; + p2.value = d2; + } + + @Override + public void + paramTest2(BHolder p1, BHolder p2, Ice.Current current) + { + paramTest1(p2, p1, current); + } + + @Override + public B + paramTest3(BHolder p1, BHolder p2, Ice.Current current) + { + D2 d2 = new D2(); + d2.sb = "D2.sb (p1 1)"; + d2.pb = null; + d2.sd2 = "D2.sd2 (p1 1)"; + p1.value = d2; + + D1 d1 = new D1(); + d1.sb = "D1.sb (p1 2)"; + d1.pb = null; + d1.sd1 = "D1.sd2 (p1 2)"; + d1.pd1 = null; + d2.pd2 = d1; + + D2 d4 = new D2(); + d4.sb = "D2.sb (p2 1)"; + d4.pb = null; + d4.sd2 = "D2.sd2 (p2 1)"; + p2.value = d4; + + D1 d3 = new D1(); + d3.sb = "D1.sb (p2 2)"; + d3.pb = null; + d3.sd1 = "D1.sd2 (p2 2)"; + d3.pd1 = null; + d4.pd2 = d3; + + return d3; + } + + @Override + public B + paramTest4(BHolder p1, Ice.Current current) + { + D4 d4 = new D4(); + d4.sb = "D4.sb (1)"; + d4.pb = null; + d4.p1 = new B(); + d4.p1.sb = "B.sb (1)"; + d4.p2 = new B(); + d4.p2.sb = "B.sb (2)"; + p1.value = d4; + return d4.p2; + } + + @Override + public B + returnTest1(BHolder p1, BHolder p2, Ice.Current current) + { + Ice.Current c; + paramTest1(p1, p2, current); + return p1.value; + } + + @Override + public B + returnTest2(BHolder p1, BHolder p2, Ice.Current current) + { + Ice.Current c; + paramTest1(p2, p1, current); + return p1.value; + } + + @Override + public B + returnTest3(B p1, B p2, Ice.Current current) + { + return p1; + } + + @Override + public SS3 + sequenceTest(SS1 p1, SS2 p2, Ice.Current current) + { + SS3 ss = new SS3(); + ss.c1 = p1; + ss.c2 = p2; + return ss; + } + + @Override + public java.util.Map<Integer, B> + dictionaryTest(java.util.Map<Integer, B> bin, BDictHolder bout, Ice.Current current) + { + bout.value = new java.util.HashMap<Integer, B>(); + int i; + for(i = 0; i < 10; ++i) + { + B b = bin.get(i); + D2 d2 = new D2(); + d2.sb = b.sb; + d2.pb = b.pb; + d2.sd2 = "D2"; + d2.pd2 = d2; + bout.value.put(i * 10, d2); + } + java.util.Map<Integer, B> r = new java.util.HashMap<Integer, B>(); + for(i = 0; i < 10; ++i) + { + String s = "D1." + new Integer(i * 20).toString(); + D1 d1 = new D1(); + d1.sb = s; + d1.pb = (i == 0 ? null : r.get((i - 1) * 20)); + d1.sd1 = s; + d1.pd1 = d1; + r.put(i * 20, d1); + } + return r; + } + + @Override + public PBase + exchangePBase(PBase pb, Ice.Current current) + { + return pb; + } + + @Override + public Preserved + PBSUnknownAsPreserved(Ice.Current current) + { + PSUnknown r = new PSUnknown(); + r.pi = 5; + r.ps = "preserved"; + r.psu = "unknown"; + r.graph = null; + if(!current.encoding.equals(Ice.Util.Encoding_1_0)) + { + // + // 1.0 encoding doesn't support unmarshaling unknown classes even if referenced + // from unread slice. + // + r.cl = new MyClass(15); + } + return r; + } + + @Override + public void + checkPBSUnknown(Preserved p, Ice.Current current) + { + if(current.encoding.equals(Ice.Util.Encoding_1_0)) + { + test(!(p instanceof PSUnknown)); + test(p.pi == 5); + test(p.ps.equals("preserved")); + } + else + { + PSUnknown pu = (PSUnknown)p; + test(pu.pi == 5); + test(pu.ps.equals("preserved")); + test(pu.psu.equals("unknown")); + test(pu.graph == null); + test(pu.cl != null && pu.cl.i == 15); + } + } + + @Override + public void + PBSUnknownAsPreservedWithGraph_async(AMD_TestIntf_PBSUnknownAsPreservedWithGraph cb, Ice.Current current) + { + PSUnknown r = new PSUnknown(); + r.pi = 5; + r.ps = "preserved"; + r.psu = "unknown"; + r.graph = new PNode(); + r.graph.next = new PNode(); + r.graph.next.next = new PNode(); + r.graph.next.next.next = r.graph; + cb.ice_response(r); + r.graph.next.next.next = null; // Break the cycle. + } + + @Override + public void + checkPBSUnknownWithGraph(Preserved p, Ice.Current current) + { + if(current.encoding.equals(Ice.Util.Encoding_1_0)) + { + test(!(p instanceof PSUnknown)); + test(p.pi == 5); + test(p.ps.equals("preserved")); + } + else + { + PSUnknown pu = (PSUnknown)p; + test(pu.pi == 5); + test(pu.ps.equals("preserved")); + test(pu.psu.equals("unknown")); + test(pu.graph != pu.graph.next); + test(pu.graph.next != pu.graph.next.next); + test(pu.graph.next.next.next == pu.graph); + pu.graph.next.next.next = null; // Break the cycle. + } + } + + @Override + public void + PBSUnknown2AsPreservedWithGraph_async(AMD_TestIntf_PBSUnknown2AsPreservedWithGraph cb, Ice.Current current) + { + PSUnknown2 r = new PSUnknown2(); + r.pi = 5; + r.ps = "preserved"; + r.pb = r; + cb.ice_response(r); + r.pb = null; // Break the cycle. + } + + @Override + public void + checkPBSUnknown2WithGraph(Preserved p, Ice.Current current) + { + if(current.encoding.equals(Ice.Util.Encoding_1_0)) + { + test(!(p instanceof PSUnknown2)); + test(p.pi == 5); + test(p.ps.equals("preserved")); + } + else + { + PSUnknown2 pu = (PSUnknown2)p; + test(pu.pi == 5); + test(pu.ps.equals("preserved")); + test(pu.pb == pu); + pu.pb = null; // Break the cycle. + } + } + + @Override + public PNode + exchangePNode(PNode pn, Ice.Current current) + { + return pn; + } + + @Override + public void + throwBaseAsBase(Ice.Current current) + throws BaseException + { + BaseException be = new BaseException(); + be.sbe = "sbe"; + be.pb = new B(); + be.pb.sb = "sb"; + be.pb.pb = be.pb; + throw be; + } + + @Override + public void + throwDerivedAsBase(Ice.Current current) + throws BaseException + { + DerivedException de = new DerivedException(); + de.sbe = "sbe"; + de.pb = new B(); + de.pb.sb = "sb1"; + de.pb.pb = de.pb; + de.sde = "sde1"; + de.pd1 = new D1(); + de.pd1.sb = "sb2"; + de.pd1.pb = de.pd1; + de.pd1.sd1 = "sd2"; + de.pd1.pd1 = de.pd1; + throw de; + } + + @Override + public void + throwDerivedAsDerived(Ice.Current current) + throws DerivedException + { + DerivedException de = new DerivedException(); + de.sbe = "sbe"; + de.pb = new B(); + de.pb.sb = "sb1"; + de.pb.pb = de.pb; + de.sde = "sde1"; + de.pd1 = new D1(); + de.pd1.sb = "sb2"; + de.pd1.pb = de.pd1; + de.pd1.sd1 = "sd2"; + de.pd1.pd1 = de.pd1; + throw de; + } + + @Override + public void + throwUnknownDerivedAsBase(Ice.Current current) + throws BaseException + { + D2 d2 = new D2(); + d2.sb = "sb d2"; + d2.pb = d2; + d2.sd2 = "sd2 d2"; + d2.pd2 = d2; + + UnknownDerivedException ude = new UnknownDerivedException(); + ude.sbe = "sbe"; + ude.pb = d2; + ude.sude = "sude"; + ude.pd2 = d2; + throw ude; + } + + @Override + public void + throwPreservedException_async(AMD_TestIntf_throwPreservedException cb, Ice.Current current) + { + PSUnknownException ue = new PSUnknownException(); + ue.p = new PSUnknown2(); + ue.p.pi = 5; + ue.p.ps = "preserved"; + ue.p.pb = ue.p; + cb.ice_exception(ue); + ue.p.pb = null; // Break the cycle. + } + + @Override + public void + useForward(ForwardHolder f, Ice.Current current) + { + f.value = new Forward(); + f.value.h = new Hidden(); + f.value.h.f = f.value; + } +} diff --git a/java/test/src/main/java/test/Ice/slicing/objects/run.py b/java/test/src/main/java/test/Ice/slicing/objects/run.py new file mode 100755 index 00000000000..cabf77e2817 --- /dev/null +++ b/java/test/src/main/java/test/Ice/slicing/objects/run.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("Running test with sliced format.") +TestUtil.clientServerTest() + +print("Running test with 1.0 encoding.") +TestUtil.clientServerTest(additionalClientOptions="--Ice.Default.EncodingVersion=1.0", + additionalServerOptions="--Ice.Default.EncodingVersion=1.0") + +print("Running test with sliced format and AMD server.") +TestUtil.clientServerTest(server="test.Ice.slicing.objects.AMDServer") + +print("Running test with 1.0 encoding and AMD server.") +TestUtil.clientServerTest(server="test.Ice.slicing.objects.AMDServer", + additionalClientOptions="--Ice.Default.EncodingVersion=1.0", + additionalServerOptions="--Ice.Default.EncodingVersion=1.0") diff --git a/java/test/src/main/java/test/Ice/stream/Client.java b/java/test/src/main/java/test/Ice/stream/Client.java new file mode 100644 index 00000000000..5d88f303e5d --- /dev/null +++ b/java/test/src/main/java/test/Ice/stream/Client.java @@ -0,0 +1,960 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.stream; + +import java.io.PrintWriter; + +import Ice.BoolSeqHelper; +import Ice.ByteSeqHelper; +import Ice.DoubleSeqHelper; +import Ice.FloatSeqHelper; +import Ice.ShortSeqHelper; +import Ice.IntSeqHelper; +import Ice.LongSeqHelper; +import Ice.StringSeqHelper; +import test.Ice.stream.Test.*; + +public class Client extends test.Util.Application +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class TestObjectWriter extends Ice.ObjectWriter + { + TestObjectWriter(MyClass obj) + { + this.obj = obj; + } + + @Override + public void + write(Ice.OutputStream out) + { + obj.__write(out); + called = true; + } + + MyClass obj; + boolean called = false; + } + + private static class TestObjectReader extends Ice.ObjectReader + { + @Override + public void + read(Ice.InputStream in) + { + obj = new MyClass(); + obj.__read(in); + called = true; + } + + MyClass obj; + boolean called = false; + } + + private static class TestObjectFactory implements Ice.ObjectFactory + { + @Override + public Ice.Object + create(String type) + { + assert(type.equals(MyClass.ice_staticId())); + return new TestObjectReader(); + } + + @Override + public void + destroy() + { + } + } + + private static class MyInterfaceI extends _MyInterfaceDisp + { + }; + + private static class MyInterfaceFactory implements Ice.ObjectFactory + { + @Override + public Ice.Object + create(String type) + { + assert(type.equals(_MyInterfaceDisp.ice_staticId())); + return new MyInterfaceI(); + } + + @Override + public void + destroy() + { + } + } + + private static class TestReadObjectCallback implements Ice.ReadObjectCallback + { + @Override + public void + invoke(Ice.Object obj) + { + this.obj = obj; + } + + Ice.Object obj; + } + + private static class MyClassFactoryWrapper implements Ice.ObjectFactory + { + MyClassFactoryWrapper() + { + _factory = MyClass.ice_factory(); + } + + @Override + public Ice.Object + create(String type) + { + return _factory.create(type); + } + + @Override + public void + destroy() + { + } + + void + setFactory(Ice.ObjectFactory factory) + { + if(factory == null) + { + _factory = MyClass.ice_factory(); + } + else + { + _factory = factory; + } + } + + private Ice.ObjectFactory _factory; + } + + @Override + public int + run(String[] args) + { + Ice.Communicator comm = communicator(); + MyClassFactoryWrapper factoryWrapper = new MyClassFactoryWrapper(); + comm.addObjectFactory(factoryWrapper, MyClass.ice_staticId()); + comm.addObjectFactory(new MyInterfaceFactory(), _MyInterfaceDisp.ice_staticId()); + + Ice.InputStream in; + Ice.OutputStream out; + + PrintWriter printWriter = getWriter(); + printWriter.print("testing primitive types... "); + printWriter.flush(); + + { + byte[] data = new byte[0]; + in = Ice.Util.createInputStream(comm, data); + in.destroy(); + } + + { + out = Ice.Util.createOutputStream(comm); + out.startEncapsulation(); + out.writeBool(true); + out.endEncapsulation(); + byte[] data = out.finished(); + out.destroy(); + + in = Ice.Util.createInputStream(comm, data); + in.startEncapsulation(); + test(in.readBool()); + in.endEncapsulation(); + in.destroy(); + + in = Ice.Util.wrapInputStream(comm, data); + in.startEncapsulation(); + test(in.readBool()); + in.endEncapsulation(); + in.destroy(); + } + + { + byte[] data = new byte[0]; + in = Ice.Util.createInputStream(comm, data); + try + { + in.readBool(); + test(false); + } + catch(Ice.UnmarshalOutOfBoundsException ex) + { + } + in.destroy(); + } + + { + out = Ice.Util.createOutputStream(comm); + out.writeBool(true); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + test(in.readBool()); + out.destroy(); + in.destroy(); + } + + { + out = Ice.Util.createOutputStream(comm); + out.writeByte((byte)1); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + test(in.readByte() == (byte)1); + out.destroy(); + in.destroy(); + } + + { + out = Ice.Util.createOutputStream(comm); + out.writeShort((short)2); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + test(in.readShort() == (short)2); + out.destroy(); + in.destroy(); + } + + { + out = Ice.Util.createOutputStream(comm); + out.writeInt(3); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + test(in.readInt() == 3); + out.destroy(); + in.destroy(); + } + + { + out = Ice.Util.createOutputStream(comm); + out.writeLong(4); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + test(in.readLong() == 4); + out.destroy(); + in.destroy(); + } + + { + out = Ice.Util.createOutputStream(comm); + out.writeFloat((float)5.0); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + test(in.readFloat() == (float)5.0); + out.destroy(); + in.destroy(); + } + + { + out = Ice.Util.createOutputStream(comm); + out.writeDouble(6.0); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + test(in.readDouble() == 6.0); + out.destroy(); + in.destroy(); + } + + { + out = Ice.Util.createOutputStream(comm); + out.writeString("hello world"); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + test(in.readString().equals("hello world")); + out.destroy(); + in.destroy(); + } + + printWriter.println("ok"); + + printWriter.print("testing constructed types... "); + printWriter.flush(); + + { + out = Ice.Util.createOutputStream(comm); + MyEnum.enum3.ice_write(out); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + test(MyEnum.ice_read(in) == MyEnum.enum3); + out.destroy(); + in.destroy(); + } + + { + out = Ice.Util.createOutputStream(comm); + SmallStruct s = new SmallStruct(); + 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 = MyEnum.enum2; + s.p = MyClassPrxHelper.uncheckedCast(comm.stringToProxy("test:default")); + s.ice_write(out); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + SmallStruct s2 = new SmallStruct(); + s2.ice_read(in); + test(s2.equals(s)); + out.destroy(); + in.destroy(); + } + + { + out = Ice.Util.createOutputStream(comm); + OptionalClass o = new OptionalClass(); + o.bo = true; + o.by = (byte)5; + o.setSh((short)4); + o.setI(3); + out.writeObject(o); + out.writePendingObjects(); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + TestReadObjectCallback cb = new TestReadObjectCallback(); + in.readObject(cb); + in.readPendingObjects(); + OptionalClass o2 = (OptionalClass)cb.obj; + test(o2.bo == o.bo); + test(o2.by == o.by); + if(comm.getProperties().getProperty("Ice.Default.EncodingVersion").equals("1.0")) + { + test(!o2.hasSh()); + test(!o2.hasI()); + } + else + { + test(o2.getSh() == o.getSh()); + test(o2.getI() == o.getI()); + } + out.destroy(); + in.destroy(); + } + + { + out = Ice.Util.createOutputStream(comm, Ice.Util.Encoding_1_0); + OptionalClass o = new OptionalClass(); + o.bo = true; + o.by = (byte)5; + o.setSh((short)4); + o.setI(3); + out.writeObject(o); + out.writePendingObjects(); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data, Ice.Util.Encoding_1_0); + TestReadObjectCallback cb = new TestReadObjectCallback(); + in.readObject(cb); + in.readPendingObjects(); + OptionalClass o2 = (OptionalClass)cb.obj; + test(o2.bo == o.bo); + test(o2.by == o.by); + test(!o2.hasSh()); + test(!o2.hasI()); + out.destroy(); + in.destroy(); + } + + { + final boolean[] arr = + { + true, + false, + true, + false + }; + out = Ice.Util.createOutputStream(comm); + BoolSeqHelper.write(out, arr); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + boolean[] arr2 = BoolSeqHelper.read(in); + test(java.util.Arrays.equals(arr2, arr)); + out.destroy(); + in.destroy(); + + final boolean[][] arrS = + { + arr, + new boolean[0], + arr + }; + out = Ice.Util.createOutputStream(comm); + BoolSSHelper.write(out, arrS); + data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + boolean[][] arr2S = BoolSSHelper.read(in); + test(java.util.Arrays.deepEquals(arr2S, arrS)); + out.destroy(); + in.destroy(); + } + + { + final byte[] arr = + { + (byte)0x01, + (byte)0x11, + (byte)0x12, + (byte)0x22 + }; + out = Ice.Util.createOutputStream(comm); + ByteSeqHelper.write(out, arr); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + byte[] arr2 = ByteSeqHelper.read(in); + test(java.util.Arrays.equals(arr2, arr)); + out.destroy(); + in.destroy(); + + final byte[][] arrS = + { + arr, + new byte[0], + arr + }; + out = Ice.Util.createOutputStream(comm); + ByteSSHelper.write(out, arrS); + data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + byte[][] arr2S = ByteSSHelper.read(in); + test(java.util.Arrays.deepEquals(arr2S, arrS)); + out.destroy(); + in.destroy(); + } + + { + test.Ice.stream.Serialize.Small small = new test.Ice.stream.Serialize.Small(); + small.i = 99; + out = Ice.Util.createOutputStream(comm); + out.writeSerializable(small); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + test.Ice.stream.Serialize.Small small2 = (test.Ice.stream.Serialize.Small)in.readSerializable(); + test(small2.i == 99); + out.destroy(); + in.destroy(); + } + + { + final short[] arr = + { + (short)0x01, + (short)0x11, + (short)0x12, + (short)0x22 + }; + out = Ice.Util.createOutputStream(comm); + ShortSeqHelper.write(out, arr); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + short[] arr2 = ShortSeqHelper.read(in); + test(java.util.Arrays.equals(arr2, arr)); + out.destroy(); + in.destroy(); + + final short[][] arrS = + { + arr, + new short[0], + arr + }; + out = Ice.Util.createOutputStream(comm); + ShortSSHelper.write(out, arrS); + data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + short[][] arr2S = ShortSSHelper.read(in); + test(java.util.Arrays.deepEquals(arr2S, arrS)); + out.destroy(); + in.destroy(); + } + + { + final int[] arr = + { + 0x01, + 0x11, + 0x12, + 0x22 + }; + out = Ice.Util.createOutputStream(comm); + IntSeqHelper.write(out, arr); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + int[] arr2 = IntSeqHelper.read(in); + test(java.util.Arrays.equals(arr2, arr)); + out.destroy(); + in.destroy(); + + final int[][] arrS = + { + arr, + new int[0], + arr + }; + out = Ice.Util.createOutputStream(comm); + IntSSHelper.write(out, arrS); + data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + int[][] arr2S = IntSSHelper.read(in); + test(java.util.Arrays.deepEquals(arr2S, arrS)); + out.destroy(); + in.destroy(); + } + + { + final long[] arr = + { + 0x01, + 0x11, + 0x12, + 0x22 + }; + out = Ice.Util.createOutputStream(comm); + LongSeqHelper.write(out, arr); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + long[] arr2 = LongSeqHelper.read(in); + test(java.util.Arrays.equals(arr2, arr)); + out.destroy(); + in.destroy(); + + final long[][] arrS = + { + arr, + new long[0], + arr + }; + out = Ice.Util.createOutputStream(comm); + LongSSHelper.write(out, arrS); + data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + long[][] arr2S = LongSSHelper.read(in); + test(java.util.Arrays.deepEquals(arr2S, arrS)); + out.destroy(); + in.destroy(); + } + + { + final float[] arr = + { + 1, + 2, + 3, + 4 + }; + out = Ice.Util.createOutputStream(comm); + FloatSeqHelper.write(out, arr); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + float[] arr2 = FloatSeqHelper.read(in); + test(java.util.Arrays.equals(arr2, arr)); + out.destroy(); + in.destroy(); + + final float[][] arrS = + { + arr, + new float[0], + arr + }; + out = Ice.Util.createOutputStream(comm); + FloatSSHelper.write(out, arrS); + data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + float[][] arr2S = FloatSSHelper.read(in); + test(java.util.Arrays.deepEquals(arr2S, arrS)); + out.destroy(); + in.destroy(); + } + + { + final double[] arr = + { + 1, + 2, + 3, + 4 + }; + out = Ice.Util.createOutputStream(comm); + DoubleSeqHelper.write(out, arr); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + double[] arr2 = DoubleSeqHelper.read(in); + test(java.util.Arrays.equals(arr2, arr)); + out.destroy(); + in.destroy(); + + final double[][] arrS = + { + arr, + new double[0], + arr + }; + out = Ice.Util.createOutputStream(comm); + DoubleSSHelper.write(out, arrS); + data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + double[][] arr2S = DoubleSSHelper.read(in); + test(java.util.Arrays.deepEquals(arr2S, arrS)); + out.destroy(); + in.destroy(); + } + + { + final String[] arr = + { + "string1", + "string2", + "string3", + "string4" + }; + out = Ice.Util.createOutputStream(comm); + StringSeqHelper.write(out, arr); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + String[] arr2 = StringSeqHelper.read(in); + test(java.util.Arrays.equals(arr2, arr)); + out.destroy(); + in.destroy(); + + final String[][] arrS = + { + arr, + new String[0], + arr + }; + out = Ice.Util.createOutputStream(comm); + StringSSHelper.write(out, arrS); + data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + String[][] arr2S = StringSSHelper.read(in); + test(java.util.Arrays.deepEquals(arr2S, arrS)); + out.destroy(); + in.destroy(); + } + + { + final MyEnum[] arr = + { + MyEnum.enum3, + MyEnum.enum2, + MyEnum.enum1, + MyEnum.enum2 + }; + out = Ice.Util.createOutputStream(comm); + MyEnumSHelper.write(out, arr); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + MyEnum[] arr2 = MyEnumSHelper.read(in); + test(java.util.Arrays.equals(arr2, arr)); + out.destroy(); + in.destroy(); + + final MyEnum[][] arrS = + { + arr, + new MyEnum[0], + arr + }; + out = Ice.Util.createOutputStream(comm); + MyEnumSSHelper.write(out, arrS); + data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + MyEnum[][] arr2S = MyEnumSSHelper.read(in); + test(java.util.Arrays.deepEquals(arr2S, arrS)); + out.destroy(); + in.destroy(); + } + + { + MyClass[] arr = new MyClass[4]; + for(int i = 0; i < arr.length; ++i) + { + arr[i] = new MyClass(); + arr[i].c = arr[i]; + arr[i].o = arr[i]; + arr[i].s = new SmallStruct(); + arr[i].s.e = MyEnum.enum2; + arr[i].seq1 = new boolean[] { true, false, true, false }; + arr[i].seq2 = new byte[] { (byte)1, (byte)2, (byte)3, (byte)4 }; + arr[i].seq3 = new short[] { (short)1, (short)2, (short)3, (short)4 }; + arr[i].seq4 = new int[] { 1, 2, 3, 4 }; + arr[i].seq5 = new long[] { 1, 2, 3, 4 }; + arr[i].seq6 = new float[] { 1, 2, 3, 4 }; + arr[i].seq7 = new double[] { 1, 2, 3, 4 }; + arr[i].seq8 = new String[] { "string1", "string2", "string3", "string4" }; + arr[i].seq9 = new MyEnum[] { MyEnum.enum3, MyEnum.enum2, MyEnum.enum1 }; + arr[i].seq10 = new MyClass[4]; // null elements. + arr[i].d = new java.util.HashMap<String, MyClass>(); + arr[i].d.put("hi", arr[i]); + } + out = Ice.Util.createOutputStream(comm); + MyClassSHelper.write(out, arr); + out.writePendingObjects(); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + MyClass[] arr2 = MyClassSHelper.read(in); + in.readPendingObjects(); + test(arr2.length == arr.length); + for(int i = 0; i < arr2.length; ++i) + { + test(arr2[i] != null); + test(arr2[i].c == arr2[i]); + test(arr2[i].o == arr2[i]); + test(arr2[i].s.e == MyEnum.enum2); + test(java.util.Arrays.equals(arr2[i].seq1, arr[i].seq1)); + test(java.util.Arrays.equals(arr2[i].seq2, arr[i].seq2)); + test(java.util.Arrays.equals(arr2[i].seq3, arr[i].seq3)); + test(java.util.Arrays.equals(arr2[i].seq4, arr[i].seq4)); + test(java.util.Arrays.equals(arr2[i].seq5, arr[i].seq5)); + test(java.util.Arrays.equals(arr2[i].seq6, arr[i].seq6)); + test(java.util.Arrays.equals(arr2[i].seq7, arr[i].seq7)); + test(java.util.Arrays.equals(arr2[i].seq8, arr[i].seq8)); + test(java.util.Arrays.equals(arr2[i].seq9, arr[i].seq9)); + test(arr2[i].d.get("hi") == arr2[i]); + } + out.destroy(); + in.destroy(); + + final MyClass[][] arrS = + { + arr, + new MyClass[0], + arr + }; + out = Ice.Util.createOutputStream(comm); + MyClassSSHelper.write(out, arrS); + data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + MyClass[][] arr2S = MyClassSSHelper.read(in); + test(arr2S.length == arrS.length); + test(arr2S[0].length == arrS[0].length); + test(arr2S[1].length == arrS[1].length); + test(arr2S[2].length == arrS[2].length); + out.destroy(); + in.destroy(); + } + + { + MyInterface i = new MyInterfaceI(); + out = Ice.Util.createOutputStream(comm); + MyInterfaceHelper.write(out, i); + out.writePendingObjects(); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + MyInterfaceHolder j = new MyInterfaceHolder(); + MyInterfaceHelper.read(in, j); + in.readPendingObjects(); + test(j.value != null); + } + + { + out = Ice.Util.createOutputStream(comm); + MyClass obj = new MyClass(); + obj.s = new SmallStruct(); + obj.s.e = MyEnum.enum2; + TestObjectWriter writer = new TestObjectWriter(obj); + out.writeObject(writer); + out.writePendingObjects(); + out.finished(); + test(writer.called); + out.destroy(); + } + + { + out = Ice.Util.createOutputStream(comm); + MyClass obj = new MyClass(); + obj.s = new SmallStruct(); + obj.s.e = MyEnum.enum2; + TestObjectWriter writer = new TestObjectWriter(obj); + out.writeObject(writer); + out.writePendingObjects(); + byte[] data = out.finished(); + test(writer.called); + factoryWrapper.setFactory(new TestObjectFactory()); + in = Ice.Util.createInputStream(comm, data); + TestReadObjectCallback cb = new TestReadObjectCallback(); + in.readObject(cb); + in.readPendingObjects(); + test(cb.obj != null); + test(cb.obj instanceof TestObjectReader); + TestObjectReader reader = (TestObjectReader)cb.obj; + test(reader.called); + test(reader.obj != null); + test(reader.obj.s.e == MyEnum.enum2); + out.destroy(); + in.destroy(); + factoryWrapper.setFactory(null); + } + + { + out = Ice.Util.createOutputStream(comm); + MyException ex = new MyException(); + + MyClass c = new MyClass(); + c.c = c; + c.o = c; + c.s = new SmallStruct(); + c.s.e = MyEnum.enum2; + c.seq1 = new boolean[] { true, false, true, false }; + c.seq2 = new byte[] { (byte)1, (byte)2, (byte)3, (byte)4 }; + c.seq3 = new short[] { (short)1, (short)2, (short)3, (short)4 }; + c.seq4 = new int[] { 1, 2, 3, 4 }; + c.seq5 = new long[] { 1, 2, 3, 4 }; + c.seq6 = new float[] { 1, 2, 3, 4 }; + c.seq7 = new double[] { 1, 2, 3, 4 }; + c.seq8 = new String[] { "string1", "string2", "string3", "string4" }; + c.seq9 = new MyEnum[] { MyEnum.enum3, MyEnum.enum2, MyEnum.enum1 }; + c.seq10 = new MyClass[4]; // null elements. + c.d = new java.util.HashMap<String, MyClass>(); + c.d.put("hi", c); + + ex.c = c; + + out.writeException(ex); + byte[] data = out.finished(); + + in = Ice.Util.createInputStream(comm, data); + try + { + in.throwException(); + test(false); + } + catch(MyException ex1) + { + test(ex1.c.s.e == c.s.e); + test(java.util.Arrays.equals(ex1.c.seq1, c.seq1)); + test(java.util.Arrays.equals(ex1.c.seq2, c.seq2)); + test(java.util.Arrays.equals(ex1.c.seq3, c.seq3)); + test(java.util.Arrays.equals(ex1.c.seq4, c.seq4)); + test(java.util.Arrays.equals(ex1.c.seq5, c.seq5)); + test(java.util.Arrays.equals(ex1.c.seq6, c.seq6)); + test(java.util.Arrays.equals(ex1.c.seq7, c.seq7)); + test(java.util.Arrays.equals(ex1.c.seq8, c.seq8)); + test(java.util.Arrays.equals(ex1.c.seq9, c.seq9)); + } + catch(Ice.UserException ex1) + { + test(false); + } + } + + { + java.util.Map<Byte, Boolean> dict = new java.util.HashMap<Byte, Boolean>(); + dict.put((byte)4, true); + dict.put((byte)1, false); + out = Ice.Util.createOutputStream(comm); + ByteBoolDHelper.write(out, dict); + byte data[] = out.finished(); + in = Ice.Util.createInputStream(comm, data); + java.util.Map<Byte, Boolean> dict2 = ByteBoolDHelper.read(in); + test(dict2.equals(dict)); + } + + { + java.util.Map<Short, Integer> dict = new java.util.HashMap<Short, Integer>(); + dict.put((short)1, 9); + dict.put((short)4, 8); + out = Ice.Util.createOutputStream(comm); + ShortIntDHelper.write(out, dict); + byte data[] = out.finished(); + in = Ice.Util.createInputStream(comm, data); + java.util.Map<Short, Integer> dict2 = ShortIntDHelper.read(in); + test(dict2.equals(dict)); + } + + + { + java.util.Map<Long, Float> dict = new java.util.HashMap<Long, Float>(); + dict.put((long)123809828, 0.51f); + dict.put((long)123809829, 0.56f); + out = Ice.Util.createOutputStream(comm); + LongFloatDHelper.write(out, dict); + byte data[] = out.finished(); + in = Ice.Util.createInputStream(comm, data); + java.util.Map<Long, Float> dict2 = LongFloatDHelper.read(in); + test(dict2.equals(dict)); + } + + { + java.util.Map<String, String> dict = new java.util.HashMap<String, String>(); + dict.put("key1", "value1"); + dict.put("key2", "value2"); + out = Ice.Util.createOutputStream(comm); + StringStringDHelper.write(out, dict); + byte data[] = out.finished(); + in = Ice.Util.createInputStream(comm, data); + java.util.Map<String, String> dict2 = StringStringDHelper.read(in); + test(dict2.equals(dict)); + } + + { + java.util.Map<String, MyClass> dict = new java.util.HashMap<String, MyClass>(); + MyClass c; + c = new MyClass(); + c.s = new SmallStruct(); + c.s.e = MyEnum.enum2; + dict.put("key1", c); + c = new MyClass(); + c.s = new SmallStruct(); + c.s.e = MyEnum.enum3; + dict.put("key2", c); + out = Ice.Util.createOutputStream(comm); + StringMyClassDHelper.write(out, dict); + out.writePendingObjects(); + byte[] data = out.finished(); + in = Ice.Util.createInputStream(comm, data); + java.util.Map<String, MyClass> dict2 = StringMyClassDHelper.read(in); + in.readPendingObjects(); + test(dict2.size() == dict.size()); + test(dict2.get("key1").s.e == MyEnum.enum2); + test(dict2.get("key2").s.e == MyEnum.enum3); + } + + printWriter.println("ok"); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.stream"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/stream/Serialize/Small.java b/java/test/src/main/java/test/Ice/stream/Serialize/Small.java new file mode 100644 index 00000000000..572d3ba10cf --- /dev/null +++ b/java/test/src/main/java/test/Ice/stream/Serialize/Small.java @@ -0,0 +1,15 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.stream.Serialize; + +public class Small implements java.io.Serializable // Fewer than 254 bytes when serialized. +{ + public int i; +} diff --git a/java/test/src/main/java/test/Ice/stream/Test.ice b/java/test/src/main/java/test/Ice/stream/Test.ice new file mode 100644 index 00000000000..5be23454461 --- /dev/null +++ b/java/test/src/main/java/test/Ice/stream/Test.ice @@ -0,0 +1,123 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/BuiltinSequences.ice> + +[["java:package:test.Ice.stream"]] +module Test +{ + +enum MyEnum +{ + enum1, + enum2, + enum3 +}; + +class MyClass; + +["java:serializable:test.Ice.stream.Serialize.Small"] sequence<byte> SerialSmall; + +struct SmallStruct +{ + bool bo; + byte by; + short sh; + int i; + long l; + float f; + double d; + string str; + MyEnum e; + MyClass* p; + SerialSmall ss; +}; + +struct Point +{ + int x; + int y; +}; + +sequence<MyEnum> MyEnumS; +sequence<MyClass> MyClassS; +dictionary<byte, bool> ByteBoolD; +dictionary<short, int> ShortIntD; +dictionary<string, MyClass> StringMyClassD; + +class OptionalClass +{ + bool bo; + byte by; + optional(1) short sh; + optional(2) int i; + optional(3) SmallStruct sm; + + optional(4) MyEnumS enumS4; + optional(5) MyClassS myClassS5; + + optional(6) ByteBoolD byteBoolD6; + optional(7) ShortIntD shortIntD7; + + optional(8) MyEnum enum8; + optional(9) MyClass class9; + optional(10) StringMyClassD stringMyClassD10; + optional(12) Ice::IntSeq intSeq12; + optional(13) Ice::ByteSeq byteSeq13; + optional(14) Ice::StringSeq stringSeq14; + optional(15) Point p15; +}; + +sequence<Ice::BoolSeq> BoolSS; +sequence<Ice::ByteSeq> ByteSS; +sequence<Ice::ShortSeq> ShortSS; +sequence<Ice::IntSeq> IntSS; +sequence<Ice::LongSeq> LongSS; +sequence<Ice::FloatSeq> FloatSS; +sequence<Ice::DoubleSeq> DoubleSS; +sequence<Ice::StringSeq> StringSS; +sequence<MyEnumS> MyEnumSS; +sequence<MyClassS> MyClassSS; + +dictionary<long, float> LongFloatD; +dictionary<string, string> StringStringD; + +class Bar; + +class MyClass +{ + MyClass c; + MyClass* prx; + Object o; + SmallStruct s; + Ice::BoolSeq seq1; + Ice::ByteSeq seq2; + Ice::ShortSeq seq3; + Ice::IntSeq seq4; + Ice::LongSeq seq5; + Ice::FloatSeq seq6; + Ice::DoubleSeq seq7; + Ice::StringSeq seq8; + MyEnumS seq9; + MyClassS seq10; + StringMyClassD d; +}; + +interface MyInterface +{ +}; + +exception MyException +{ + MyClass c; +}; + +}; diff --git a/java/test/src/main/java/test/Ice/stream/run.py b/java/test/src/main/java/test/Ice/stream/run.py new file mode 100755 index 00000000000..b071a5d9733 --- /dev/null +++ b/java/test/src/main/java/test/Ice/stream/run.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("Running test with default encoding...") +TestUtil.simpleTest("test.Ice.stream.Client") + +print("Running test with 1.0 encoding...") +TestUtil.simpleTest("test.Ice.stream.Client", "--Ice.Default.EncodingVersion=1.0") diff --git a/java/test/src/main/java/test/Ice/threadPoolPriority/Client.java b/java/test/src/main/java/test/Ice/threadPoolPriority/Client.java new file mode 100644 index 00000000000..86dd9468d47 --- /dev/null +++ b/java/test/src/main/java/test/Ice/threadPoolPriority/Client.java @@ -0,0 +1,50 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.threadPoolPriority; + +import test.Ice.threadPoolPriority.Test.PriorityPrx; +import test.Ice.threadPoolPriority.Test.PriorityPrxHelper; + +public class Client extends test.Util.Application +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + @Override + public int run(String[] args) + { + java.io.PrintWriter out = getWriter(); + Ice.ObjectPrx object = communicator().stringToProxy("test:default -p 12010 -t 10000"); + PriorityPrx priority = PriorityPrxHelper.checkedCast(object); + out.print("testing thread priority... "); + out.flush(); + int prio = priority.getPriority(); + test(prio == 10); + out.println("ok"); + + priority.shutdown(); + return 0; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/threadPoolPriority/PriorityI.java b/java/test/src/main/java/test/Ice/threadPoolPriority/PriorityI.java new file mode 100644 index 00000000000..18579e7713a --- /dev/null +++ b/java/test/src/main/java/test/Ice/threadPoolPriority/PriorityI.java @@ -0,0 +1,20 @@ + +package test.Ice.threadPoolPriority; + +import test.Ice.threadPoolPriority.Test._PriorityDisp; + +public class PriorityI extends _PriorityDisp +{ + + @Override + public void shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + @Override + public int getPriority(Ice.Current current) + { + return Thread.currentThread().getPriority(); + } +} diff --git a/java/test/src/main/java/test/Ice/threadPoolPriority/Server.java b/java/test/src/main/java/test/Ice/threadPoolPriority/Server.java new file mode 100644 index 00000000000..a1bdc6a0a31 --- /dev/null +++ b/java/test/src/main/java/test/Ice/threadPoolPriority/Server.java @@ -0,0 +1,43 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.threadPoolPriority; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + communicator().getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010 -t 10000:udp"); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + adapter.add(new PriorityI(), communicator().stringToIdentity("test")); + adapter.activate(); + + communicator().waitForShutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.ThreadPool.Server.ThreadPriority", "10"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/threadPoolPriority/Test.ice b/java/test/src/main/java/test/Ice/threadPoolPriority/Test.ice new file mode 100644 index 00000000000..d69a2fac75a --- /dev/null +++ b/java/test/src/main/java/test/Ice/threadPoolPriority/Test.ice @@ -0,0 +1,22 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.threadPoolPriority"]] +module Test +{ + +interface Priority +{ + void shutdown(); + int getPriority(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/threadPoolPriority/run.py b/java/test/src/main/java/test/Ice/threadPoolPriority/run.py new file mode 100755 index 00000000000..46e1ee20e8d --- /dev/null +++ b/java/test/src/main/java/test/Ice/threadPoolPriority/run.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +print("tests with regular server.") +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/throughput/Client.java b/java/test/src/main/java/test/Ice/throughput/Client.java new file mode 100644 index 00000000000..b508b11bc96 --- /dev/null +++ b/java/test/src/main/java/test/Ice/throughput/Client.java @@ -0,0 +1,494 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.throughput; + +import java.io.PrintWriter; + +import test.Ice.throughput.Demo.ByteSeqSize; +import test.Ice.throughput.Demo.Fixed; +import test.Ice.throughput.Demo.FixedSeqSize; +import test.Ice.throughput.Demo.StringDouble; +import test.Ice.throughput.Demo.StringDoubleSeqSize; +import test.Ice.throughput.Demo.StringSeqSize; +import test.Ice.throughput.Demo.ThroughputPrx; +import test.Ice.throughput.Demo.ThroughputPrxHelper; + +public class Client extends test.Util.Application +{ + class ShutdownHook extends Thread + { + @Override + public void + run() + { + try + { + communicator().destroy(); + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + } + } + } + + private static void + menu() + { + System.out.println( + "usage:\n" + + "\n" + + "toggle type of data to send:\n" + + "1: sequence of bytes (default)\n" + + "2: sequence of strings (\"hello\")\n" + + "3: sequence of structs with a string (\"hello\") and a double\n" + + "4: sequence of structs with two ints and a double\n" + + "\n" + + "select test to run:\n" + + "t: Send sequence as twoway\n" + + "o: Send sequence as oneway\n" + + "r: Receive sequence\n" + + "e: Echo (send and receive) sequence\n" + + "\n" + + "other commands:\n" + + "s: shutdown server\n" + + "x: exit\n" + + "?: help\n"); + } + + @Override + public int + run(String[] args) + { + PrintWriter out = getWriter(); + PrintWriter err = out; + if(args.length > 0) + { + 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. + // + ThroughputPrx throughput = ThroughputPrxHelper.checkedCast(communicator().propertyToProxy("Throughput.Proxy")); + if(throughput == null) + { + err.println("invalid proxy"); + return 1; + } + ThroughputPrx throughputOneway = ThroughputPrxHelper.uncheckedCast(throughput.ice_oneway()); + + byte[] byteSeq = new byte[ByteSeqSize.value]; + + String[] stringSeq = new String[StringSeqSize.value]; + for(int i = 0; i < StringSeqSize.value; ++i) + { + stringSeq[i] = "hello"; + } + + StringDouble[] structSeq = new StringDouble[StringDoubleSeqSize.value]; + for(int i = 0; i < StringDoubleSeqSize.value; ++i) + { + structSeq[i] = new StringDouble(); + structSeq[i].s = "hello"; + structSeq[i].d = 3.14; + } + + Fixed[] fixedSeq = new Fixed[FixedSeqSize.value]; + for(int i = 0; i < FixedSeqSize.value; ++i) + { + fixedSeq[i] = new Fixed(); + fixedSeq[i].i = 0; + fixedSeq[i].j = 0; + fixedSeq[i].d = 0; + } + + // + // A method needs to be invoked thousands of times before the + // JIT compiler will convert it to native code. To ensure an + // accurate throughput measurement, we need to "warm up" the + // JIT compiler. + // + +/* + { + byte[] emptyBytes= new byte[1]; + String[] emptyStrings = new String[1]; + StringDouble[] emptyStructs = new StringDouble[1]; + emptyStructs[0] = new StringDouble(); + Fixed[] emptyFixed = new Fixed[1]; + emptyFixed[0] = new Fixed(); + + throughput.startWarmup(); + + out.print("warming up the client/server..."); + out.flush(); + for(int i = 0; i < 10000; i++) + { + throughput.sendByteSeq(emptyBytes); + throughput.sendStringSeq(emptyStrings); + throughput.sendStructSeq(emptyStructs); + throughput.sendFixedSeq(emptyFixed); + + throughput.recvByteSeq(); + throughput.recvStringSeq(); + throughput.recvStructSeq(); + throughput.recvFixedSeq(); + + throughput.echoByteSeq(emptyBytes); + throughput.echoStringSeq(emptyStrings); + throughput.echoStructSeq(emptyStructs); + throughput.echoFixedSeq(emptyFixed); + } + throughput.endWarmup(); + + out.println(" ok"); + } +*/ + + menu(); + + char currentType = '1'; + int seqSize = ByteSeqSize.value; + + // Initial ping to setup the connection. + throughput.ice_ping(); + + String[] input = { "t", "o", "r", "e", "s", "x", null }; + int inputIndex = 0; + String line = null; + do + { + try + { + line = input[inputIndex++]; + + long tmsec = System.currentTimeMillis(); + final int repetitions = 100; + + if(line.equals("1") || line.equals("2") || line.equals("3") || line.equals("4")) + { + currentType = line.charAt(0); + + switch(currentType) + { + case '1': + { + out.println("using byte sequences"); + seqSize = ByteSeqSize.value; + break; + } + + case '2': + { + out.println("using string sequences"); + seqSize = StringSeqSize.value; + break; + } + + case '3': + { + out.println("using variable-length struct sequences"); + seqSize = StringDoubleSeqSize.value; + break; + } + + case '4': + { + out.println("using fixed-length struct sequences"); + seqSize = FixedSeqSize.value; + break; + } + } + } + else if(line.equals("t") || line.equals("o") || line.equals("r") || line.equals("e")) + { + char c = line.charAt(0); + + switch(c) + { + case 't': + case 'o': + { + out.print("sending"); + break; + } + + case 'r': + { + out.print("receiving"); + break; + } + + case 'e': + { + out.print("sending and receiving"); + break; + } + } + + out.print(" " + repetitions); + switch(currentType) + { + case '1': + { + out.print(" byte"); + break; + } + + case '2': + { + out.print(" string"); + break; + } + + case '3': + { + out.print(" variable-length struct"); + break; + } + + case '4': + { + out.print(" fixed-length struct"); + break; + } + } + + out.print(" sequences of size " + seqSize); + + if(c == 'o') + { + out.print(" as oneway"); + } + + out.println("..."); + out.flush(); + + for(int i = 0; i < repetitions; ++i) + { + switch(currentType) + { + case '1': + { + switch(c) + { + case 't': + { + throughput.sendByteSeq(byteSeq); + break; + } + + case 'o': + { + throughputOneway.sendByteSeq(byteSeq); + break; + } + + case 'r': + { + throughput.recvByteSeq(); + break; + } + + case 'e': + { + throughput.echoByteSeq(byteSeq); + break; + } + } + break; + } + + case '2': + { + switch(c) + { + case 't': + { + throughput.sendStringSeq(stringSeq); + break; + } + + case 'o': + { + throughputOneway.sendStringSeq(stringSeq); + break; + } + + case 'r': + { + throughput.recvStringSeq(); + break; + } + + case 'e': + { + throughput.echoStringSeq(stringSeq); + break; + } + } + break; + } + + case '3': + { + switch(c) + { + case 't': + { + throughput.sendStructSeq(structSeq); + break; + } + + case 'o': + { + throughputOneway.sendStructSeq(structSeq); + break; + } + + case 'r': + { + throughput.recvStructSeq(); + break; + } + + case 'e': + { + throughput.echoStructSeq(structSeq); + break; + } + } + break; + } + + case '4': + { + switch(c) + { + case 't': + { + throughput.sendFixedSeq(fixedSeq); + break; + } + + case 'o': + { + throughputOneway.sendFixedSeq(fixedSeq); + break; + } + + case 'r': + { + throughput.recvFixedSeq(); + break; + } + + case 'e': + { + throughput.echoFixedSeq(fixedSeq); + break; + } + } + break; + } + } + } + + double dmsec = System.currentTimeMillis() - tmsec; + out.println("time for " + repetitions + " sequences: " + dmsec + "ms"); + out.println("time per sequence: " + dmsec / repetitions + "ms"); + out.flush(); + int wireSize = 0; + switch(currentType) + { + case '1': + { + wireSize = 1; + break; + } + + case '2': + { + wireSize = stringSeq[0].length(); + break; + } + + case '3': + { + wireSize = structSeq[0].s.length(); + wireSize += 8; // Size of double on the wire. + break; + } + + case '4': + { + wireSize = 16; // Size of two ints and a double on the wire. + break; + } + } + double mbit = repetitions * seqSize * wireSize * 8.0 / dmsec / 1000.0; + if(c == 'e') + { + mbit *= 2; + } + out.println("throughput: " + new java.text.DecimalFormat("#.##").format(mbit) + "Mbps"); + out.flush(); + } + else if(line.equals("s")) + { + throughput.shutdown(); + } + else if(line.equals("x")) + { + // Nothing to do + } + else if(line.equals("?")) + { + menu(); + } + else + { + out.println("unknown command `" + line + "'"); + menu(); + } + } + catch(Ice.LocalException ex) + { + ex.printStackTrace(); + } + } + while(!line.equals("x")); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Demo", "test.Ice.throughput"); + initData.properties.setProperty("Throughput.Proxy", "throughput:default -p 10000 -h 127.0.0.1"); + initData.properties.setProperty("Ice.ACM.Client", "0"); + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/throughput/Server.java b/java/test/src/main/java/test/Ice/throughput/Server.java new file mode 100644 index 00000000000..95737f3dc10 --- /dev/null +++ b/java/test/src/main/java/test/Ice/throughput/Server.java @@ -0,0 +1,41 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.throughput; + +public class Server extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("Throughput"); + adapter.add(new ThroughputI(), communicator().stringToIdentity("throughput")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Demo", "test.Ice.throughput"); + initData.properties.setProperty("Throughput.Endpoints", "default -p 10000 -h 127.0.0.1"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/throughput/Throughput.ice b/java/test/src/main/java/test/Ice/throughput/Throughput.ice new file mode 100644 index 00000000000..d1ebb567ec7 --- /dev/null +++ b/java/test/src/main/java/test/Ice/throughput/Throughput.ice @@ -0,0 +1,66 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.throughput"]] +module Demo +{ + +sequence<byte> ByteSeq; +//const int ByteSeqSize = 500000; +const int ByteSeqSize = 250000; + +sequence<string> StringSeq; +const int StringSeqSize = 50000; + +struct StringDouble +{ + string s; + double d; +}; +sequence<StringDouble> StringDoubleSeq; +const int StringDoubleSeqSize = 50000; + +struct Fixed +{ + int i; + int j; + double d; +}; +sequence<Fixed> FixedSeq; +const int FixedSeqSize = 50000; + +interface Throughput +{ + bool needsWarmup(); + void startWarmup(); + void endWarmup(); + + void sendByteSeq(ByteSeq seq); + ByteSeq recvByteSeq(); + ByteSeq echoByteSeq(ByteSeq seq); + + void sendStringSeq(StringSeq seq); + StringSeq recvStringSeq(); + StringSeq echoStringSeq(StringSeq seq); + + void sendStructSeq(StringDoubleSeq seq); + StringDoubleSeq recvStructSeq(); + StringDoubleSeq echoStructSeq(StringDoubleSeq seq); + + void sendFixedSeq(FixedSeq seq); + FixedSeq recvFixedSeq(); + FixedSeq echoFixedSeq(FixedSeq seq); + + void shutdown(); +}; + +}; + diff --git a/java/test/src/main/java/test/Ice/throughput/ThroughputI.java b/java/test/src/main/java/test/Ice/throughput/ThroughputI.java new file mode 100644 index 00000000000..53253549102 --- /dev/null +++ b/java/test/src/main/java/test/Ice/throughput/ThroughputI.java @@ -0,0 +1,201 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.throughput; + +import test.Ice.throughput.Demo.ByteSeqSize; +import test.Ice.throughput.Demo.Fixed; +import test.Ice.throughput.Demo.FixedSeqSize; +import test.Ice.throughput.Demo.StringDouble; +import test.Ice.throughput.Demo.StringDoubleSeqSize; +import test.Ice.throughput.Demo.StringSeqSize; +import test.Ice.throughput.Demo._ThroughputDisp; + +public final class ThroughputI extends _ThroughputDisp +{ + public + ThroughputI() + { + _byteSeq = new byte[ByteSeqSize.value]; + + _stringSeq = new String[StringSeqSize.value]; + for(int i = 0; i < StringSeqSize.value; ++i) + { + _stringSeq[i] = "hello"; + } + + _structSeq = new StringDouble[StringDoubleSeqSize.value]; + for(int i = 0; i < StringDoubleSeqSize.value; ++i) + { + _structSeq[i] = new StringDouble(); + _structSeq[i].s = "hello"; + _structSeq[i].d = 3.14; + } + + _fixedSeq = new Fixed[FixedSeqSize.value]; + for(int i = 0; i < FixedSeqSize.value; ++i) + { + _fixedSeq[i] = new Fixed(); + _fixedSeq[i].i = 0; + _fixedSeq[i].j = 0; + _fixedSeq[i].d = 0; + } + } + + @Override + public boolean + needsWarmup(Ice.Current current) + { + _warmup = false; + return _needsWarmup; + } + + @Override + public void + startWarmup(Ice.Current current) + { + _warmup = true; + } + + @Override + public void + endWarmup(Ice.Current current) + { + _warmup = false; + _needsWarmup = false; + } + + @Override + public void + sendByteSeq(byte[] seq, Ice.Current current) + { + } + + @Override + public byte[] + recvByteSeq(Ice.Current current) + { + if(_warmup) + { + return _emptyByteSeq; + } + else + { + return _byteSeq; + } + } + + @Override + public byte[] + echoByteSeq(byte[] seq, Ice.Current current) + { + return seq; + } + + @Override + public void + sendStringSeq(String[] seq, Ice.Current current) + { + } + + @Override + public String[] + recvStringSeq(Ice.Current current) + { + if(_warmup) + { + return _emptyStringSeq; + } + else + { + return _stringSeq; + } + } + + @Override + public String[] + echoStringSeq(String[] seq, Ice.Current current) + { + return seq; + } + + @Override + public void + sendStructSeq(StringDouble[] seq, Ice.Current current) + { + } + + @Override + public StringDouble[] + recvStructSeq(Ice.Current current) + { + if(_warmup) + { + return _emptyStructSeq; + } + else + { + return _structSeq; + } + } + + @Override + public StringDouble[] + echoStructSeq(StringDouble[] seq, Ice.Current current) + { + return seq; + } + + @Override + public void + sendFixedSeq(Fixed[] seq, Ice.Current current) + { + } + + @Override + public Fixed[] + recvFixedSeq(Ice.Current current) + { + if(_warmup) + { + return _emptyFixedSeq; + } + else + { + return _fixedSeq; + } + } + + @Override + public Fixed[] + echoFixedSeq(Fixed[] seq, Ice.Current current) + { + return seq; + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + private byte[] _byteSeq; + private String[] _stringSeq; + private StringDouble[] _structSeq; + private Fixed[] _fixedSeq; + + private byte[] _emptyByteSeq = new byte[0]; + private String[] _emptyStringSeq = new String[0]; + private StringDouble[] _emptyStructSeq = new StringDouble[0]; + private Fixed[] _emptyFixedSeq = new Fixed[0]; + + private boolean _needsWarmup = true; + private boolean _warmup = false; +} diff --git a/java/test/src/main/java/test/Ice/timeout/AllTests.java b/java/test/src/main/java/test/Ice/timeout/AllTests.java new file mode 100644 index 00000000000..7f0239f32c5 --- /dev/null +++ b/java/test/src/main/java/test/Ice/timeout/AllTests.java @@ -0,0 +1,531 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.timeout; + +import java.io.PrintWriter; + +import test.Ice.timeout.Test.TimeoutPrx; +import test.Ice.timeout.Test.TimeoutPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static class Callback + { + Callback() + { + _called = false; + } + + public synchronized void + check() + { + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + } + + public synchronized void + called() + { + assert(!_called); + _called = true; + notify(); + } + + private boolean _called; + } + + private static class CallbackSuccess extends Ice.Callback + { + @Override + public void + completed(Ice.AsyncResult result) + { + try + { + TimeoutPrx p = TimeoutPrxHelper.uncheckedCast(result.getProxy()); + if(result.getOperation().equals("sendData")) + { + p.end_sendData(result); + } + else if(result.getOperation().equals("sleep")) + { + p.end_sleep(result); + } + } + catch(Ice.LocalException ex) + { + test(false); + } + callback.called(); + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + private static class CallbackFail extends Ice.Callback + { + @Override + public void + completed(Ice.AsyncResult result) + { + try + { + TimeoutPrx p = TimeoutPrxHelper.uncheckedCast(result.getProxy()); + if(result.getOperation().equals("sendData")) + { + p.end_sendData(result); + } + else if(result.getOperation().equals("sleep")) + { + p.end_sleep(result); + } + test(false); + } + catch(Ice.TimeoutException ex) + { + callback.called(); + } + catch(Ice.LocalException ex) + { + test(false); + } + } + + public void + check() + { + callback.check(); + } + + private Callback callback = new Callback(); + } + + public static TimeoutPrx + allTests(test.Util.Application app) + { + Ice.Communicator communicator = app.communicator(); + PrintWriter out = app.getWriter(); + + String sref = "timeout:default -p 12010"; + Ice.ObjectPrx obj = communicator.stringToProxy(sref); + test(obj != null); + + int mult = 1; + if(!communicator.getProperties().getPropertyWithDefault("Ice.Default.Protocol", "tcp").equals("tcp")) + { + mult = 4; + } + + TimeoutPrx timeout = TimeoutPrxHelper.checkedCast(obj); + test(timeout != null); + + out.print("testing connect timeout... "); + out.flush(); + { + // + // Expect ConnectTimeoutException. + // + TimeoutPrx to = TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(250 * mult)); + to.holdAdapter(500 * mult); + to.ice_getConnection().close(true); // Force a reconnect. + try + { + to.op(); + test(false); + } + catch(Ice.ConnectTimeoutException ex) + { + // Expected. + } + } + { + // + // Expect success. + // + timeout.op(); // Ensure adapter is active. + TimeoutPrx to = TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(1000 * mult)); + to.holdAdapter(500 * mult); + to.ice_getConnection().close(true); // Force a reconnect. + try + { + to.op(); + } + catch(Ice.ConnectTimeoutException ex) + { + test(false); + } + } + out.println("ok"); + + // The sequence needs to be large enough to fill the write/recv buffers + byte[] seq = new byte[20000000]; + + out.print("testing connection timeout... "); + out.flush(); + { + // + // Expect TimeoutException. + // + TimeoutPrx to = TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(250)); + to.holdAdapter(500 * mult); + try + { + to.sendData(seq); + test(false); + } + catch(Ice.TimeoutException ex) + { + // Expected. + } + } + { + // + // Expect success. + // + timeout.op(); // Ensure adapter is active. + TimeoutPrx to = TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(1000 * mult)); + to.holdAdapter(500 * mult); + try + { + to.sendData(new byte[1000000]); + } + catch(Ice.TimeoutException ex) + { + test(false); + } + } + out.println("ok"); + + out.print("testing invocation timeout... "); + out.flush(); + { + Ice.Connection connection = obj.ice_getConnection(); + TimeoutPrx to = TimeoutPrxHelper.uncheckedCast(obj.ice_invocationTimeout(250)); + test(connection == to.ice_getConnection()); + try + { + to.sleep(500 * mult); + test(false); + } + catch(Ice.InvocationTimeoutException ex) + { + } + to = TimeoutPrxHelper.checkedCast(obj.ice_invocationTimeout(500 * mult)); + test(connection == to.ice_getConnection()); + try + { + to.sleep(250 * mult); + } + catch(Ice.InvocationTimeoutException ex) + { + test(false); + } + test(connection == to.ice_getConnection()); + } + { + // + // Expect InvocationTimeoutException. + // + TimeoutPrx to = TimeoutPrxHelper.uncheckedCast(obj.ice_invocationTimeout(250)); + CallbackFail cb = new CallbackFail(); + to.begin_sleep(500 * mult, cb); + cb.check(); + } + { + // + // Expect success. + // + TimeoutPrx to = TimeoutPrxHelper.uncheckedCast(obj.ice_invocationTimeout(500 * mult)); + CallbackSuccess cb = new CallbackSuccess(); + to.begin_sleep(250 * mult, cb); + cb.check(); + } + { + // + // Backward compatible connection timeouts + // + TimeoutPrx to = TimeoutPrxHelper.uncheckedCast(obj.ice_invocationTimeout(-2).ice_timeout(250)); + Ice.Connection con = null; + try + { + con = to.ice_getConnection(); + to.sleep(500); + test(false); + } + catch(Ice.TimeoutException ex) + { + assert(con != null); + try + { + con.getInfo(); + test(false); + } + catch(Ice.TimeoutException exc) + { + // Connection got closed as well. + } + } + + try + { + con = to.ice_getConnection(); + to.end_sleep(to.begin_sleep(500)); + test(false); + } + catch(Ice.TimeoutException ex) + { + assert(con != null); + try + { + con.getInfo(); + test(false); + } + catch(Ice.TimeoutException exc) + { + // Connection got closed as well. + } + } + } + out.println("ok"); + + out.print("testing close timeout... "); + out.flush(); + { + TimeoutPrx to = TimeoutPrxHelper.checkedCast(obj.ice_timeout(250 * mult)); + Ice.Connection connection = to.ice_getConnection(); + timeout.holdAdapter(750); + connection.close(false); + try + { + connection.getInfo(); // getInfo() doesn't throw in the closing state. + } + catch(Ice.LocalException ex) + { + test(false); + } + try + { + Thread.sleep(500 * mult); + } + catch(java.lang.InterruptedException ex) + { + } + try + { + connection.getInfo(); + test(false); + } + catch(Ice.CloseConnectionException ex) + { + // Expected. + } + timeout.op(); // Ensure adapter is active. + } + out.println("ok"); + + out.print("testing timeout overrides... "); + out.flush(); + { + // + // Test Ice.Override.Timeout. This property overrides all + // endpoint timeouts. + // + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + initData.properties.setProperty("Ice.Override.Timeout", "250"); + Ice.Communicator comm = app.initialize(initData); + TimeoutPrx to = TimeoutPrxHelper.checkedCast(comm.stringToProxy(sref)); + to.holdAdapter(1000 * mult); + try + { + to.sendData(seq); + test(false); + } + catch(Ice.TimeoutException ex) + { + // Expected. + } + // + // Calling ice_timeout() should have no effect. + // + timeout.op(); // Ensure adapter is active. + to = TimeoutPrxHelper.checkedCast(to.ice_timeout(1000 * mult)); + to.holdAdapter(500 * mult); + try + { + to.sendData(seq); + test(false); + } + catch(Ice.TimeoutException ex) + { + // Expected. + } + comm.destroy(); + } + { + // + // Test Ice.Override.ConnectTimeout. + // + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + initData.properties.setProperty("Ice.Override.ConnectTimeout", "250"); + + Ice.Communicator comm = app.initialize(initData); + TimeoutPrx to = TimeoutPrxHelper.uncheckedCast(comm.stringToProxy(sref)); + timeout.holdAdapter(1000 * mult); + try + { + to.op(); + test(false); + } + catch(Ice.ConnectTimeoutException ex) + { + // Expected. + } + // + // Calling ice_timeout() should have no effect on the connect timeout. + // + timeout.op(); // Ensure adapter is active. + timeout.holdAdapter(1000 * mult); + to = TimeoutPrxHelper.uncheckedCast(to.ice_timeout(750 * mult)); + try + { + to.op(); + test(false); + } + catch(Ice.ConnectTimeoutException ex) + { + // Expected. + } + // + // Verify that timeout set via ice_timeout() is still used for requests. + // + timeout.op(); // Ensure adapter is active. + to.op(); // Force connection. + timeout.holdAdapter(1500 * mult); + to = TimeoutPrxHelper.uncheckedCast(to.ice_timeout(500)); + try + { + to.sendData(seq); + test(false); + } + catch(Ice.TimeoutException ex) + { + // Expected. + } + comm.destroy(); + } + { + // + // Test Ice.Override.CloseTimeout. + // + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + initData.properties.setProperty("Ice.Override.CloseTimeout", "200"); + Ice.Communicator comm = app.initialize(initData); + comm.stringToProxy(sref).ice_getConnection(); + timeout.holdAdapter(750); + long now = System.nanoTime(); + comm.destroy(); + test(System.nanoTime() - now < 500 * 1000000); + } + out.println("ok"); + + out.print("testing invocation timeouts with collocated calls... "); + out.flush(); + { + communicator.getProperties().setProperty("TimeoutCollocated.AdapterId", "timeoutAdapter"); + + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TimeoutCollocated"); + adapter.activate(); + + TimeoutPrx proxy = TimeoutPrxHelper.uncheckedCast(adapter.addWithUUID(new TimeoutI())); + proxy = (TimeoutPrx)proxy.ice_invocationTimeout(100); + try + { + proxy.sleep(150); + test(false); + } + catch(Ice.InvocationTimeoutException ex) + { + } + + try + { + proxy.end_sleep(proxy.begin_sleep(150)); + test(false); + } + catch(Ice.InvocationTimeoutException ex) + { + } + + ((TimeoutPrx)proxy.ice_invocationTimeout(-1)).ice_ping(); + + TimeoutPrx batchTimeout = (TimeoutPrx)proxy.ice_batchOneway(); + batchTimeout.ice_ping(); + batchTimeout.ice_ping(); + batchTimeout.ice_ping(); + + ((TimeoutPrx)proxy.ice_invocationTimeout(-1)).begin_sleep(150); // Keep the server thread pool busy. + try + { + batchTimeout.ice_flushBatchRequests(); + test(false); + } + catch(Ice.InvocationTimeoutException ex) + { + } + + batchTimeout.ice_ping(); + batchTimeout.ice_ping(); + batchTimeout.ice_ping(); + + ((TimeoutPrx)proxy.ice_invocationTimeout(-1)).begin_sleep(150); // Keep the server thread pool busy. + try + { + batchTimeout.end_ice_flushBatchRequests(batchTimeout.begin_ice_flushBatchRequests()); + test(false); + } + catch(Ice.InvocationTimeoutException ex) + { + } + + adapter.destroy(); + } + out.println("ok"); + + return timeout; + } +} diff --git a/java/test/src/main/java/test/Ice/timeout/Client.java b/java/test/src/main/java/test/Ice/timeout/Client.java new file mode 100644 index 00000000000..7476eb5c0e8 --- /dev/null +++ b/java/test/src/main/java/test/Ice/timeout/Client.java @@ -0,0 +1,57 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.timeout; + +import test.Ice.timeout.Test.TimeoutPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + TimeoutPrx timeout = AllTests.allTests(this); + timeout.shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.timeout"); + + // + // We need to send messages large enough to cause the transport + // buffers to fill up. + // + initData.properties.setProperty("Ice.MessageSizeMax", "20000"); + + // + // For this test, we want to disable retries. + // + initData.properties.setProperty("Ice.RetryIntervals", "-1"); + + // + // This test kills connections, so we don't want warnings. + // + initData.properties.setProperty("Ice.Warn.Connections", "0"); + + return initData; + } + + public static void main(String[] args) + { + Client app = new Client(); + int result = app.main("Client", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/timeout/Server.java b/java/test/src/main/java/test/Ice/timeout/Server.java new file mode 100644 index 00000000000..b4006770863 --- /dev/null +++ b/java/test/src/main/java/test/Ice/timeout/Server.java @@ -0,0 +1,46 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.timeout; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new TimeoutI(), communicator.stringToIdentity("timeout")); + adapter.activate(); + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.timeout"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010"); + + // + // This test kills connections, so we don't want warnings. + // + initData.properties.setProperty("Ice.Warn.Connections", "0"); + return initData; + } + + public static void main(String[] args) + { + Server app = new Server(); + int result = app.main("Server", args); + System.gc(); + System.exit(result); + } +} diff --git a/java/test/src/main/java/test/Ice/timeout/Test.ice b/java/test/src/main/java/test/Ice/timeout/Test.ice new file mode 100644 index 00000000000..69ca37fb5c5 --- /dev/null +++ b/java/test/src/main/java/test/Ice/timeout/Test.ice @@ -0,0 +1,29 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Ice.timeout"]] +module Test +{ + +sequence<byte> ByteSeq; + +interface Timeout +{ + void op(); + void sendData(ByteSeq seq); + void sleep(int to); + + void holdAdapter(int to); + + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/timeout/TimeoutI.java b/java/test/src/main/java/test/Ice/timeout/TimeoutI.java new file mode 100644 index 00000000000..61b8f7702c2 --- /dev/null +++ b/java/test/src/main/java/test/Ice/timeout/TimeoutI.java @@ -0,0 +1,84 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.timeout; +import test.Ice.timeout.Test._TimeoutDisp; + + +class TimeoutI extends _TimeoutDisp +{ + static class ActivateAdapterThread extends Thread + { + ActivateAdapterThread(Ice.ObjectAdapter adapter, int timeout) + { + _adapter = adapter; + _timeout = timeout; + } + + @Override + public void + run() + { + _adapter.waitForHold(); + try + { + sleep(_timeout); + } + catch(InterruptedException ex) + { + } + _adapter.activate(); + } + + Ice.ObjectAdapter _adapter; + int _timeout; + } + + @Override + public void + op(Ice.Current current) + { + } + + @Override + public void + sendData(byte[] seq, Ice.Current current) + { + } + + @Override + public void + sleep(int to, Ice.Current current) + { + try + { + Thread.currentThread(); + Thread.sleep(to); + } + catch(InterruptedException ex) + { + } + } + + @Override + public void + holdAdapter(int to, Ice.Current current) + { + current.adapter.hold(); + Thread thread = new ActivateAdapterThread(current.adapter, to); + thread.start(); + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/timeout/run.py b/java/test/src/main/java/test/Ice/timeout/run.py new file mode 100755 index 00000000000..d5fe04787c9 --- /dev/null +++ b/java/test/src/main/java/test/Ice/timeout/run.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest() diff --git a/java/test/src/main/java/test/Ice/timeout/timeout.jar b/java/test/src/main/java/test/Ice/timeout/timeout.jar Binary files differnew file mode 100644 index 00000000000..81d74d85812 --- /dev/null +++ b/java/test/src/main/java/test/Ice/timeout/timeout.jar diff --git a/java/test/src/main/java/test/Ice/udp/AllTests.java b/java/test/src/main/java/test/Ice/udp/AllTests.java new file mode 100644 index 00000000000..82dc1224d46 --- /dev/null +++ b/java/test/src/main/java/test/Ice/udp/AllTests.java @@ -0,0 +1,241 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.udp; + +import test.Ice.udp.Test.*; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static class PingReplyI extends _PingReplyDisp + { + @Override + public synchronized void + reply(Ice.Current current) + { + ++_replies; + notify(); + } + + public synchronized void + reset() + { + _replies = 0; + } + + public synchronized boolean + waitReply(int expectedReplies, long timeout) + { + long end = System.currentTimeMillis() + timeout; + while(_replies < expectedReplies) + { + long delay = end - System.currentTimeMillis(); + if(delay > 0) + { + try + { + wait(delay); + } + catch(java.lang.InterruptedException ex) + { + } + } + else + { + break; + } + } + return _replies == expectedReplies; + } + + private int _replies; + } + + public static void + allTests(Ice.Communicator communicator) + { + communicator.getProperties().setProperty("ReplyAdapter.Endpoints", "udp -p 12030"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("ReplyAdapter"); + PingReplyI replyI = new PingReplyI(); + + PingReplyPrx reply = + (PingReplyPrx)PingReplyPrxHelper.uncheckedCast(adapter.addWithUUID(replyI)).ice_datagram(); + adapter.activate(); + + System.out.print("testing udp... "); + System.out.flush(); + Ice.ObjectPrx base = communicator.stringToProxy("test -d:udp -p 12010"); + TestIntfPrx obj = TestIntfPrxHelper.uncheckedCast(base); + + 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 = (PingReplyPrx)PingReplyPrxHelper.uncheckedCast(adapter.addWithUUID(replyI)).ice_datagram(); + } + test(ret == true); + + if(communicator.getProperties().getPropertyAsInt("Ice.Override.Compress") == 0) + { + // + // Only run this test if compression is disabled, the test expect fixed message size + // to be sent over the wire. + // + byte[] seq = null; + try + { + seq = new byte[1024]; + while(true) + { + seq = new byte[seq.length * 2 + 10]; + replyI.reset(); + obj.sendByteSeq(seq, reply); + replyI.waitReply(1, 10000); + } + } + catch(Ice.DatagramLimitException ex) + { + test(seq.length > 16384); + } + obj.ice_getConnection().close(false); + communicator.getProperties().setProperty("Ice.UDP.SndSize", "64000"); + seq = new byte[50000]; + try + { + replyI.reset(); + obj.sendByteSeq(seq, reply); + test(!replyI.waitReply(1, 500)); + } + catch(Ice.LocalException ex) + { + System.err.println(ex); + test(false); + } + } + + System.out.println("ok"); + + System.out.print("testing udp multicast... "); + System.out.flush(); + String endpoint; + if(communicator.getProperties().getProperty("Ice.IPv6").equals("1")) + { + if(System.getProperty("os.name").contains("OS X")) + { + endpoint = "udp -h \"ff02::1:1\" -p 12020 --interface \"lo0\""; + } + else + { + endpoint = "udp -h \"ff01::1:1\" -p 12020"; + } + } + else + { + endpoint = "udp -h 239.255.1.1 -p 12020"; + } + base = communicator.stringToProxy("test -d:" + endpoint); + TestIntfPrx objMcast = TestIntfPrxHelper.uncheckedCast(base); + + nRetry = 5; + while(nRetry-- > 0) + { + replyI.reset(); + objMcast.ping(reply); + ret = replyI.waitReply(5, 2000); + if(ret) + { + break; // Success + } + replyI = new PingReplyI(); + reply = (PingReplyPrx)PingReplyPrxHelper.uncheckedCast(adapter.addWithUUID(replyI)).ice_datagram(); + } + if(!ret) + { + System.out.println("failed (is a firewall enabled?)"); + } + else + { + System.out.println("ok"); + } + + System.out.print("testing udp bi-dir connection... "); + System.out.flush(); + obj.ice_getConnection().setAdapter(adapter); + objMcast.ice_getConnection().setAdapter(adapter); + nRetry = 5; + while(nRetry-- > 0) + { + replyI.reset(); + obj.pingBiDir(reply.ice_getIdentity()); + obj.pingBiDir(reply.ice_getIdentity()); + obj.pingBiDir(reply.ice_getIdentity()); + ret = replyI.waitReply(3, 2000); + if(ret) + { + break; // Success + } + replyI = new PingReplyI(); + reply = (PingReplyPrx)PingReplyPrxHelper.uncheckedCast(adapter.addWithUUID(replyI)).ice_datagram(); + } + test(ret); + System.out.println("ok"); + + // + // Sending the replies back on the multicast UDP connection doesn't work for most + // platform (it works for OS X Leopard but not Snow Leopard, doesn't work on SLES, + // Windows...). For Windows, see UdpTransceiver constructor for the details. So + // we don't run this test. + // +// System.out.print("testing udp bi-dir connection... "); +// nRetry = 5; +// while(nRetry-- > 0) +// { +// replyI.reset(); +// objMcast.pingBiDir(reply.ice_getIdentity()); +// ret = replyI.waitReply(5, 2000); +// if(ret) +// { +// break; // Success +// } +// replyI = new PingReplyI(); +// reply = (PingReplyPrx)PingReplyPrxHelper.uncheckedCast(adapter.addWithUUID(replyI)).ice_datagram(); +// } + +// if(!ret) +// { +// System.out.println("failed (is a firewall enabled?)"); +// } +// else +// { +// System.out.println("ok"); +// } + } +} diff --git a/java/test/src/main/java/test/Ice/udp/Client.java b/java/test/src/main/java/test/Ice/udp/Client.java new file mode 100644 index 00000000000..afd4927a470 --- /dev/null +++ b/java/test/src/main/java/test/Ice/udp/Client.java @@ -0,0 +1,57 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.udp; + +import test.Ice.udp.Test.*; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + AllTests.allTests(communicator()); + + int num; + try + { + num = args.length == 1 ? Integer.parseInt(args[0]) : 0; + } + catch(NumberFormatException ex) + { + num = 0; + } + for(int i = 0; i < num; ++i) + { + TestIntfPrxHelper.uncheckedCast(communicator().stringToProxy("control:tcp -p " + (12010 + i))).shutdown(); + } + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.udp"); + initData.properties.setProperty("Ice.Warn.Connections", "0"); + initData.properties.setProperty("Ice.UDP.RcvSize", "16384"); + initData.properties.setProperty("Ice.UDP.SndSize", "16384"); + return initData; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/udp/Server.java b/java/test/src/main/java/test/Ice/udp/Server.java new file mode 100644 index 00000000000..05cfc43cbc8 --- /dev/null +++ b/java/test/src/main/java/test/Ice/udp/Server.java @@ -0,0 +1,85 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.udp; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Properties properties = communicator().getProperties(); + + int port = 12010; + try + { + port += args.length == 1 ? Integer.parseInt(args[0]) : 0; + } + catch(NumberFormatException ex) + { + } + properties.setProperty("ControlAdapter.Endpoints", "tcp -p " + port); + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("ControlAdapter"); + adapter.add(new TestIntfI(), communicator().stringToIdentity("control")); + adapter.activate(); + + if(port == 12010) + { + properties.setProperty("TestAdapter.Endpoints", "udp -p 12010"); + Ice.ObjectAdapter adapter2 = communicator().createObjectAdapter("TestAdapter"); + adapter2.add(new TestIntfI(), communicator().stringToIdentity("test")); + adapter2.activate(); + } + + Ice.ObjectAdapter mcastAdapter = communicator().createObjectAdapter("McastTestAdapter"); + mcastAdapter.add(new TestIntfI(), communicator().stringToIdentity("test")); + mcastAdapter.activate(); + + return WAIT; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.Ice.udp"); + initData.properties.setProperty("Ice.Warn.Connections", "0"); + initData.properties.setProperty("Ice.UDP.RcvSize", "16384"); + initData.properties.setProperty("Ice.UDP.SndSize", "16384"); + + String endpoint; + if(initData.properties.getProperty("Ice.IPv6").equals("1")) + { + if(System.getProperty("os.name").contains("OS X")) + { + endpoint = "udp -h \"ff02::1:1\" -p 12020 --interface \"lo0\""; + } + else + { + endpoint = "udp -h \"ff01::1:1\" -p 12020"; + } + } + else + { + endpoint = "udp -h 239.255.1.1 -p 12020"; + } + initData.properties.setProperty("McastTestAdapter.Endpoints", endpoint); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Ice/udp/Test.ice b/java/test/src/main/java/test/Ice/udp/Test.ice new file mode 100644 index 00000000000..be7a3269229 --- /dev/null +++ b/java/test/src/main/java/test/Ice/udp/Test.ice @@ -0,0 +1,32 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once +#include <Ice/Identity.ice> + +[["java:package:test.Ice.udp"]] +module Test +{ + +interface PingReply +{ + void reply(); +}; + +sequence<byte> ByteSeq; + +interface TestIntf +{ + void ping(PingReply* reply); + void sendByteSeq(ByteSeq seq, PingReply* reply); + void pingBiDir(Ice::Identity id); + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/Ice/udp/TestIntfI.java b/java/test/src/main/java/test/Ice/udp/TestIntfI.java new file mode 100644 index 00000000000..d4aba78a2c3 --- /dev/null +++ b/java/test/src/main/java/test/Ice/udp/TestIntfI.java @@ -0,0 +1,74 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Ice.udp; + +import test.Ice.udp.Test.*; + +public final class TestIntfI extends _TestIntfDisp +{ + @Override + public void ping(PingReplyPrx reply, Ice.Current current) + { + try + { + reply.reply(); + } + catch(Ice.LocalException ex) + { + assert(false); + } + } + + @Override + public void sendByteSeq(byte[] seq, PingReplyPrx reply, Ice.Current current) + { + try + { + reply.reply(); + } + catch(Ice.LocalException ex) + { + assert(false); + } + } + + @Override + public void pingBiDir(Ice.Identity id, Ice.Current current) + { + try + { + // + // Ensure sending too much data doesn't cause the UDP connection + // to be closed. + // + try + { + byte[] seq = new byte[32 * 1024]; + TestIntfPrxHelper.uncheckedCast(current.con.createProxy(id)).sendByteSeq(seq, null); + } + catch(Ice.DatagramLimitException ex) + { + // Expected. + } + + PingReplyPrxHelper.uncheckedCast(current.con.createProxy(id)).reply(); + } + catch(Ice.LocalException ex) + { + assert(false); + } + } + + @Override + public void shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/test/src/main/java/test/Ice/udp/run.py b/java/test/src/main/java/test/Ice/udp/run.py new file mode 100755 index 00000000000..efbd3b862cb --- /dev/null +++ b/java/test/src/main/java/test/Ice/udp/run.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.addClasspath(os.path.join(os.getcwd(), "classes")) + +num = 5 + +serverProc = [] +for i in range(0, num): + sys.stdout.write("starting server #%d... " % (i + 1)) + sys.stdout.flush() + serverProc.append(TestUtil.startServer("test.Ice.udp.Server", "%d" % i , adapter="McastTestAdapter")) + print("ok") + +sys.stdout.write("starting client... ") +sys.stdout.flush() +clientProc = TestUtil.startClient("test.Ice.udp.Client", "%d" % num, startReader=False) +print("ok") +clientProc.startReader() + +clientProc.waitTestSuccess() +for p in serverProc: + p.waitTestSuccess() diff --git a/java/test/src/main/java/test/IceBox/admin/AllTests.java b/java/test/src/main/java/test/IceBox/admin/AllTests.java new file mode 100644 index 00000000000..4063486d1da --- /dev/null +++ b/java/test/src/main/java/test/IceBox/admin/AllTests.java @@ -0,0 +1,128 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceBox.admin; + +import test.IceBox.admin.Test.*; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + allTests(Ice.Communicator communicator) + { + String ref = "DemoIceBox/admin:default -p 9996 -t 10000"; + Ice.ObjectPrx admin = communicator.stringToProxy(ref); + + TestFacetPrx facet = null; + + System.out.print("testing custom facet... "); + System.out.flush(); + { + // + // Test: Verify that the custom facet is present. + // + facet = TestFacetPrxHelper.checkedCast(admin, "TestFacet"); + facet.ice_ping(); + } + System.out.println("ok"); + + System.out.print("testing properties facet... "); + System.out.flush(); + { + Ice.PropertiesAdminPrx pa = + Ice.PropertiesAdminPrxHelper.checkedCast(admin, "IceBox.Service.TestService.Properties"); + + // + // Test: PropertiesAdmin::getProperty() + // + test(pa.getProperty("Prop1").equals("1")); + test(pa.getProperty("Bogus").equals("")); + + // + // Test: PropertiesAdmin::getProperties() + // + java.util.Map<String, String> pd = pa.getPropertiesForPrefix(""); + test(pd.size() == 6); + test(pd.get("Prop1").equals("1")); + test(pd.get("Prop2").equals("2")); + test(pd.get("Prop3").equals("3")); + test(pd.get("Ice.Config").equals("config.service")); + test(pd.get("Ice.ProgramName").equals("IceBox-TestService")); + test(pd.get("Ice.Admin.Enabled").equals("1")); + + java.util.Map<String, String> changes; + + // + // Test: PropertiesAdmin::setProperties() + // + java.util.Map<String, String> setProps = new java.util.HashMap<String, String>(); + setProps.put("Prop1", "10"); // Changed + setProps.put("Prop2", "20"); // Changed + setProps.put("Prop3", ""); // Removed + setProps.put("Prop4", "4"); // Added + setProps.put("Prop5", "5"); // Added + pa.setProperties(setProps); + test(pa.getProperty("Prop1").equals("10")); + test(pa.getProperty("Prop2").equals("20")); + test(pa.getProperty("Prop3").equals("")); + test(pa.getProperty("Prop4").equals("4")); + test(pa.getProperty("Prop5").equals("5")); + changes = facet.getChanges(); + test(changes.size() == 5); + test(changes.get("Prop1").equals("10")); + test(changes.get("Prop2").equals("20")); + test(changes.get("Prop3").equals("")); + test(changes.get("Prop4").equals("4")); + test(changes.get("Prop5").equals("5")); + pa.setProperties(setProps); + changes = facet.getChanges(); + test(changes.isEmpty()); + } + System.out.println("ok"); + + System.out.print("testing metrics admin facet... "); + System.out.flush(); + { + IceMX.MetricsAdminPrx ma = + IceMX.MetricsAdminPrxHelper.checkedCast(admin, "IceBox.Service.TestService.Metrics"); + + Ice.PropertiesAdminPrx pa = + Ice.PropertiesAdminPrxHelper.checkedCast(admin, "IceBox.Service.TestService.Properties"); + + String[] views; + Ice.StringSeqHolder disabledViews = new Ice.StringSeqHolder(); + views = ma.getMetricsViewNames(disabledViews); + test(views.length == 0); + + java.util.Map<String, String> setProps = new java.util.HashMap<String, String>(); + setProps.put("IceMX.Metrics.Debug.GroupBy", "id"); + setProps.put("IceMX.Metrics.All.GroupBy", "none"); + setProps.put("IceMX.Metrics.Parent.GroupBy", "parent"); + pa.setProperties(setProps); + pa.setProperties(new java.util.HashMap<String, String>()); + + views = ma.getMetricsViewNames(disabledViews); + test(views.length == 3); + + // Make sure that the IceBox communicator metrics admin is a separate instance. + test(IceMX.MetricsAdminPrxHelper.checkedCast(admin, + "Metrics").getMetricsViewNames(disabledViews).length == 0); + } + System.out.println("ok"); + } +} diff --git a/java/test/src/main/java/test/IceBox/admin/Client.java b/java/test/src/main/java/test/IceBox/admin/Client.java new file mode 100644 index 00000000000..80664c2edd0 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/admin/Client.java @@ -0,0 +1,60 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceBox.admin; + +public class Client +{ + private static int + run(String[] args, Ice.Communicator communicator) + { + AllTests.allTests(communicator); + + // + // Shutdown the IceBox server. + // + Ice.ProcessPrxHelper.uncheckedCast( + communicator.stringToProxy("DemoIceBox/admin -f Process:default -p 9996")).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/src/main/java/test/IceBox/admin/Test.ice b/java/test/src/main/java/test/IceBox/admin/Test.ice new file mode 100644 index 00000000000..88ab72b5322 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/admin/Test.ice @@ -0,0 +1,26 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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 + +#include <Ice/Properties.ice> + +[["java:package:test.IceBox.admin"]] +module Test +{ + +interface TestFacet +{ + Ice::PropertyDict getChanges(); +}; + +}; + +#endif diff --git a/java/test/src/main/java/test/IceBox/admin/TestFacetI.java b/java/test/src/main/java/test/IceBox/admin/TestFacetI.java new file mode 100644 index 00000000000..642ee400d20 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/admin/TestFacetI.java @@ -0,0 +1,57 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceBox.admin; + +import test.IceBox.admin.Test.*; + +public class TestFacetI extends _TestFacetDisp implements Ice.PropertiesAdminUpdateCallback +{ + public TestFacetI() + { + _called = false; + } + + @Override + public synchronized java.util.Map<String, String> getChanges(Ice.Current current) + { + // + // The client calls PropertiesAdmin::setProperties() and then invokes + // this operation. Since setProperties() is implemented using AMD, the + // client might receive its reply and then call getChanges() before our + // updated() method is called. We block here to ensure that updated() + // gets called before we return the most recent set of changes. + // + while(!_called) + { + try + { + wait(); + } + catch(InterruptedException ex) + { + } + } + + _called = false; + + return _changes; + } + + @Override + public synchronized void updated(java.util.Map<String, String> changes) + { + _changes = changes; + _called = true; + notify(); + } + + private java.util.Map<String, String> _changes; + private boolean _called; +} diff --git a/java/test/src/main/java/test/IceBox/admin/TestServiceI.java b/java/test/src/main/java/test/IceBox/admin/TestServiceI.java new file mode 100644 index 00000000000..7497771d248 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/admin/TestServiceI.java @@ -0,0 +1,46 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceBox.admin; + +public class TestServiceI implements IceBox.Service +{ + public TestServiceI(Ice.Communicator serviceManagerCommunicator) + { + TestFacetI facet = new TestFacetI(); + + // + // Install a custom admin facet. + // + serviceManagerCommunicator.addAdminFacet(facet, "TestFacet"); + + // + // The TestFacetI servant also implements PropertiesAdminUpdateCallback. + // Set the callback on the admin facet. + // + Ice.Object propFacet = serviceManagerCommunicator.findAdminFacet("IceBox.Service.TestService.Properties"); + if(propFacet != null) + { + Ice.NativePropertiesAdmin admin = (Ice.NativePropertiesAdmin)propFacet; + admin.addUpdateCallback(facet); + } + } + + @Override + public void + start(String name, Ice.Communicator communicator, String[] args) + { + } + + @Override + public void + stop() + { + } +} diff --git a/java/test/src/main/java/test/IceBox/admin/config.icebox b/java/test/src/main/java/test/IceBox/admin/config.icebox new file mode 100644 index 00000000000..34d0b233419 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/admin/config.icebox @@ -0,0 +1,5 @@ +Ice.Admin.InstanceName=DemoIceBox +Ice.Admin.Endpoints=default -p 9996 -h 127.0.0.1 +Ice.ProgramName=IceBox + +IceBox.Service.TestService=test.IceBox.admin.TestServiceI --Ice.Config=config.service diff --git a/java/test/src/main/java/test/IceBox/admin/config.service b/java/test/src/main/java/test/IceBox/admin/config.service new file mode 100644 index 00000000000..23c6f841859 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/admin/config.service @@ -0,0 +1,3 @@ +Prop1=1 +Prop2=2 +Prop3=3 diff --git a/java/test/src/main/java/test/IceBox/admin/run.py b/java/test/src/main/java/test/IceBox/admin/run.py new file mode 100755 index 00000000000..f84c3203acd --- /dev/null +++ b/java/test/src/main/java/test/IceBox/admin/run.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest(additionalServerOptions='--Ice.Config="%s"' % os.path.join(os.getcwd(), "config.icebox"), + server=TestUtil.getIceBox()) diff --git a/java/test/src/main/java/test/IceBox/configuration/AllTests.java b/java/test/src/main/java/test/IceBox/configuration/AllTests.java new file mode 100644 index 00000000000..68f5dd65dc6 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/AllTests.java @@ -0,0 +1,101 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceBox.configuration; + +import java.io.PrintWriter; + +import test.IceBox.configuration.Test.TestIntfPrx; +import test.IceBox.configuration.Test.TestIntfPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if (!b) + { + throw new RuntimeException(); + } + } + + public static void + allTests(Ice.Communicator communicator, PrintWriter out) + { + TestIntfPrx service1 = TestIntfPrxHelper.uncheckedCast(communicator.stringToProxy("test:tcp -p 12010")); + TestIntfPrx service2 = TestIntfPrxHelper.uncheckedCast(communicator.stringToProxy("test:tcp -p 12011")); + TestIntfPrx service3 = TestIntfPrxHelper.uncheckedCast(communicator.stringToProxy("test:tcp -p 12012")); + TestIntfPrx service4 = TestIntfPrxHelper.uncheckedCast(communicator.stringToProxy("test:tcp -p 12013")); + + if(service1.getProperty("IceBox.InheritProperties").equals("")) + { + out.print("testing service properties... "); + out.flush(); + + test(service1.getProperty("Ice.ProgramName").equals("IceBox-Service1")); + test(service1.getProperty("Service").equals("1")); + test(service1.getProperty("Service1.Ovrd").equals("2")); + test(service1.getProperty("Service1.Unset").equals("")); + test(service1.getProperty("Arg").equals("1")); + + String[] args1 = {"-a", "--Arg=2"}; + test(java.util.Arrays.equals(service1.getArgs(), args1)); + + test(service2.getProperty("Ice.ProgramName").equals("Test")); + test(service2.getProperty("Service").equals("2")); + test(service2.getProperty("Service1.ArgProp").equals("")); + test(service2.getProperty("IceBox.InheritProperties").equals("1")); + + String[] args2 = {"--Service1.ArgProp=1"}; + test(java.util.Arrays.equals(service2.getArgs(), args2)); + + out.println("ok"); + + out.print("testing with shared communicator... "); + out.flush(); + + test(service3.getProperty("Ice.ProgramName").equals("IceBox-SharedCommunicator")); + test(service3.getProperty("Service").equals("4")); + test(service3.getProperty("Prop").equals("")); + test(service3.getProperty("Service3.Prop").equals("1")); + 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.Slicing").equals("3")); + + String[] args4 = {"--Service3.Prop=2"}; + test(java.util.Arrays.equals(service4.getArgs(), args4)); + + out.println("ok"); + } + else + { + out.print("testing property inheritance... "); + out.flush(); + + test(service1.getProperty("Ice.ProgramName").equals("IceBox2-Service1")); + test(service1.getProperty("ServerProp").equals("1")); + test(service1.getProperty("OverrideMe").equals("2")); + test(service1.getProperty("UnsetMe").equals("")); + test(service1.getProperty("Service1.Prop").equals("1")); + test(service1.getProperty("Service1.ArgProp").equals("2")); + + test(service2.getProperty("Ice.ProgramName").equals("IceBox2-SharedCommunicator")); + test(service2.getProperty("ServerProp").equals("1")); + test(service2.getProperty("OverrideMe").equals("3")); + test(service2.getProperty("UnsetMe").equals("")); + test(service2.getProperty("Service2.Prop").equals("1")); + + out.println("ok"); + } + } +} diff --git a/java/test/src/main/java/test/IceBox/configuration/Client.java b/java/test/src/main/java/test/IceBox/configuration/Client.java new file mode 100644 index 00000000000..39785e9de8a --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/Client.java @@ -0,0 +1,45 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceBox.configuration; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + AllTests.allTests(communicator, getWriter()); + + // + // Shutdown the IceBox server. + // + Ice.ProcessPrxHelper.uncheckedCast(communicator.stringToProxy("DemoIceBox/admin -f Process:default -p 9996")) + .shutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.IceBox.configuration"); + return initData; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/IceBox/configuration/Test.ice b/java/test/src/main/java/test/IceBox/configuration/Test.ice new file mode 100644 index 00000000000..757de8ea164 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/Test.ice @@ -0,0 +1,25 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +#include <Ice/BuiltinSequences.ice> + +[["java:package:test.IceBox.configuration"]] +module Test +{ + +interface TestIntf +{ + string getProperty(string name); + Ice::StringSeq getArgs(); + +}; + +}; diff --git a/java/test/src/main/java/test/IceBox/configuration/TestI.java b/java/test/src/main/java/test/IceBox/configuration/TestI.java new file mode 100644 index 00000000000..abe96b912f8 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/TestI.java @@ -0,0 +1,38 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceBox.configuration; + +import test.IceBox.configuration.Test._TestIntfDisp; + + +public class TestI extends _TestIntfDisp +{ + public + TestI(String[] args) + { + _args = args; + } + + @Override + public String + getProperty(String name, Ice.Current current) + { + return current.adapter.getCommunicator().getProperties().getProperty(name); + } + + @Override + public String[] + getArgs(Ice.Current current) + { + return _args; + } + + final private String[] _args; +} diff --git a/java/test/src/main/java/test/IceBox/configuration/TestServiceI.java b/java/test/src/main/java/test/IceBox/configuration/TestServiceI.java new file mode 100644 index 00000000000..037d5465968 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/TestServiceI.java @@ -0,0 +1,30 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceBox.configuration; + +public class TestServiceI implements IceBox.Service +{ + @Override + public void + start(String name, Ice.Communicator communicator, String[] args) + { + communicator.getProperties().setProperty("Ice.Package.Test", "test.IceBox.configuration"); + + Ice.ObjectAdapter adapter = communicator.createObjectAdapter(name + "OA"); + adapter.add(new TestI(args), communicator.stringToIdentity("test")); + adapter.activate(); + } + + @Override + public void + stop() + { + } +} diff --git a/java/test/src/main/java/test/IceBox/configuration/config.icebox b/java/test/src/main/java/test/IceBox/configuration/config.icebox new file mode 100644 index 00000000000..1dd4b90957c --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/config.icebox @@ -0,0 +1,13 @@ +Ice.Admin.InstanceName=DemoIceBox +Ice.Admin.Endpoints=default -p 9996 -h 127.0.0.1 +Ice.ProgramName=IceBox + +IceBox.Service.Service1=test.IceBox.configuration.TestServiceI --Ice.Config=config.service1 --Service1.ArgProp=1 --Service1.Ovrd=2 --Service1.Unset= -a --Arg=2 +IceBox.Service.Service2=test.IceBox.configuration.TestServiceI --Ice.Config=config.service2 --Service1.ArgProp=1 --IceBox.InheritProperties + +IceBox.UseSharedCommunicator.Service3=1 +IceBox.Service.Service3=test.IceBox.configuration.TestServiceI --Ice.Config=config.service3 +IceBox.UseSharedCommunicator.Service4=1 +IceBox.Service.Service4=test.IceBox.configuration.TestServiceI --Ice.Config=config.service4 --Service3.Prop=2 --Ice.Trace.Slicing=3 + +IceBox.LoadOrder=Service1 Service2 Service3 Service4 diff --git a/java/test/src/main/java/test/IceBox/configuration/config.icebox2 b/java/test/src/main/java/test/IceBox/configuration/config.icebox2 new file mode 100644 index 00000000000..2866764f19f --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/config.icebox2 @@ -0,0 +1,16 @@ +Ice.Admin.InstanceName=DemoIceBox +Ice.Admin.Endpoints=default -p 9996 -h 127.0.0.1 +Ice.ProgramName=IceBox2 + +IceBox.InheritProperties=1 + +ServerProp=1 +OverrideMe=1 +UnsetMe=1 + +IceBox.Service.Service1=test.IceBox.configuration.TestServiceI --Ice.Config=config.service1-2 --Service1.ArgProp=2 + +IceBox.UseSharedCommunicator.Service2=1 +IceBox.Service.Service2=test.IceBox.configuration.TestServiceI --Ice.Config=config.service2-2 + +IceBox.LoadOrder=Service1 Service2 diff --git a/java/test/src/main/java/test/IceBox/configuration/config.service1 b/java/test/src/main/java/test/IceBox/configuration/config.service1 new file mode 100644 index 00000000000..6028e615ff5 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/config.service1 @@ -0,0 +1,9 @@ +Service1OA.Endpoints=tcp -p 12010 -h 127.0.0.1 + +#Ice.ProgramName +Service=1 +Service1.Ovrd=1 +Service1.Unset=1 + +Arg=1 +ArgUnset=2 diff --git a/java/test/src/main/java/test/IceBox/configuration/config.service1-2 b/java/test/src/main/java/test/IceBox/configuration/config.service1-2 new file mode 100644 index 00000000000..c173914db2a --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/config.service1-2 @@ -0,0 +1,11 @@ +Service1OA.Endpoints=tcp -p 12010 -h 127.0.0.1 + +#Ice.ProgramName +Service1.Prop=1 +Service1.ArgProp=1 + +OverrideMe=2 +UnsetMe= + + +Ice.PrintAdapterReady=0 diff --git a/java/test/src/main/java/test/IceBox/configuration/config.service2 b/java/test/src/main/java/test/IceBox/configuration/config.service2 new file mode 100644 index 00000000000..78e08aadba6 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/config.service2 @@ -0,0 +1,4 @@ +Service2OA.Endpoints=tcp -p 12011 -h 127.0.0.1 + +Ice.ProgramName=Test +Service=2 diff --git a/java/test/src/main/java/test/IceBox/configuration/config.service2-2 b/java/test/src/main/java/test/IceBox/configuration/config.service2-2 new file mode 100644 index 00000000000..36c8d0812cb --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/config.service2-2 @@ -0,0 +1,9 @@ +Service2OA.Endpoints=tcp -p 12011 -h 127.0.0.1 + +#Ice.ProgramName +Service2.Prop=1 + +OverrideMe=3 +UnsetMe= + +Ice.PrintAdapterReady=0 diff --git a/java/test/src/main/java/test/IceBox/configuration/config.service3 b/java/test/src/main/java/test/IceBox/configuration/config.service3 new file mode 100644 index 00000000000..c93ed144701 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/config.service3 @@ -0,0 +1,8 @@ +Service3OA.Endpoints=tcp -p 12012 -h 127.0.0.1 + +#Ice.ProgramName +Service=3 +Prop=2 +Service3.Prop=1 + +Ice.Trace.Slicing=2 diff --git a/java/test/src/main/java/test/IceBox/configuration/config.service4 b/java/test/src/main/java/test/IceBox/configuration/config.service4 new file mode 100644 index 00000000000..182fb3a7289 --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/config.service4 @@ -0,0 +1,6 @@ +Service4OA.Endpoints=tcp -p 12013 -h 127.0.0.1 + +#Ice.ProgramName +Service=4 +Prop= + diff --git a/java/test/src/main/java/test/IceBox/configuration/run.py b/java/test/src/main/java/test/IceBox/configuration/run.py new file mode 100755 index 00000000000..32ce304919c --- /dev/null +++ b/java/test/src/main/java/test/IceBox/configuration/run.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +TestUtil.clientServerTest(additionalServerOptions='--Ice.Config="%s"' % os.path.join(os.getcwd(), "config.icebox"), + server=TestUtil.getIceBox()) +TestUtil.clientServerTest(additionalServerOptions='--Ice.Config="%s"' % os.path.join(os.getcwd(), "config.icebox2"), + server=TestUtil.getIceBox()) diff --git a/java/test/src/main/java/test/IceDiscovery/simple/AllTests.java b/java/test/src/main/java/test/IceDiscovery/simple/AllTests.java new file mode 100644 index 00000000000..97546028b59 --- /dev/null +++ b/java/test/src/main/java/test/IceDiscovery/simple/AllTests.java @@ -0,0 +1,220 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2013 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.IceDiscovery.simple; + +import test.IceDiscovery.simple.Test.*; + +import java.util.List; +import java.util.ArrayList; + +import java.util.Set; +import java.util.HashSet; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + allTests(Ice.Communicator communicator, int num) + { + List<ControllerPrx> proxies = new ArrayList<ControllerPrx>(); + List<ControllerPrx> indirectProxies = new ArrayList<ControllerPrx>(); + for(int i = 0; i < num; ++i) + { + String id = "controller" + i; + proxies.add(ControllerPrxHelper.uncheckedCast(communicator.stringToProxy(id))); + indirectProxies.add(ControllerPrxHelper.uncheckedCast(communicator.stringToProxy(id + "@control" + i))); + } + + System.out.print("testing indirect proxies... "); + System.out.flush(); + { + for(ControllerPrx prx : indirectProxies) + { + prx.ice_ping(); + } + } + System.out.println("ok"); + + System.out.print("testing well-known proxies... "); + System.out.flush(); + { + for(ControllerPrx prx : proxies) + { + prx.ice_ping(); + } + } + System.out.println("ok"); + + System.out.print("testing object adapter registration... "); + System.out.flush(); + { + try + { + communicator.stringToProxy("object @ oa1").ice_ping(); + } + catch(Ice.NoEndpointException ex) + { + } + + proxies.get(0).activateObjectAdapter("oa", "oa1", ""); + + try + { + communicator.stringToProxy("object @ oa1").ice_ping(); + } + catch(Ice.ObjectNotExistException ex) + { + } + + proxies.get(0).deactivateObjectAdapter("oa"); + + try + { + communicator.stringToProxy("object @ oa1").ice_ping(); + } + catch(Ice.NoEndpointException ex) + { + } + } + System.out.println("ok"); + + System.out.print("testing object adapter migration..."); + System.out.flush(); + { + proxies.get(0).activateObjectAdapter("oa", "oa1", ""); + proxies.get(0).addObject("oa", "object"); + communicator.stringToProxy("object @ oa1").ice_ping(); + proxies.get(0).removeObject("oa", "object"); + proxies.get(0).deactivateObjectAdapter("oa"); + + proxies.get(1).activateObjectAdapter("oa", "oa1", ""); + proxies.get(1).addObject("oa", "object"); + communicator.stringToProxy("object @ oa1").ice_ping(); + proxies.get(1).removeObject("oa", "object"); + proxies.get(1).deactivateObjectAdapter("oa"); + } + System.out.println("ok"); + + System.out.print("testing object migration..."); + System.out.flush(); + { + proxies.get(0).activateObjectAdapter("oa", "oa1", ""); + proxies.get(1).activateObjectAdapter("oa", "oa2", ""); + + proxies.get(0).addObject("oa", "object"); + communicator.stringToProxy("object @ oa1").ice_ping(); + communicator.stringToProxy("object").ice_ping(); + proxies.get(0).removeObject("oa", "object"); + + proxies.get(1).addObject("oa", "object"); + communicator.stringToProxy("object @ oa2").ice_ping(); + communicator.stringToProxy("object").ice_ping(); + proxies.get(1).removeObject("oa", "object"); + + try + { + communicator.stringToProxy("object @ oa1").ice_ping(); + } + catch(Ice.ObjectNotExistException ex) + { + } + try + { + communicator.stringToProxy("object @ oa2").ice_ping(); + } + catch(Ice.ObjectNotExistException ex) + { + } + + proxies.get(0).deactivateObjectAdapter("oa"); + proxies.get(1).deactivateObjectAdapter("oa"); + } + System.out.println("ok"); + + System.out.print("testing replica groups..."); + System.out.flush(); + { + proxies.get(0).activateObjectAdapter("oa", "oa1", "rg"); + proxies.get(1).activateObjectAdapter("oa", "oa2", "rg"); + proxies.get(2).activateObjectAdapter("oa", "oa3", "rg"); + + proxies.get(0).addObject("oa", "object"); + proxies.get(1).addObject("oa", "object"); + proxies.get(2).addObject("oa", "object"); + + communicator.stringToProxy("object @ oa1").ice_ping(); + communicator.stringToProxy("object @ oa2").ice_ping(); + communicator.stringToProxy("object @ oa3").ice_ping(); + + communicator.stringToProxy("object @ rg").ice_ping(); + + Set<String> adapterIds = new HashSet<String>(); + adapterIds.add("oa1"); + adapterIds.add("oa2"); + adapterIds.add("oa3"); + TestIntfPrx intf = TestIntfPrxHelper.uncheckedCast(communicator.stringToProxy("object")); + intf = (TestIntfPrx)intf.ice_connectionCached(false).ice_locatorCacheTimeout(0); + while(!adapterIds.isEmpty()) + { + adapterIds.remove(intf.getAdapterId()); + } + + while(true) + { + adapterIds.add("oa1"); + adapterIds.add("oa2"); + adapterIds.add("oa3"); + intf = TestIntfPrxHelper.uncheckedCast( + communicator.stringToProxy("object @ rg").ice_connectionCached(false)); + int nRetry = 100; + while(!adapterIds.isEmpty() && --nRetry > 0) + { + adapterIds.remove(intf.getAdapterId()); + } + if(nRetry > 0) + { + break; + } + + // The previous locator lookup probably didn't return all the replicas... try again. + communicator.stringToProxy("object @ rg").ice_locatorCacheTimeout(0).ice_ping(); + } + + proxies.get(0).deactivateObjectAdapter("oa"); + proxies.get(1).deactivateObjectAdapter("oa"); + test(TestIntfPrxHelper.uncheckedCast( + communicator.stringToProxy("object @ rg")).getAdapterId().equals("oa3")); + proxies.get(2).deactivateObjectAdapter("oa"); + + proxies.get(0).activateObjectAdapter("oa", "oa1", "rg"); + proxies.get(0).addObject("oa", "object"); + test(TestIntfPrxHelper.uncheckedCast( + communicator.stringToProxy("object @ rg")).getAdapterId().equals("oa1")); + proxies.get(0).deactivateObjectAdapter("oa"); + } + System.out.println("ok"); + + System.out.print("shutting down... "); + System.out.flush(); + for(ControllerPrx prx : proxies) + { + prx.shutdown(); + } + System.out.println("ok"); + } +} diff --git a/java/test/src/main/java/test/IceDiscovery/simple/Client.java b/java/test/src/main/java/test/IceDiscovery/simple/Client.java new file mode 100644 index 00000000000..7b93371328e --- /dev/null +++ b/java/test/src/main/java/test/IceDiscovery/simple/Client.java @@ -0,0 +1,38 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2013 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.IceDiscovery.simple; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + int num; + try + { + num = args.length == 1 ? Integer.parseInt(args[0]) : 0; + } + catch(NumberFormatException ex) + { + num = 0; + } + AllTests.allTests(communicator(), num); + return 0; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/IceDiscovery/simple/ControllerI.java b/java/test/src/main/java/test/IceDiscovery/simple/ControllerI.java new file mode 100644 index 00000000000..188b1c7182d --- /dev/null +++ b/java/test/src/main/java/test/IceDiscovery/simple/ControllerI.java @@ -0,0 +1,66 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2013 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.IceDiscovery.simple; + +import test.IceDiscovery.simple.Test.*; + +public final class ControllerI extends _ControllerDisp +{ + @Override + public void + activateObjectAdapter(String name, String adapterId, String replicaGroupId, Ice.Current current) + { + Ice.Communicator communicator = current.adapter.getCommunicator(); + Ice.Properties properties = communicator.getProperties(); + properties.setProperty(name + ".AdapterId", adapterId); + properties.setProperty(name + ".ReplicaGroupId", replicaGroupId); + properties.setProperty(name + ".Endpoints", "default"); + Ice.ObjectAdapter oa = communicator.createObjectAdapter(name); + _adapters.put(name, oa); + oa.activate(); + } + + @Override + public void + deactivateObjectAdapter(String name, Ice.Current current) + { + _adapters.get(name).destroy(); + _adapters.remove(name); + } + + @Override + public void + addObject(String oaName, String id, Ice.Current current) + { + assert(_adapters.containsKey(oaName)); + Ice.Identity identity = new Ice.Identity(); + identity.name = id; + _adapters.get(oaName).add(new TestIntfI(), identity); + } + + @Override + public void + removeObject(String oaName, String id, Ice.Current current) + { + assert(_adapters.containsKey(oaName)); + Ice.Identity identity = new Ice.Identity(); + identity.name = id; + _adapters.get(oaName).remove(identity); + } + + @Override + public void shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } + + final private java.util.Map<String, Ice.ObjectAdapter> _adapters = + new java.util.HashMap<String, Ice.ObjectAdapter>(); +} diff --git a/java/test/src/main/java/test/IceDiscovery/simple/Server.java b/java/test/src/main/java/test/IceDiscovery/simple/Server.java new file mode 100644 index 00000000000..7bc444355f4 --- /dev/null +++ b/java/test/src/main/java/test/IceDiscovery/simple/Server.java @@ -0,0 +1,46 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2013 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.IceDiscovery.simple; + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Properties properties = communicator().getProperties(); + + int num = 0; + try + { + num = Integer.parseInt(args[0]); + } + catch(NumberFormatException ex) + { + } + + properties.setProperty("ControlAdapter.Endpoints", "default -p " + (12010 + num)); + properties.setProperty("ControlAdapter.AdapterId", "control" + num); + properties.setProperty("ControlAdapter.ThreadPool.Size", "1"); + + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("ControlAdapter"); + adapter.add(new ControllerI(), communicator().stringToIdentity("controller" + num)); + adapter.activate(); + + return WAIT; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/IceDiscovery/simple/Test.ice b/java/test/src/main/java/test/IceDiscovery/simple/Test.ice new file mode 100644 index 00000000000..03d59e513a7 --- /dev/null +++ b/java/test/src/main/java/test/IceDiscovery/simple/Test.ice @@ -0,0 +1,33 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2013 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. +// +// ********************************************************************** + +#pragma once + + +[["java:package:test.IceDiscovery.simple"]] +module Test +{ + +interface TestIntf +{ + string getAdapterId(); +}; + +interface Controller +{ + void activateObjectAdapter(string name, string adapterId, string replicaGroupId); + void deactivateObjectAdapter(string name); + + void addObject(string oaName, string id); + void removeObject(string oaName, string id); + + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/IceDiscovery/simple/TestIntfI.java b/java/test/src/main/java/test/IceDiscovery/simple/TestIntfI.java new file mode 100644 index 00000000000..339bc281081 --- /dev/null +++ b/java/test/src/main/java/test/IceDiscovery/simple/TestIntfI.java @@ -0,0 +1,22 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2013 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.IceDiscovery.simple; + +import test.IceDiscovery.simple.Test.*; + +public final class TestIntfI extends _TestIntfDisp +{ + @Override + public String + getAdapterId(Ice.Current current) + { + return current.adapter.getCommunicator().getProperties().getProperty(current.adapter.getName() + ".AdapterId"); + } +} diff --git a/java/test/src/main/java/test/IceDiscovery/simple/run.py b/java/test/src/main/java/test/IceDiscovery/simple/run.py new file mode 100755 index 00000000000..2f14ff0442f --- /dev/null +++ b/java/test/src/main/java/test/IceDiscovery/simple/run.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2013 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +server = "test.IceDiscovery.simple.Server" +client = "test.IceDiscovery.simple.Client" + +num = 3 + +args = " --Ice.Plugin.IceDiscovery=IceDiscovery:IceDiscovery.PluginFactory" +args += " --IceDiscovery.Timeout=30" +args += " --IceDiscovery.RetryCount=1" +if not TestUtil.ipv6: + args += " --IceDiscovery.Interface=127.0.0.1" + +serverProc = [] +for i in range(0, num): + sys.stdout.write("starting server #%d... " % (i + 1)) + sys.stdout.flush() + serverProc.append(TestUtil.startServer(server, "%d %s" % (i, args))) + print("ok") + +sys.stdout.write("starting client... ") +sys.stdout.flush() +clientProc = TestUtil.startClient(client, "%d %s" % (num, args), startReader = False) +print("ok") +clientProc.startReader() + +clientProc.waitTestSuccess() +for p in serverProc: + p.waitTestSuccess() diff --git a/java/test/src/main/java/test/IceGrid/simple/.gitignore b/java/test/src/main/java/test/IceGrid/simple/.gitignore new file mode 100644 index 00000000000..1a5104f3c93 --- /dev/null +++ b/java/test/src/main/java/test/IceGrid/simple/.gitignore @@ -0,0 +1,4 @@ +db/node/* +db/registry/* +db/replica-1/* +db/replica-2/* diff --git a/java/test/src/main/java/test/IceGrid/simple/AllTests.java b/java/test/src/main/java/test/IceGrid/simple/AllTests.java new file mode 100644 index 00000000000..b6aba8b8594 --- /dev/null +++ b/java/test/src/main/java/test/IceGrid/simple/AllTests.java @@ -0,0 +1,349 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceGrid.simple; +import java.io.PrintWriter; + +import test.IceGrid.simple.Test.TestIntfPrx; +import test.IceGrid.simple.Test.TestIntfPrxHelper; + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + allTests(Ice.Communicator communicator, PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + String ref = "test @ TestAdapter"; + Ice.ObjectPrx base = communicator.stringToProxy(ref); + test(base != null); + out.println("ok"); + + out.print("testing IceGrid.Locator is present... "); + IceGrid.LocatorPrx locator = IceGrid.LocatorPrxHelper.uncheckedCast(base); + test(locator != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + TestIntfPrx obj = TestIntfPrxHelper.checkedCast(base); + test(obj != null); + test(obj.equals(base)); + out.println("ok"); + + out.print("pinging server... "); + out.flush(); + obj.ice_ping(); + out.println("ok"); + + out.print("testing locator finder... "); + Ice.Identity finderId = new Ice.Identity(); + finderId.category = "Ice"; + finderId.name = "LocatorFinder"; + Ice.LocatorFinderPrx finder = Ice.LocatorFinderPrxHelper.checkedCast( + communicator.getDefaultLocator().ice_identity(finderId)); + test(finder.getLocator() != null); + out.println("ok"); + + out.print("testing discovery... "); + out.flush(); + { + // Add test well-known object + IceGrid.RegistryPrx registry = IceGrid.RegistryPrxHelper.checkedCast( + communicator.stringToProxy(communicator.getDefaultLocator().ice_getIdentity().category + "/Registry")); + test(registry != null); + + try + { + IceGrid.AdminSessionPrx session = registry.createAdminSession("foo", "bar"); + session.getAdmin().addObjectWithType(base, "::Test"); + session.destroy(); + } + catch(Ice.UserException ex) + { + test(false); + } + + // + // Ensure the IceGrid discovery locator can discover the + // registries and make sure locator requests are forwarded. + // + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = communicator.getProperties()._clone(); + initData.properties.setProperty("Ice.Default.Locator", ""); + initData.properties.setProperty("Ice.Plugin.IceGridDiscovery", "IceGrid:IceGrid.DiscoveryPluginFactoryI"); + initData.properties.setProperty("AdapterForDiscoveryTest.AdapterId", "discoveryAdapter"); + initData.properties.setProperty("AdapterForDiscoveryTest.Endpoints", "default"); + + Ice.Communicator com = Ice.Util.initialize(initData); + test(com.getDefaultLocator() != null); + com.stringToProxy("test @ TestAdapter").ice_ping(); + com.stringToProxy("test").ice_ping(); + + test(com.getDefaultLocator().getRegistry() != null); + test(IceGrid.LocatorPrxHelper.uncheckedCast(com.getDefaultLocator()).getLocalRegistry() != null); + test(IceGrid.LocatorPrxHelper.uncheckedCast(com.getDefaultLocator()).getLocalQuery() != null); + + Ice.ObjectAdapter adapter = com.createObjectAdapter("AdapterForDiscoveryTest"); + adapter.activate(); + adapter.deactivate(); + com.destroy(); + + // + // Now, ensure that the IceGrid discovery locator correctly + // handles failure to find a locator. + // + initData.properties.setProperty("IceGridDiscovery.InstanceName", "unknown"); + initData.properties.setProperty("IceGridDiscovery.RetryCount", "1"); + initData.properties.setProperty("IceGridDiscovery.Timeout", "100"); + com = Ice.Util.initialize(initData); + test(com.getDefaultLocator() != null); + try + { + com.stringToProxy("test @ TestAdapter").ice_ping(); + } + catch(Ice.NoEndpointException ex) + { + } + try + { + com.stringToProxy("test").ice_ping(); + } + catch(Ice.NoEndpointException ex) + { + } + test(com.getDefaultLocator().getRegistry() == null); + test(IceGrid.LocatorPrxHelper.uncheckedCast(com.getDefaultLocator()).getLocalRegistry() == null); + test(IceGrid.LocatorPrxHelper.uncheckedCast(com.getDefaultLocator()).getLocalQuery() == null); + + adapter = com.createObjectAdapter("AdapterForDiscoveryTest"); + adapter.activate(); + adapter.deactivate(); + + com.destroy(); + } + out.println("ok"); + + out.print("shutting down server... "); + out.flush(); + obj.shutdown(); + out.println("ok"); + } + + public static void + allTestsWithDeploy(Ice.Communicator communicator, PrintWriter out) + { + out.print("testing stringToProxy... "); + out.flush(); + Ice.ObjectPrx base = communicator.stringToProxy("test @ TestAdapter"); + test(base != null); + Ice.ObjectPrx base2 = communicator.stringToProxy("test"); + test(base2 != null); + out.println("ok"); + + out.print("testing checked cast... "); + out.flush(); + TestIntfPrx obj = TestIntfPrxHelper.checkedCast(base); + test(obj != null); + test(obj.equals(base)); + TestIntfPrx obj2 = TestIntfPrxHelper.checkedCast(base2); + test(obj2 != null); + test(obj2.equals(base2)); + out.println("ok"); + + out.print("pinging server... "); + out.flush(); + obj.ice_ping(); + obj2.ice_ping(); + out.println("ok"); + + out.print("testing encoding versioning... "); + out.flush(); + Ice.ObjectPrx base10 = communicator.stringToProxy("test10 @ TestAdapter10"); + test(base10 != null); + Ice.ObjectPrx base102 = communicator.stringToProxy("test10"); + test(base102 != null); + try + { + base10.ice_ping(); + test(false); + } + catch(Ice.NoEndpointException ex) + { + } + try + { + base102.ice_ping(); + test(false); + } + catch(Ice.NoEndpointException ex) + { + } + base10 = base10.ice_encodingVersion(Ice.Util.Encoding_1_0); + base102 = base102.ice_encodingVersion(Ice.Util.Encoding_1_0); + base10.ice_ping(); + base102.ice_ping(); + out.println("ok"); + + out.print("testing reference with unknown identity... "); + out.flush(); + try + { + communicator.stringToProxy("unknown/unknown").ice_ping(); + test(false); + } + catch(Ice.NotRegisteredException ex) + { + test(ex.kindOfObject.equals("object")); + test(ex.id.equals("unknown/unknown")); + } + out.println("ok"); + + out.print("testing reference with unknown adapter... "); + out.flush(); + try + { + communicator.stringToProxy("test @ TestAdapterUnknown").ice_ping(); + test(false); + } + catch(Ice.NotRegisteredException ex) + { + test(ex.kindOfObject.equals("object adapter")); + test(ex.id.equals("TestAdapterUnknown")); + } + out.println("ok"); + + IceGrid.RegistryPrx registry = IceGrid.RegistryPrxHelper.checkedCast( + communicator.stringToProxy(communicator.getDefaultLocator().ice_getIdentity().category + "/Registry")); + test(registry != null); + IceGrid.AdminSessionPrx session = null; + try + { + session = registry.createAdminSession("foo", "bar"); + } + catch(IceGrid.PermissionDeniedException e) + { + test(false); + } + + session.ice_getConnection().setACM(new Ice.IntOptional(registry.getACMTimeout()), null, + new Ice.Optional<Ice.ACMHeartbeat>(Ice.ACMHeartbeat.HeartbeatAlways)); + + IceGrid.AdminPrx admin = session.getAdmin(); + test(admin != null); + + try + { + admin.enableServer("server", false); + admin.stopServer("server"); + } + catch(IceGrid.ServerNotExistException ex) + { + test(false); + } + catch(IceGrid.ServerStopException ex) + { + test(false); + } + catch(IceGrid.NodeUnreachableException ex) + { + test(false); + } + catch(IceGrid.DeploymentException ex) + { + test(false); + } + + out.print("testing whether server is still reachable... "); + out.flush(); + try + { + obj = TestIntfPrxHelper.checkedCast(base); + test(false); + } + catch(Ice.NoEndpointException ex) + { + } + try + { + obj2 = TestIntfPrxHelper.checkedCast(base2); + test(false); + } + catch(Ice.NoEndpointException ex) + { + } + + try + { + admin.enableServer("server", true); + } + catch(IceGrid.ServerNotExistException ex) + { + test(false); + } + catch(IceGrid.NodeUnreachableException ex) + { + test(false); + } + catch(IceGrid.DeploymentException ex) + { + test(false); + } + + try + { + obj = TestIntfPrxHelper.checkedCast(base); + } + catch(Ice.NoEndpointException ex) + { + test(false); + } + try + { + obj2 = TestIntfPrxHelper.checkedCast(base2); + } + catch(Ice.NoEndpointException ex) + { + test(false); + } + out.println("ok"); + + try + { + admin.stopServer("server"); + } + catch(IceGrid.ServerNotExistException ex) + { + test(false); + } + catch(IceGrid.ServerStopException ex) + { + test(false); + } + catch(IceGrid.NodeUnreachableException ex) + { + test(false); + } + catch(IceGrid.DeploymentException ex) + { + test(false); + } + + session.destroy(); + } +} diff --git a/java/test/src/main/java/test/IceGrid/simple/Client.java b/java/test/src/main/java/test/IceGrid/simple/Client.java new file mode 100644 index 00000000000..0da92bbeffe --- /dev/null +++ b/java/test/src/main/java/test/IceGrid/simple/Client.java @@ -0,0 +1,57 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceGrid.simple; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + boolean withDeploy = false; + for(String arg : args) + { + if(arg.equals("--with-deploy")) + { + withDeploy = true; + break; + } + } + + if(!withDeploy) + { + AllTests.allTests(communicator, getWriter()); + } + else + { + AllTests.allTestsWithDeploy(communicator, getWriter()); + } + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.IceGrid.simple"); + return initData; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/IceGrid/simple/Server.java b/java/test/src/main/java/test/IceGrid/simple/Server.java new file mode 100644 index 00000000000..1b349a70773 --- /dev/null +++ b/java/test/src/main/java/test/IceGrid/simple/Server.java @@ -0,0 +1,62 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceGrid.simple; + +public class Server extends test.Util.Application +{ + @Override + public int + run(String[] args) + { + Ice.StringSeqHolder argsH = new Ice.StringSeqHolder(args); + argsH.value = communicator().getProperties().parseCommandLineOptions("TestAdapter", argsH.value); + + Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); + Ice.Object object = new TestI(); + String id = communicator().getProperties().getPropertyWithDefault("Identity", "test"); + adapter.add(object, communicator().stringToIdentity(id)); + //shutdownOnInterrupt(); + try + { + adapter.activate(); + } + catch(Ice.ObjectAdapterDeactivatedException ex) + { + } + communicator().waitForShutdown(); + //defaultInterrupt(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + // + // Its possible to have batch oneway requests dispatched + // after the adapter is deactivated due to thread + // scheduling so we supress this warning. + // + initData.properties.setProperty("Ice.Warn.Dispatch", "0"); + initData.properties.setProperty("Ice.Package.Test", "test.IceGrid.simple"); + return initData; + } + + public static void + main(String[] args) + { + Server c = new Server(); + int status = c.main("test.IceGrid.simple.Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/IceGrid/simple/Test.ice b/java/test/src/main/java/test/IceGrid/simple/Test.ice new file mode 100644 index 00000000000..645988ffff1 --- /dev/null +++ b/java/test/src/main/java/test/IceGrid/simple/Test.ice @@ -0,0 +1,21 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.IceGrid.simple"]] +module Test +{ + +interface TestIntf +{ + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/IceGrid/simple/TestI.java b/java/test/src/main/java/test/IceGrid/simple/TestI.java new file mode 100644 index 00000000000..82ba95b7aad --- /dev/null +++ b/java/test/src/main/java/test/IceGrid/simple/TestI.java @@ -0,0 +1,27 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceGrid.simple; + +import test.IceGrid.simple.Test._TestIntfDisp; + +public class TestI extends _TestIntfDisp +{ + public + TestI() + { + } + + @Override + public void + shutdown(Ice.Current current) + { + current.adapter.getCommunicator().shutdown(); + } +} diff --git a/java/test/src/main/java/test/IceGrid/simple/db/.gitignore b/java/test/src/main/java/test/IceGrid/simple/db/.gitignore new file mode 100644 index 00000000000..39af5887579 --- /dev/null +++ b/java/test/src/main/java/test/IceGrid/simple/db/.gitignore @@ -0,0 +1 @@ +# Dummy file, so that git retains this otherwise empty directory. diff --git a/java/test/src/main/java/test/IceGrid/simple/run.py b/java/test/src/main/java/test/IceGrid/simple/run.py new file mode 100755 index 00000000000..1dea25f18d6 --- /dev/null +++ b/java/test/src/main/java/test/IceGrid/simple/run.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil, IceGridAdmin + +# Test IceGrid discovery with multiple replicas +IceGridAdmin.nreplicas=2 + +# +# Test client/server without on demand activation. +# +IceGridAdmin.iceGridClientServerTest("", "--TestAdapter.Endpoints=default --TestAdapter.AdapterId=TestAdapter") + +# +# Test client/server with on demand activation. +# +IceGridAdmin.iceGridTest("simple_server.xml", "--with-deploy") diff --git a/java/test/src/main/java/test/IceGrid/simple/simple_server.xml b/java/test/src/main/java/test/IceGrid/simple/simple_server.xml new file mode 100644 index 00000000000..1548b0e482d --- /dev/null +++ b/java/test/src/main/java/test/IceGrid/simple/simple_server.xml @@ -0,0 +1,22 @@ +<icegrid> + <application name="Test"> + <node name="localnode"> + <server id="server" exe="java" pwd="." activation="on-demand"> + <option>-Djava.security.egd=file:/dev/urandom</option> + <option>test.IceGrid.simple.Server</option> + <adapter name="TestAdapter" id="TestAdapter" endpoints="default"> + <object identity="test" type="Test"/> + </adapter> + </server> + + <server id="server10" exe="java" pwd="." activation="on-demand"> + <option>-Djava.security.egd=file:/dev/urandom</option> + <option>test.IceGrid.simple.Server</option> + <adapter name="TestAdapter" endpoints="default" id="TestAdapter10"> + <object identity="test10" type="Test" property="Identity"/> + </adapter> + <property name="Ice.Default.EncodingVersion" value="1.0"/> + </server> + </node> + </application> +</icegrid> diff --git a/java/test/src/main/java/test/IceSSL/certs/c_dsa_ca1.jks b/java/test/src/main/java/test/IceSSL/certs/c_dsa_ca1.jks Binary files differnew file mode 100644 index 00000000000..fd0b5d6e56d --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/c_dsa_ca1.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/c_rsa_ca1.jks b/java/test/src/main/java/test/IceSSL/certs/c_rsa_ca1.jks Binary files differnew file mode 100644 index 00000000000..ee0b1afc7b2 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/c_rsa_ca1.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/c_rsa_ca1_exp.jks b/java/test/src/main/java/test/IceSSL/certs/c_rsa_ca1_exp.jks Binary files differnew file mode 100644 index 00000000000..fdac5c1508a --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/c_rsa_ca1_exp.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/c_rsa_ca2.jks b/java/test/src/main/java/test/IceSSL/certs/c_rsa_ca2.jks Binary files differnew file mode 100644 index 00000000000..56f0b25815c --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/c_rsa_ca2.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/cacert1.jks b/java/test/src/main/java/test/IceSSL/certs/cacert1.jks Binary files differnew file mode 100644 index 00000000000..d17718e981f --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/cacert1.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/cacert2.jks b/java/test/src/main/java/test/IceSSL/certs/cacert2.jks Binary files differnew file mode 100644 index 00000000000..0a22dfe4696 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/cacert2.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/cacerts.jks b/java/test/src/main/java/test/IceSSL/certs/cacerts.jks Binary files differnew file mode 100644 index 00000000000..b45456de292 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/cacerts.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/makecerts.py b/java/test/src/main/java/test/IceSSL/certs/makecerts.py new file mode 100644 index 00000000000..3aea85737c8 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/makecerts.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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, shutil + +for toplevel in [".", "..", "../..", "../../..", "../../../..", "../../../../.."]: + toplevel = os.path.normpath(toplevel) + if os.path.exists(os.path.join(toplevel, "scripts", "TestUtil.py")): + break +else: + raise RuntimeError("can't find toplevel directory!") + +sys.path.append(toplevel) +from scripts import * + +# +# Show usage information. +# +def usage(): + print "Usage: " + sys.argv[0] + " [options]" + print + print "Options:" + print "-h Show this message." + print "-f Force an update to the Java files." + +# +# Check arguments +# +force = 0 +for x in sys.argv[1:]: + if x == "-h": + usage() + sys.exit(0) + elif x == "-f": + force = 1 + elif x.startswith("-"): + print sys.argv[0] + ": unknown option `" + x + "'" + print + usage() + sys.exit(1) + else: + usage() + sys.exit(1) + +cppcerts = os.path.join(TestUtil.getIceDir("cpp"), "test", "IceSSL", "certs") + +certs = [\ + "c_dsa_nopass_ca1", \ + "c_rsa_nopass_ca1_exp", \ + "c_rsa_nopass_ca1", \ + "c_rsa_nopass_ca2", \ + "s_dsa_nopass_ca1", \ + "s_rsa_nopass_ca1_exp", \ + "s_rsa_nopass_ca1", \ + "s_rsa_nopass_ca2", \ + "s_rsa_nopass_ca1_cn1", \ + "s_rsa_nopass_ca1_cn2", \ +] + +# +# Create truststores from the CA certificates. +# +for x in ("cacert1", "cacert2"): + ts = x + ".jks" + os.system("openssl x509 -in " + os.path.join(cppcerts, x) + ".pem -outform DER -out " + x + ".der") + if force or not os.path.exists(ts): + if os.path.exists(ts): + os.remove(ts) + os.system("keytool -import -alias cacert -file " + x + ".der -keystore " + ts + \ + " -storepass password -noprompt") + print "Created " + ts + +# +# Create a truststore containing both CA certificates. +# +if force or not os.path.exists("cacerts.jks"): + if os.path.exists("cacerts.jks"): + os.remove("cacerts.jks") + os.system("keytool -import -alias cacert1 -file cacert1.der -keystore cacerts.jks -storepass password -noprompt") + os.system("keytool -import -alias cacert2 -file cacert2.der -keystore cacerts.jks -storepass password -noprompt") + print "Created cacerts.jks" + +# +# Convert key/certificate pairs into PKCS12 format and then import them +# into keystores. +# +for x in certs: + p12 = x.replace("nopass_", "") + ".p12" + ks = x.replace("nopass_", "") + ".jks" + if x.find("1") > 0: + cacert = "cacert1" + else: + cacert = "cacert2" + if force or not os.path.exists(ks): + if os.path.exists(ks): + os.remove(ks) + cert = os.path.join(cppcerts, x) + ca = os.path.join(cppcerts, cacert) + ".pem" + os.system("openssl pkcs12 -in " + cert + "_pub.pem -inkey " + cert + "_priv.pem -export -out " + p12 + \ + " -name cert -passout pass:password -certfile " + ca) + os.system("java -classpath ../../../../certs ImportKey " + p12 + " cert " + cacert + ".der " + ks + " password") + os.remove(p12) + print "Created " + ks + +p12 = "cacert2.pfx" +ks = "s_cacert2.jks" +if force or not os.path.exists(ks): + cert = os.path.join(cppcerts, "cacert2.pem") + key = os.path.join(cppcerts, "cakey2.pem") + os.system("openssl pkcs12 -in " + cert + " -inkey " + key + " -export -out " + p12 + \ + " -name cert -passout pass:password -certfile " + cert) + os.system("java -classpath ../../../../certs ImportKey " + p12 + " cert cacert2.der " + ks + " password") + os.remove(p12) + print "Created " + ks + +# +# Create a keystore that contains both RSA and DSS certificates. +# +ks = "s_rsa_dsa_ca1.jks" +if force or not os.path.exists(ks): + if os.path.exists(ks): + os.remove(ks) + cacert = "cacert1" + ca = os.path.join(cppcerts, cacert) + ".pem" + p12 = "s_dsa_nopass_ca1.p12" + cert = os.path.join(cppcerts, "s_dsa_nopass_ca1") + os.system("openssl pkcs12 -in " + cert + "_pub.pem -inkey " + cert + "_priv.pem -export -out " + p12 + \ + " -name dsacert -passout pass:password -certfile " + ca) + os.system("java -classpath ../../../../certs ImportKey " + p12 + " dsacert " + cacert + ".der " + ks + " password") + os.remove(p12) + p12 = "s_rsa_nopass_ca1.p12" + cert = os.path.join(cppcerts, "s_rsa_nopass_ca1") + os.system("openssl pkcs12 -in " + cert + "_pub.pem -inkey " + cert + "_priv.pem -export -out " + p12 + \ + " -name rsacert -passout pass:password -certfile " + ca) + os.system("java -classpath ../../../../certs ImportKey " + p12 + " rsacert " + cacert + ".der " + ks + " password") + os.remove(p12) + print "Created " + ks + +# +# Clean up. +# +for x in ("cacert1", "cacert2"): + cert = x + ".der" + if os.path.exists(cert): + os.remove(cert) +# +# Done. +# +print "Done." diff --git a/java/test/src/main/java/test/IceSSL/certs/s_cacert2.jks b/java/test/src/main/java/test/IceSSL/certs/s_cacert2.jks Binary files differnew file mode 100644 index 00000000000..7d55050b1a5 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/s_cacert2.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/s_dsa_ca1.jks b/java/test/src/main/java/test/IceSSL/certs/s_dsa_ca1.jks Binary files differnew file mode 100644 index 00000000000..c2e9fb20e71 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/s_dsa_ca1.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca1.jks b/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca1.jks Binary files differnew file mode 100644 index 00000000000..f7c85ae50d5 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca1.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca1_cn1.jks b/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca1_cn1.jks Binary files differnew file mode 100644 index 00000000000..0bc38875428 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca1_cn1.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca1_cn2.jks b/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca1_cn2.jks Binary files differnew file mode 100644 index 00000000000..1f734a49687 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca1_cn2.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca1_exp.jks b/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca1_exp.jks Binary files differnew file mode 100644 index 00000000000..ca6a874a0b5 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca1_exp.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca2.jks b/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca2.jks Binary files differnew file mode 100644 index 00000000000..e2403e84e53 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/s_rsa_ca2.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/s_rsa_dsa_ca1.jks b/java/test/src/main/java/test/IceSSL/certs/s_rsa_dsa_ca1.jks Binary files differnew file mode 100644 index 00000000000..4b7f7ff0a5e --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/s_rsa_dsa_ca1.jks diff --git a/java/test/src/main/java/test/IceSSL/certs/seed.dat b/java/test/src/main/java/test/IceSSL/certs/seed.dat Binary files differnew file mode 100644 index 00000000000..ba313c59460 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/certs/seed.dat diff --git a/java/test/src/main/java/test/IceSSL/configuration/AllTests.java b/java/test/src/main/java/test/IceSSL/configuration/AllTests.java new file mode 100644 index 00000000000..1e955c8c1f5 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/configuration/AllTests.java @@ -0,0 +1,2265 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceSSL.configuration; +import java.io.PrintWriter; + +import test.IceSSL.configuration.Test.ServerFactoryPrx; +import test.IceSSL.configuration.Test.ServerFactoryPrxHelper; +import test.IceSSL.configuration.Test.ServerPrx; + +// +// NOTE: This test is not interoperable with other language mappings. +// + +public class AllTests +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static Ice.InitializationData + createClientProps(Ice.Properties defaultProperties, String defaultDir, String defaultHost) + { + Ice.InitializationData result = new Ice.InitializationData(); + result.properties = Ice.Util.createProperties(); + result.properties.setProperty("Ice.Plugin.IceSSL", "IceSSL.PluginFactory"); + if(defaultProperties.getProperty("Ice.IPv6").length() > 0) + { + result.properties.setProperty("Ice.IPv6", defaultProperties.getProperty("Ice.IPv6")); + } + result.properties.setProperty("Ice.RetryIntervals", "-1"); + result.properties.setProperty("IceSSL.DefaultDir", defaultDir); + result.properties.setProperty("IceSSL.Random", "seed.dat"); + if(defaultHost.length() > 0) + { + result.properties.setProperty("Ice.Default.Host", defaultHost); + } + return result; + } + + private static java.util.Map<String, String> + createServerProps(Ice.Properties defaultProperties, String defaultDir, String defaultHost) + { + java.util.Map<String, String> result = new java.util.HashMap<String, String>(); + result.put("Ice.Plugin.IceSSL", "IceSSL.PluginFactory"); + if(defaultProperties.getProperty("Ice.IPv6").length() > 0) + { + result.put("Ice.IPv6", defaultProperties.getProperty("Ice.IPv6")); + } + result.put("IceSSL.DefaultDir", defaultDir); + result.put("IceSSL.Random", "seed.dat"); + if(defaultHost.length() > 0) + { + result.put("Ice.Default.Host", defaultHost); + } + return result; + } + + public static ServerFactoryPrx + allTests(test.Util.Application app, String testDir, PrintWriter out) + { + Ice.Communicator communicator = app.communicator(); + final String factoryRef = "factory:tcp -p 12010"; + Ice.ObjectPrx b = communicator.stringToProxy(factoryRef); + test(b != null); + ServerFactoryPrx factory = ServerFactoryPrxHelper.checkedCast(b); + + final String defaultHost = communicator.getProperties().getProperty("Ice.Default.Host"); + final String defaultDir = testDir + "/../certs"; + final Ice.Properties defaultProperties = communicator.getProperties(); + final String[] args = new String[0]; + + out.print("testing manual initialization... "); + out.flush(); + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("Ice.InitPlugins", "0"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + Ice.ObjectPrx p = comm.stringToProxy("dummy:ssl -p 9999"); + try + { + p.ice_ping(); + test(false); + } + catch(Ice.PluginInitializationException ex) + { + // Expected. + } + catch(Ice.LocalException ex) + { + test(false); + } + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("Ice.InitPlugins", "0"); + initData.properties.setProperty("IceSSL.Ciphers", "NONE (.*DH_anon.*)"); + initData.properties.setProperty("IceSSL.VerifyPeer", "0"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + Ice.PluginManager pm = comm.getPluginManager(); + pm.initializePlugins(); + Ice.ObjectPrx obj = comm.stringToProxy(factoryRef); + test(obj != null); + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(obj); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Ciphers", "NONE (.*DH_anon.*)"); + d.put("IceSSL.VerifyPeer", "0"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + out.println("ok"); + + out.print("testing certificate verification... "); + out.flush(); + { + // + // Test IceSSL.VerifyPeer=0. Client does not have a certificate, + // but it still verifies the server's. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "0"); + ServerPrx server = fact.createServer(d); + try + { + server.noCert(); + } + catch(Ice.LocalException ex) + { + test(false); + } + // + // Validate that we can get the connection info. + // + try + { + IceSSL.NativeConnectionInfo info = (IceSSL.NativeConnectionInfo)server.ice_getConnection().getInfo(); + test(info.nativeCerts.length == 2); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + + // + // Test IceSSL.VerifyPeer=1. Client does not have a certificate. + // + initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + comm = Ice.Util.initialize(args, initData); + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "1"); + server = fact.createServer(d); + try + { + server.noCert(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + + // + // Test IceSSL.VerifyPeer=2. This should fail because the client + // does not supply a certificate. + // + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "2"); + server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.ConnectionLostException ex) + { + // Expected. + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + + comm.destroy(); + + // + // Test IceSSL.VerifyPeer=0. This should succeed even though the client + // does not trust the server's certificate. + // + initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.VerifyPeer", "0"); + comm = Ice.Util.initialize(args, initData); + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "0"); + server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + + // + // Test IceSSL.VerifyPeer=1. This should fail because the server + // does not supply a certificate. + // + initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Ciphers", "NONE (.*DH_anon.*)"); + initData.properties.setProperty("IceSSL.VerifyPeer", "1"); + comm = Ice.Util.initialize(args, initData); + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Ciphers", "NONE (.*DH_anon.*)"); + d.put("IceSSL.VerifyPeer", "0"); + server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + + // + // This should succeed because the self signed certificate used by the server is + // trusted. + // + initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.VerifyPeer", "1"); + initData.properties.setProperty("IceSSL.Truststore", "cacert2.jks"); + comm = Ice.Util.initialize(args, initData); + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_cacert2.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.VerifyPeer", "0"); + server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + + // + // This should fail because the self signed certificate used by the server is not + // trusted. + // + initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.VerifyPeer", "1"); + comm = Ice.Util.initialize(args, initData); + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_cacert2.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.VerifyPeer", "0"); + server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + + // + // Test IceSSL.VerifyPeer=1. Client has a certificate. + // + initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + comm = Ice.Util.initialize(args, initData); + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "1"); + server = fact.createServer(d); + try + { + char[] password = "password".toCharArray(); + + java.io.FileInputStream fis = new java.io.FileInputStream(defaultDir + "/c_rsa_ca1.jks"); + java.security.KeyStore clientKeystore = java.security.KeyStore.getInstance("JKS"); + clientKeystore.load(fis, password); + java.security.cert.X509Certificate clientCert = + (java.security.cert.X509Certificate)clientKeystore.getCertificate("cert"); + server.checkCert(clientCert.getSubjectDN().toString(), clientCert.getIssuerDN().toString()); + + fis = new java.io.FileInputStream(defaultDir + "/s_rsa_ca1.jks"); + java.security.KeyStore serverKeystore = java.security.KeyStore.getInstance("JKS"); + serverKeystore.load(fis, password); + java.security.cert.X509Certificate serverCert = + (java.security.cert.X509Certificate)serverKeystore.getCertificate("cert"); + java.security.cert.X509Certificate caCert = + (java.security.cert.X509Certificate)serverKeystore.getCertificate("cacert"); + + IceSSL.NativeConnectionInfo info = (IceSSL.NativeConnectionInfo)server.ice_getConnection().getInfo(); + + test(info.nativeCerts.length == 2); + + test(caCert.equals(info.nativeCerts[1])); + test(serverCert.equals(info.nativeCerts[0])); + } + catch(Exception ex) + { + test(false); + } + fact.destroyServer(server); + + // + // Test IceSSL.VerifyPeer=2. Client has a certificate. + // + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "2"); + server = fact.createServer(d); + try + { + char[] password = "password".toCharArray(); + + java.io.FileInputStream fis = new java.io.FileInputStream(defaultDir + "/c_rsa_ca1.jks"); + java.security.KeyStore clientKeystore = java.security.KeyStore.getInstance("JKS"); + clientKeystore.load(fis, password); + java.security.cert.X509Certificate clientCert = + (java.security.cert.X509Certificate)clientKeystore.getCertificate("cert"); + server.checkCert(clientCert.getSubjectDN().toString(), clientCert.getIssuerDN().toString()); + } + catch(Exception ex) + { + test(false); + } + fact.destroyServer(server); + + comm.destroy(); + + // + // Test IceSSL.VerifyPeer=1. This should fail because the + // client doesn't trust the server's CA. + // + initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca2.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert2.jks"); + comm = Ice.Util.initialize(args, initData); + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "1"); + server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + + comm.destroy(); + + // + // Test IceSSL.VerifyPeer=2. This should fail because the + // server doesn't trust the client's CA. + // + // NOTE: In C++ this test fails with VerifyPeer=1, but JSSE seems + // to allow the handshake to continue unless we set VerifyPeer=2. + // + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca2.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + comm = Ice.Util.initialize(args, initData); + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "2"); + server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.ConnectionLostException ex) + { + // Expected. + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + + // + // Verify that IceSSL.CheckCertName has no effect in a server. + // + initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + comm = Ice.Util.initialize(args, initData); + + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.CheckCertName", "1"); + server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + + // + // Test IceSSL.CheckCertName. The test certificates for the server contain "127.0.0.1" + // as the common name or as a subject alternative name, so we only perform this test when + // the default host is "127.0.0.1". + // + if(defaultHost.equals("127.0.0.1")) + { + // + // Test subject alternative name. + // + { + initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.CheckCertName", "1"); + comm = Ice.Util.initialize(args, initData); + + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + // + // Test common name. + // + { + initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.CheckCertName", "1"); + comm = Ice.Util.initialize(args, initData); + + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1_cn1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + // + // Test common name again. The certificate used in this test has "127.0.0.11" as its + // common name, therefore the address "127.0.0.1" must NOT match. + // + { + initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.CheckCertName", "1"); + comm = Ice.Util.initialize(args, initData); + + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1_cn2.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + // Expected. + } + fact.destroyServer(server); + comm.destroy(); + } + } + } + out.println("ok"); + + out.print("testing custom certificate verifier... "); + out.flush(); + { + // + // ADH is allowed but will not have a certificate. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Ciphers", "NONE (.*DH_anon.*)"); + initData.properties.setProperty("IceSSL.VerifyPeer", "0"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + IceSSL.Plugin plugin = (IceSSL.Plugin)comm.getPluginManager().getPlugin("IceSSL"); + test(plugin != null); + CertificateVerifierI verifier = new CertificateVerifierI(); + plugin.setCertificateVerifier(verifier); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Ciphers", "NONE (.*DH_anon.*)"); + d.put("IceSSL.VerifyPeer", "0"); + ServerPrx server = fact.createServer(d); + try + { + String cipherSub = "DH_anon"; + server.checkCipher(cipherSub); + IceSSL.NativeConnectionInfo info = (IceSSL.NativeConnectionInfo)server.ice_getConnection().getInfo(); + test(info.cipher.indexOf(cipherSub) >= 0); + } + catch(Ice.LocalException ex) + { + test(false); + } + test(verifier.invoked()); + test(!verifier.hadCert()); + + // + // Have the verifier return false. Close the connection explicitly + // to force a new connection to be established. + // + verifier.reset(); + verifier.returnValue(false); + server.ice_getConnection().close(false); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.LocalException ex) + { + test(false); + } + test(verifier.invoked()); + test(!verifier.hadCert()); + + fact.destroyServer(server); + comm.destroy(); + } + { + // + // Verify that a server certificate is present. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + IceSSL.Plugin plugin = (IceSSL.Plugin)comm.getPluginManager().getPlugin("IceSSL"); + test(plugin != null); + CertificateVerifierI verifier = new CertificateVerifierI(); + plugin.setCertificateVerifier(verifier); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "2"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + test(verifier.invoked()); + test(verifier.hadCert()); + fact.destroyServer(server); + comm.destroy(); + } + { + // + // Verify that verifier is installed via property. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.CertVerifier", "test.IceSSL.configuration.CertificateVerifierI"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + IceSSL.Plugin plugin = (IceSSL.Plugin)comm.getPluginManager().getPlugin("IceSSL"); + test(plugin != null); + test(plugin.getCertificateVerifier() != null); + comm.destroy(); + } + out.println("ok"); + + out.print("testing protocols... "); + out.flush(); + { + // + // This should fail because the client and server have no protocol + // in common. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.Protocols", "ssl3"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "2"); + d.put("IceSSL.Protocols", "tls1"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.ConnectionLostException ex) + { + // Expected for thread pool. + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + + // + // This should succeed. + // + comm = Ice.Util.initialize(args, initData); + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "2"); + d.put("IceSSL.Protocols", "tls1, ssl3"); + server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + + { + // + // This should fail because the client ony enables SSLv3 and the server + // uses the default protocol set that disables SSLv3 + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.Protocols", "ssl3"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "2"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.ConnectionLostException ex) + { + // Expected for thread pool. + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + + { + // + // This should success because the client and the server enables SSLv3 + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.Protocols", "ssl3"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "2"); + d.put("IceSSL.Protocols", "ssl3, tls1_0, tls1_1, tls1_2"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.ConnectionLostException ex) + { + // Expected for thread pool. + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + + out.println("ok"); + + out.print("testing expired certificates... "); + out.flush(); + { + // + // This should fail because the server's certificate is expired. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1_exp.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "2"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + + // + // This should fail because the client's certificate is expired. + // + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1_exp.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + comm = Ice.Util.initialize(args, initData); + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "2"); + server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.ConnectionLostException ex) + { + // Expected. + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + out.println("ok"); + + out.print("testing multiple CA certificates... "); + out.flush(); + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacerts.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca2.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacerts.jks"); + d.put("IceSSL.VerifyPeer", "2"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + out.println("ok"); + + out.print("testing passwords... "); + out.flush(); + { + // + // Test password failure. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + // Don't specify the password. + //initData.properties.setProperty("IceSSL.Password", "password"); + try + { + Ice.Util.initialize(args, initData); + test(false); + } + catch(Ice.PluginInitializationException ex) + { + // Expected. + } + catch(Ice.LocalException ex) + { + test(false); + } + } + { + // + // Test password failure with callback. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("Ice.InitPlugins", "0"); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + Ice.PluginManager pm = comm.getPluginManager(); + IceSSL.Plugin plugin = (IceSSL.Plugin)pm.getPlugin("IceSSL"); + test(plugin != null); + PasswordCallbackI cb = new PasswordCallbackI("bogus"); + plugin.setPasswordCallback(cb); + try + { + pm.initializePlugins(); + test(false); + } + catch(Ice.PluginInitializationException ex) + { + // Expected. + } + catch(Ice.LocalException ex) + { + test(false); + } + comm.destroy(); + } + { + // + // Test installation of password callback. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("Ice.InitPlugins", "0"); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + Ice.PluginManager pm = comm.getPluginManager(); + IceSSL.Plugin plugin = (IceSSL.Plugin)pm.getPlugin("IceSSL"); + test(plugin != null); + PasswordCallbackI cb = new PasswordCallbackI(); + plugin.setPasswordCallback(cb); + test(plugin.getPasswordCallback() == cb); + try + { + pm.initializePlugins(); + } + catch(Ice.LocalException ex) + { + test(false); + } + comm.destroy(); + } + { + // + // Test password callback property. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.PasswordCallback", "test.IceSSL.configuration.PasswordCallbackI"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + Ice.PluginManager pm = comm.getPluginManager(); + IceSSL.Plugin plugin = (IceSSL.Plugin)pm.getPlugin("IceSSL"); + test(plugin != null); + test(plugin.getPasswordCallback() != null); + comm.destroy(); + } + out.println("ok"); + + out.print("testing ciphers... "); + out.flush(); + { + // + // The server has a certificate but the client doesn't. They should + // negotiate to use ADH since we explicitly enable it. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Ciphers", "NONE (.*DH_anon.*)"); + initData.properties.setProperty("IceSSL.VerifyPeer", "0"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.Ciphers", "ALL"); + d.put("IceSSL.VerifyPeer", "1"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + // + // Configure a server with RSA and DSA certificates. + // + // First try a client with a DSA certificate. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_dsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "1"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + + // + // Next try a client with an RSA certificate. + // + initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + comm = Ice.Util.initialize(args, initData); + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "1"); + server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + + // + // Next try a client with ADH. This should fail. + // + initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Ciphers", "NONE (.*DH_anon.*)"); + comm = Ice.Util.initialize(args, initData); + fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "1"); + server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.ConnectionLostException ex) + { + // Expected for thread pool. + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + // + // Configure a server with RSA and a client with DSA. This should fail. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_dsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.Ciphers", "NONE (.*DSS.*)"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "2"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.ConnectionLostException ex) + { + // Expected for thread pool. + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + // + // Configure the server with both RSA and DSA certificates, but use the + // Alias property to select the RSA certificate. This should fail. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_dsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.Ciphers", "NONE (.*DSS.*)"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Alias", "rsacert"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "2"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.SecurityException ex) + { + // Expected. + } + catch(Ice.ConnectionLostException ex) + { + // Expected for thread pool. + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + // + // Configure the server with both RSA and DSA certificates, but use the + // Alias property to select the DSA certificate. This should succeed. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Alias", "dsacert"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.VerifyPeer", "1"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + // + // RSA is used by default, so we examine the negotiated cipher to determine whether + // DSA was actually used. + // + IceSSL.ConnectionInfo info = (IceSSL.ConnectionInfo)server.ice_getConnection().getInfo(); + test(info.cipher.toLowerCase().contains("dss")); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + out.println("ok"); + + out.print("testing IceSSL.TrustOnly... "); + out.flush(); + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly", + "C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Server"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly", + "!C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Server"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly", + "C=US, ST=Florida, O=\"ZeroC, Inc.\", OU=Ice, emailAddress=info@zeroc.com, CN=Server"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly", + "C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Client"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly", + "!C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Client"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly", "CN=Server"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly", "!CN=Server"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly", "CN=Client"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly", "!CN=Client"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly", "CN=Client"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly", "CN=Server"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly", "C=Canada,CN=Server"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly", "!C=Canada,CN=Server"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly", "C=Canada;CN=Server"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly", "!C=Canada;!CN=Server"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly", "!CN=Server1"); // Should not match "Server" + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly", "!CN=Client1"); // Should not match "Client" + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + // + // Test rejection when client does not supply a certificate. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Ciphers", "NONE (.*DH_anon.*)"); + initData.properties.setProperty("IceSSL.VerifyPeer", "0"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.TrustOnly", + "C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Client"); + d.put("IceSSL.Ciphers", "NONE (.*DH_anon.*)"); + d.put("IceSSL.VerifyPeer", "0"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + // + // Test rejection when client does not supply a certificate. + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Ciphers", "NONE (.*DH_anon.*)"); + initData.properties.setProperty("IceSSL.VerifyPeer", "0"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.TrustOnly", + "!C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Client"); + d.put("IceSSL.Ciphers", "NONE (.*DH_anon.*)"); + d.put("IceSSL.VerifyPeer", "0"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + // + // Rejection takes precedence (client). + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly", "ST=Florida;!CN=Server;C=US"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + // + // Rejection takes precedence (server). + // + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly", "ST=Florida;!CN=Client;C=US"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + out.println("ok"); + + out.print("testing IceSSL.TrustOnly.Client... "); + out.flush(); + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly.Client", + "C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Server"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + // Should have no effect. + d.put("IceSSL.TrustOnly.Client", + "C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Server"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly.Client", + "!C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Server"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + // Should have no effect. + d.put("IceSSL.TrustOnly.Client", "CN=Client"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly.Client", "CN=Client"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + initData.properties.setProperty("IceSSL.TrustOnly.Client", "!CN=Client"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + out.println("ok"); + + out.print("testing IceSSL.TrustOnly.Server... "); + out.flush(); + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + // Should have no effect. + initData.properties.setProperty("IceSSL.TrustOnly.Server", + "C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Client"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly.Server", + "C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Client"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly.Server", + "!C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Client"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + // Should have no effect. + initData.properties.setProperty("IceSSL.TrustOnly.Server", "!CN=Server"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly.Server", "CN=Server"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly.Server", "!CN=Client"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + out.println("ok"); + + out.print("testing IceSSL.TrustOnly.Server.<AdapterName>... "); + out.flush(); + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly.Server", "CN=bogus"); + d.put("IceSSL.TrustOnly.Server.ServerAdapter", + "C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Client"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly.Server.ServerAdapter", + "!C=US, ST=Florida, O=ZeroC\\, Inc., OU=Ice, emailAddress=info@zeroc.com, CN=Client"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly.Server.ServerAdapter", "CN=bogus"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + test(false); + } + catch(Ice.LocalException ex) + { + } + fact.destroyServer(server); + comm.destroy(); + } + { + Ice.InitializationData initData = createClientProps(defaultProperties, defaultDir, defaultHost); + initData.properties.setProperty("IceSSL.Keystore", "c_rsa_ca1.jks"); + initData.properties.setProperty("IceSSL.Password", "password"); + initData.properties.setProperty("IceSSL.Truststore", "cacert1.jks"); + Ice.Communicator comm = Ice.Util.initialize(args, initData); + ServerFactoryPrx fact = ServerFactoryPrxHelper.checkedCast(comm.stringToProxy(factoryRef)); + test(fact != null); + java.util.Map<String, String> d = createServerProps(defaultProperties, defaultDir, defaultHost); + d.put("IceSSL.Keystore", "s_rsa_dsa_ca1.jks"); + d.put("IceSSL.Password", "password"); + d.put("IceSSL.Truststore", "cacert1.jks"); + d.put("IceSSL.TrustOnly.Server.ServerAdapter", "!CN=bogus"); + ServerPrx server = fact.createServer(d); + try + { + server.ice_ping(); + } + catch(Ice.LocalException ex) + { + test(false); + } + fact.destroyServer(server); + comm.destroy(); + } + out.println("ok"); + + return factory; + } +} diff --git a/java/test/src/main/java/test/IceSSL/configuration/CertificateVerifierI.java b/java/test/src/main/java/test/IceSSL/configuration/CertificateVerifierI.java new file mode 100644 index 00000000000..03ae75ad659 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/configuration/CertificateVerifierI.java @@ -0,0 +1,99 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceSSL.configuration; + +public class CertificateVerifierI implements IceSSL.CertificateVerifier +{ + public + CertificateVerifierI() + { + reset(); + } + + @Override + public boolean + verify(IceSSL.NativeConnectionInfo info) + { + if(info.nativeCerts != null) + { + try + { + java.util.Collection<java.util.List<?> > subjectAltNames = + ((java.security.cert.X509Certificate)info.nativeCerts[0]).getSubjectAlternativeNames(); + test(subjectAltNames != null); + java.util.List<String> ipAddresses = new java.util.ArrayList<String>(); + java.util.List<String> dnsNames = new java.util.ArrayList<String>(); + for(java.util.List<?> l : subjectAltNames) + { + test(!l.isEmpty()); + Integer n = (Integer)l.get(0); + if(n.intValue() == 7) + { + ipAddresses.add((String)l.get(1)); + } + else if(n.intValue() == 2) + { + dnsNames.add((String)l.get(1)); + } + } + + test(dnsNames.contains("server")); + test(ipAddresses.contains("127.0.0.1")); + } + catch(java.security.cert.CertificateParsingException ex) + { + test(false); + } + } + + _hadCert = info.nativeCerts != null; + _invoked = true; + return _returnValue; + } + + void + reset() + { + _returnValue = true; + _invoked = false; + _hadCert = false; + } + + void + returnValue(boolean b) + { + _returnValue = b; + } + + boolean + invoked() + { + return _invoked; + } + + boolean + hadCert() + { + return _hadCert; + } + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private boolean _returnValue; + private boolean _invoked; + private boolean _hadCert; +} diff --git a/java/test/src/main/java/test/IceSSL/configuration/Client.java b/java/test/src/main/java/test/IceSSL/configuration/Client.java new file mode 100644 index 00000000000..36ecfde860d --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/configuration/Client.java @@ -0,0 +1,51 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceSSL.configuration; + +import java.io.PrintWriter; + +import test.IceSSL.configuration.Test.ServerFactoryPrx; + +public class Client extends test.Util.Application +{ + @Override + public int run(String[] args) + { + PrintWriter out = getWriter(); + if(args.length < 1) + { + out.println("Usage: client testdir"); + return 1; + } + + ServerFactoryPrx factory = AllTests.allTests(this, args[0], out); + factory.shutdown(); + + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.IceSSL.configuration"); + return initData; + } + + public static void main(String[] args) + { + Client c = new Client(); + int status = c.main("Client", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/IceSSL/configuration/PasswordCallbackI.java b/java/test/src/main/java/test/IceSSL/configuration/PasswordCallbackI.java new file mode 100644 index 00000000000..b7493caaffc --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/configuration/PasswordCallbackI.java @@ -0,0 +1,48 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceSSL.configuration; + +public class PasswordCallbackI implements IceSSL.PasswordCallback +{ + public + PasswordCallbackI() + { + _password = "password"; + } + + public + PasswordCallbackI(String password) + { + _password = password; + } + + @Override + public char[] + getPassword(String alias) + { + return _password.toCharArray(); + } + + @Override + public char[] + getTruststorePassword() + { + return null; + } + + @Override + public char[] + getKeystorePassword() + { + return null; + } + + private String _password; +} diff --git a/java/test/src/main/java/test/IceSSL/configuration/Server.java b/java/test/src/main/java/test/IceSSL/configuration/Server.java new file mode 100644 index 00000000000..9438f73d419 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/configuration/Server.java @@ -0,0 +1,46 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceSSL.configuration; + + +public class Server extends test.Util.Application +{ + @Override + public int run(String[] args) + { + Ice.Communicator communicator = communicator(); + communicator.getProperties().setProperty("TestAdapter.Endpoints", "tcp -p 12010"); + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + Ice.Identity id = communicator.stringToIdentity("factory"); + adapter.add(new ServerFactoryI(), id); + adapter.activate(); + + communicator.waitForShutdown(); + return 0; + } + + @Override + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package.Test", "test.IceSSL.configuration"); + return initData; + } + + public static void main(String[] args) + { + Server c = new Server(); + int status = c.main("Server", args); + + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/IceSSL/configuration/ServerFactoryI.java b/java/test/src/main/java/test/IceSSL/configuration/ServerFactoryI.java new file mode 100644 index 00000000000..34271e03f89 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/configuration/ServerFactoryI.java @@ -0,0 +1,70 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceSSL.configuration; +import test.IceSSL.configuration.Test.ServerPrx; +import test.IceSSL.configuration.Test.ServerPrxHelper; +import test.IceSSL.configuration.Test._ServerFactoryDisp; + +class ServerFactoryI extends _ServerFactoryDisp +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + @Override + public ServerPrx + createServer(java.util.Map<String, String> props, Ice.Current current) + { + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(); + for(java.util.Map.Entry<String, String> i : props.entrySet()) + { + initData.properties.setProperty(i.getKey(), i.getValue()); + } + + String[] args = new String[0]; + Ice.Communicator communicator = Ice.Util.initialize(args, initData); + Ice.ObjectAdapter adapter = communicator.createObjectAdapterWithEndpoints("ServerAdapter", "ssl"); + ServerI server = new ServerI(communicator); + Ice.ObjectPrx obj = adapter.addWithUUID(server); + _servers.put(obj.ice_getIdentity(), server); + adapter.activate(); + + return ServerPrxHelper.uncheckedCast(obj); + } + + @Override + public void + destroyServer(ServerPrx srv, Ice.Current current) + { + Ice.Identity key = srv.ice_getIdentity(); + if(_servers.containsKey(key)) + { + ServerI server = _servers.get(key); + server.destroy(); + _servers.remove(key); + } + } + + @Override + public void + shutdown(Ice.Current current) + { + test(_servers.size() == 0); + current.adapter.getCommunicator().shutdown(); + } + + private java.util.Map<Ice.Identity, ServerI> _servers = new java.util.HashMap<Ice.Identity, ServerI>(); +} diff --git a/java/test/src/main/java/test/IceSSL/configuration/ServerI.java b/java/test/src/main/java/test/IceSSL/configuration/ServerI.java new file mode 100644 index 00000000000..ca3e2835e23 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/configuration/ServerI.java @@ -0,0 +1,84 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceSSL.configuration; +import test.IceSSL.configuration.Test._ServerDisp; + +class ServerI extends _ServerDisp +{ + ServerI(Ice.Communicator communicator) + { + _communicator = communicator; + } + + @Override + public void + noCert(Ice.Current current) + { + try + { + IceSSL.NativeConnectionInfo info = (IceSSL.NativeConnectionInfo)current.con.getInfo(); + test(info.certs == null); + } + catch(Ice.LocalException ex) + { + test(false); + } + } + + @Override + public void + checkCert(String subjectDN, String issuerDN, Ice.Current current) + { + try + { + IceSSL.NativeConnectionInfo info = (IceSSL.NativeConnectionInfo)current.con.getInfo(); + java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate)info.nativeCerts[0]; + test(info.nativeCerts.length == 2 && + cert.getSubjectDN().toString().equals(subjectDN) && + cert.getIssuerDN().toString().equals(issuerDN)); + } + catch(Ice.LocalException ex) + { + test(false); + } + } + + @Override + public void + checkCipher(String cipher, Ice.Current current) + { + try + { + IceSSL.NativeConnectionInfo info = (IceSSL.NativeConnectionInfo)current.con.getInfo(); + test(info.cipher.indexOf(cipher) >= 0); + } + catch(Ice.LocalException ex) + { + test(false); + } + } + + public void + destroy() + { + _communicator.destroy(); + } + + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private Ice.Communicator _communicator; +} diff --git a/java/test/src/main/java/test/IceSSL/configuration/Test.ice b/java/test/src/main/java/test/IceSSL/configuration/Test.ice new file mode 100644 index 00000000000..b884e914104 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/configuration/Test.ice @@ -0,0 +1,32 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.IceSSL.configuration"]] +module Test +{ + +interface Server +{ + void noCert(); + void checkCert(string subjectDN, string issuerDN); + void checkCipher(string cipher); +}; + +dictionary<string, string> Properties; + +interface ServerFactory +{ + Server* createServer(Properties props); + void destroyServer(Server* srv); + void shutdown(); +}; + +}; diff --git a/java/test/src/main/java/test/IceSSL/configuration/run.py b/java/test/src/main/java/test/IceSSL/configuration/run.py new file mode 100755 index 00000000000..791f566f4b2 --- /dev/null +++ b/java/test/src/main/java/test/IceSSL/configuration/run.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +testdir = '"%s"' % os.getcwd() + +TestUtil.clientServerTest(additionalClientOptions=testdir) diff --git a/java/test/src/main/java/test/IceUtil/fileLock/.gitignore b/java/test/src/main/java/test/IceUtil/fileLock/.gitignore new file mode 100644 index 00000000000..3c97cdc2906 --- /dev/null +++ b/java/test/src/main/java/test/IceUtil/fileLock/.gitignore @@ -0,0 +1 @@ +run.pid diff --git a/java/test/src/main/java/test/IceUtil/fileLock/Client.java b/java/test/src/main/java/test/IceUtil/fileLock/Client.java new file mode 100644 index 00000000000..ce67ad3fe50 --- /dev/null +++ b/java/test/src/main/java/test/IceUtil/fileLock/Client.java @@ -0,0 +1,63 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceUtil.fileLock; + +import java.io.BufferedReader; +import java.io.InputStreamReader; + +public class Client +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + main(String[] argvs) + { + IceUtilInternal.FileLock lock = null; + + lock = new IceUtilInternal.FileLock("file.lock"); + test(true); + + // + // Force GC here to ensure that temp references in FileLock + // are collected and that not affect file locking. + // + java.lang.Runtime.getRuntime().gc(); + + System.out.println("File lock acquired."); + System.out.println("Enter some input and press enter, to release the lock and terminate the program."); + + // + // Block the test waiting for IO, so the file lock is preserved. + // + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + try + { + br.readLine(); + } + catch(java.io.IOException ex) + { + System.out.println("exception:\n " + ex.toString()); + test(false); + } + + if(lock != null) + { + lock.release(); + } + System.out.println("File lock released."); + } +} diff --git a/java/test/src/main/java/test/IceUtil/fileLock/ClientFail.java b/java/test/src/main/java/test/IceUtil/fileLock/ClientFail.java new file mode 100644 index 00000000000..c96dc7c9b57 --- /dev/null +++ b/java/test/src/main/java/test/IceUtil/fileLock/ClientFail.java @@ -0,0 +1,85 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceUtil.fileLock; + +import java.io.File; +import java.io.RandomAccessFile; +import java.io.EOFException; +import java.io.UTFDataFormatException; +import java.io.IOException; + + +public class ClientFail +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + main(String[] argvs) + { + + try + { + new IceUtilInternal.FileLock("file.lock"); + test(false); + } + catch(IceUtil.FileLockException ex) + { + System.out.println("File lock not acquired."); + // + // Try to read the pid of the lock owner from the lock file, in Windows + // we don't write pid to lock files. + // + if(!System.getProperty("os.name").startsWith("Windows")) + { + String pid = ""; + try + { + RandomAccessFile file = new RandomAccessFile(new File("file.lock"), "r"); + try + { + pid = file.readUTF(); + } + finally + { + file.close(); + } + } + catch(EOFException eofEx) + { + System.out.println("exception:\n" + eofEx.toString()); + test(false); + } + catch(UTFDataFormatException utfEx) + { + System.out.println("exception:\n" + utfEx.toString()); + test(false); + } + catch(IOException ioEx) + { + System.out.println("exception:\n" + ioEx.toString()); + test(false); + } + + if(pid.length() == 0) + { + test(false); + } + System.out.println("Lock owned by: " + pid); + } + } + } +} diff --git a/java/test/src/main/java/test/IceUtil/fileLock/run.py b/java/test/src/main/java/test/IceUtil/fileLock/run.py new file mode 100755 index 00000000000..26ab933f034 --- /dev/null +++ b/java/test/src/main/java/test/IceUtil/fileLock/run.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +sys.stdout.write("testing process file lock... ") +sys.stdout.flush() + +client = os.path.join("test.IceUtil.fileLock.Client") +clientFail = os.path.join("test.IceUtil.fileLock.ClientFail") + +clientExe = TestUtil.startClient(client, "", None, None, False) +clientExe.expect('File lock acquired.\.*') + +# +# Ensure that the file lock exists. +# +assert(os.path.exists("file.lock")); + +clientFailExe = TestUtil.startClient(clientFail, "", None, None, False) +clientFailExe.expect('File lock not acquired.') +clientFailExe.wait() + +# send some output to client to terminate it. +clientExe.sendline('go') +clientExe.expect('File lock released.') +clientExe.wait() + +# +# Ensure that the file lock was removed. +# +assert(not os.path.exists("file.lock")); + +# The lock is gone try to acquire it again. +clientExe = TestUtil.startClient(client, "", None, None, False) +clientExe.expect('File lock acquired.\.*') +clientExe.sendline('go') +clientExe.expect('File lock released.') +clientExe.wait() + +print("ok") diff --git a/java/test/src/main/java/test/IceUtil/inputUtil/Client.java b/java/test/src/main/java/test/IceUtil/inputUtil/Client.java new file mode 100644 index 00000000000..5d29a45452c --- /dev/null +++ b/java/test/src/main/java/test/IceUtil/inputUtil/Client.java @@ -0,0 +1,169 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.IceUtil.inputUtil; + +public class Client +{ + private static void + test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + main(String[] argvs) + { + System.out.print("testing string to command line arguments... "); + System.out.flush(); + String[] args; + + try + { + test(IceUtilInternal.Options.split("").length == 0); + + args = IceUtilInternal.Options.split("\"\""); + test(args.length == 1 && args[0].equals("")); + args = IceUtilInternal.Options.split("''"); + test(args.length == 1 && args[0].equals("")); + args = IceUtilInternal.Options.split("$''"); + test(args.length == 1 && args[0].equals("")); + + args = IceUtilInternal.Options.split("-a -b -c"); + test(args.length == 3 && args[0].equals("-a") && args[1].equals("-b") && args[2].equals("-c")); + args = IceUtilInternal.Options.split("\"-a\" '-b' $'-c'"); + test(args.length == 3 && args[0].equals("-a") && args[1].equals("-b") && args[2].equals("-c")); + args = IceUtilInternal.Options.split(" '-b' \"-a\" $'-c' "); + test(args.length == 3 && args[0].equals("-b") && args[1].equals("-a") && args[2].equals("-c")); + args = IceUtilInternal.Options.split(" $'-c' '-b' \"-a\" "); + test(args.length == 3 && args[0].equals("-c") && args[1].equals("-b") && args[2].equals("-a")); + + // Testing single quote + args = IceUtilInternal.Options.split("-Dir='C:\\\\test\\\\file'"); // -Dir='C:\\test\\file' + test(args.length == 1 && args[0].equals("-Dir=C:\\\\test\\\\file")); // -Dir=C:\\test\\file + args = IceUtilInternal.Options.split("-Dir='C:\\test\\file'"); // -Dir='C:\test\file' + test(args.length == 1 && args[0].equals("-Dir=C:\\test\\file")); // -Dir=C:\test\file + args = IceUtilInternal.Options.split("-Dir='C:\\test\\filewith\"quote'"); // -Dir='C:\test\filewith"quote' + test(args.length == 1 && args[0].equals("-Dir=C:\\test\\filewith\"quote")); // -Dir=C:\test\filewith"quote + + // Testing double quote + args = IceUtilInternal.Options.split("-Dir=\"C:\\\\test\\\\file\""); // -Dir="C:\\test\\file" + test(args.length == 1 && args[0].equals("-Dir=C:\\test\\file")); // -Dir=C:\test\file + args = IceUtilInternal.Options.split("-Dir=\"C:\\test\\file\""); // -Dir="C:\test\file" + test(args.length == 1 && args[0].equals("-Dir=C:\\test\\file")); // -Dir=C:\test\file + args = IceUtilInternal.Options.split("-Dir=\"C:\\test\\filewith\\\"quote\""); // -Dir="C:\test\filewith\"quote" + test(args.length == 1 && args[0].equals("-Dir=C:\\test\\filewith\"quote")); // -Dir=C:\test\filewith"quote + + // Testing ANSI quote + args = IceUtilInternal.Options.split("-Dir=$'C:\\\\test\\\\file'"); // -Dir=$'C:\\test\\file' + test(args.length == 1 && args[0].equals("-Dir=C:\\test\\file")); // -Dir=C:\test\file + args = IceUtilInternal.Options.split("-Dir=$'C:\\oest\\oile'"); // -Dir='C:\oest\oile' + test(args.length == 1 && args[0].equals("-Dir=C:\\oest\\oile")); // -Dir=C:\oest\oile + args = IceUtilInternal.Options.split("-Dir=$'C:\\oest\\oilewith\"quote'"); // -Dir=$'C:\oest\oilewith"quote' + test(args.length == 1 && args[0].equals("-Dir=C:\\oest\\oilewith\"quote")); // -Dir=C:\oest\oilewith"quote + args = IceUtilInternal.Options.split("-Dir=$'\\103\\072\\134\\164\\145\\163\\164\\134\\146\\151\\154\\145'"); + test(args.length == 1 && args[0].equals("-Dir=C:\\test\\file")); // -Dir=C:\test\file + args = IceUtilInternal.Options.split("-Dir=$'\\x43\\x3A\\x5C\\x74\\x65\\x73\\x74\\x5C\\x66\\x69\\x6C\\x65'"); + test(args.length == 1 && args[0].equals("-Dir=C:\\test\\file")); // -Dir=C:\test\file + args = IceUtilInternal.Options.split("-Dir=$'\\cM\\c_'"); // Control characters + test(args.length == 1 && args[0].equals("-Dir=\015\037")); + args = IceUtilInternal.Options.split("-Dir=$'C:\\\\\\146\\x66\\cMi'"); // -Dir=$'C:\\\146\x66i\cMi' + test(args.length == 1 && args[0].equals("-Dir=C:\\ff\015i")); + args = IceUtilInternal.Options.split("-Dir=$'C:\\\\\\cM\\x66\\146i'"); // -Dir=$'C:\\\cM\x66\146i' + test(args.length == 1 && args[0].equals("-Dir=C:\\\015ffi")); + } + catch(IceUtilInternal.Options.BadQuote ex) + { + test(false); + } + + String[] badQuoteCommands = new String[6]; + badQuoteCommands[0] = "\""; + badQuoteCommands[1] = "'"; + badQuoteCommands[2] = "\\$'"; + badQuoteCommands[3] = "-Dir=\"test"; + badQuoteCommands[4] = "-Dir='test"; + badQuoteCommands[5] = "-Dir=$'test"; + for(int i = 0; i < 6; ++i) + { + try + { + IceUtilInternal.Options.split(badQuoteCommands[i]); + test(false); + } + catch(IceUtilInternal.Options.BadQuote ex) + { + } + } + + System.out.println("ok"); + + System.out.print("checking string splitting... "); + System.out.flush(); + { + String[] arr; + + arr = IceUtilInternal.StringUtil.splitString("", ""); + test(arr.length == 0); + arr = IceUtilInternal.StringUtil.splitString("", ":"); + test(arr.length == 0); + arr = IceUtilInternal.StringUtil.splitString("a", ""); + test(arr.length == 1 && arr[0].equals("a")); + arr = IceUtilInternal.StringUtil.splitString("a", ":"); + test(arr.length == 1 && arr[0].equals("a")); + arr = IceUtilInternal.StringUtil.splitString("ab", ""); + test(arr.length == 1 && arr[0].equals("ab")); + arr = IceUtilInternal.StringUtil.splitString("ab:", ":"); + test(arr.length == 1 && arr[0].equals("ab")); + arr = IceUtilInternal.StringUtil.splitString(":ab", ":"); + test(arr.length == 1 && arr[0].equals("ab")); + arr = IceUtilInternal.StringUtil.splitString("a:b", ":"); + test(arr.length == 2 && arr[0].equals("a") && arr[1].equals("b")); + arr = IceUtilInternal.StringUtil.splitString(":a:b:", ":"); + test(arr.length == 2 && arr[0].equals("a") && arr[1].equals("b")); + + arr = IceUtilInternal.StringUtil.splitString("\"a\"", ":"); + test(arr.length == 1 && arr[0].equals("a")); + arr = IceUtilInternal.StringUtil.splitString("\"a\":b", ":"); + test(arr.length == 2 && arr[0].equals("a") && arr[1].equals("b")); + arr = IceUtilInternal.StringUtil.splitString("\"a\":\"b\"", ":"); + test(arr.length == 2 && arr[0].equals("a") && arr[1].equals("b")); + arr = IceUtilInternal.StringUtil.splitString("\"a:b\"", ":"); + test(arr.length == 1 && arr[0].equals("a:b")); + arr = IceUtilInternal.StringUtil.splitString("a=\"a:b\"", ":"); + test(arr.length == 1 && arr[0].equals("a=a:b")); + + arr = IceUtilInternal.StringUtil.splitString("'a'", ":"); + test(arr.length == 1 && arr[0].equals("a")); + arr = IceUtilInternal.StringUtil.splitString("'\"a'", ":"); + test(arr.length == 1 && arr[0].equals("\"a")); + arr = IceUtilInternal.StringUtil.splitString("\"'a\"", ":"); + test(arr.length == 1 && arr[0].equals("'a")); + + arr = IceUtilInternal.StringUtil.splitString("a\\'b", ":"); + test(arr.length == 1 && arr[0].equals("a'b")); + arr = IceUtilInternal.StringUtil.splitString("'a:b\\'c'", ":"); + test(arr.length == 1 && arr[0].equals("a:b'c")); + arr = IceUtilInternal.StringUtil.splitString("a\\\"b", ":"); + test(arr.length == 1 && arr[0].equals("a\"b")); + arr = IceUtilInternal.StringUtil.splitString("\"a:b\\\"c\"", ":"); + test(arr.length == 1 && arr[0].equals("a:b\"c")); + arr = IceUtilInternal.StringUtil.splitString("'a:b\"c'", ":"); + test(arr.length == 1 && arr[0].equals("a:b\"c")); + arr = IceUtilInternal.StringUtil.splitString("\"a:b'c\"", ":"); + test(arr.length == 1 && arr[0].equals("a:b'c")); + + test(IceUtilInternal.StringUtil.splitString("a\"b", ":") == null); + } + System.out.println("ok"); + } +} diff --git a/java/test/src/main/java/test/IceUtil/inputUtil/run.py b/java/test/src/main/java/test/IceUtil/inputUtil/run.py new file mode 100755 index 00000000000..cb15b614259 --- /dev/null +++ b/java/test/src/main/java/test/IceUtil/inputUtil/run.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +sys.stdout.write("starting client... ") +sys.stdout.flush() +clientProc = TestUtil.startClient("test.IceUtil.inputUtil.Client",startReader=False) +print("ok") +clientProc.startReader() +clientProc.waitTestSuccess() diff --git a/java/test/src/main/java/test/Slice/generation/.gitignore b/java/test/src/main/java/test/Slice/generation/.gitignore new file mode 100644 index 00000000000..90b07e9d451 --- /dev/null +++ b/java/test/src/main/java/test/Slice/generation/.gitignore @@ -0,0 +1 @@ +classes diff --git a/java/test/src/main/java/test/Slice/generation/File1.ice b/java/test/src/main/java/test/Slice/generation/File1.ice new file mode 100644 index 00000000000..c92e0a00b2d --- /dev/null +++ b/java/test/src/main/java/test/Slice/generation/File1.ice @@ -0,0 +1,21 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Slice.generation"]] +module Test +{ + +interface Interface1 +{ + void method(); +}; + +}; diff --git a/java/test/src/main/java/test/Slice/generation/File2.ice b/java/test/src/main/java/test/Slice/generation/File2.ice new file mode 100644 index 00000000000..2d6f7a498f7 --- /dev/null +++ b/java/test/src/main/java/test/Slice/generation/File2.ice @@ -0,0 +1,21 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Slice.generation"]] +module Test +{ + +interface Interface2 +{ + void method(); +}; + +}; diff --git a/java/test/src/main/java/test/Slice/generation/list-generated.out b/java/test/src/main/java/test/Slice/generation/list-generated.out new file mode 100644 index 00000000000..cbacf36a41c --- /dev/null +++ b/java/test/src/main/java/test/Slice/generation/list-generated.out @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<generated> + <source name="File1.ice"> + <file name="classes/test/Slice/generation/Test/_Interface1Operations.java"/> + <file name="classes/test/Slice/generation/Test/_Interface1OperationsNC.java"/> + <file name="classes/test/Slice/generation/Test/_Marker.java"/> + <file name="classes/test/Slice/generation/Test/Interface1.java"/> + <file name="classes/test/Slice/generation/Test/Interface1Holder.java"/> + <file name="classes/test/Slice/generation/Test/Interface1PrxHolder.java"/> + <file name="classes/test/Slice/generation/Test/Interface1PrxHelper.java"/> + <file name="classes/test/Slice/generation/Test/Interface1Prx.java"/> + <file name="classes/test/Slice/generation/Test/_Interface1Disp.java"/> + <file name="classes/test/Slice/generation/Test/Callback_Interface1_method.java"/> + <output></output> + </source> + <source name="File2.ice"> + <file name="classes/test/Slice/generation/Test/_Interface2Operations.java"/> + <file name="classes/test/Slice/generation/Test/_Interface2OperationsNC.java"/> + <file name="classes/test/Slice/generation/Test/_Marker.java"/> + <file name="classes/test/Slice/generation/Test/Interface2.java"/> + <file name="classes/test/Slice/generation/Test/Interface2Holder.java"/> + <file name="classes/test/Slice/generation/Test/Interface2PrxHolder.java"/> + <file name="classes/test/Slice/generation/Test/Interface2PrxHelper.java"/> + <file name="classes/test/Slice/generation/Test/Interface2Prx.java"/> + <file name="classes/test/Slice/generation/Test/_Interface2Disp.java"/> + <file name="classes/test/Slice/generation/Test/Callback_Interface2_method.java"/> + <output></output> + </source> +</generated> diff --git a/java/test/src/main/java/test/Slice/generation/run.py b/java/test/src/main/java/test/Slice/generation/run.py new file mode 100755 index 00000000000..72f21335e28 --- /dev/null +++ b/java/test/src/main/java/test/Slice/generation/run.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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, re + +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 RuntimeError("can't find toplevel os.getcwd()!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +sys.stdout.write("testing list-generated... ") +sys.stdout.flush() + +slice2java = os.path.join(TestUtil.getCppBinDir(), "slice2java") +if not os.path.exists("classes"): + os.mkdir("classes") + +command = '"' + slice2java + '" --list-generated --output-dir classes File1.ice File2.ice' +if TestUtil.debug: + sys.stdout.write("(%s) " % command) +p = TestUtil.runCommand(command) +lines1 = p.stdout.readlines() +lines2 = open(os.path.join(os.getcwd(), "list-generated.out"), "r").readlines() +if len(lines1) != len(lines2): + print("failed!") + sys.exit(1) + +i = 0 +while i < len(lines1): + if sys.version_info[0] == 2: + line1 = lines1[i].strip() + line2 = lines2[i].strip() + else: + line1 = lines1[i].decode("utf-8").strip() + line2 = lines2[i].strip() + if line1 != line2: + print("failed!") + sys.exit(1) + i = i + 1 +else: + print("ok") + +sys.exit(0) diff --git a/java/test/src/main/java/test/Slice/keyword/Client.java b/java/test/src/main/java/test/Slice/keyword/Client.java new file mode 100644 index 00000000000..df96ebc985f --- /dev/null +++ b/java/test/src/main/java/test/Slice/keyword/Client.java @@ -0,0 +1,229 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Slice.keyword; +import test.Slice.keyword._abstract.AMD_catch_checkedCast; +import test.Slice.keyword._abstract._assert; +import test.Slice.keyword._abstract._break; +import test.Slice.keyword._abstract._catch; +import test.Slice.keyword._abstract._catchDisp; +import test.Slice.keyword._abstract._default; +import test.Slice.keyword._abstract._defaultDisp; +import test.Slice.keyword._abstract._else; +import test.Slice.keyword._abstract._finalize; +import test.Slice.keyword._abstract._hashCode; +import test.Slice.keyword._abstract._import; +import test.Slice.keyword._abstract._new; +import test.Slice.keyword._abstract._switch; +import test.Slice.keyword._abstract.catchPrx; +import test.Slice.keyword._abstract.defaultPrx; +import test.Slice.keyword._abstract.defaultPrxHelper; +import test.Slice.keyword._abstract.elsePrx; +import test.Slice.keyword._abstract.finalizePrx; +import test.Slice.keyword._abstract.forHolder; +import test.Slice.keyword._abstract.gotoHolder; + +public class Client +{ + static public class catchI extends _catchDisp + { + public + catchI() + { + } + + @Override + public void + checkedCast_async(AMD_catch_checkedCast __cb, int _clone, Ice.Current __current) + { + int _continue = 0; + __cb.ice_response(_continue); + } + } + + static public class defaultI extends _defaultDisp + { + public + defaultI() + { + } + + @Override + public void + _do(Ice.Current __current) + { + assert __current.operation.equals("do"); + } + } + + static public class elseI extends _else + { + public + elseI() + { + } + + @Override + public void + foo(defaultPrx _equals, Ice.IntHolder _final, Ice.Current __current) + { + } + } + + static public class newI implements _new + { + public + newI() + { + } + + @Override + public _assert + _notify(_break _notifyAll, _else _null, _finalize _package, + elsePrx _private, finalizePrx _protected, + catchPrx _public, defaultPrx _return, int _static, int _strictfp, int _super) + throws _hashCode, _import + { + return null; + } + } + + static public class finalizeI extends _finalize + { + public + finalizeI() + { + } + + @Override + public void + checkedCast_async(AMD_catch_checkedCast __cb, int _clone, Ice.Current __current) + { + int _continue = 0; + __cb.ice_response(_continue); + } + + @Override + public void + _do(Ice.Current __current) + { + } + + @Override + public void + foo(defaultPrx _equals, Ice.IntHolder _final, Ice.Current __current) + { + } + } + + // + // This section of the test is present to ensure that the C++ types + // are named correctly. It is not expected to run. + // + @SuppressWarnings({ "unused", "null" }) + private static void + testtypes() + { + _assert v = _assert._boolean; + _break b = new _break(); + b._case = 0; + catchPrx c = null; + c._checkedCast(0, new Ice.IntHolder()); + _catch c1 = new catchI(); + defaultPrx d = null; + d._do(); + _default d1 = new defaultI(); + elsePrx e; + _else e1 = new elseI(); + finalizePrx f = null; + f._checkedCast(0, new Ice.IntHolder()); + f._do(); + _finalize f1 = new finalizeI(); + forHolder g; + gotoHolder h; + _hashCode i = new _hashCode(); + i._if = 0; + _import j = new _import(); + j._if = 0; + j._instanceof = 1; + j._native = 2; + _new k = new newI(); + assert _switch.value == 0; + } + + private static int + run(String[] args, Ice.Communicator communicator) + { + Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter"); + adapter.add(new defaultI(), communicator.stringToIdentity("test")); + adapter.activate(); + + System.out.print("Testing operation name... "); + System.out.flush(); + defaultPrx p = defaultPrxHelper.uncheckedCast( + adapter.createProxy(communicator.stringToIdentity("test"))); + p._do(); + System.out.println("ok"); + + return 0; + } + + public static void + main(String[] args) + { + int status = 0; + Ice.Communicator communicator = null; + + try + { + // + // In this test, we need at least two threads in the + // client side thread pool for nested AMI. + // + Ice.StringSeqHolder argsH = new Ice.StringSeqHolder(args); + Ice.InitializationData initData = new Ice.InitializationData(); + initData.properties = Ice.Util.createProperties(argsH); + initData.properties.setProperty("Ice.Package._abstract", "test.Slice.keyword"); + initData.properties.setProperty("Ice.ThreadPool.Client.Size", "2"); + initData.properties.setProperty("Ice.ThreadPool.Client.SizeWarn", "0"); + initData.properties.setProperty("TestAdapter.Endpoints", "default -p 12010:udp"); + + // + // We must set MessageSizeMax to an explicit values, + // because we run tests to check whether + // Ice.MemoryLimitException is raised as expected. + // + initData.properties.setProperty("Ice.MessageSizeMax", "100"); + + communicator = Ice.Util.initialize(argsH, initData); + status = run(argsH.value, 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/src/main/java/test/Slice/keyword/Key.ice b/java/test/src/main/java/test/Slice/keyword/Key.ice new file mode 100644 index 00000000000..f2002f43ccc --- /dev/null +++ b/java/test/src/main/java/test/Slice/keyword/Key.ice @@ -0,0 +1,79 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Slice.keyword"]] +module abstract +{ + +enum assert +{ + boolean +}; + +struct break +{ + int case; +}; + +interface catch +{ + ["amd"] void checkedCast(int clone, out int continue); +}; + +interface default +{ + void do(); +}; + +class else +{ + int if; + void foo(default* equals, out int final); +}; + +class finalize extends else implements default, catch +{ +}; +sequence<assert> for; +dictionary<string, assert> goto; + +exception hashCode +{ + int if; +}; + +exception import extends hashCode +{ + int instanceof; + int native; +}; + +local interface new +{ + assert notify( break notifyAll, else null, finalize package, else* private, finalize * protected, catch* public, + default* return, int static, int strictfp, int super) + throws hashCode, import; +}; + +const int switch = 0; +const int synchronized = 0; +const int this = 0; +const int throw = 0; +const int toString = 0; +const int try = 0; +const int uncheckedCast = 0; +const int volatile = 0; +const int wait = 0; +const int while = 0; +const int finally = 0; +const int getClass = 0; + +}; diff --git a/java/test/src/main/java/test/Slice/keyword/run.py b/java/test/src/main/java/test/Slice/keyword/run.py new file mode 100755 index 00000000000..1b7865a118d --- /dev/null +++ b/java/test/src/main/java/test/Slice/keyword/run.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +sys.stdout.write("starting client... ") +sys.stdout.flush() +clientProc = TestUtil.startClient("test.Slice.keyword.Client",startReader=False) +print("ok") +clientProc.startReader() +clientProc.waitTestSuccess() diff --git a/java/test/src/main/java/test/Slice/macros/Client.java b/java/test/src/main/java/test/Slice/macros/Client.java new file mode 100644 index 00000000000..4c4fa0e7b0a --- /dev/null +++ b/java/test/src/main/java/test/Slice/macros/Client.java @@ -0,0 +1,54 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Slice.macros; + +import test.Slice.macros.Test.Default; +import test.Slice.macros.Test.NoDefault; +import test.Slice.macros.Test.JavaOnly; + +public class Client +{ + private static void test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + public static void + main(String[] args) + { + int status = 0; + try + { + System.out.print("testing Slice predefined macros... "); + Default d = new Default(); + test(d.x == 10); + test(d.y == 10); + + NoDefault nd = new NoDefault(); + test(nd.x != 10); + test(nd.y != 10); + + JavaOnly c = new JavaOnly(); + test(c.lang.equals("java")); + test(c.version == Ice.Util.intVersion()); + System.out.println("ok"); + } + catch(Exception ex) + { + ex.printStackTrace(); + status = 1; + } + System.gc(); + System.exit(status); + } +} diff --git a/java/test/src/main/java/test/Slice/macros/Test.ice b/java/test/src/main/java/test/Slice/macros/Test.ice new file mode 100644 index 00000000000..2a791540afa --- /dev/null +++ b/java/test/src/main/java/test/Slice/macros/Test.ice @@ -0,0 +1,58 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Slice.macros"]] + +// +// This macro sets the default value only when compiling with slice2java. +// +#ifdef __SLICE2JAVA__ +# define DEFAULT(X) = X +#else +# define DEFAULT(X) /**/ +#endif + +// +// This macro sets the default value only when not compiling with slice2java. +// +#ifndef __SLICE2JAVA__ +# define NODEFAULT(X) = X +#else +# define NODEFAULT(X) /**/ +#endif + +module Test +{ + +class Default +{ + int x DEFAULT(10); + int y DEFAULT(10); +}; + +class NoDefault +{ + int x NODEFAULT(10); + int y NODEFAULT(10); +}; + +// +// This class is only defined when compiling with slice2java. +// +#ifdef __SLICE2JAVA__ +class JavaOnly +{ + string lang DEFAULT("java"); + int version DEFAULT(ICE_VERSION); +}; +#endif + +}; diff --git a/java/test/src/main/java/test/Slice/macros/run.py b/java/test/src/main/java/test/Slice/macros/run.py new file mode 100755 index 00000000000..4b62a2b9c3a --- /dev/null +++ b/java/test/src/main/java/test/Slice/macros/run.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +sys.stdout.write("starting client... ") +sys.stdout.flush() +clientProc = TestUtil.startClient("test.Slice.macros.Client",startReader=False) +print("ok") +clientProc.startReader() +clientProc.waitTestSuccess() diff --git a/java/test/src/main/java/test/Slice/structure/Client.java b/java/test/src/main/java/test/Slice/structure/Client.java new file mode 100644 index 00000000000..74f2239ae2e --- /dev/null +++ b/java/test/src/main/java/test/Slice/structure/Client.java @@ -0,0 +1,315 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Slice.structure; + +import test.Slice.structure.Test.S1; +import test.Slice.structure.Test.S2; +import test.Slice.structure.Test.C; +import java.util.ArrayList; +import java.util.Map; +import java.util.HashMap; + +public class Client +{ + private static void test(boolean b) + { + if(!b) + { + throw new RuntimeException(); + } + } + + private static void allTests(Ice.Communicator communicator) + { + System.out.print("testing equals() for Slice structures... "); + System.out.flush(); + + // + // Define some default values. + // + C def_cls = new C(5); + S1 def_s = new S1("name"); + String[] def_ss = new String[]{ "one", "two", "three" }; + ArrayList<Integer> def_il = new ArrayList<Integer>(); + def_il.add(1); + def_il.add(2); + def_il.add(3); + Map<String, String> def_sd = new HashMap<String, String>(); + def_sd.put("abc", "def"); + Ice.ObjectPrx def_prx = communicator.stringToProxy("test"); + S2 def_s2 = new S2(true, (byte)98, (short)99, 100, 101, (float)1.0, 2.0, "string", def_ss, def_il, def_sd, + def_s, def_cls, def_prx); + + // + // Compare default-constructed structures. + // + { + test(new S2().equals(new S2())); + } + + // + // Change one primitive member at a time. + // + { + S2 v; + + v = (S2)def_s2.clone(); + test(v.equals(def_s2)); + + v = (S2)def_s2.clone(); + v.bo = false; + test(!v.equals(def_s2)); + + v = (S2)def_s2.clone(); + v.by--; + test(!v.equals(def_s2)); + + v = (S2)def_s2.clone(); + v.sh--; + test(!v.equals(def_s2)); + + v = (S2)def_s2.clone(); + v.i--; + test(!v.equals(def_s2)); + + v = (S2)def_s2.clone(); + v.l--; + test(!v.equals(def_s2)); + + v = (S2)def_s2.clone(); + v.f--; + test(!v.equals(def_s2)); + + v = (S2)def_s2.clone(); + v.d--; + test(!v.equals(def_s2)); + + v = (S2)def_s2.clone(); + v.str = ""; + test(!v.equals(def_s2)); + } + + // + // String member + // + { + S2 v1, v2; + + v1 = (S2)def_s2.clone(); + v1.str = new String(def_s2.str); + test(v1.equals(def_s2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v1.str = null; + test(!v1.equals(v2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v2.str = null; + test(!v1.equals(v2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v1.str = null; + v2.str = null; + test(v1.equals(v2)); + } + + // + // Sequence member + // + { + S2 v1, v2; + + v1 = (S2)def_s2.clone(); + v1.ss = def_s2.ss.clone(); + test(v1.equals(def_s2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v1.ss = null; + test(!v1.equals(v2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v2.ss = null; + test(!v1.equals(v2)); + } + + // + // Custom sequence member + // + { + S2 v1, v2; + + v1 = (S2)def_s2.clone(); + v1.il = new ArrayList<Integer>(def_s2.il); + test(v1.equals(def_s2)); + + v1 = (S2)def_s2.clone(); + v1.il = new ArrayList<Integer>(); + test(!v1.equals(def_s2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v1.il = null; + test(!v1.equals(v2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v2.il = null; + test(!v1.equals(v2)); + } + + // + // Dictionary member + // + { + S2 v1, v2; + + v1 = (S2)def_s2.clone(); + v1.sd = new HashMap<String, String>(def_s2.sd); + test(v1.equals(def_s2)); + + v1 = (S2)def_s2.clone(); + v1.sd = new HashMap<String, String>(); + test(!v1.equals(def_s2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v1.sd = null; + test(!v1.equals(v2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v2.sd = null; + test(!v1.equals(v2)); + } + + // + // Struct member + // + { + S2 v1, v2; + + v1 = (S2)def_s2.clone(); + v1.s = (S1)def_s2.s.clone(); + test(v1.equals(def_s2)); + + v1 = (S2)def_s2.clone(); + v1.s = new S1("name"); + test(v1.equals(def_s2)); + + v1 = (S2)def_s2.clone(); + v1.s = new S1("noname"); + test(!v1.equals(def_s2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v1.s = null; + test(!v1.equals(v2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v2.s = null; + test(!v1.equals(v2)); + } + + // + // Class member + // + { + S2 v1, v2; + + v1 = (S2)def_s2.clone(); + v1.cls = (C)def_s2.cls.clone(); + test(!v1.equals(def_s2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v1.cls = null; + test(!v1.equals(v2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v2.cls = null; + test(!v1.equals(v2)); + } + + // + // Proxy member + // + { + S2 v1, v2; + + v1 = (S2)def_s2.clone(); + v1.prx = communicator.stringToProxy("test"); + test(v1.equals(def_s2)); + + v1 = (S2)def_s2.clone(); + v1.prx = communicator.stringToProxy("test2"); + test(!v1.equals(def_s2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v1.prx = null; + test(!v1.equals(v2)); + + v1 = (S2)def_s2.clone(); + v2 = (S2)def_s2.clone(); + v2.prx = null; + test(!v1.equals(v2)); + } + + System.out.println("ok"); + } + + private static int run(String[] args, Ice.Communicator communicator) + { + allTests(communicator); + + return 0; + } + + public static void main(String[] args) + { + int status = 0; + Ice.Communicator communicator = null; + + try + { + Ice.StringSeqHolder argsH = new Ice.StringSeqHolder(args); + communicator = Ice.Util.initialize(argsH); + status = run(argsH.value, 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/src/main/java/test/Slice/structure/Test.ice b/java/test/src/main/java/test/Slice/structure/Test.ice new file mode 100644 index 00000000000..5cda671b732 --- /dev/null +++ b/java/test/src/main/java/test/Slice/structure/Test.ice @@ -0,0 +1,48 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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. +// +// ********************************************************************** + +#pragma once + +[["java:package:test.Slice.structure"]] +module Test +{ + +sequence<string> StringSeq; +["java:type:java.util.ArrayList<Integer>"] sequence<int> IntList; +dictionary<string, string> StringDict; + +class C +{ + int i; +}; + +struct S1 +{ + string name; +}; + +struct S2 +{ + bool bo; + byte by; + short sh; + int i; + long l; + float f; + double d; + string str; + StringSeq ss; + IntList il; + StringDict sd; + S1 s; + C cls; + Object* prx; +}; + +}; diff --git a/java/test/src/main/java/test/Slice/structure/run.py b/java/test/src/main/java/test/Slice/structure/run.py new file mode 100755 index 00000000000..c48b8cf432c --- /dev/null +++ b/java/test/src/main/java/test/Slice/structure/run.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# ********************************************************************** +# +# Copyright (c) 2003-2014 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 RuntimeError("can't find toplevel directory!") +sys.path.append(os.path.join(path[0], "scripts")) +import TestUtil + +sys.stdout.write("starting client... ") +sys.stdout.flush() +clientProc = TestUtil.startClient("test.Slice.structure.Client",startReader=False) +print("ok") +clientProc.startReader() +clientProc.waitTestSuccess() diff --git a/java/test/src/main/java/test/Util/Application.java b/java/test/src/main/java/test/Util/Application.java new file mode 100644 index 00000000000..07c7d28b54e --- /dev/null +++ b/java/test/src/main/java/test/Util/Application.java @@ -0,0 +1,244 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2014 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.Util; + +import Ice.Communicator; +import Ice.InitializationData; +import Ice.LocalException; +import Ice.LoggerI; +import Ice.StringSeqHolder; +import Ice.Util; + +public abstract class Application +{ + public final int WAIT = 2; + + public interface ServerReadyListener + { + void serverReady(); + } + + public interface CommunicatorListener + { + void communicatorInitialized(Communicator c); + } + + public + Application() + { + } + + // + // This main() must be called by the global main(). main() + // initializes the Communicator, calls run(), and destroys + // the Communicator upon return from run(). It thereby handles + // all exceptions properly, i.e., error messages are printed + // if exceptions propagate to main(), and the Communicator is + // always destroyed, regardless of exceptions. + // + public final int + main(String appName, String[] args) + { + Ice.StringSeqHolder argsH = new Ice.StringSeqHolder(args); + Ice.InitializationData initData = getInitData(argsH); + return main(appName, argsH.value, initData); + } + + public final int + main(String appName, String[] args, InitializationData initializationData) + { + java.io.PrintWriter writer = getWriter(); + if(_communicator != null) + { + writer.println(appName + ": only one instance of the Application class can be used"); + return 1; + } + + _testName = appName; + + // + // We parse the properties here to extract Ice.ProgramName. + // + StringSeqHolder argHolder = new StringSeqHolder(args); + if(initializationData == null) + { + initializationData = getInitData(argHolder); + } + + InitializationData initData; + if(initializationData != null) + { + initData = (InitializationData)initializationData.clone(); + } + else + { + initData = new InitializationData(); + } + initData.properties = Util.createProperties(argHolder, initData.properties); + + // + // If the process logger is the default logger, we replace it with a + // a logger that uses the program name as the prefix. + // + if(Util.getProcessLogger() instanceof LoggerI) + { + Util.setProcessLogger(new LoggerI(initData.properties.getProperty("Ice.ProgramName"), "")); + } + + int status = 0; + + try + { + _communicator = Util.initialize(argHolder, initData); + if(_communicatorListener != null) + { + _communicatorListener.communicatorInitialized(_communicator); + } + status = run(argHolder.value); + if(status == WAIT) + { + if(_cb != null) + { + _cb.serverReady(); + } + _communicator.waitForShutdown(); + status = 0; + } + } + catch(LocalException ex) + { + writer.println(_testName + ": " + ex); + ex.printStackTrace(); + status = 1; + } + catch(java.lang.Exception ex) + { + writer.println(_testName + ": unknown exception"); + ex.printStackTrace(writer); + status = 1; + } + catch(java.lang.Error err) + { + // + // We catch Error to avoid hangs in some non-fatal situations + // + writer.println(_testName + ": Java error"); + err.printStackTrace(writer); + status = 1; + } + writer.flush(); + + if(_communicator != null) + { + try + { + _communicator.destroy(); + } + catch(LocalException ex) + { + writer.println(_testName + ": " + ex); + ex.printStackTrace(writer); + status = 1; + } + catch(java.lang.Exception ex) + { + writer.println(_testName + ": unknown exception"); + ex.printStackTrace(writer); + status = 1; + } + _communicator = null; + } + writer.flush(); + + return status; + } + + public void stop() + { + if(_communicator != null) + { + _communicator.shutdown(); + } + } + + // + // Initialize a new communicator. + // + public Ice.Communicator initialize(InitializationData initData) + { + Ice.Communicator communicator = Util.initialize(initData); + if(_communicatorListener != null) + { + _communicatorListener.communicatorInitialized(communicator); + } + return communicator; + } + + public abstract int run(String[] args); + + // + // Hook to override the initialization data. This hook is + // necessary because some properties must be set prior to + // communicator initialization. + // + protected Ice.InitializationData getInitData(Ice.StringSeqHolder argsH) + { + return null; + } + + public java.io.PrintWriter getWriter() + { + return _printWriter; + } + + public void setWriter(java.io.Writer writer) + { + _printWriter = new java.io.PrintWriter(writer); + } + + public void setServerReadyListener(ServerReadyListener cb) + { + _cb = cb; + } + + public void setCommunicatorListener(CommunicatorListener listener) + { + _communicatorListener = listener; + } + + public void serverReady() + { + if(_cb != null) + { + _cb.serverReady(); + } + } + + // + // Return the application name, i.e., argv[0]. + // + public String + appName() + { + return _testName; + } + + public Communicator + communicator() + { + return _communicator; + } + + private String _testName; + private Communicator _communicator; + private java.io.PrintWriter _printWriter = new java.io.PrintWriter(new java.io.OutputStreamWriter(System.out)); + private ServerReadyListener _cb = null; + private CommunicatorListener _communicatorListener = null; +} |