From 93ca701f2677600a62ad1733bb2dea8c22735742 Mon Sep 17 00:00:00 2001 From: Lyor Goldstein Date: Tue, 15 Dec 2015 09:43:04 +0200 Subject: [PATCH] Fix return type of Native#loadLibrary to match unconstrained generic type --- CHANGES.md | 1 + .../sun/jna/platform/mac/MacFileUtils.java | 2 +- .../src/com/sun/jna/platform/unix/X11.java | 10 +- .../src/com/sun/jna/platform/win32/Msi.java | 31 ++- .../com/sun/jna/platform/win32/SetupApi.java | 16 +- .../com/sun/jna/platform/win32/Version.java | 3 +- .../jna/platform/win32/VersionUtilTest.java | 23 +- src/com/sun/jna/Native.java | 15 +- test/com/sun/jna/AnnotatedLibraryTest.java | 3 +- test/com/sun/jna/ArgumentsMarshalTest.java | 139 ++++++------ .../sun/jna/BufferArgumentsMarshalTest.java | 32 ++- .../com/sun/jna/ByReferenceArgumentsTest.java | 12 +- test/com/sun/jna/CallbacksTest.java | 198 ++++++++++++------ .../sun/jna/DirectArgumentsMarshalTest.java | 77 +++++-- test/com/sun/jna/JNALoadTest.java | 41 ++-- test/com/sun/jna/LastErrorTest.java | 19 +- test/com/sun/jna/LibraryLoadTest.java | 34 +-- test/com/sun/jna/NativeLibraryTest.java | 56 ++--- test/com/sun/jna/NativeTest.java | 115 ++++++---- test/com/sun/jna/PerformanceTest.java | 24 +-- test/com/sun/jna/ReturnTypesTest.java | 83 ++++---- test/com/sun/jna/StructureByValueTest.java | 10 +- test/com/sun/jna/StructureTest.java | 114 +++++++++- test/com/sun/jna/TypeMapperTest.java | 27 +-- test/com/sun/jna/VarArgsTest.java | 23 +- test/com/sun/jna/WebStartTest.java | 6 +- test/com/sun/jna/win32/W32StdCallTest.java | 37 ++-- test/com/sun/jna/wince/CoreDLLTest.java | 5 +- 28 files changed, 719 insertions(+), 437 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index bca64c6c90..3fdbeb87e3 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -33,6 +33,7 @@ Bug Fixes * [#549](https://github.com/java-native-access/jna/pull/549): Fixed bug in types derived from XID - [@twall](https://github.com/twall). * [#536](https://github.com/java-native-access/jna/pull/536): Fixed bug in determining the Library and options associated with types defined outside of a Library - [@twall](https://github.com/twall). * [#531](https://github.com/java-native-access/jna/pull/531): Ensure direct-mapped callbacks use the right calling convention - [@twall](https://github.com/twall). +* [#566](https://github.com/java-native-access/jna/pull/566): Fix return type of Native#loadLibrary to match unconstrained generic [@lgoldstein](https://github.com/lgoldstein) Release 4.2.1 ============= diff --git a/contrib/platform/src/com/sun/jna/platform/mac/MacFileUtils.java b/contrib/platform/src/com/sun/jna/platform/mac/MacFileUtils.java index 3dc368af7e..c569713b39 100644 --- a/contrib/platform/src/com/sun/jna/platform/mac/MacFileUtils.java +++ b/contrib/platform/src/com/sun/jna/platform/mac/MacFileUtils.java @@ -32,7 +32,7 @@ public class MacFileUtils extends FileUtils { public interface FileManager extends Library { - public FileManager INSTANCE = (FileManager)Native.loadLibrary("CoreServices", FileManager.class); + FileManager INSTANCE = Native.loadLibrary("CoreServices", FileManager.class); int kFSFileOperationDefaultOptions = 0; int kFSFileOperationsOverwrite = 0x01; diff --git a/contrib/platform/src/com/sun/jna/platform/unix/X11.java b/contrib/platform/src/com/sun/jna/platform/unix/X11.java index 3856302dd2..b1596a9219 100644 --- a/contrib/platform/src/com/sun/jna/platform/unix/X11.java +++ b/contrib/platform/src/com/sun/jna/platform/unix/X11.java @@ -278,7 +278,7 @@ class XImage extends PointerType { } /** Definition (incomplete) of the Xext library. */ interface Xext extends Library { - Xext INSTANCE = (Xext)Native.loadLibrary("Xext", Xext.class); + Xext INSTANCE = Native.loadLibrary("Xext", Xext.class); // Shape Kinds int ShapeBounding = 0; int ShapeClip = 1; @@ -296,7 +296,7 @@ void XShapeCombineMask(Display display, Window window, int dest_kind, /** Definition (incomplete) of the Xrender library. */ interface Xrender extends Library { - Xrender INSTANCE = (Xrender)Native.loadLibrary("Xrender", Xrender.class); + Xrender INSTANCE = Native.loadLibrary("Xrender", Xrender.class); class XRenderDirectFormat extends Structure { public short red, redMask; public short green, greenMask; @@ -338,7 +338,7 @@ protected List getFieldOrder() { /** Definition of the Xevie library. */ interface Xevie extends Library { /** Instance of Xevie. Note: This extension has been removed from xorg/xserver on Oct 22, 2008 because it is broken and maintainerless. */ - Xevie INSTANCE = (Xevie)Native.loadLibrary("Xevie", Xevie.class); + Xevie INSTANCE = Native.loadLibrary("Xevie", Xevie.class); int XEVIE_UNMODIFIED = 0; int XEVIE_MODIFIED = 1; // Bool XevieQueryVersion (Display* display, int* major_version, int* minor_version); @@ -355,7 +355,7 @@ interface Xevie extends Library { /** Definition of the XTest library. */ interface XTest extends Library { - XTest INSTANCE = (XTest)Native.loadLibrary("Xtst", XTest.class);///usr/lib/libxcb-xtest.so.0 + XTest INSTANCE = Native.loadLibrary("Xtst", XTest.class);///usr/lib/libxcb-xtest.so.0 boolean XTestQueryExtension(Display display, IntByReference event_basep, IntByReference error_basep, IntByReference majorp, IntByReference minorp); boolean XTestCompareCursorWithWindow(Display display, Window window, Cursor cursor); boolean XTestCompareCurrentCursorWithWindow(Display display, Window window); @@ -393,7 +393,7 @@ protected List getFieldOrder() { } } - X11 INSTANCE = (X11)Native.loadLibrary("X11", X11.class); + X11 INSTANCE = Native.loadLibrary("X11", X11.class); /* typedef struct { diff --git a/contrib/platform/src/com/sun/jna/platform/win32/Msi.java b/contrib/platform/src/com/sun/jna/platform/win32/Msi.java index 7fc72b2937..327fa81582 100644 --- a/contrib/platform/src/com/sun/jna/platform/win32/Msi.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/Msi.java @@ -20,78 +20,77 @@ */ public interface Msi extends StdCallLibrary { - Msi INSTANCE = (Msi) - Native.loadLibrary("msi", Msi.class, W32APIOptions.DEFAULT_OPTIONS); + Msi INSTANCE = Native.loadLibrary("msi", Msi.class, W32APIOptions.DEFAULT_OPTIONS); /** * The component being requested is disabled on the computer. */ - static int INSTALLSTATE_NOTUSED = -7; + int INSTALLSTATE_NOTUSED = -7; /** * The configuration data is corrupt. */ - static int INSTALLSTATE_BADCONFIG = -6; + int INSTALLSTATE_BADCONFIG = -6; /** * The installation is suspended or in progress. */ - static int INSTALLSTATE_INCOMPLETE = -5; + int INSTALLSTATE_INCOMPLETE = -5; /** * The feature must run from the source, and the source is unavailable. */ - static int INSTALLSTATE_SOURCEABSENT = -4; + int INSTALLSTATE_SOURCEABSENT = -4; /** * The return buffer is full. */ - static int INSTALLSTATE_MOREDATA = -3; + int INSTALLSTATE_MOREDATA = -3; /** * An invalid parameter was passed to the function. */ - static int INSTALLSTATE_INVALIDARG = -2; + int INSTALLSTATE_INVALIDARG = -2; /** * An unrecognized product or feature was specified. */ - static int INSTALLSTATE_UNKNOWN = -1; + int INSTALLSTATE_UNKNOWN = -1; /** * The feature is broken. */ - static int INSTALLSTATE_BROKEN = 0; + int INSTALLSTATE_BROKEN = 0; /** * The advertised feature. */ - static int INSTALLSTATE_ADVERTISED = 1; + int INSTALLSTATE_ADVERTISED = 1; /** * The component is being removed. */ - static int INSTALLSTATE_REMOVED = 1; + int INSTALLSTATE_REMOVED = 1; /** * The feature was uninstalled. */ - static int INSTALLSTATE_ABSENT = 2; + int INSTALLSTATE_ABSENT = 2; /** * The feature was installed on the local drive. */ - static int INSTALLSTATE_LOCAL = 3; + int INSTALLSTATE_LOCAL = 3; /** * The feature must run from the source, CD-ROM, or network. */ - static int INSTALLSTATE_SOURCE = 4; + int INSTALLSTATE_SOURCE = 4; /** * The feature is installed in the default location: local or source. */ - static int INSTALLSTATE_DEFAULT = 5; + int INSTALLSTATE_DEFAULT = 5; /** * The MsiGetComponentPath function returns the full path to an installed component. If the key path for the diff --git a/contrib/platform/src/com/sun/jna/platform/win32/SetupApi.java b/contrib/platform/src/com/sun/jna/platform/win32/SetupApi.java index fc2abb1866..8ffd701bb0 100644 --- a/contrib/platform/src/com/sun/jna/platform/win32/SetupApi.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/SetupApi.java @@ -29,8 +29,7 @@ */ public interface SetupApi extends StdCallLibrary { - SetupApi INSTANCE = (SetupApi) - Native.loadLibrary("setupapi", SetupApi.class, W32APIOptions.DEFAULT_OPTIONS); + SetupApi INSTANCE = Native.loadLibrary("setupapi", SetupApi.class, W32APIOptions.DEFAULT_OPTIONS); /** * The GUID_DEVINTERFACE_DISK device interface class is defined for hard disk storage devices. @@ -82,7 +81,6 @@ public interface SetupApi extends StdCallLibrary { * Removable. */ int CM_DEVCAP_REMOVABLE = 0x00000004; - /** make change in all hardware profiles */ int DICS_FLAG_GLOBAL = 0x00000001; @@ -94,23 +92,22 @@ public interface SetupApi extends StdCallLibrary { /** * Open/Create/Delete device key. * - * @see #SetupDiOpenDevRegKey + * @see #SetupDiOpenDevRegKey */ - int DIREG_DEV = 0x00000001; + /** * Open/Create/Delete driver key * - * @see #SetupDiOpenDevRegKey + * @see #SetupDiOpenDevRegKey */ - int DIREG_DRV = 0x00000002; + /** * Delete both driver and Device key * - * @see #SetupDiOpenDevRegKey + * @see #SetupDiOpenDevRegKey */ - int DIREG_BOTH = 0x00000004; /** @@ -124,7 +121,6 @@ public interface SetupApi extends StdCallLibrary { */ int SPDRP_DEVICEDESC = 0x00000000; - /** * The SetupDiGetClassDevs function returns a handle to a device information set that contains requested device * information elements for a local computer. diff --git a/contrib/platform/src/com/sun/jna/platform/win32/Version.java b/contrib/platform/src/com/sun/jna/platform/win32/Version.java index c5799fc561..a13f2c877b 100644 --- a/contrib/platform/src/com/sun/jna/platform/win32/Version.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/Version.java @@ -22,8 +22,7 @@ */ public interface Version extends StdCallLibrary { - Version INSTANCE = (Version) - Native.loadLibrary("version", Version.class, W32APIOptions.DEFAULT_OPTIONS); + Version INSTANCE = Native.loadLibrary("version", Version.class, W32APIOptions.DEFAULT_OPTIONS); /** * Determines whether the operating system can retrieve version information for a specified file. If version diff --git a/contrib/platform/test/com/sun/jna/platform/win32/VersionUtilTest.java b/contrib/platform/test/com/sun/jna/platform/win32/VersionUtilTest.java index eb8b397d8c..e59b308e60 100644 --- a/contrib/platform/test/com/sun/jna/platform/win32/VersionUtilTest.java +++ b/contrib/platform/test/com/sun/jna/platform/win32/VersionUtilTest.java @@ -23,21 +23,20 @@ public static void main(String[] args) { } public void testGetFileVersionNumbers() { - String testFileName = "regedit.exe"; - File file = new File(System.getenv("SystemRoot"), testFileName); - assertTrue("Test file with version info in it should exist.", file.exists()); + File file = new File(System.getenv("SystemRoot"), "regedit.exe"); + assertTrue("Test file with version info in it should exist: " + file, file.exists()); VS_FIXEDFILEINFO version = VersionUtil.getFileVersionInfo(file.getAbsolutePath()); assertNotNull("Version info should have been returned.", version); - assertTrue("The major file version number should be greater than 0 when pulling version from \"" + testFileName + "\"", version.getFileVersionMajor() > 0); - assertTrue("The minor file version number should be greater than or equal to 0 when pulling version from \"" + testFileName + "\"", version.getFileVersionMinor() >= 0); - assertTrue("The revision file version number should be greater than or equal to 0 when pulling version from \"" + testFileName + "\"", version.getFileVersionRevision() >= 0); - assertTrue("The build file version number should be greater than or equal to 0 when pulling version from \"" + testFileName + "\"", version.getFileVersionBuild() > 0); - - assertTrue("The major product version number should be greater than 0 when pulling version from \"" + testFileName + "\"", version.getProductVersionMajor() > 0); - assertTrue("The minor product version number should be greater than or equal to 0 when pulling version from \"" + testFileName + "\"", version.getProductVersionMinor() >= 0); - assertTrue("The revision product version number should be greater than or equal to 0 when pulling version from \"" + testFileName + "\"", version.getProductVersionRevision() >= 0); - assertTrue("The build product version number should be greater than or equal to 0 when pulling version from \"" + testFileName + "\"", version.getProductVersionBuild() > 0); + assertTrue("The major file version number should be greater than 0 when pulling version from \"" + file + "\"", version.getFileVersionMajor() > 0); + assertTrue("The minor file version number should be greater than or equal to 0 when pulling version from \"" + file + "\"", version.getFileVersionMinor() >= 0); + assertTrue("The revision file version number should be greater than or equal to 0 when pulling version from \"" + file + "\"", version.getFileVersionRevision() >= 0); + assertTrue("The build file version number should be greater than or equal to 0 when pulling version from \"" + file + "\"", version.getFileVersionBuild() > 0); + + assertTrue("The major product version number should be greater than 0 when pulling version from \"" + file + "\"", version.getProductVersionMajor() > 0); + assertTrue("The minor product version number should be greater than or equal to 0 when pulling version from \"" + file + "\"", version.getProductVersionMinor() >= 0); + assertTrue("The revision product version number should be greater than or equal to 0 when pulling version from \"" + file + "\"", version.getProductVersionRevision() >= 0); + assertTrue("The build product version number should be greater than or equal to 0 when pulling version from \"" + file + "\"", version.getProductVersionBuild() > 0); } } diff --git a/src/com/sun/jna/Native.java b/src/com/sun/jna/Native.java index 08a13411b4..25f820a7ee 100644 --- a/src/com/sun/jna/Native.java +++ b/src/com/sun/jna/Native.java @@ -446,7 +446,7 @@ public static List toStringList(char[] buf, int offset, int len) { * @throws UnsatisfiedLinkError if the library cannot be found or * dependent libraries are missing. */ - public static T loadLibrary(Class interfaceClass) { + public static T loadLibrary(Class interfaceClass) { return loadLibrary(null, interfaceClass); } @@ -465,7 +465,7 @@ public static T loadLibrary(Class interfaceClass) { * dependent libraries are missing. * @see #loadLibrary(String, Class, Map) */ - public static T loadLibrary(Class interfaceClass, Map options) { + public static T loadLibrary(Class interfaceClass, Map options) { return loadLibrary(null, interfaceClass, options); } @@ -483,7 +483,7 @@ public static T loadLibrary(Class interfaceClass, Map opt * dependent libraries are missing. * @see #loadLibrary(String, Class, Map) */ - public static T loadLibrary(String name, Class interfaceClass) { + public static T loadLibrary(String name, Class interfaceClass) { return loadLibrary(name, interfaceClass, Collections.emptyMap()); } @@ -503,7 +503,12 @@ public static T loadLibrary(String name, Class interfaceC * @throws UnsatisfiedLinkError if the library cannot be found or * dependent libraries are missing. */ - public static T loadLibrary(String name, Class interfaceClass, Map options) { + public static T loadLibrary(String name, Class interfaceClass, Map options) { + if (!Library.class.isAssignableFrom(interfaceClass)) { + throw new IllegalArgumentException("Interface (" + interfaceClass.getSimpleName() + ")" + + " of library=" + name + " does not extend " + Library.class.getSimpleName()); + } + Library.Handler handler = new Library.Handler(name, interfaceClass, options); ClassLoader loader = interfaceClass.getClassLoader(); Object proxy = Proxy.newProxyInstance(loader, new Class[] {interfaceClass}, handler); @@ -1396,7 +1401,7 @@ public static boolean registered(Class cls) { /** Unregister the native methods for the given class. */ private static native void unregister(Class cls, long[] handles); - private static String getSignature(Class cls) { + static String getSignature(Class cls) { if (cls.isArray()) { return "[" + getSignature(cls.getComponentType()); } diff --git a/test/com/sun/jna/AnnotatedLibraryTest.java b/test/com/sun/jna/AnnotatedLibraryTest.java index 99067ef4d2..f3f0ff3615 100644 --- a/test/com/sun/jna/AnnotatedLibraryTest.java +++ b/test/com/sun/jna/AnnotatedLibraryTest.java @@ -68,8 +68,7 @@ public Class nativeType() { }); options.put(Library.OPTION_TYPE_MAPPER, mapper); - AnnotationTestLibrary lib = (AnnotationTestLibrary) - Native.loadLibrary("testlib", AnnotationTestLibrary.class, options); + AnnotationTestLibrary lib = Native.loadLibrary("testlib", AnnotationTestLibrary.class, options); assertEquals("Failed to convert integer return to boolean TRUE", true, lib.returnInt32Argument(true)); assertTrue("Failed to get annotation from ParameterContext", hasAnnotation[0]); diff --git a/test/com/sun/jna/ArgumentsMarshalTest.java b/test/com/sun/jna/ArgumentsMarshalTest.java index a6431594f6..cf16174234 100644 --- a/test/com/sun/jna/ArgumentsMarshalTest.java +++ b/test/com/sun/jna/ArgumentsMarshalTest.java @@ -8,7 +8,7 @@ * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna; @@ -29,20 +29,21 @@ public class ArgumentsMarshalTest extends TestCase { private static final String UNICODE = "[\0444]"; public static interface TestLibrary extends Library { - + class CheckFieldAlignment extends Structure { - public static class ByValue extends CheckFieldAlignment + public static class ByValue extends CheckFieldAlignment implements Structure.ByValue { } public static class ByReference extends CheckFieldAlignment implements Structure.ByReference { } - + public byte int8Field; public short int16Field; public int int32Field; public long int64Field; public float floatField; public double doubleField; - + + @Override public List getFieldOrder() { return Arrays.asList(new String[] { "int8Field", "int16Field", "int32Field", "int64Field", "floatField", "doubleField" }); } @@ -89,7 +90,7 @@ public TestPointerType() { } int testStructureByReferenceArrayInitialization(CheckFieldAlignment.ByReference[] p, int len); void modifyStructureArray(CheckFieldAlignment[] p, int length); void modifyStructureByReferenceArray(CheckFieldAlignment.ByReference[] p, int length); - + int fillInt8Buffer(byte[] buf, int len, byte value); int fillInt16Buffer(short[] buf, int len, short value); int fillInt32Buffer(int[] buf, int len, int value); @@ -97,12 +98,13 @@ public TestPointerType() { } int fillFloatBuffer(float[] buf, int len, float value); int fillDoubleBuffer(double[] buf, int len, double value); - // Nonexistent functions + // Nonexistent functions boolean returnBooleanArgument(Object arg); // Structure class MinTestStructure extends Structure { public int field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -112,6 +114,7 @@ protected List getFieldOrder() { class VariableSizedStructure extends Structure { public int length; public byte[] buffer; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "length", "buffer" }); } @@ -127,6 +130,7 @@ public static interface TestCallback extends Callback { int callback(int arg1, int arg2); } public TestCallback cb; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "cb" }); } @@ -135,14 +139,16 @@ protected List getFieldOrder() { } TestLibrary lib; + @Override protected void setUp() { - lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + lib = Native.loadLibrary("testlib", TestLibrary.class); } - + + @Override protected void tearDown() { lib = null; } - + public void testJavaObjectArgument() { Object o = this; try { @@ -159,24 +165,24 @@ public void testJavaObjectArgument() { } public void testBooleanArgument() { - assertTrue("True argument should be returned", + assertTrue("True argument should be returned", lib.returnBooleanArgument(true)); - assertFalse("False argument should be returned", + assertFalse("False argument should be returned", lib.returnBooleanArgument(false)); } public void testInt8Argument() { byte b = 0; - assertEquals("Wrong value returned", + assertEquals("Wrong value returned", b, lib.returnInt8Argument(b)); b = 127; - assertEquals("Wrong value returned", + assertEquals("Wrong value returned", b, lib.returnInt8Argument(b)); b = -128; - assertEquals("Wrong value returned", + assertEquals("Wrong value returned", b, lib.returnInt8Argument(b)); } - + public void testWideCharArgument() { char c = 0; assertEquals("Wrong value returned", @@ -191,64 +197,64 @@ public void testWideCharArgument() { public void testInt16Argument() { short v = 0; - assertEquals("Wrong value returned", + assertEquals("Wrong value returned", v, lib.returnInt16Argument(v)); v = 32767; - assertEquals("Wrong value returned", + assertEquals("Wrong value returned", v, lib.returnInt16Argument(v)); v = -32768; - assertEquals("Wrong value returned", + assertEquals("Wrong value returned", v, lib.returnInt16Argument(v)); } public void testIntArgument() { int value = 0; - assertEquals("Should return 32-bit argument", + assertEquals("Should return 32-bit argument", value, lib.returnInt32Argument(value)); value = 1; - assertEquals("Should return 32-bit argument", + assertEquals("Should return 32-bit argument", value, lib.returnInt32Argument(value)); value = 0x7FFFFFFF; - assertEquals("Should return 32-bit argument", + assertEquals("Should return 32-bit argument", value, lib.returnInt32Argument(value)); value = 0x80000000; - assertEquals("Should return 32-bit argument", + assertEquals("Should return 32-bit argument", value, lib.returnInt32Argument(value)); } public void testLongArgument() { long value = 0L; - assertEquals("Should return 64-bit argument", + assertEquals("Should return 64-bit argument", value, lib.returnInt64Argument(value)); value = 1L; - assertEquals("Should return 64-bit argument", + assertEquals("Should return 64-bit argument", value, lib.returnInt64Argument(value)); value = 0x7FFFFFFFL; - assertEquals("Should return 64-bit argument", + assertEquals("Should return 64-bit argument", value, lib.returnInt64Argument(value)); value = 0x80000000L; - assertEquals("Should return 64-bit argument", + assertEquals("Should return 64-bit argument", value, lib.returnInt64Argument(value)); value = 0x7FFFFFFF00000000L; - assertEquals("Should return 64-bit argument", + assertEquals("Should return 64-bit argument", value, lib.returnInt64Argument(value)); value = 0x8000000000000000L; - assertEquals("Should return 64-bit argument", + assertEquals("Should return 64-bit argument", value, lib.returnInt64Argument(value)); } public void testNativeLongArgument() { NativeLong value = new NativeLong(0); - assertEquals("Should return 0", + assertEquals("Should return 0", value, lib.returnLongArgument(value)); value = new NativeLong(1); - assertEquals("Should return 1", + assertEquals("Should return 1", value, lib.returnLongArgument(value)); value = new NativeLong(0x7FFFFFFF); - assertEquals("Should return 0x7FFFFFFF", + assertEquals("Should return 0x7FFFFFFF", value, lib.returnLongArgument(value)); value = new NativeLong(0x80000000); - assertEquals("Should return 0x80000000", + assertEquals("Should return 0x80000000", value, lib.returnLongArgument(value)); } @@ -272,19 +278,21 @@ public Custom() { } public Custom(int value) { this.value = value; } + @Override public Object fromNative(Object nativeValue, FromNativeContext context) { return new Custom(((Integer)nativeValue).intValue()); } + @Override public Class nativeType() { return Integer.class; } + @Override public Object toNative() { return new Integer(value); } } protected NativeMappedLibrary loadNativeMappedLibrary() { - return (NativeMappedLibrary) - Native.loadLibrary("testlib", NativeMappedLibrary.class); + return Native.loadLibrary("testlib", NativeMappedLibrary.class); } public void testNativeMappedArgument() { NativeMappedLibrary lib = loadNativeMappedLibrary(); @@ -302,13 +310,13 @@ public void testNativeMappedArgument() { assertEquals("Argument not mapped", MAGIC64, lib.returnInt64Argument(size)); } } - + public void testPointerArgumentReturn() { assertEquals("Expect null pointer", null, lib.returnPointerArgument(null)); Structure s = new TestLibrary.CheckFieldAlignment(); assertEquals("Expect structure pointer", - s.getPointer(), + s.getPointer(), lib.returnPointerArgument(s.getPointer())); } @@ -323,9 +331,9 @@ public void testWStringArgumentReturn() { assertEquals("Expect null pointer", null, lib.returnWStringArgument(null)); assertEquals("Expect string magic", WMAGIC.toString(), lib.returnWStringArgument(WMAGIC).toString()); } - + public void testInt64ArgumentAlignment() { - long value = lib.checkInt64ArgumentAlignment(0x10101010, 0x1111111111111111L, + long value = lib.checkInt64ArgumentAlignment(0x10101010, 0x1111111111111111L, 0x01010101, 0x2222222222222222L); assertEquals("Improper handling of interspersed int32/int64", 0x3333333344444444L, value); @@ -340,7 +348,7 @@ public void testDoubleArgumentAlignment() { public void testStructurePointerArgument() { TestLibrary.CheckFieldAlignment struct = new TestLibrary.CheckFieldAlignment(); assertEquals("Native address of structure should be returned", - struct.getPointer(), + struct.getPointer(), lib.testStructurePointerArgument(struct)); // ensure that even if the argument is ByValue, it's passed as ptr struct = new TestLibrary.CheckFieldAlignment.ByValue(); @@ -355,12 +363,12 @@ public void testStructurePointerArgument() { } public void testStructureByValueArgument() { - TestLibrary.CheckFieldAlignment.ByValue struct = + TestLibrary.CheckFieldAlignment.ByValue struct = new TestLibrary.CheckFieldAlignment.ByValue(); assertEquals("Wrong alignment in " + struct.toString(true), "0", Integer.toHexString(lib.testStructureByValueArgument(struct))); } - + public void testStructureByValueTypeInfo() { class TestStructure extends Structure implements Structure.ByValue { public byte b; @@ -372,6 +380,7 @@ class TestStructure extends Structure implements Structure.ByValue { public double d; public Pointer[] parray = new Pointer[2]; public byte[] barray = new byte[2]; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "b", "c", "s", "i", "j", "f", "d", "parray", "barray" }); } @@ -381,23 +390,23 @@ protected List getFieldOrder() { s.size(); } - + public void testWriteStructureArrayArgumentMemory() { final int LENGTH = 10; TestLibrary.CheckFieldAlignment block = new TestLibrary.CheckFieldAlignment(); - TestLibrary.CheckFieldAlignment[] array = + TestLibrary.CheckFieldAlignment[] array = (TestLibrary.CheckFieldAlignment[])block.toArray(LENGTH); for (int i=0;i < array.length;i++) { array[i].int32Field = i; } assertEquals("Structure array memory not properly initialized", -1, lib.testStructureArrayInitialization(array, array.length)); - + } - + public void testUninitializedStructureArrayArgument() { final int LENGTH = 10; - TestLibrary.CheckFieldAlignment[] block = + TestLibrary.CheckFieldAlignment[] block = new TestLibrary.CheckFieldAlignment[LENGTH]; lib.modifyStructureArray(block, block.length); for (int i=0;i < block.length;i++) { @@ -426,7 +435,7 @@ public void testRejectNoncontiguousStructureArrayArgument() { catch(IllegalArgumentException e) { } } - + public void testRejectIncompatibleStructureArrayArgument() { TestLibrary.CheckFieldAlignment s1 = new TestLibrary.CheckFieldAlignment.ByReference(); TestLibrary.CheckFieldAlignment[] autoArray = (TestLibrary.CheckFieldAlignment[])s1.toArray(3); @@ -489,43 +498,43 @@ public void testReadStructureByReferenceArrayArgumentMemory() { public void testByteArrayArgument() { byte[] buf = new byte[1024]; final byte MAGIC = (byte)0xED; - assertEquals("Wrong return value", buf.length, + assertEquals("Wrong return value", buf.length, lib.fillInt8Buffer(buf, buf.length, MAGIC)); for (int i=0;i < buf.length;i++) { assertEquals("Bad value at index " + i, MAGIC, buf[i]); } } - + public void testShortArrayArgument() { short[] buf = new short[1024]; final short MAGIC = (short)0xABED; - assertEquals("Wrong return value", buf.length, + assertEquals("Wrong return value", buf.length, lib.fillInt16Buffer(buf, buf.length, MAGIC)); for (int i=0;i < buf.length;i++) { assertEquals("Bad value at index " + i, MAGIC, buf[i]); } } - + public void testIntArrayArgument() { int[] buf = new int[1024]; final int MAGIC = 0xABEDCF23; - assertEquals("Wrong return value", buf.length, + assertEquals("Wrong return value", buf.length, lib.fillInt32Buffer(buf, buf.length, MAGIC)); for (int i=0;i < buf.length;i++) { assertEquals("Bad value at index " + i, MAGIC, buf[i]); } } - - public void testLongArrayArgument() { + + public void testLongArrayArgument() { long[] buf = new long[1024]; final long MAGIC = 0x1234567887654321L; - assertEquals("Wrong return value", buf.length, + assertEquals("Wrong return value", buf.length, lib.fillInt64Buffer(buf, buf.length, MAGIC)); for (int i=0;i < buf.length;i++) { assertEquals("Bad value at index " + i, MAGIC, buf[i]); } } - + public void testUnsupportedJavaObjectArgument() { try { lib.returnBooleanArgument(this); @@ -534,23 +543,23 @@ public void testUnsupportedJavaObjectArgument() { catch(IllegalArgumentException e) { } } - + public void testStringArrayArgument() { String[] args = { "one"+UNICODE, "two"+UNICODE, "three"+UNICODE }; assertEquals("Wrong value returned", args[0], lib.returnStringArrayElement(args, 0)); - assertNull("Native String array should be null terminated", + assertNull("Native String array should be null terminated", lib.returnStringArrayElement(args, args.length)); } - + public void testWideStringArrayArgument() { WString[] args = { new WString("one"+UNICODE), new WString("two"+UNICODE), new WString("three"+UNICODE) }; assertEquals("Wrong value returned", args[0], lib.returnWideStringArrayElement(args, 0)); assertNull("Native WString array should be null terminated", lib.returnWideStringArrayElement(args, args.length)); } - + public void testPointerArrayArgument() { - Pointer[] args = { + Pointer[] args = { new NativeString(getName()).getPointer(), null, new NativeString(getName()+"2").getPointer(), @@ -581,7 +590,7 @@ public void testNativeMappedArrayArgument() { }; public void testStructureByReferenceArrayArgument() { - CheckFieldAlignment.ByReference[] args = { + CheckFieldAlignment.ByReference[] args = { new CheckFieldAlignment.ByReference(), null, new CheckFieldAlignment.ByReference(), @@ -599,7 +608,7 @@ public void testModifiedCharArrayArgument() { Arrays.asList(new String[] { "two", "three", "one" }), Arrays.asList(args)); } - + public void testReadFunctionPointerAsCallback() { TestLibrary.CbStruct s = new TestLibrary.CbStruct(); assertNull("Function pointer field should be null", s.cb); @@ -640,5 +649,5 @@ public void testDisableAutoSynch() { public static void main(java.lang.String[] argList) { junit.textui.TestRunner.run(ArgumentsMarshalTest.class); } - + } diff --git a/test/com/sun/jna/BufferArgumentsMarshalTest.java b/test/com/sun/jna/BufferArgumentsMarshalTest.java index b47153942f..88027030a3 100644 --- a/test/com/sun/jna/BufferArgumentsMarshalTest.java +++ b/test/com/sun/jna/BufferArgumentsMarshalTest.java @@ -8,7 +8,7 @@ * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna; @@ -19,10 +19,6 @@ import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; -import java.util.Arrays; - -import com.sun.jna.ArgumentsMarshalTest.TestLibrary.CheckFieldAlignment; - import junit.framework.TestCase; /** Exercise a range of native methods. @@ -33,7 +29,7 @@ public class BufferArgumentsMarshalTest extends TestCase { public static interface TestLibrary extends Library { - + // ByteBuffer alternative definitions int fillInt8Buffer(ByteBuffer buf, int len, byte value); int fillInt16Buffer(ByteBuffer buf, int len, short value); @@ -41,7 +37,7 @@ public static interface TestLibrary extends Library { int fillInt64Buffer(ByteBuffer buf, int len, long value); int fillFloatBuffer(ByteBuffer buf, int len, float value); int fillDoubleBuffer(ByteBuffer buf, int len, double value); - + // {Short|Int|Long|,Float|Double}Buffer alternative definitions int fillInt16Buffer(ShortBuffer buf, int len, short value); int fillInt32Buffer(IntBuffer buf, int len, int value); @@ -51,14 +47,16 @@ public static interface TestLibrary extends Library { } TestLibrary lib; + @Override protected void setUp() { - lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + lib = Native.loadLibrary("testlib", TestLibrary.class); } - + + @Override protected void tearDown() { lib = null; } - + public void testByteBufferArgument() { ByteBuffer buf = ByteBuffer.allocate(1024).order(ByteOrder.nativeOrder()); final byte MAGIC = (byte)0xED; @@ -91,7 +89,7 @@ public void testLongBufferArgument() { assertEquals("Bad value at index " + i, MAGIC, buf.get(i)); } } - + public void testDirectByteBufferArgument() { ByteBuffer buf = ByteBuffer.allocateDirect(1024).order(ByteOrder.nativeOrder()); final byte MAGIC = (byte)0xED; @@ -106,7 +104,7 @@ public void testDirectByteBufferArgument() { i < 512 ? MAGIC : 0, buf.get(i)); } } - + public void testDirectShortBufferArgument() { ByteBuffer buf = ByteBuffer.allocateDirect(1024*2).order(ByteOrder.nativeOrder()); ShortBuffer shortBuf = buf.asShortBuffer(); @@ -116,7 +114,7 @@ public void testDirectShortBufferArgument() { assertEquals("Bad value at index " + i, MAGIC, shortBuf.get(i)); } } - + public void testDirectIntBufferArgument() { ByteBuffer buf = ByteBuffer.allocateDirect(1024*4).order(ByteOrder.nativeOrder()); IntBuffer intBuf = buf.asIntBuffer(); @@ -126,7 +124,7 @@ public void testDirectIntBufferArgument() { assertEquals("Bad value at index " + i, MAGIC, intBuf.get(i)); } } - + public void testDirectLongBufferArgument() { ByteBuffer buf = ByteBuffer.allocateDirect(1024*8).order(ByteOrder.nativeOrder()); LongBuffer longBuf = buf.asLongBuffer(); @@ -136,7 +134,7 @@ public void testDirectLongBufferArgument() { assertEquals("Bad value at index " + i, MAGIC, longBuf.get(i)); } } - + public void testWrappedByteArrayArgument() { byte[] array = new byte[1024]; ByteBuffer buf = ByteBuffer.wrap(array, 512, 512); @@ -197,9 +195,9 @@ public void testWrappedDoubleArrayArguent() { i < 512 ? 0 : MAGIC, array[i]); } } - + public static void main(java.lang.String[] argList) { junit.textui.TestRunner.run(BufferArgumentsMarshalTest.class); } - + } diff --git a/test/com/sun/jna/ByReferenceArgumentsTest.java b/test/com/sun/jna/ByReferenceArgumentsTest.java index f987caf2ce..a7263f74af 100644 --- a/test/com/sun/jna/ByReferenceArgumentsTest.java +++ b/test/com/sun/jna/ByReferenceArgumentsTest.java @@ -8,7 +8,7 @@ * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna; @@ -41,10 +41,12 @@ public static interface TestLibrary extends Library { } TestLibrary lib; + @Override protected void setUp() { - lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + lib = Native.loadLibrary("testlib", TestLibrary.class); } - + + @Override protected void tearDown() { lib = null; } @@ -93,9 +95,9 @@ public void testPointerByReference() { lib.setPointerByReferenceNull(pref); assertNull("Default pointer should be NULL after call", pref.getValue()); } - + public static void main(java.lang.String[] argList) { junit.textui.TestRunner.run(ByReferenceArgumentsTest.class); } - + } diff --git a/test/com/sun/jna/CallbacksTest.java b/test/com/sun/jna/CallbacksTest.java index d147e401db..c7d38c01bc 100644 --- a/test/com/sun/jna/CallbacksTest.java +++ b/test/com/sun/jna/CallbacksTest.java @@ -8,12 +8,11 @@ * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna; import java.io.ByteArrayOutputStream; -import java.io.File; import java.io.PrintStream; import java.lang.ref.WeakReference; import java.util.Arrays; @@ -39,7 +38,7 @@ //@SuppressWarnings("unused") public class CallbacksTest extends TestCase implements Paths { - // On OSX, on Oracle JVM 1.8+, pthread cleanup thinks the native thread is + // On OSX, on Oracle JVM 1.8+, pthread cleanup thinks the native thread is // not attached, and the JVM never unmaps the defunct native thread. In // order to avoid this situation causing tests to time out, we need to // explicitly detach the native thread after our Java code is done with it. @@ -67,12 +66,14 @@ protected void waitFor(Thread thread) { public static class SmallTestStructure extends Structure { public double value; public static int allocations = 0; + @Override protected void allocateMemory(int size) { super.allocateMemory(size); ++allocations; } public SmallTestStructure() { } public SmallTestStructure(Pointer p) { super(p); read(); } + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "value" }); } @@ -87,8 +88,9 @@ public static interface TestCallback extends Callback { public int i; public long j; public SmallTestStructure inner; + @Override protected List getFieldOrder() { - return Arrays.asList(new String[] { "c", "s", "i", "j", "inner" }); + return Arrays.asList(new String[] { "c", "s", "i", "j", "inner" }); } } public static interface TestLibrary extends Library { @@ -114,6 +116,7 @@ interface VoidCallbackCustom extends Callback { void customMethodName(); } abstract class VoidCallbackCustomAbstract implements VoidCallbackCustom { + @Override public void customMethodName() { } } class VoidCallbackCustomDerived extends VoidCallbackCustomAbstract { } @@ -189,6 +192,7 @@ interface CustomCallback extends Callback { class CbStruct extends Structure { public Callback cb; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "cb" }); } @@ -208,10 +212,12 @@ interface UnionCallback extends Callback { TestLibrary lib; + @Override protected void setUp() { - lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + lib = Native.loadLibrary("testlib", TestLibrary.class); } - + + @Override protected void tearDown() { lib = null; } @@ -222,15 +228,19 @@ public Custom() { } public Custom(int value) { this.value = value; } + @Override public Object fromNative(Object nativeValue, FromNativeContext context) { return new Custom(((Integer)nativeValue).intValue()); } + @Override public Class nativeType() { return Integer.class; } + @Override public Object toNative() { return new Integer(value); } + @Override public boolean equals(Object o) { return o instanceof Custom && ((Custom)o).value == value; } @@ -303,7 +313,7 @@ public void testNativeFunctionPointerStringValue() { public void testLookupSameCallback() { Callback cb = CallbackReference.getCallback(TestLibrary.VoidCallback.class, new Pointer(getName().hashCode())); Callback cb2 = CallbackReference.getCallback(TestLibrary.VoidCallback.class, new Pointer(getName().hashCode())); - + assertEquals("Callback lookups for same pointer should return same Callback object", cb, cb2); } @@ -316,19 +326,20 @@ protected Map callbackCache() { public void testGCCallbackOnFinalize() throws Exception { final boolean[] called = { false }; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { + @Override public void callback() { called[0] = true; } }; lib.callVoidCallback(cb); assertTrue("Callback not called", called[0]); - + Map refs = new WeakHashMap(callbackCache()); assertTrue("Callback not cached", refs.containsKey(cb)); CallbackReference ref = (CallbackReference)refs.get(cb); refs = callbackCache(); Pointer cbstruct = ref.cbstruct; - + cb = null; System.gc(); for (int i = 0; i < 100 && (ref.get() != null || refs.containsValue(ref)); ++i) { @@ -339,7 +350,7 @@ public void callback() { } assertNull("Callback not GC'd", ref.get()); assertFalse("Callback still in map", refs.containsValue(ref)); - + ref = null; System.gc(); for (int i = 0; i < 100 && (cbstruct.peer != 0 || refs.size() > 0); ++i) { @@ -352,9 +363,10 @@ public void callback() { } assertEquals("Callback trampoline not freed", 0, cbstruct.peer); } - + public void testFindCallbackInterface() { TestLibrary.Int32Callback cb = new TestLibrary.Int32Callback() { + @Override public int callback(int arg, int arg2) { return arg + arg2; } @@ -367,6 +379,7 @@ public int callback(int arg, int arg2) { public void testCallVoidCallback() { final boolean[] called = { false }; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { + @Override public void callback() { called[0] = true; } @@ -379,6 +392,7 @@ public void testCallInt32Callback() { final int MAGIC = 0x11111111; final boolean[] called = { false }; TestLibrary.Int32Callback cb = new TestLibrary.Int32Callback() { + @Override public int callback(int arg, int arg2) { called[0] = true; return arg + arg2; @@ -387,17 +401,18 @@ public int callback(int arg, int arg2) { final int EXPECTED = MAGIC*3; int value = lib.callInt32Callback(cb, MAGIC, MAGIC*2); assertTrue("Callback not called", called[0]); - assertEquals("Wrong callback value", Integer.toHexString(EXPECTED), + assertEquals("Wrong callback value", Integer.toHexString(EXPECTED), Integer.toHexString(value)); - + value = lib.callInt32Callback(cb, -1, -2); assertEquals("Wrong callback return", -3, value); } - + public void testCallInt64Callback() { final long MAGIC = 0x1111111111111111L; final boolean[] called = { false }; TestLibrary.Int64Callback cb = new TestLibrary.Int64Callback() { + @Override public long callback(long arg, long arg2) { called[0] = true; return arg + arg2; @@ -406,17 +421,18 @@ public long callback(long arg, long arg2) { final long EXPECTED = MAGIC*3; long value = lib.callInt64Callback(cb, MAGIC, MAGIC*2); assertTrue("Callback not called", called[0]); - assertEquals("Wrong callback value", Long.toHexString(EXPECTED), + assertEquals("Wrong callback value", Long.toHexString(EXPECTED), Long.toHexString(value)); - + value = lib.callInt64Callback(cb, -1, -2); assertEquals("Wrong callback return", -3, value); } - + public void testCallFloatCallback() { final boolean[] called = { false }; final float[] args = { 0, 0 }; TestLibrary.FloatCallback cb = new TestLibrary.FloatCallback() { + @Override public float callback(float arg, float arg2) { called[0] = true; args[0] = arg; @@ -430,15 +446,16 @@ public float callback(float arg, float arg2) { assertEquals("Wrong first argument", FLOAT_MAGIC, args[0], 0); assertEquals("Wrong second argument", FLOAT_MAGIC*2, args[1], 0); assertEquals("Wrong callback value", EXPECTED, value, 0); - + value = lib.callFloatCallback(cb, -1f, -2f); assertEquals("Wrong callback return", -3f, value, 0); } - + public void testCallDoubleCallback() { final boolean[] called = { false }; final double[] args = { 0, 0 }; TestLibrary.DoubleCallback cb = new TestLibrary.DoubleCallback() { + @Override public double callback(double arg, double arg2) { called[0] = true; args[0] = arg; @@ -451,18 +468,19 @@ public double callback(double arg, double arg2) { assertTrue("Callback not called", called[0]); assertEquals("Wrong first argument", DOUBLE_MAGIC, args[0], 0); assertEquals("Wrong second argument", DOUBLE_MAGIC*2, args[1], 0); - assertEquals("Wrong callback value", EXPECTED, value, 0); - + assertEquals("Wrong callback value", EXPECTED, value, 0); + value = lib.callDoubleCallback(cb, -1d, -2d); assertEquals("Wrong callback return", -3d, value, 0); } - + public void testCallStructureCallback() { final boolean[] called = {false}; final Pointer[] cbarg = { null }; final SmallTestStructure s = new SmallTestStructure(); final double MAGIC = 118.625; TestLibrary.StructureCallback cb = new TestLibrary.StructureCallback() { + @Override public SmallTestStructure callback(SmallTestStructure arg) { called[0] = true; cbarg[0] = arg.getPointer(); @@ -480,15 +498,16 @@ public SmallTestStructure callback(SmallTestStructure arg) { assertEquals("Structure return not synched", MAGIC, value.value, 0d); // All structures involved should be created from pointers, with no - // memory allocation at all. + // memory allocation at all. assertEquals("No structure memory should be allocated", 0, SmallTestStructure.allocations); } - + public void testCallStructureArrayCallback() { final SmallTestStructure s = new SmallTestStructure(); final SmallTestStructure[] array = (SmallTestStructure[])s.toArray(2); final double MAGIC = 118.625; TestLibrary.StructureCallback cb = new TestLibrary.StructureCallback() { + @Override public SmallTestStructure callback(SmallTestStructure arg) { SmallTestStructure[] array = (SmallTestStructure[])arg.toArray(2); @@ -503,11 +522,12 @@ public SmallTestStructure callback(SmallTestStructure arg) { assertEquals("Structure array element 1 not synched on callback return", MAGIC*2, array[1].value, 0d); } - + public void testCallBooleanCallback() { final boolean[] called = {false}; final boolean[] cbargs = { false, false }; TestLibrary.BooleanCallback cb = new TestLibrary.BooleanCallback() { + @Override public boolean callback(boolean arg, boolean arg2) { called[0] = true; cbargs[0] = arg; @@ -521,11 +541,12 @@ public boolean callback(boolean arg, boolean arg2) { assertEquals("Wrong second callback argument", false, cbargs[1]); assertFalse("Wrong boolean return", value); } - + public void testCallInt8Callback() { final boolean[] called = {false}; final byte[] cbargs = { 0, 0 }; TestLibrary.ByteCallback cb = new TestLibrary.ByteCallback() { + @Override public byte callback(byte arg, byte arg2) { called[0] = true; cbargs[0] = arg; @@ -533,27 +554,28 @@ public byte callback(byte arg, byte arg2) { return (byte)(arg + arg2); } }; - final byte MAGIC = 0x11; + final byte MAGIC = 0x11; byte value = lib.callInt8Callback(cb, MAGIC, (byte)(MAGIC*2)); assertTrue("Callback not called", called[0]); - assertEquals("Wrong first callback argument", - Integer.toHexString(MAGIC), + assertEquals("Wrong first callback argument", + Integer.toHexString(MAGIC), Integer.toHexString(cbargs[0])); - assertEquals("Wrong second callback argument", - Integer.toHexString(MAGIC*2), + assertEquals("Wrong second callback argument", + Integer.toHexString(MAGIC*2), Integer.toHexString(cbargs[1])); - assertEquals("Wrong byte return", - Integer.toHexString(MAGIC*3), + assertEquals("Wrong byte return", + Integer.toHexString(MAGIC*3), Integer.toHexString(value)); - + value = lib.callInt8Callback(cb, (byte)-1, (byte)-2); assertEquals("Wrong byte return (hi bit)", (byte)-3, value); } - + public void testCallInt16Callback() { final boolean[] called = {false}; final short[] cbargs = { 0, 0 }; TestLibrary.ShortCallback cb = new TestLibrary.ShortCallback() { + @Override public short callback(short arg, short arg2) { called[0] = true; cbargs[0] = arg; @@ -564,24 +586,25 @@ public short callback(short arg, short arg2) { final short MAGIC = 0x1111; short value = lib.callInt16Callback(cb, MAGIC, (short)(MAGIC*2)); assertTrue("Callback not called", called[0]); - assertEquals("Wrong first callback argument", - Integer.toHexString(MAGIC), + assertEquals("Wrong first callback argument", + Integer.toHexString(MAGIC), Integer.toHexString(cbargs[0])); - assertEquals("Wrong second callback argument", - Integer.toHexString(MAGIC*2), + assertEquals("Wrong second callback argument", + Integer.toHexString(MAGIC*2), Integer.toHexString(cbargs[1])); - assertEquals("Wrong short return", - Integer.toHexString(MAGIC*3), + assertEquals("Wrong short return", + Integer.toHexString(MAGIC*3), Integer.toHexString(value)); value = lib.callInt16Callback(cb, (short)-1, (short)-2); assertEquals("Wrong short return (hi bit)", (short)-3, value); } - + public void testCallNativeLongCallback() { final boolean[] called = {false}; final NativeLong[] cbargs = { null, null}; TestLibrary.NativeLongCallback cb = new TestLibrary.NativeLongCallback() { + @Override public NativeLong callback(NativeLong arg, NativeLong arg2) { called[0] = true; cbargs[0] = arg; @@ -595,11 +618,12 @@ public NativeLong callback(NativeLong arg, NativeLong arg2) { assertEquals("Wrong second callback argument", new NativeLong(2), cbargs[1]); assertEquals("Wrong boolean return", new NativeLong(3), value); } - + public void testCallNativeMappedCallback() { final boolean[] called = {false}; final Custom[] cbargs = { null, null}; TestLibrary.CustomCallback cb = new TestLibrary.CustomCallback() { + @Override public Custom callback(Custom arg, Custom arg2) { called[0] = true; cbargs[0] = arg; @@ -613,11 +637,12 @@ public Custom callback(Custom arg, Custom arg2) { assertEquals("Wrong second callback argument", new Custom(2), cbargs[1]); assertEquals("Wrong NativeMapped return", 3, value); } - + public void testCallStringCallback() { final boolean[] called = {false}; final String[] cbargs = { null, null }; TestLibrary.StringCallback cb = new TestLibrary.StringCallback() { + @Override public String callback(String arg, String arg2) { called[0] = true; cbargs[0] = arg; @@ -633,9 +658,10 @@ public String callback(String arg, String arg2) { assertEquals("Wrong String callback argument 1", VALUE2, cbargs[1]); assertEquals("Wrong String return", VALUE + VALUE2, value); } - + public void testStringCallbackMemoryReclamation() throws InterruptedException { TestLibrary.StringCallback cb = new TestLibrary.StringCallback() { + @Override public String callback(String arg, String arg2) { return arg + arg2; } @@ -649,7 +675,7 @@ public String callback(String arg, String arg2) { String arg2 = getName() + "2" + UNICODE; String value = lib.callStringCallback(cb, arg, arg2); WeakReference ref = new WeakReference(value); - + arg = null; value = null; System.gc(); @@ -667,6 +693,7 @@ public void testCallWideStringCallback() { final boolean[] called = {false}; final WString[] cbargs = { null, null }; TestLibrary.WideStringCallback cb = new TestLibrary.WideStringCallback() { + @Override public WString callback(WString arg, WString arg2) { called[0] = true; cbargs[0] = arg; @@ -682,11 +709,12 @@ public WString callback(WString arg, WString arg2) { assertEquals("Wrong second callback argument", VALUE2, cbargs[1]); assertEquals("Wrong wide string return", new WString(VALUE.toString() + VALUE2.toString()), value); } - + public void testCallStringArrayCallback() { final boolean[] called = {false}; final String[][] cbargs = { null }; TestLibrary.StringArrayCallback cb = new TestLibrary.StringArrayCallback() { + @Override public String[] callback(String[] arg) { called[0] = true; cbargs[0] = arg; @@ -708,10 +736,11 @@ public String[] callback(String[] arg) { assertEquals("Terminating null should be removed from return value", VALUE_ARRAY.length-1, result.length); } - + public void testCallCallbackWithByReferenceArgument() { final boolean[] called = {false}; TestLibrary.CopyArgToByReference cb = new TestLibrary.CopyArgToByReference() { + @Override public int callback(int arg, IntByReference result) { called[0] = true; result.setValue(arg); @@ -724,12 +753,13 @@ public int callback(int arg, IntByReference result) { assertEquals("Wrong value returned", VALUE, value); assertEquals("Wrong value in by reference memory", VALUE, ref.getValue()); } - + public void testCallCallbackWithStructByValue() throws Exception { final boolean[] called = { false }; final TestStructure.ByValue[] arg = { null }; final TestStructure.ByValue s = new TestStructure.ByValue(); TestStructure.TestCallback cb = new TestStructure.TestCallback() { + @Override public TestStructure.ByValue callback(TestStructure.ByValue s) { // Copy the argument value for later comparison called[0] = true; @@ -741,7 +771,7 @@ public TestStructure.ByValue callback(TestStructure.ByValue s) { s.i = 0x33333333; s.j = 0x4444444444444444L; s.inner.value = 5; - + TestStructure result = lib.callCallbackWithStructByValue(cb, s); assertTrue("Callback not called", called[0]); assertTrue("ByValue argument should own its own memory, instead was " @@ -759,8 +789,8 @@ public TestStructure.ByValue callback(TestStructure.ByValue s) { } assertTrue("Wrong value for callback result", s.dataEquals(result, true)); } - - public void testUnionByValueCallbackArgument() throws Exception{ + + public void testUnionByValueCallbackArgument() throws Exception{ TestLibrary.TestUnion arg = new TestLibrary.TestUnion(); arg.setType(String.class); final String VALUE = getName() + UNICODE; @@ -768,6 +798,7 @@ public void testUnionByValueCallbackArgument() throws Exception{ final boolean[] called = { false }; final TestLibrary.TestUnion[] cbvalue = { null }; TestLibrary.TestUnion result = lib.testUnionByValueCallbackArgument(new TestLibrary.UnionCallback() { + @Override public TestLibrary.TestUnion invoke(TestLibrary.TestUnion v) { called[0] = true; v.setType(String.class); @@ -786,6 +817,7 @@ public TestLibrary.TestUnion invoke(TestLibrary.TestUnion v) { public void testCallCallbackWithCallbackArgumentAndResult() { TestLibrary.CbCallback cb = new TestLibrary.CbCallback() { + @Override public CbCallback callback(CbCallback arg) { return arg; } @@ -793,7 +825,7 @@ public CbCallback callback(CbCallback arg) { TestLibrary.CbCallback cb2 = lib.callCallbackWithCallback(cb); assertEquals("Callback reference should be reused", cb, cb2); } - + public void testDefaultCallbackExceptionHandler() { final RuntimeException ERROR = new RuntimeException(getName()); PrintStream ps = System.err; @@ -801,6 +833,7 @@ public void testDefaultCallbackExceptionHandler() { System.setErr(new PrintStream(s)); try { TestLibrary.CbCallback cb = new TestLibrary.CbCallback() { + @Override public CbCallback callback(CbCallback arg) { throw ERROR; } @@ -822,6 +855,7 @@ public void testCallbackExceptionHandler() { final Callback CALLBACK[] = { null }; UncaughtExceptionHandler old = Native.getCallbackExceptionHandler(); UncaughtExceptionHandler handler = new UncaughtExceptionHandler() { + @Override public void uncaughtException(Callback cb, Throwable e) { CALLBACK[0] = cb; CAUGHT[0] = e; @@ -830,6 +864,7 @@ public void uncaughtException(Callback cb, Throwable e) { Native.setCallbackExceptionHandler(handler); try { TestLibrary.CbCallback cb = new TestLibrary.CbCallback() { + @Override public CbCallback callback(CbCallback arg) { throw ERROR; } @@ -852,6 +887,7 @@ public void testCallbackExceptionHandlerWithCallbackProxy() throws Throwable { final Callback CALLBACK[] = { null }; UncaughtExceptionHandler old = Native.getCallbackExceptionHandler(); UncaughtExceptionHandler handler = new UncaughtExceptionHandler() { + @Override public void uncaughtException(Callback cb, Throwable e) { CALLBACK[0] = cb; CAUGHT[0] = e; @@ -860,15 +896,19 @@ public void uncaughtException(Callback cb, Throwable e) { Native.setCallbackExceptionHandler(handler); try { class TestProxy implements CallbackProxy, TestLibrary.CbCallback { + @Override public CbCallback callback(CbCallback arg) { throw new Error("Should never be called"); } + @Override public Object callback(Object[] args) { throw ERROR; } + @Override public Class[] getParameterTypes() { return new Class[] { CbCallback.class }; } + @Override public Class getReturnType() { return CbCallback.class; } @@ -895,8 +935,9 @@ public void testInvokeCallback() { TestLibrary.Int32CallbackX cb = lib.returnCallback(); assertNotNull("Callback should not be null", cb); assertEquals("Callback should be callable", 1, cb.callback(1)); - + TestLibrary.Int32CallbackX cb2 = new TestLibrary.Int32CallbackX() { + @Override public int callback(int arg) { return 0; } @@ -906,7 +947,7 @@ public int callback(int arg) { assertSame("Existing native function wrapper should be reused", cb, lib.returnCallbackArgument(cb)); } - + public void testCallCallbackInStructure() { final boolean[] flag = {false}; final TestLibrary.CbStruct s = new TestLibrary.CbStruct(); @@ -922,9 +963,11 @@ public void callback() { public void testCustomCallbackMethodName() { final boolean[] called = {false}; TestLibrary.VoidCallbackCustom cb = new TestLibrary.VoidCallbackCustom() { + @Override public void customMethodName() { called[0] = true; } + @Override public String toString() { return "Some debug output"; } @@ -937,6 +980,7 @@ public void testDisallowDetachFromJVMThread() { final boolean[] called = {false}; final boolean[] exceptionThrown = {true}; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { + @Override public void callback() { called[0] = true; try { @@ -961,20 +1005,23 @@ public void testCustomCallbackVariedInheritance() { protected static class CallbackTypeMapper extends DefaultTypeMapper { public int fromNativeConversions = 0; public int toNativeConversions = 0; - public void clear() { + public void clear() { fromNativeConversions = 0; toNativeConversions = 0; } { // Convert java doubles into native integers and back TypeConverter converter = new TypeConverter() { + @Override public Object fromNative(Object value, FromNativeContext context) { ++fromNativeConversions; return new Double(((Integer)value).intValue()); } + @Override public Class nativeType() { return Integer.class; } + @Override public Object toNative(Object value, ToNativeContext ctx) { ++toNativeConversions; return new Integer(((Double)value).intValue()); @@ -982,13 +1029,16 @@ public Object toNative(Object value, ToNativeContext ctx) { }; addTypeConverter(double.class, converter); converter = new TypeConverter() { + @Override public Object fromNative(Object value, FromNativeContext context) { ++fromNativeConversions; return new Float(((Long)value).intValue()); } + @Override public Class nativeType() { return Long.class; } + @Override public Object toNative(Object value, ToNativeContext ctx) { ++toNativeConversions; return new Long(((Float)value).longValue()); @@ -996,6 +1046,7 @@ public Object toNative(Object value, ToNativeContext ctx) { }; addTypeConverter(float.class, converter); converter = new TypeConverter() { + @Override public Object fromNative(Object value, FromNativeContext context) { ++fromNativeConversions; if (value == null) { @@ -1006,9 +1057,11 @@ public Object fromNative(Object value, FromNativeContext context) { } return value.toString(); } + @Override public Class nativeType() { return WString.class; } + @Override public Object toNative(Object value, ToNativeContext ctx) { ++toNativeConversions; return new WString(value.toString()); @@ -1040,14 +1093,13 @@ interface WStringCallback extends Callback { } protected CallbackTestLibrary loadCallbackTestLibrary() { - return (CallbackTestLibrary) - Native.loadLibrary("testlib", CallbackTestLibrary.class, CallbackTestLibrary._OPTIONS); + return Native.loadLibrary("testlib", CallbackTestLibrary.class, CallbackTestLibrary._OPTIONS); } /** This test is here instead of NativeTest in order to facilitate running the exact same test on a direct-mapped library without the tests interfering with one another due to persistent/cached state in library - loading. + loading. */ public void testCallbackUsesTypeMapper() throws Exception { CallbackTestLibrary lib = loadCallbackTestLibrary(); @@ -1056,6 +1108,7 @@ public void testCallbackUsesTypeMapper() throws Exception { final double[] ARGS = new double[2]; CallbackTestLibrary.DoubleCallback cb = new CallbackTestLibrary.DoubleCallback() { + @Override public double callback(double arg, double arg2) { ARGS[0] = arg; ARGS[1] = arg2; @@ -1085,6 +1138,7 @@ public void testTypeMapperWithWideStrings() throws Exception { final String[] ARGS = new String[2]; CallbackTestLibrary.WStringCallback cb = new CallbackTestLibrary.WStringCallback() { + @Override public String callback(String arg, String arg2) { ARGS[0] = arg; ARGS[1] = arg2; @@ -1114,6 +1168,7 @@ public void testCallbackUsesTypeMapperWithDifferentReturnTypeSize() throws Excep final float[] ARGS = new float[2]; CallbackTestLibrary.FloatCallback cb = new CallbackTestLibrary.FloatCallback() { + @Override public float callback(float arg, float arg2) { ARGS[0] = arg; ARGS[1] = arg2; @@ -1165,6 +1220,7 @@ public void testCallbackThreadDefaults() throws Exception { ThreadGroup testGroup = new ThreadGroup(getName() + UNICODE); TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { + @Override public void callback() { Thread thread = Thread.currentThread(); daemon[0] = thread.isDaemon(); @@ -1193,6 +1249,7 @@ public void testCustomizeCallbackThread() throws Exception { ThreadGroup testGroup = new ThreadGroup("Thread group for " + getName()); CallbackThreadInitializer init = new CallbackThreadInitializer(true, false, tname, testGroup); TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { + @Override public void callback() { Thread thread = Thread.currentThread(); daemon[0] = thread.isDaemon(); @@ -1240,11 +1297,13 @@ public void testCallbackThreadPersistence() throws Exception { final int COUNT = 5; CallbackThreadInitializer init = new CallbackThreadInitializer(true, false) { + @Override public String getName(Callback cb) { return "Test thread (native) for " + CallbacksTest.this.getName() + " (call count: " + called[0] + ")"; } }; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { + @Override public void callback() { threads.add(Thread.currentThread()); ++called[0]; @@ -1266,6 +1325,7 @@ public void testCleanupUndetachedThreadOnThreadExit() throws Exception { final Set threads = new HashSet(); final int[] called = { 0 }; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { + @Override public void callback() { threads.add(new WeakReference(Thread.currentThread())); if (++called[0] == 1) { @@ -1276,7 +1336,8 @@ public void callback() { }; // Always attach as daemon to ensure tests will exit CallbackThreadInitializer asDaemon = new CallbackThreadInitializer(true) { - public String getName(Callback cb) { + @Override + public String getName(Callback cb) { return "Test thread (native) for " + CallbacksTest.this.getName(); } }; @@ -1312,13 +1373,14 @@ public String getName(Callback cb) { } // Callback indicates detach preference (instead of - // CallbackThreadInitializer); thread is non-daemon (default), + // CallbackThreadInitializer); thread is non-daemon (default), // but callback explicitly detaches it on final invocation. public void testCallbackIndicatedThreadDetach() throws Exception { final int[] called = {0}; final Set threads = new HashSet(); final int COUNT = 5; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { + @Override public void callback() { threads.add(Thread.currentThread()); // detach on final invocation @@ -1348,6 +1410,7 @@ public void testDLLCallback() throws Exception { final boolean[] called = { false }; class TestCallback implements TestLibrary.VoidCallback, com.sun.jna.win32.DLLCallback { + @Override public void callback() { called[0] = true; } @@ -1383,7 +1446,7 @@ public void callback() { refs = callbackCache(); Pointer cbstruct = ref.cbstruct; Pointer first_fptr = cbstruct.getPointer(0); - + cb = null; System.gc(); for (int i = 0; i < 100 && (ref.get() != null || refs.containsValue(ref)); ++i) { @@ -1392,7 +1455,7 @@ public void callback() { } assertNull("Callback not GC'd", ref.get()); assertFalse("Callback still in map", refs.containsValue(ref)); - + ref = null; System.gc(); for (int i = 0; i < 100 && (cbstruct.peer != 0 || refs.size() > 0); ++i) { @@ -1423,6 +1486,7 @@ public void testThrowOutOfMemoryWhenDLLCallbacksExhausted() throws Exception { final boolean[] called = { false }; class TestCallback implements TestLibrary.VoidCallback, com.sun.jna.win32.DLLCallback { + @Override public void callback() { called[0] = true; } @@ -1446,9 +1510,9 @@ interface TestCallbackTagged extends Callback, AltCallingConvention { } public void testCallingConventionFromInterface() { - TaggedCallingConventionTestLibrary lib = (TaggedCallingConventionTestLibrary) - Native.loadLibrary("testlib", TaggedCallingConventionTestLibrary.class); + TaggedCallingConventionTestLibrary lib = Native.loadLibrary("testlib", TaggedCallingConventionTestLibrary.class); TaggedCallingConventionTestLibrary.TestCallbackTagged cb = new TaggedCallingConventionTestLibrary.TestCallbackTagged() { + @Override public void invoke() { } }; try { @@ -1471,9 +1535,9 @@ interface TestCallback extends Callback { public void testCallingConventionFromOptions() { Map options = new HashMap(); options.put(Library.OPTION_CALLING_CONVENTION, Function.ALT_CONVENTION); - OptionCallingConventionTestLibrary lib = (OptionCallingConventionTestLibrary) - Native.loadLibrary("testlib", OptionCallingConventionTestLibrary.class, options); + OptionCallingConventionTestLibrary lib = Native.loadLibrary("testlib", OptionCallingConventionTestLibrary.class, options); OptionCallingConventionTestLibrary.TestCallback cb = new OptionCallingConventionTestLibrary.TestCallback() { + @Override public void invoke() { } }; try { diff --git a/test/com/sun/jna/DirectArgumentsMarshalTest.java b/test/com/sun/jna/DirectArgumentsMarshalTest.java index 801ae23d33..0b4a81f1a3 100644 --- a/test/com/sun/jna/DirectArgumentsMarshalTest.java +++ b/test/com/sun/jna/DirectArgumentsMarshalTest.java @@ -8,19 +8,10 @@ * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna; -import java.nio.ByteBuffer; -import java.nio.FloatBuffer; -import java.nio.DoubleBuffer; -import java.nio.IntBuffer; -import java.nio.LongBuffer; -import java.nio.ShortBuffer; - -import com.sun.jna.ArgumentsMarshalTest.TestLibrary.CheckFieldAlignment.ByReference; - /** Exercise a range of native methods. * * @author twall@users.sf.net @@ -29,55 +20,92 @@ public class DirectArgumentsMarshalTest extends ArgumentsMarshalTest { public static class DirectTestLibrary implements TestLibrary { /** Dummy. Automatically fail when passed an object. */ + @Override public String returnStringArgument(Object arg) {throw new IllegalArgumentException(arg.getClass().getName()); } + @Override public native boolean returnBooleanArgument(boolean arg); + @Override public native byte returnInt8Argument(byte arg); + @Override public native char returnWideCharArgument(char arg); + @Override public native short returnInt16Argument(short arg); + @Override public native int returnInt32Argument(int i); + @Override public native long returnInt64Argument(long l); + @Override public native NativeLong returnLongArgument(NativeLong l); + @Override public native float returnFloatArgument(float f); + @Override public native double returnDoubleArgument(double d); + @Override public native String returnStringArgument(String s); + @Override public native WString returnWStringArgument(WString s); + @Override public native Pointer returnPointerArgument(Pointer p); + @Override public String returnStringArrayElement(String[] args, int which) {throw new UnsupportedOperationException();} + @Override public WString returnWideStringArrayElement(WString[] args, int which) {throw new UnsupportedOperationException();} + @Override public Pointer returnPointerArrayElement(Pointer[] args, int which) {throw new UnsupportedOperationException();} + @Override public TestPointerType returnPointerArrayElement(TestPointerType[] args, int which) {throw new UnsupportedOperationException();} + @Override public CheckFieldAlignment returnPointerArrayElement(CheckFieldAlignment.ByReference[] args, int which) {throw new UnsupportedOperationException();} + @Override public int returnRotatedArgumentCount(String[] args) {throw new UnsupportedOperationException();} + @Override public native long checkInt64ArgumentAlignment(int i, long j, int i2, long j2); + @Override public native double checkDoubleArgumentAlignment(float i, double j, float i2, double j2); + @Override public native Pointer testStructurePointerArgument(CheckFieldAlignment p); + @Override public native int testStructureByValueArgument(CheckFieldAlignment.ByValue p); + @Override public int testStructureArrayInitialization(CheckFieldAlignment[] p, int len) { throw new UnsupportedOperationException(); } + @Override public int testStructureByReferenceArrayInitialization(CheckFieldAlignment.ByReference[] p, int len) { throw new UnsupportedOperationException(); } + @Override public void modifyStructureArray(CheckFieldAlignment[] p, int length) { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } + @Override public void modifyStructureByReferenceArray(CheckFieldAlignment.ByReference[] p, int length) { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } - + + @Override public native int fillInt8Buffer(byte[] buf, int len, byte value); + @Override public native int fillInt16Buffer(short[] buf, int len, short value); + @Override public native int fillInt32Buffer(int[] buf, int len, int value); + @Override public native int fillInt64Buffer(long[] buf, int len, long value); + @Override public native int fillFloatBuffer(float[] buf, int len, float value); + @Override public native int fillDoubleBuffer(double[] buf, int len, double value); // dummy to avoid causing Native.register to fail + @Override public boolean returnBooleanArgument(Object arg) {throw new IllegalArgumentException();} + @Override public native Pointer testStructurePointerArgument(MinTestStructure s); + @Override public native String returnStringFromVariableSizedStructure(VariableSizedStructure s); + @Override public native void setCallbackInStruct(CbStruct s); static { @@ -86,24 +114,30 @@ public void modifyStructureByReferenceArray(CheckFieldAlignment.ByReference[] p, } /* Override original. */ + @Override protected void setUp() { lib = new DirectTestLibrary(); } - + public static class DirectNativeMappedLibrary implements NativeMappedLibrary { + @Override public native int returnInt32Argument(Custom arg); + @Override public native int returnInt32Argument(size_t arg); + @Override public native long returnInt64Argument(size_t arg); static { Native.register("testlib"); } } + @Override protected NativeMappedLibrary loadNativeMappedLibrary() { return new DirectNativeMappedLibrary(); } // This test crashes on w32 IBM J9 unless -Xint is used // (jvmwi3260-20080415_18762) + @Override public void testWideCharArgument() { if (Platform.isWindows() && "IBM".equals(System.getProperty("java.vm.vendor"))) { @@ -113,6 +147,7 @@ public void testWideCharArgument() { } // This test crashes on w32 IBM J9 unless -Xint is used // (jvmwi3260-20080415_18762) + @Override public void testWStringArgumentReturn() { if (Platform.isWindows() && "IBM".equals(System.getProperty("java.vm.vendor"))) { @@ -122,21 +157,33 @@ public void testWStringArgumentReturn() { } // Override tests not yet supported in direct mode + @Override public void testStringArrayArgument() { } + @Override public void testWriteStructureArrayArgumentMemory() { } + @Override public void testUninitializedStructureArrayArgument() { } + @Override public void testRejectNoncontiguousStructureArrayArgument() { } + @Override public void testRejectIncompatibleStructureArrayArgument() { } + @Override public void testWideStringArrayArgument() { } + @Override public void testPointerArrayArgument() { } + @Override public void testNativeMappedArrayArgument() { } + @Override public void testStructureByReferenceArrayArgument() { } + @Override public void testWriteStructureByReferenceArrayArgumentMemory() { } + @Override public void testReadStructureByReferenceArrayArgumentMemory() { } + @Override public void testModifiedCharArrayArgument() { } public static void main(java.lang.String[] argList) { junit.textui.TestRunner.run(DirectArgumentsMarshalTest.class); } - + } diff --git a/test/com/sun/jna/JNALoadTest.java b/test/com/sun/jna/JNALoadTest.java index 35137077d3..42ffc2122c 100644 --- a/test/com/sun/jna/JNALoadTest.java +++ b/test/com/sun/jna/JNALoadTest.java @@ -1,14 +1,14 @@ /* Copyright (c) 2007-2009 Timothy Wall, All Rights Reserved - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna; @@ -26,11 +26,11 @@ * that no JNI classes are directly referenced in these tests. */ public class JNALoadTest extends TestCase implements Paths, GCWaits { - + private class TestLoader extends URLClassLoader { public TestLoader(boolean fromJar) throws MalformedURLException { super(new URL[] { - Platform.isWindowsCE() + Platform.isWindowsCE() ? new File("/Storage Card/" + (fromJar ? "jna.jar" : "test.jar")).toURI().toURL() : new File(BUILDDIR + (fromJar ? "/jna.jar" : "/classes")).toURI().toURL(), }, new CloverLoader()); @@ -41,12 +41,14 @@ public TestLoader(boolean fromJar) throws MalformedURLException { assertLibraryExists(); } } - protected Class findClass(String name) throws ClassNotFoundException { + + @Override + protected Class findClass(String name) throws ClassNotFoundException { String boot = System.getProperty("jna.boot.library.path"); if (boot != null) { System.setProperty("jna.boot.library.path", ""); } - Class cls = super.findClass(name); + Class cls = super.findClass(name); if (boot != null) { System.setProperty("jna.boot.library.path", boot); } @@ -60,7 +62,7 @@ protected void assertJarExists() { throw new Error("Expected JNA jar file at " + jar + " is missing"); } } - + protected void assertLibraryExists() { String osPrefix = Platform.getNativeLibraryResourcePrefix(); String name = System.mapLibraryName("jnidispatch").replace(".dylib", ".jnilib"); @@ -73,7 +75,7 @@ protected void assertLibraryExists() { public void testAvoidJarUnpacking() throws Exception { System.setProperty("jna.nounpack", "true"); try { - Class cls = Class.forName("com.sun.jna.Native", true, new TestLoader(true)); + Class cls = Class.forName("com.sun.jna.Native", true, new TestLoader(true)); fail("Class com.sun.jna.Native should not be loadable if jna.nounpack=true: " + cls.getClassLoader()); @@ -88,7 +90,7 @@ public void testAvoidJarUnpacking() throws Exception { public void testAvoidResourcePathLoading() throws Exception { System.setProperty("jna.noclasspath", "true"); try { - Class cls = Class.forName("com.sun.jna.Native", true, new TestLoader(false)); + Class cls = Class.forName("com.sun.jna.Native", true, new TestLoader(false)); fail("Class com.sun.jna.Native should not be loadable if jna.noclasspath=true: " + cls.getClassLoader()); @@ -102,7 +104,7 @@ public void testAvoidResourcePathLoading() throws Exception { public void testLoadAndUnloadFromJar() throws Exception { ClassLoader loader = new TestLoader(true); - Class cls = Class.forName("com.sun.jna.Native", true, loader); + Class cls = Class.forName("com.sun.jna.Native", true, loader); assertEquals("Wrong class loader", loader, cls.getClassLoader()); assertTrue("System property jna.loaded not set", Boolean.getBoolean("jna.loaded")); @@ -158,7 +160,7 @@ public void testLoadAndUnloadFromJar() throws Exception { // GC Fails under OpenJDK(linux/ppc) public void testLoadAndUnloadFromResourcePath() throws Exception { ClassLoader loader = new TestLoader(false); - Class cls = Class.forName("com.sun.jna.Native", true, loader); + Class cls = Class.forName("com.sun.jna.Native", true, loader); assertEquals("Wrong class loader", loader, cls.getClassLoader()); assertTrue("System property jna.loaded not set", Boolean.getBoolean("jna.loaded")); @@ -209,9 +211,18 @@ public void testLoadAndUnloadFromResourcePath() throws Exception { } } - // Fails on Sun JVM windows (32 and 64-bit) (JVM bug) - // Works with IBM J9 (jdk6) windows public void testLoadFromUnicodePath() throws Exception { + if (Platform.isWindows()) { + String vendor = System.getProperty("java.vendor"); + if (vendor != null) { + vendor = vendor.toLowerCase(); + if (vendor.contains("oracle") || vendor.contains("sun")) { + System.out.println("Skip " + getName() + " - Fails on Sun JVM windows (32 and 64-bit) (JVM bug), Works with IBM J9 (jdk6) windows"); + return; + } + } + } + final String UNICODE = getName() + "-\u0444\u043b\u0441\u0432\u0443"; File tmpdir = new File(System.getProperty("java.io.tmpdir")); File unicodeDir = new File(tmpdir, UNICODE); @@ -221,7 +232,7 @@ public void testLoadFromUnicodePath() throws Exception { System.setProperty("jnidispatch.preserve", "true"); System.setProperty("jna.tmpdir", unicodeDir.getAbsolutePath()); ClassLoader loader = new TestLoader(true); - Class cls = Class.forName("com.sun.jna.Native", true, loader); + Class cls = Class.forName("com.sun.jna.Native", true, loader); assertEquals("Wrong class loader", loader, cls.getClassLoader()); assertTrue("System property jna.loaded not set", Boolean.getBoolean("jna.loaded")); diff --git a/test/com/sun/jna/LastErrorTest.java b/test/com/sun/jna/LastErrorTest.java index 064d100f65..d8ccde6a96 100644 --- a/test/com/sun/jna/LastErrorTest.java +++ b/test/com/sun/jna/LastErrorTest.java @@ -1,14 +1,14 @@ /* Copyright (c) 2009 Timothy Wall, All Rights Reserved - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna; @@ -22,9 +22,10 @@ //@SuppressWarnings("unused") public class LastErrorTest extends TestCase { - + private static final Map OPTIONS = new HashMap() {{ put(Library.OPTION_FUNCTION_MAPPER, new FunctionMapper() { + @Override public String getFunctionName(NativeLibrary library, Method m) { if (m.getName().equals("noThrowLastError") || m.getName().equals("throwLastError")) { @@ -42,8 +43,11 @@ public interface TestLibrary extends Library { } public static class DirectTestLibrary implements TestLibrary { + @Override public native void setLastError(int code); + @Override public native void noThrowLastError(int code); + @Override public native void throwLastError(int code) throws LastErrorException; static { Native.register(NativeLibrary.getInstance("testlib", OPTIONS)); @@ -51,13 +55,14 @@ public static class DirectTestLibrary implements TestLibrary { } public void testLastErrorPerThreadStorage() throws Exception { - final TestLibrary lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + final TestLibrary lib = Native.loadLibrary("testlib", TestLibrary.class); final int NTHREADS = 100; final int[] errors = new int[NTHREADS]; Set threads = new HashSet(); for (int i=0;i < NTHREADS;i++) { final int idx = i; - Thread t = new Thread() { public void run() { + Thread t = new Thread() { @Override + public void run() { lib.setLastError(-idx-1); errors[idx] = Native.getLastError(); }}; @@ -80,7 +85,7 @@ public void testLastErrorPerThreadStorage() throws Exception { private final int ERROR = Platform.isWindows() ? 1 : -1; public void testThrowLastError() { - TestLibrary lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class, OPTIONS); + TestLibrary lib = Native.loadLibrary("testlib", TestLibrary.class, OPTIONS); lib.noThrowLastError(ERROR); assertEquals("Last error not preserved", ERROR, Native.getLastError()); diff --git a/test/com/sun/jna/LibraryLoadTest.java b/test/com/sun/jna/LibraryLoadTest.java index 51de74ab40..7d976c195c 100644 --- a/test/com/sun/jna/LibraryLoadTest.java +++ b/test/com/sun/jna/LibraryLoadTest.java @@ -1,14 +1,14 @@ /* Copyright (c) 2007-20013 Timothy Wall, All Rights Reserved - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna; @@ -27,7 +27,7 @@ import junit.framework.TestCase; public class LibraryLoadTest extends TestCase implements Paths { - + private class TestLoader extends URLClassLoader { public TestLoader(File path) throws MalformedURLException { super(new URL[] { path.toURI().toURL(), }, @@ -38,7 +38,7 @@ public TestLoader(File path) throws MalformedURLException { public void testLoadJNALibrary() { assertTrue("Pointer size should never be zero", Pointer.SIZE > 0); } - + public void testLoadJAWT() { if (!Platform.HAS_AWT || !Platform.HAS_JAWT) return; @@ -48,7 +48,7 @@ public void testLoadJAWT() { // AWT is unavailable AWT.loadJAWT(getName()); } - + public void testLoadAWTAfterJNA() { if (!Platform.HAS_AWT) return; @@ -58,7 +58,7 @@ public void testLoadAWTAfterJNA() { Toolkit.getDefaultToolkit(); } } - + public void testExtractFromResourcePath() throws Exception { // doesn't actually load the resource assertNotNull(Native.extractFromResourcePath("testlib-path", new TestLoader(new File(TESTPATH)))); @@ -115,19 +115,19 @@ public static interface CLibrary extends Library { private Object load() { return Native.loadLibrary(Platform.C_LIBRARY_NAME, CLibrary.class); } - + public void testLoadProcess() { Native.loadLibrary(CLibrary.class); } - + public void testLoadProcessWithOptions() { Native.loadLibrary(CLibrary.class, Collections.EMPTY_MAP); } - + public void testLoadCLibrary() { load(); } - + private void copy(File src, File dst) throws Exception { FileInputStream is = new FileInputStream(src); FileOutputStream os = new FileOutputStream(dst); @@ -140,7 +140,7 @@ private void copy(File src, File dst) throws Exception { } finally { try { is.close(); } catch(IOException e) { } - try { os.close(); } catch(IOException e) { } + try { os.close(); } catch(IOException e) { } } } @@ -163,7 +163,7 @@ public void testLoadLibraryWithUnicodeName() throws Exception { fail("Library '" + newLibName + "' at " + dst + " could not be loaded: " + e); } } - + public void testLoadLibraryWithLongName() throws Exception { File tmpdir = Native.getTempDir(); String libName = NativeLibrary.mapSharedLibraryName("testlib"); @@ -202,7 +202,7 @@ public void testLoadFrameworkLibrary() { } } } - + public void testLoadFrameworkLibraryAbsolute() { if (Platform.isMac()) { final String PATH = "/System/Library/Frameworks/CoreServices"; @@ -255,7 +255,7 @@ public interface TestLib2 extends Library { // dependent libraries in the same directory as the original public void testLoadDependentLibraryWithAlteredSearchPath() { try { - TestLib2 lib = (TestLib2)Native.loadLibrary("testlib2", TestLib2.class); + TestLib2 lib = Native.loadLibrary("testlib2", TestLib2.class); lib.dependentReturnFalse(); } catch(UnsatisfiedLinkError e) { @@ -271,11 +271,11 @@ public void testLoadDependentLibraryWithAlteredSearchPath() { public void testLoadProperCLibraryVersion() { if (Platform.isWindows()) return; - CLibrary lib = (CLibrary)Native.loadLibrary("c", CLibrary.class); + CLibrary lib = Native.loadLibrary("c", CLibrary.class); assertNotNull("Couldn't get current user", lib.getpwuid(lib.geteuid())); } - + private static class AWT { public static void loadJAWT(String name) { Frame f = new Frame(name); diff --git a/test/com/sun/jna/NativeLibraryTest.java b/test/com/sun/jna/NativeLibraryTest.java index bf3c76c8eb..2c6688134d 100644 --- a/test/com/sun/jna/NativeLibraryTest.java +++ b/test/com/sun/jna/NativeLibraryTest.java @@ -1,14 +1,14 @@ /* Copyright (c) 2007 Timothy Wall, All Rights Reserved - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna; @@ -27,7 +27,7 @@ import junit.framework.TestCase; public class NativeLibraryTest extends TestCase { - + public static interface TestLibrary extends Library { int callCount(); } @@ -65,7 +65,7 @@ public void testGCNativeLibrary() throws Exception { long start = System.currentTimeMillis(); while (ref.get() != null) { Thread.sleep(10); - if (System.currentTimeMillis() - start > 5000) + if (System.currentTimeMillis() - start > 5000) break; } assertNull("Library not GC'd", ref.get()); @@ -77,41 +77,41 @@ public void testAvoidDuplicateLoads() throws Exception { // occasionally get the same library handle back on subsequent dlopen Thread.sleep(2); - TestLibrary lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + TestLibrary lib = Native.loadLibrary("testlib", TestLibrary.class); assertEquals("Library should be newly loaded after explicit dispose of all native libraries", 1, lib.callCount()); if (lib.callCount() <= 1) { fail("Library should not be reloaded without dispose"); } } - + public void testUseSingleLibraryInstance() { - TestLibrary lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + TestLibrary lib = Native.loadLibrary("testlib", TestLibrary.class); int count = lib.callCount(); - TestLibrary lib2 = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + TestLibrary lib2 = Native.loadLibrary("testlib", TestLibrary.class); int count2 = lib2.callCount(); assertEquals("Interfaces should share a library instance", count + 1, count2); } public void testAliasLibraryFilename() { - TestLibrary lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + TestLibrary lib = Native.loadLibrary("testlib", TestLibrary.class); int count = lib.callCount(); NativeLibrary nl = NativeLibrary.getInstance("testlib"); - TestLibrary lib2 = (TestLibrary)Native.loadLibrary(nl.getFile().getName(), TestLibrary.class); + TestLibrary lib2 = Native.loadLibrary(nl.getFile().getName(), TestLibrary.class); int count2 = lib2.callCount(); assertEquals("Simple filename load not aliased", count + 1, count2); } - + public void testAliasLibraryFullPath() { - TestLibrary lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + TestLibrary lib = Native.loadLibrary("testlib", TestLibrary.class); int count = lib.callCount(); NativeLibrary nl = NativeLibrary.getInstance("testlib"); - TestLibrary lib2 = (TestLibrary)Native.loadLibrary(nl.getFile().getAbsolutePath(), TestLibrary.class); + TestLibrary lib2 = Native.loadLibrary(nl.getFile().getAbsolutePath(), TestLibrary.class); int count2 = lib2.callCount(); assertEquals("Full pathname load not aliased", count + 1, count2); } - + public void testAliasSimpleLibraryName() throws Exception { NativeLibrary nl = NativeLibrary.getInstance("testlib"); File file = nl.getFile(); @@ -121,12 +121,12 @@ public void testAliasSimpleLibraryName() throws Exception { long start = System.currentTimeMillis(); while (ref.get() != null) { Thread.sleep(10); - if (System.currentTimeMillis() - start > 5000) + if (System.currentTimeMillis() - start > 5000) fail("Timed out waiting for library to be GC'd"); } - TestLibrary lib = (TestLibrary)Native.loadLibrary(file.getAbsolutePath(), TestLibrary.class); + TestLibrary lib = Native.loadLibrary(file.getAbsolutePath(), TestLibrary.class); int count = lib.callCount(); - TestLibrary lib2 = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + TestLibrary lib2 = Native.loadLibrary("testlib", TestLibrary.class); int count2 = lib2.callCount(); assertEquals("Simple library name not aliased", count + 1, count2); } @@ -160,29 +160,29 @@ public void testFunctionHoldsLibraryReference() throws Exception { System.gc(); long start = System.currentTimeMillis(); while (ref.get() != null && System.currentTimeMillis() - start < 2000) { - Thread.sleep(10); + Thread.sleep(10); } assertNotNull("Library GC'd when it should not be", ref.get()); f.invokeInt(new Object[0]); f = null; System.gc(); while (ref.get() != null && System.currentTimeMillis() - start < 5000) { - Thread.sleep(10); + Thread.sleep(10); } assertNull("Library not GC'd", ref.get()); } - + public void testLookupGlobalVariable() { NativeLibrary lib = NativeLibrary.getInstance("testlib"); Pointer global = lib.getGlobalVariableAddress("test_global"); assertNotNull("Test variable not found", global); final int MAGIC = 0x12345678; assertEquals("Wrong value for library global variable", MAGIC, global.getInt(0)); - + global.setInt(0, MAGIC+1); assertEquals("Library global variable not updated", MAGIC+1, global.getInt(0)); } - + public void testMatchUnversionedToVersioned() throws Exception { File lib0 = File.createTempFile("lib", ".so.0"); File dir = lib0.getParentFile(); @@ -200,7 +200,7 @@ public void testMatchUnversionedToVersioned() throws Exception { lib1_1.getCanonicalPath(), NativeLibrary.matchLibrary(name, path)); } - + public void testAvoidFalseMatch() throws Exception { File lib0 = File.createTempFile("lib", ".so.1"); File dir = lib0.getParentFile(); @@ -230,7 +230,7 @@ public void testParseVersion() throws Exception { assertEquals("Badly parsed version", EXPECTED[i], NativeLibrary.parseVersion(VERSIONS[i]), 0.0000001); } } - + // XFAIL on android public void testGetProcess() { if (Platform.isAndroid()) { @@ -277,10 +277,10 @@ public void testInterceptLastError() { if (!Platform.isWindows()) { return; } - NativeLibrary kernel32 = (NativeLibrary)NativeLibrary.getInstance("kernel32", W32APIOptions.DEFAULT_OPTIONS); + NativeLibrary kernel32 = NativeLibrary.getInstance("kernel32", W32APIOptions.DEFAULT_OPTIONS); Function get = kernel32.getFunction("GetLastError"); Function set = kernel32.getFunction("SetLastError"); - assertEquals("SetLastError should not be customized", Function.class, set.getClass()); + assertEquals("SetLastError should not be customized", Function.class, set.getClass()); assertTrue("GetLastError should be a Function", Function.class.isAssignableFrom(get.getClass())); assertTrue("GetLastError should be a customized Function", get.getClass() != Function.class); final int EXPECTED = 42; @@ -303,6 +303,7 @@ public void testCleanupOnLoadError() throws Exception { // returns unloadable "shared library" on any input private class DisfunctClassLoader extends ClassLoader { + @Override public URL getResource(String name) { try { return new URL("jar", "", name); @@ -312,6 +313,7 @@ public URL getResource(String name) { } } + @Override public InputStream getResourceAsStream(String name) { return new ByteArrayInputStream(new byte[0]); } diff --git a/test/com/sun/jna/NativeTest.java b/test/com/sun/jna/NativeTest.java index 11300163b7..3058239344 100644 --- a/test/com/sun/jna/NativeTest.java +++ b/test/com/sun/jna/NativeTest.java @@ -1,18 +1,19 @@ /* Copyright (c) 2007-2013 Timothy Wall, All Rights Reserved - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna; import java.io.File; +import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -24,9 +25,37 @@ //@SuppressWarnings("unused") public class NativeTest extends TestCase { - + private static final String UNICODE = "[\u0444]"; + public void testLoadLibraryMethods() throws Exception { + Class[][] params = { + { Class.class }, + { Class.class, Map.class }, + { String.class, Class.class }, + { String.class, Class.class, Map.class } + }; + + StringBuilder signature = new StringBuilder(Long.SIZE); + for (Class[] paramTypes : params) { + signature.setLength(0); + signature.append('('); + for (Class p : paramTypes) { + signature.append(Native.getSignature(p)); + } + signature.append(')'); + + try { + Method m = Native.class.getMethod("loadLibrary", paramTypes); + Class returnType = m.getReturnType(); + signature.append(Native.getSignature(returnType)); + assertSame("Mismatched return type for signature=" + signature, Object.class, returnType); +// System.out.println("===>" + m.getName() + ": " + signature); + } catch(NoSuchMethodError err) { + fail("No method for signature=" + signature); + } + } + } public void testVersion() { String[] INPUTS = { "1.0", "1.0.1", "2.1.3" }; float[] EXPECTED = { 1.0f, 1.0f, 2.1f }; @@ -55,9 +84,9 @@ public void testCustomStringEncoding() throws Exception { // Keep stuff within the extended ASCII range so we work with more // limited native encodings String UNICODE = "Un \u00e9l\u00e9ment gr\u00e2ce \u00e0 l'index"; - + if (!UNICODE.equals(new String(UNICODE.getBytes()))) { - // If the extended characters aren't encodable in the default + // If the extended characters aren't encodable in the default // encoding, punt and use straight ASCII UNICODE = ""; for (char ch=1;ch < 128;ch++) { @@ -65,23 +94,23 @@ public void testCustomStringEncoding() throws Exception { } } final String UNICODEZ = UNICODE + "\0more stuff"; - + byte[] customEncoded = Native.getBytes(UNICODE, ENCODING); byte[] expected = UNICODE.getBytes(ENCODING); for (int i=0;i < Math.min(customEncoded.length, expected.length);i++) { - assertEquals("Improperly encoded (" + ENCODING + ") from Java at " + i, + assertEquals("Improperly encoded (" + ENCODING + ") from Java at " + i, expected[i], customEncoded[i]); } - assertEquals("Wrong number of encoded characters (" + ENCODING + ")", + assertEquals("Wrong number of encoded characters (" + ENCODING + ")", expected.length, customEncoded.length); String result = Native.toString(customEncoded, ENCODING); - assertEquals("Improperly decoded from native bytes (" + ENCODING + ")", + assertEquals("Improperly decoded from native bytes (" + ENCODING + ")", UNICODE, result); - + assertEquals("Should truncate bytes at NUL terminator", UNICODE, Native.toString(UNICODEZ.getBytes(ENCODING), ENCODING)); } - + public void testToStringList() { List expected = Arrays.asList(getClass().getPackage().getName(), getClass().getSimpleName(), "testToStringList"); StringBuilder sb = new StringBuilder(); @@ -89,7 +118,7 @@ public void testToStringList() { sb.append(value).append('\0'); } sb.append('\0'); - + List actual = Native.toStringList(sb.toString().toCharArray()); assertEquals("Mismatched result size", expected.size(), actual.size()); for (int index = 0; index < expected.size(); index++) { @@ -105,17 +134,17 @@ public void testDefaultStringEncoding() throws Exception { byte[] utf8 = Native.getBytes(UNICODE); byte[] expected = UNICODE.getBytes(Native.DEFAULT_ENCODING); for (int i=0;i < Math.min(utf8.length, expected.length);i++) { - assertEquals("Improperly encoded at " + i, + assertEquals("Improperly encoded at " + i, expected[i], utf8[i]); } assertEquals("Wrong number of encoded characters", expected.length, utf8.length); String result = Native.toString(utf8); assertEquals("Improperly decoded", UNICODE, result); - + assertEquals("Should truncate bytes at NUL terminator", UNICODE, Native.toString(UNICODEZ.getBytes(Native.DEFAULT_ENCODING))); } - + public void testCustomizeDefaultStringEncoding() { Properties oldprops = (Properties)System.getProperties().clone(); final String ENCODING = System.getProperty("file.encoding"); @@ -137,14 +166,16 @@ interface VoidCallback extends Callback { public void testSynchronizedAccess() throws Exception { final boolean[] lockHeld = { false }; final NativeLibrary nlib = NativeLibrary.getInstance("testlib", TestLib.class.getClassLoader()); - final TestLib lib = (TestLib)Native.loadLibrary("testlib", TestLib.class); - final TestLib synchlib = (TestLib)Native.synchronizedLibrary(lib); + final TestLib lib = Native.loadLibrary("testlib", TestLib.class); + final TestLib synchlib = (TestLib)Native.synchronizedLibrary(lib); final TestLib.VoidCallback cb = new TestLib.VoidCallback() { + @Override public void callback() { lockHeld[0] = Thread.holdsLock(nlib); } }; Thread t0 = new Thread() { + @Override public void run() { lib.callVoidCallback(cb); } @@ -155,6 +186,7 @@ public void run() { lockHeld[0]); Thread t1 = new Thread() { + @Override public void run() { synchlib.callVoidCallback(cb); } @@ -169,12 +201,13 @@ interface TestInterface extends Library { static class InnerTestClass extends Structure { interface TestCallback extends Callback { } static class InnerSubclass extends InnerTestClass implements Structure.ByReference { } - protected List getFieldOrder() { + @Override + protected List getFieldOrder() { return Collections.EMPTY_LIST; } } } - + public void testFindInterfaceClass() throws Exception { Class interfaceClass = TestInterface.class; Class cls = TestInterface.InnerTestClass.class; @@ -198,26 +231,25 @@ public interface TestInterfaceWithInstance extends Library { put(OPTION_STRUCTURE_ALIGNMENT, new Integer(TEST_ALIGNMENT)); put(OPTION_STRING_ENCODING, TEST_ENCODING); }}; - TestInterfaceWithInstance ARBITRARY = (TestInterfaceWithInstance) - Native.loadLibrary("testlib", TestInterfaceWithInstance.class, TEST_OPTS); + TestInterfaceWithInstance ARBITRARY = Native.loadLibrary("testlib", TestInterfaceWithInstance.class, TEST_OPTS); abstract class TestStructure extends Structure {} } public void testOptionsInferenceFromInstanceField() { Class[] classes = { TestInterfaceWithInstance.class, TestInterfaceWithInstance.TestStructure.class }; String[] desc = { "interface", "structure from interface" }; for (int i=0;i < classes.length;i++) { - assertEquals("Wrong type mapper found for " + desc[i], + assertEquals("Wrong type mapper found for " + desc[i], TestInterfaceWithInstance.TEST_MAPPER, Native.getTypeMapper(classes[i])); - assertEquals("Wrong alignment found for " + desc[i], + assertEquals("Wrong alignment found for " + desc[i], TestInterfaceWithInstance.TEST_ALIGNMENT, Native.getStructureAlignment(classes[i])); - assertEquals("Wrong string encoding found for " + desc[i], + assertEquals("Wrong string encoding found for " + desc[i], TestInterfaceWithInstance.TEST_ENCODING, Native.getStringEncoding(classes[i])); } } - + public interface TestInterfaceWithOptions extends Library { int TEST_ALIGNMENT = Structure.ALIGN_NONE; TypeMapper TEST_MAPPER = new DefaultTypeMapper(); @@ -232,13 +264,13 @@ abstract class TestStructure extends Structure {} public void testOptionsInferenceFromOptionsField() { Class[] classes = { TestInterfaceWithOptions.class, TestInterfaceWithOptions.TestStructure.class }; for (int i=0;i < classes.length;i++) { - assertEquals("Wrong type mapper found", + assertEquals("Wrong type mapper found", TestInterfaceWithOptions.TEST_MAPPER, Native.getTypeMapper(classes[i])); - assertEquals("Wrong alignment found", + assertEquals("Wrong alignment found", TestInterfaceWithOptions.TEST_ALIGNMENT, Native.getStructureAlignment(classes[i])); - assertEquals("Wrong encoding found", + assertEquals("Wrong encoding found", TestInterfaceWithOptions.TEST_ENCODING, Native.getStringEncoding(classes[i])); } @@ -250,10 +282,10 @@ public interface TestInterfaceWithTypeMapper extends Library { abstract class TestStructure extends Structure { } } public void testOptionsInferenceFromTypeMapperField() { - assertEquals("Wrong type mapper found for interface which provides TYPE_MAPPER", + assertEquals("Wrong type mapper found for interface which provides TYPE_MAPPER", TestInterfaceWithTypeMapper.TEST_MAPPER, Native.getTypeMapper(TestInterfaceWithTypeMapper.class)); - assertEquals("Wrong type mapper found for structure from interface which provides TYPE_MAPPER", + assertEquals("Wrong type mapper found for structure from interface which provides TYPE_MAPPER", TestInterfaceWithTypeMapper.TEST_MAPPER, Native.getTypeMapper(TestInterfaceWithTypeMapper.TestStructure.class)); } @@ -263,10 +295,10 @@ public interface TestInterfaceWithAlignment extends Library { abstract class TestStructure extends Structure { } } public void testOptionsInferenceFromAlignmentField() { - assertEquals("Wrong alignment found for interface which provides STRUCTURE_ALIGNMENT", + assertEquals("Wrong alignment found for interface which provides STRUCTURE_ALIGNMENT", Structure.ALIGN_NONE, Native.getStructureAlignment(TestInterfaceWithAlignment.class)); - assertEquals("Wrong alignment found for structure from interface which provides STRUCTURE_ALIGNMENT", + assertEquals("Wrong alignment found for structure from interface which provides STRUCTURE_ALIGNMENT", Structure.ALIGN_NONE, Native.getStructureAlignment(TestInterfaceWithAlignment.TestStructure.class)); } @@ -276,10 +308,10 @@ public interface TestInterfaceWithEncoding extends Library { abstract class TestStructure extends Structure { } } public void testOptionsInferenceFromEncodingField() { - assertEquals("Wrong encoding found for interface which provides STRING_ENCODING", + assertEquals("Wrong encoding found for interface which provides STRING_ENCODING", TestInterfaceWithEncoding.STRING_ENCODING, Native.getStringEncoding(TestInterfaceWithEncoding.class)); - assertEquals("Wrong encoding found for structure from interface which provides STRING_ENCODING", + assertEquals("Wrong encoding found for structure from interface which provides STRING_ENCODING", TestInterfaceWithEncoding.STRING_ENCODING, Native.getStringEncoding(TestInterfaceWithEncoding.TestStructure.class)); } @@ -289,13 +321,14 @@ public interface OptionsBase extends Library { TypeMapper TYPE_MAPPER = new DefaultTypeMapper(); class TypeMappedStructure extends Structure { public String stringField; + @Override protected List getFieldOrder() { return Arrays.asList("stringField"); } } } public interface OptionsSubclass extends OptionsBase, Library { TypeMapper _MAPPER = new DefaultTypeMapper(); Map _OPTIONS = new HashMap() { { put(Library.OPTION_TYPE_MAPPER, _MAPPER); } }; - OptionsSubclass INSTANCE = (OptionsSubclass)Native.loadLibrary("testlib", OptionsSubclass.class, _OPTIONS); + OptionsSubclass INSTANCE = Native.loadLibrary("testlib", OptionsSubclass.class, _OPTIONS); } public void testStructureOptionsInference() { Structure s = new OptionsBase.TypeMappedStructure(); @@ -422,18 +455,18 @@ public static void main(String[] args) { "com.sun.jna.NativeLibraryTest", "com.sun.jna.PointerTest", "com.sun.jna.MemoryTest", - "com.sun.jna.LibraryLoadTest", + "com.sun.jna.LibraryLoadTest", "com.sun.jna.ArgumentsMarshalTest", "com.sun.jna.ReturnTypesTest", - "com.sun.jna.TypeMapperTest", + "com.sun.jna.TypeMapperTest", "com.sun.jna.ByReferenceArgumentsTest", - "com.sun.jna.LastErrorTest", + "com.sun.jna.LastErrorTest", "com.sun.jna.StructureTest",// 1 wce failure (RO fields) "com.sun.jna.StructureByValueTest", "com.sun.jna.UnionTest", - "com.sun.jna.IntegerTypeTest", + "com.sun.jna.IntegerTypeTest", "com.sun.jna.VMCrashProtectionTest", - "com.sun.jna.CallbacksTest", + "com.sun.jna.CallbacksTest", "com.sun.jna.JNAUnloadTest", "com.sun.jna.DirectTest", "com.sun.jna.DirectArgumentsMarshalTest", diff --git a/test/com/sun/jna/PerformanceTest.java b/test/com/sun/jna/PerformanceTest.java index f8dd5ee3fb..926d6b3fbf 100644 --- a/test/com/sun/jna/PerformanceTest.java +++ b/test/com/sun/jna/PerformanceTest.java @@ -13,16 +13,13 @@ package com.sun.jna; import junit.framework.*; -import com.sun.jna.*; -import com.sun.jna.ptr.PointerByReference; -import java.lang.ref.*; import java.io.File; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Map; import java.util.HashMap; -import java.lang.reflect.Method; +import java.lang.reflect.Method; import com.sun.jna.DirectTest.TestInterface; import com.sun.jna.DirectTest.TestLibrary; @@ -40,7 +37,7 @@ private static class JNILibrary { } System.load(path); } - + private static native double cos(double x); private static native int getpid(); } @@ -52,7 +49,7 @@ public static void main(java.lang.String[] argList) { static class MathLibrary { public static native double cos(double x); - + static { Native.register(Platform.MATH_LIBRARY_NAME); } @@ -81,7 +78,7 @@ public size_t(long value) { public static native int strlen(Pointer p); public static native int strlen(byte[] b); public static native int strlen(Buffer b); - + static { Native.register(Platform.C_LIBRARY_NAME); } @@ -120,8 +117,7 @@ public static void checkPerformance() { Pointer pb = Native.getDirectBufferPointer(b); String mname = Platform.MATH_LIBRARY_NAME; - MathInterface mlib = (MathInterface) - Native.loadLibrary(mname, MathInterface.class); + MathInterface mlib = Native.loadLibrary(mname, MathInterface.class); Function f = NativeLibrary.getInstance(mname).getFunction("cos"); /////////////////////////////////////////// @@ -204,17 +200,17 @@ public static void checkPerformance() { Map options = new HashMap(); if (Platform.isWindows()) { options.put(Library.OPTION_FUNCTION_MAPPER, new FunctionMapper() { + @Override public String getFunctionName(NativeLibrary library, Method method) { String name = method.getName(); - if ("getpid".equals(name)) { + if ("getpid".equals(name)) { name = "_getpid"; } return name; } }); } - CInterface clib = (CInterface) - Native.loadLibrary(cname, CInterface.class, options); + CInterface clib = Native.loadLibrary(cname, CInterface.class, options); /////////////////////////////////////////// // getpid @@ -473,9 +469,10 @@ public String getFunctionName(NativeLibrary library, Method method) { /////////////////////////////////////////// // Callbacks - TestInterface tlib = (TestInterface)Native.loadLibrary("testlib", TestInterface.class); + TestInterface tlib = Native.loadLibrary("testlib", TestInterface.class); start = System.currentTimeMillis(); TestInterface.Int32Callback cb = new TestInterface.Int32Callback() { + @Override public int invoke(int arg1, int arg2) { return arg1 + arg2; } @@ -492,6 +489,7 @@ public int invoke(int arg1, int arg2) { start = System.currentTimeMillis(); TestInterface.NativeLongCallback nlcb = new TestInterface.NativeLongCallback() { + @Override public NativeLong invoke(NativeLong arg1, NativeLong arg2) { return new NativeLong(arg1.longValue() + arg2.longValue()); } diff --git a/test/com/sun/jna/ReturnTypesTest.java b/test/com/sun/jna/ReturnTypesTest.java index 895eb4332d..c8a31f4446 100644 --- a/test/com/sun/jna/ReturnTypesTest.java +++ b/test/com/sun/jna/ReturnTypesTest.java @@ -8,7 +8,7 @@ * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna; @@ -34,26 +34,29 @@ public class ReturnTypesTest extends TestCase { private static final float FLOAT_MAGIC = -118.625f; public static interface TestLibrary extends Library { - + public static class SimpleStructure extends Structure { public double value; public static int allocations = 0; public SimpleStructure() { } public SimpleStructure(Pointer p) { super(p); read(); } + @Override protected void allocateMemory(int size) { super.allocateMemory(size); ++allocations; } + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "value" }); } } - + public static class TestSmallStructure extends Structure { public static class ByValue extends TestSmallStructure implements Structure.ByValue { } public byte c1; public byte c2; public short s; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "c1", "c2", "s" }); } @@ -66,18 +69,20 @@ public static class ByValue extends TestStructure implements Structure.ByValue { public int i; public long j; public SimpleStructure inner; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "c", "s", "i", "j", "inner" }); } } - + class CheckFieldAlignment extends Structure { public int int32Field = 1; public long int64Field = 2; public float floatField = 3f; public double doubleField = 4d; + @Override protected List getFieldOrder() { - return Arrays.asList(new String[] { "int32Field", "int64Field", "floatField", "doubleField" }); + return Arrays.asList(new String[] { "int32Field", "int64Field", "floatField", "doubleField" }); } } @@ -109,28 +114,31 @@ class TestObject { } } TestLibrary lib; + @Override protected void setUp() { - lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + lib = Native.loadLibrary("testlib", TestLibrary.class); } - + + @Override protected void tearDown() { lib = null; } - + public void testReturnObject() throws Exception { Map options = new HashMap() { { put(Library.OPTION_ALLOW_OBJECTS, Boolean.TRUE); }}; - lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class, options); + lib = Native.loadLibrary("testlib", TestLibrary.class, options); assertNull("null value not returned", lib.returnObjectArgument(null)); final Object VALUE = new Object() { + @Override public String toString() { return getName(); } }; assertEquals("Wrong object returned", VALUE, lib.returnObjectArgument(VALUE)); } - + public void testReturnObjectUnsupported() throws Exception { try { lib.returnObjectArgument(new TestLibrary.TestObject()); @@ -152,30 +160,30 @@ public void testInvokeBoolean() { public void testInvokeInt() { assertEquals("Expect 32-bit zero", 0, lib.returnInt32Zero()); - assertEquals("Expect 32-bit magic", - "12345678", + assertEquals("Expect 32-bit magic", + "12345678", Integer.toHexString(lib.returnInt32Magic())); } public void testInvokeLong() { assertEquals("Expect 64-bit zero", 0L, lib.returnInt64Zero()); - assertEquals("Expect 64-bit magic", - "123456789abcdef0", + assertEquals("Expect 64-bit magic", + "123456789abcdef0", Long.toHexString(lib.returnInt64Magic())); } - + public void testInvokeNativeLong() { if (NativeLong.SIZE == 4) { assertEquals("Expect 32-bit zero", new NativeLong(0), lib.returnLongZero()); - assertEquals("Expect 32-bit magic", - "12345678", + assertEquals("Expect 32-bit magic", + "12345678", Integer.toHexString(lib.returnLongMagic().intValue())); - + } else { - assertEquals("Expect 64-bit zero", new NativeLong(0L), + assertEquals("Expect 64-bit zero", new NativeLong(0L), lib.returnLongZero()); - assertEquals("Expect 64-bit magic", - "123456789abcdef0", + assertEquals("Expect 64-bit magic", + "123456789abcdef0", Long.toHexString(lib.returnLongMagic().longValue())); } } @@ -200,22 +208,25 @@ public Custom() { } public Custom(int value) { this.value = value; } + @Override public Object fromNative(Object nativeValue, FromNativeContext context) { return new Custom(((Integer)nativeValue).intValue()); } + @Override public Class nativeType() { return Integer.class; } + @Override public Object toNative() { return new Integer(value); } + @Override public boolean equals(Object o) { return o instanceof Custom && ((Custom)o).value == value; } } protected NativeMappedLibrary loadNativeMappedLibrary() { - return (NativeMappedLibrary) - Native.loadLibrary("testlib", NativeMappedLibrary.class); + return Native.loadLibrary("testlib", NativeMappedLibrary.class); } public void testInvokeNativeMapped() { @@ -224,24 +235,24 @@ public void testInvokeNativeMapped() { final long MAGIC64 = 0x123456789ABCDEF0L; final Custom EXPECTED = new Custom(MAGIC); assertEquals("NativeMapped 'Custom' result not mapped", EXPECTED, lib.returnInt32Argument(MAGIC)); - - assertEquals("NativeMapped IntegerType result not mapped (32)", + + assertEquals("NativeMapped IntegerType result not mapped (32)", new size_t(MAGIC), lib.returnInt32Magic()); if (Native.SIZE_T_SIZE == 8) { - assertEquals("NativeMapped IntegerType result not mapped (64)", + assertEquals("NativeMapped IntegerType result not mapped (64)", new size_t(MAGIC64), lib.returnInt64Magic()); } } public void testInvokeFloat() { assertEquals("Expect float zero", 0f, lib.returnFloatZero(), 0d); - assertEquals("Expect float magic", + assertEquals("Expect float magic", FLOAT_MAGIC, lib.returnFloatMagic(), 0d); } public void testInvokeDouble() { assertEquals("Expect double zero", 0d, lib.returnDoubleZero(), 0d); - assertEquals("Expect double magic", + assertEquals("Expect double magic", DOUBLE_MAGIC, lib.returnDoubleMagic(), 0d); } @@ -249,26 +260,26 @@ public void testInvokeDouble() { public void testInvokeString() { assertEquals("Expect String magic", MAGIC, lib.returnStringMagic()); } - + public void testInvokeWString() { WString s = lib.returnWStringMagic(); assertEquals("Wrong length", MAGIC.length(), s.toString().length()); assertEquals("Expect WString magic", new WString(MAGIC), s); } - + public void testInvokeStructure() { SimpleStructure.allocations = 0; SimpleStructure s = lib.returnStaticTestStructure(); assertEquals("Expect test structure magic", DOUBLE_MAGIC, s.value, 0d); - // Optimized structure allocation + // Optimized structure allocation assertEquals("Returned Structure should allocate no memory", 0, SimpleStructure.allocations); } - + public void testInvokeNullStructure() { SimpleStructure s = lib.returnNullTestStructure(); assertNull("Expect null structure return", s); } - + public void testReturnSmallStructureByValue() { TestSmallStructure s = lib.returnSmallStructureByValue(); assertNotNull("Returned structure must not be null", s); @@ -276,7 +287,7 @@ public void testReturnSmallStructureByValue() { assertEquals("Wrong char field value (2)", 2, s.c2); assertEquals("Wrong short field value", 3, s.s); } - + public void testReturnStructureByValue() { TestStructure s = lib.returnStructureByValue(); assertNotNull("Returned structure must not be null", s); @@ -288,7 +299,7 @@ public void testReturnStructureByValue() { assertNotNull("Structure not initialized", s.inner); assertEquals("Wrong inner structure value", 5, s.inner.value, 0); } - + public void testReturnPointerArray() { Pointer value = new Memory(10); Pointer[] input = { @@ -328,5 +339,5 @@ public void testReturnWStringArray() { public static void main(java.lang.String[] argList) { junit.textui.TestRunner.run(ReturnTypesTest.class); } - + } diff --git a/test/com/sun/jna/StructureByValueTest.java b/test/com/sun/jna/StructureByValueTest.java index fe3b84d723..698909a526 100644 --- a/test/com/sun/jna/StructureByValueTest.java +++ b/test/com/sun/jna/StructureByValueTest.java @@ -27,6 +27,7 @@ public static void main(java.lang.String[] argList) { public static class TestNativeMappedInStructure extends Structure { public static class ByValue extends TestNativeMappedInStructure implements Structure.ByValue { } public NativeLong field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -45,10 +46,12 @@ public interface TestLibrary extends Library { TestLibrary lib; + @Override protected void setUp() { - lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + lib = Native.loadLibrary("testlib", TestLibrary.class); } + @Override protected void tearDown() { lib = null; } @@ -56,30 +59,35 @@ protected void tearDown() { public static abstract class ByValueStruct extends Structure implements Structure.ByValue { } public static class ByValue8 extends ByValueStruct { public byte data; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "data" }); } } public static class ByValue16 extends ByValueStruct { public short data; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "data" }); } } public static class ByValue32 extends ByValueStruct { public int data; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "data" }); } } public static class ByValue64 extends ByValueStruct { public long data; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "data" }); } } public static class ByValue128 extends ByValueStruct { public long data, data1; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "data", "data1" }); } diff --git a/test/com/sun/jna/StructureTest.java b/test/com/sun/jna/StructureTest.java index bc8064a5ca..33ac7f8396 100644 --- a/test/com/sun/jna/StructureTest.java +++ b/test/com/sun/jna/StructureTest.java @@ -16,8 +16,6 @@ import java.util.Arrays; import java.util.List; import java.util.Map; -import java.util.Set; - import junit.framework.TestCase; import com.sun.jna.Structure.StructureSet; @@ -40,6 +38,7 @@ public static void main(java.lang.String[] argList) { public void testSimpleSize() throws Exception { class TestStructure extends Structure { public int field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -51,6 +50,7 @@ protected List getFieldOrder() { public void testInitializeFromPointer() { class TestStructureX extends Structure { public int field1, field2; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field1", "field2" }); } @@ -73,6 +73,7 @@ public TestStructureX(Pointer p) { public void testInitializeWithTypeMapper() { class TestStructure extends Structure { public int field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -91,6 +92,7 @@ public static class TestAllocStructure extends Structure { public int f1; public int f2; public int f3; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "f0", "f1", "f2", "f3" }); } @@ -102,6 +104,7 @@ class TestStructure extends Structure { public TestStructure() { } public TestStructure(Pointer p) { super(p); } public int field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -118,6 +121,7 @@ public void testProvidedMemoryTooSmall() { class TestStructure extends Structure { public TestStructure(Pointer p) { super(p); } public int field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -154,6 +158,7 @@ class TestStructure extends Structure { public long l; public float f; public double d; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "b", "s", "i", "l", "f", "d" }); } @@ -173,6 +178,7 @@ class TestStructure extends Structure { public long l; public float f; public double d; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "b", "s", "i", "l", "f", "d" }); } @@ -184,6 +190,7 @@ protected List getFieldOrder() { public static abstract class FilledStructure extends Structure { private boolean initialized; + @Override protected void ensureAllocated() { super.ensureAllocated(); if (!initialized) { @@ -198,6 +205,7 @@ protected void ensureAllocated() { public static class TestStructure0 extends FilledStructure { public byte field0 = 0x01; public short field1 = 0x0202; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field0", "field1" }); } @@ -205,6 +213,7 @@ protected List getFieldOrder() { public static class TestStructure1 extends FilledStructure { public byte field0 = 0x01; public int field1 = 0x02020202; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field0", "field1" }); } @@ -212,6 +221,7 @@ protected List getFieldOrder() { public static class TestStructure2 extends FilledStructure { public short field0 = 0x0101; public int field1 = 0x02020202; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field0", "field1" }); } @@ -220,6 +230,7 @@ public static class TestStructure3 extends FilledStructure { public int field0 = 0x01010101; public short field1 = 0x0202; public int field2 = 0x03030303; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field0", "field1", "field2" }); } @@ -229,6 +240,7 @@ public static class TestStructure4 extends FilledStructure { public long field1 = 0x0202020202020202L; public int field2 = 0x03030303; public long field3 = 0x0404040404040404L; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field0", "field1", "field2", "field3" }); } @@ -236,6 +248,7 @@ protected List getFieldOrder() { public static class TestStructure5 extends FilledStructure { public long field0 = 0x0101010101010101L; public byte field1 = 0x02; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field0", "field1" }); } @@ -245,7 +258,7 @@ public interface SizeTest extends Library { } private void testStructureSize(int index) { try { - SizeTest lib = (SizeTest)Native.loadLibrary("testlib", SizeTest.class); + SizeTest lib = Native.loadLibrary("testlib", SizeTest.class); Class cls = Class.forName(getClass().getName() + "$TestStructure" + index); Structure s = Structure.newInstance(cls); assertEquals("Incorrect size for structure " + index + "=>" + s.toString(true), lib.getStructureSize(index), s.size()); @@ -279,7 +292,7 @@ int testStructureAlignment(Structure s, int type, } private void testAlignStruct(int index) { - AlignmentTest lib = (AlignmentTest)Native.loadLibrary("testlib", AlignmentTest.class); + AlignmentTest lib = Native.loadLibrary("testlib", AlignmentTest.class); try { IntByReference offset = new IntByReference(); LongByReference value = new LongByReference(); @@ -316,6 +329,7 @@ public void testAlignStruct5() { public void testStructureWithNoFields() { class TestStructure extends Structure { + @Override protected List getFieldOrder() { return Arrays.asList(new String[] {}); } @@ -331,6 +345,7 @@ protected List getFieldOrder() { public void testStructureWithOnlyNonPublicMemberFields() { class TestStructure extends Structure { int field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] {"field"}); } @@ -357,10 +372,12 @@ public ByReference() { } public PublicTestStructure() { } public PublicTestStructure(Pointer p) { super(p); read(); } public static int allocations = 0; + @Override protected void allocateMemory(int size) { super.allocateMemory(size); ++allocations; } + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "x", "y" }); } @@ -369,6 +386,7 @@ public void testStructureField() { class TestStructure extends Structure { public PublicTestStructure s1, s2; public int after; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "s1", "s2", "after" }); } @@ -398,6 +416,7 @@ public void testStructureByValueField() { class TestStructure extends Structure { public PublicTestStructure.ByValue s1, s2; public int after; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "s1", "s2", "after" }); } @@ -433,6 +452,7 @@ class TestStructure extends Structure { public long s_long; public TestUnion s_union; public int s_int; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "s_long", "s_union", "s_int" }); } @@ -445,6 +465,7 @@ protected List getFieldOrder() { public static class NonAllocatingTestStructure extends PublicTestStructure { public NonAllocatingTestStructure() { } public NonAllocatingTestStructure(Pointer p) { super(p); read(); } + @Override protected void allocateMemory(int size) { throw new Error("Memory unexpectedly allocated"); } @@ -458,6 +479,7 @@ public void testStructureFieldAvoidsSeparateMemoryAllocation() { class TestStructure extends Structure { public NonAllocatingTestStructure s1; public TestStructure() { } + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "s1" }); } @@ -469,6 +491,7 @@ protected List getFieldOrder() { public void testPrimitiveArrayField() { class TestStructure extends Structure { public byte[] buffer = new byte[1024]; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "buffer" }); } @@ -490,6 +513,7 @@ class TestStructure extends Structure { // initialized array elements public PublicTestStructure[] inner2 = (PublicTestStructure[]) new PublicTestStructure().toArray(2); + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "inner", "inner2" }); } @@ -532,6 +556,7 @@ protected List getFieldOrder() { public static class ToArrayTestStructure extends Structure { public PublicTestStructure[] inner = (PublicTestStructure[])new PublicTestStructure().toArray(2); + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "inner" }); } @@ -550,6 +575,7 @@ public void testToArrayWithStructureArrayField() { public void testUninitializedNestedArrayFails() { class TestStructure extends Structure { public Pointer[] buffer; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "buffer" }); } @@ -585,6 +611,7 @@ public TestStructure() { public float[] fa = new float[3]; public double[] da = new double[3]; public PublicTestStructure nested; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "z", "b", "c", "s", "i", "l", "f", "d", "ba", "ca", "sa", "ia", "la", "fa", "da", "nested" }); } @@ -645,6 +672,7 @@ protected List getFieldOrder() { public void testNativeLongSize() throws Exception { class TestStructure extends Structure { public NativeLong l; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "l" }); } @@ -657,6 +685,7 @@ public void testNativeLongRead() throws Exception { class TestStructure extends Structure { public int i; public NativeLong l; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "i", "l" }); } @@ -680,6 +709,7 @@ public void testNativeLongWrite() throws Exception { class TestStructure extends Structure { public int i; public NativeLong l; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "i", "l" }); } @@ -704,6 +734,7 @@ protected List getFieldOrder() { public void testMemoryField() { class MemoryFieldStructure extends Structure { public Memory m; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "m" }); } @@ -714,6 +745,7 @@ protected List getFieldOrder() { public void testDisallowFunctionPointerAsField() { class BadFieldStructure extends Structure { public Function cb; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "cb" }); } @@ -728,6 +760,7 @@ protected List getFieldOrder() { public static class BadFieldStructure extends Structure { public Object badField; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "badField" }); } @@ -735,6 +768,7 @@ protected List getFieldOrder() { public void testUnsupportedField() { class BadNestedStructure extends Structure { public BadFieldStructure badStruct = new BadFieldStructure(); + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "badStruct" }); } @@ -782,6 +816,7 @@ public void testByReferenceArraySync() { (PublicTestStructure.ByReference[])s.toArray(2); class TestStructure extends Structure { public PublicTestStructure.ByReference ref; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "ref" }); } @@ -808,6 +843,7 @@ protected List getFieldOrder() { static class CbStruct extends Structure { public Callback cb; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "cb" }); } @@ -830,6 +866,7 @@ public void callback() { public void testUninitializedArrayField() { class UninitializedArrayFieldStructure extends Structure { public byte[] array; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "array" }); } @@ -845,6 +882,7 @@ protected List getFieldOrder() { public static class StructureWithArrayOfStructureField extends Structure { public Structure[] array; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "array" }); } @@ -865,6 +903,7 @@ public void testPointerArrayField() { class ArrayOfPointerStructure extends Structure { final static int SIZE = 10; public Pointer[] array = new Pointer[SIZE]; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "array" }); } @@ -883,6 +922,7 @@ public void testVolatileStructureField() { class VolatileStructure extends Structure { public volatile int counter; public int value; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "counter", "value" }); } @@ -906,6 +946,7 @@ protected List getFieldOrder() { public static class StructureWithPointers extends Structure { public PublicTestStructure.ByReference s1; public PublicTestStructure.ByReference s2; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "s1", "s2" }); } @@ -951,6 +992,7 @@ class TestStructure extends Structure { public TestPointer p2 = new TestPointer() { { setPointer(new Memory(256)); } }; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "p", "p2" }); } @@ -970,6 +1012,7 @@ public void testPreserveStringFields() { class TestStructure extends Structure { public String s; public WString ws; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "s", "ws" }); } @@ -995,6 +1038,7 @@ protected List getFieldOrder() { public static class StructureFromPointer extends Structure { public String s; public WString ws; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "s", "ws" }); } @@ -1009,6 +1053,7 @@ public StructureFromPointer() { public void testInitializeStructureFieldWithStrings() { class ContainingStructure extends Structure { public StructureFromPointer inner; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "inner" }); } @@ -1058,6 +1103,7 @@ public void testAutoWriteStructureByReferenceField() { public void testStructureByReferenceArrayField() { class TestStructure extends Structure { public PublicTestStructure.ByReference[] array = new PublicTestStructure.ByReference[2]; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "array" }); } @@ -1088,6 +1134,7 @@ protected List getFieldOrder() { public void testAutoReadWriteStructureByReferenceArrayField() { class TestStructure extends Structure { public PublicTestStructure.ByReference field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -1111,12 +1158,14 @@ protected List getFieldOrder() { static class NestedTypeInfoStructure extends Structure { public static class Inner extends Structure { public int dummy; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "dummy" }); } } public Inner inner; public int dummy; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "inner", "dummy" }); } @@ -1135,6 +1184,7 @@ class TestFFIType extends Structure { public short alignment; public short type; public Pointer elements; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "size", "alignment", "type", "elements" }); } @@ -1170,6 +1220,7 @@ public void testNestedStructureTypeInfo() { public void testInnerArrayTypeInfo() { class TestStructure extends Structure { public int[] inner = new int[5]; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "inner" }); } @@ -1195,6 +1246,7 @@ public void testToString() { class TestStructure extends Structure { public int intField; public PublicTestStructure inner; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "intField", "inner" }); } @@ -1226,6 +1278,7 @@ protected List getFieldOrder() { public void testNativeMappedWrite() { class TestStructure extends Structure { public ByteByReference ref; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "ref" }); } @@ -1243,6 +1296,7 @@ protected List getFieldOrder() { public void testNativeMappedRead() { class TestStructure extends Structure { public ByteByReference ref; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "ref" }); } @@ -1263,6 +1317,7 @@ protected List getFieldOrder() { public static class ROStructure extends Structure { public final int field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -1313,6 +1368,7 @@ public void testNativeMappedArrayField() { final int SIZE = 24; class TestStructure extends Structure { public NativeLong[] longs = new NativeLong[SIZE]; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "longs" }); } @@ -1349,6 +1405,7 @@ class TestStructure extends Structure { { setAlignType(ALIGN_NONE); } public NativeLong nl = INITIAL; public NativeLong uninitialized; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "nl", "uninitialized" }); } @@ -1372,6 +1429,7 @@ protected List getFieldOrder() { public void testThrowErrorOnMissingFieldOrderOnDerivedStructure() { class TestStructure extends Structure { public int f1, f2; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "f1", "f2" }); } @@ -1390,6 +1448,7 @@ class TestStructure2 extends TestStructure { public void testThrowErrorOnIncorrectFieldOrderNameMismatch() { class TestStructure extends Structure { public int f1, f2; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "F1", "F2" }); } @@ -1405,6 +1464,7 @@ protected List getFieldOrder() { public void testThrowErrorOnIncorrectFieldOrderCount() { class TestStructure extends Structure { public int f1, f2; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "f1", "f2", "f3" }); } @@ -1419,12 +1479,14 @@ protected List getFieldOrder() { class XTestStructure extends Structure { public int first = 1; - protected List getFieldOrder() { + @Override + protected List getFieldOrder() { return Arrays.asList(new String[] { "first" }); } } class XTestStructureSub extends XTestStructure { public int second = 2; - protected List getFieldOrder() { + @Override + protected List getFieldOrder() { List list = new ArrayList(super.getFieldOrder()); list.addAll(Arrays.asList(new String[] { "second" })); return list; @@ -1447,6 +1509,7 @@ class TestStructure extends Structure { public int one = 1; public int three = 3; public int two = 2; + @Override protected List getFieldOrder() { return Arrays.asList(ORDER); } @@ -1454,6 +1517,7 @@ protected List getFieldOrder() { class DerivedTestStructure extends TestStructure { public int five = 5; public int four = 4; + @Override protected List getFieldOrder() { List list = new ArrayList(super.getFieldOrder()); list.addAll(Arrays.asList(new String[] { "four", "five" })); @@ -1493,12 +1557,15 @@ class TestField { } final DefaultTypeMapper mapper = new DefaultTypeMapper() { { addTypeConverter(TestField.class, new TypeConverter() { + @Override public Object fromNative(Object value, FromNativeContext context) { return new TestField(); } + @Override public Class nativeType() { return String.class; } + @Override public Object toNative(Object value, ToNativeContext ctx) { return value == null ? null : value.toString(); } @@ -1510,6 +1577,7 @@ class TestStructure extends Structure { public TestStructure() { super(mapper); } + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -1522,6 +1590,7 @@ public void testWriteWithNullBoxedPrimitives() { class TestStructure extends Structure { public Boolean zfield; public Integer field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "zfield", "field" }); } @@ -1537,6 +1606,7 @@ class OtherStructure extends Structure { public int first; public int[] second = new int[4]; public Pointer[] third = new Pointer[4]; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "first", "second", "third" }); } @@ -1545,6 +1615,7 @@ class TestStructure extends Structure { public int first; public int[] second = new int[4]; public Pointer[] third = new Pointer[4]; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "first", "second", "third" }); } @@ -1571,6 +1642,7 @@ public TestStructure() { } public void testStructureHashCodeMatchesWhenEqual() { class TestStructure extends Structure { public int first; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "first" }); } @@ -1594,6 +1666,7 @@ class TestStructureByRef extends Structure implements Structure.ByReference{ public TestStructureByRef() { } public int unique; public TestStructureByRef s; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "unique", "s" }); } @@ -1627,6 +1700,7 @@ public static class ByReference extends CyclicTestStructure implements Structure public CyclicTestStructure(Pointer p) { super(p); } public CyclicTestStructure() { } public CyclicTestStructure.ByReference next; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "next" }); } @@ -1653,12 +1727,14 @@ public void testCyclicRead() { public void testAvoidMemoryAllocationInPointerCTOR() { class TestStructure extends Structure { public int field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } public TestStructure(Pointer p) { super(p); } + @Override protected Memory autoAllocate(int size) { fail("Memory should not be auto-allocated"); return null; @@ -1672,6 +1748,7 @@ public void testPointerCTORWithInitializedFields() { class TestStructure extends Structure { public int intField; public byte[] arrayField = new byte[256]; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "intField", "arrayField" }); } @@ -1711,6 +1788,7 @@ public TestByReferenceArrayField(Pointer m) { public int value1; public ByReference[] array = new ByReference[13]; public int value2; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "value1", "array", "value2" }); } @@ -1738,6 +1816,7 @@ public static void testByReferenceArrayField() { public void testEquals() { class TestStructure extends Structure { public int field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -1755,6 +1834,7 @@ public TestStructure() { } public void testStructureLayoutCacheing() { class TestStructure extends Structure { public int field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -1768,6 +1848,7 @@ protected List getFieldOrder() { public void testStructureLayoutVariableNoCache() { class TestStructure extends Structure { public byte[] variable; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "variable" }); } @@ -1787,10 +1868,13 @@ public void testStructureLayoutCacheingWithTypeMapper() { class TestTypeMapper extends DefaultTypeMapper { { TypeConverter tc = new TypeConverter() { + @Override public Class nativeType() { return int.class; } + @Override public Object fromNative(Object nativeValue, FromNativeContext c) { return new Boolean(nativeValue.equals(new Integer(0))); } + @Override public Object toNative(Object value, ToNativeContext c) { return new Integer(Boolean.TRUE.equals(value) ? -1 : 0); } @@ -1802,6 +1886,7 @@ public Object toNative(Object value, ToNativeContext c) { final TestTypeMapper m = new TestTypeMapper(); class TestStructure extends Structure { public boolean field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -1823,6 +1908,7 @@ public void testStructureLayoutCacheingWithAlignment() { class TestStructure extends Structure { public byte first; public int second; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "first", "second" }); } @@ -1848,13 +1934,16 @@ public void testStructureSetIterator() { public void testFFITypeCalculationWithTypeMappedFields() { final TypeMapper mapper = new TypeMapper() { + @Override public FromNativeConverter getFromNativeConverter(Class cls) { if (Boolean.class.equals(cls) || boolean.class.equals(cls)) { return new FromNativeConverter() { + @Override public Class nativeType() { return byte.class; } + @Override public Object fromNative(Object nativeValue, FromNativeContext context) { return nativeValue.equals(new Byte((byte)0)) ? Boolean.FALSE : Boolean.TRUE; @@ -1863,13 +1952,16 @@ public Object fromNative(Object nativeValue, FromNativeContext context) { } return null; } + @Override public ToNativeConverter getToNativeConverter(Class javaType) { if (Boolean.class.equals(javaType) || boolean.class.equals(javaType)) { return new ToNativeConverter() { + @Override public Object toNative(Object value, ToNativeContext context) { return new Byte(Boolean.TRUE.equals(value) ? (byte)1 : (byte)0); } + @Override public Class nativeType() { return byte.class; } @@ -1886,6 +1978,7 @@ class TestStructure extends Structure { public TestStructure() { super(mapper); } + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "b", "s", "p0", "p1", "p2", "p3", "p4", "p5", "p6", "p7" }); } @@ -1901,6 +1994,7 @@ protected List getFieldOrder() { public void testDefaultStringEncoding() { class TestStructure extends Structure { public String field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -1914,6 +2008,7 @@ protected List getFieldOrder() { public void testStringFieldEncoding() throws Exception { class TestStructure extends Structure { public String field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } @@ -1939,18 +2034,19 @@ protected List getFieldOrder() { s.read(); assertEquals("String not decoded properly on read", VALUE, s.field); } - + public void testThreadLocalSetReleasesReferences() { class TestStructure extends Structure { public String field; + @Override protected List getFieldOrder() { return Arrays.asList(new String[] { "field" }); } } - + TestStructure ts1 = new TestStructure(); TestStructure ts2 = new TestStructure(); - + StructureSet structureSet = (StructureSet) Structure.busy(); structureSet.add(ts1); structureSet.add(ts2); diff --git a/test/com/sun/jna/TypeMapperTest.java b/test/com/sun/jna/TypeMapperTest.java index ff10c35eb4..815ad885d6 100644 --- a/test/com/sun/jna/TypeMapperTest.java +++ b/test/com/sun/jna/TypeMapperTest.java @@ -46,8 +46,7 @@ public Class nativeType() { } }); options.put(Library.OPTION_TYPE_MAPPER, mapper); - TestLibrary lib = (TestLibrary) - Native.loadLibrary("testlib", TestLibrary.class, options); + TestLibrary lib = Native.loadLibrary("testlib", TestLibrary.class, options); assertEquals("Failed to convert Boolean argument to Int", MAGIC, lib.returnInt32Argument(true)); } @@ -64,8 +63,7 @@ public Class nativeType() { Map options = new HashMap(); options.put(Library.OPTION_TYPE_MAPPER, mapper); final int MAGIC = 0x7BEDCF23; - TestLibrary lib = (TestLibrary) - Native.loadLibrary("testlib", TestLibrary.class, options); + TestLibrary lib = Native.loadLibrary("testlib", TestLibrary.class, options); assertEquals("Failed to convert String argument to Int", MAGIC, lib.returnInt32Argument(Integer.toHexString(MAGIC))); } @@ -82,8 +80,7 @@ public Class nativeType() { Map options = new HashMap(); options.put(Library.OPTION_TYPE_MAPPER, mapper); final String MAGIC = "magic" + UNICODE; - TestLibrary lib = (TestLibrary) - Native.loadLibrary("testlib", TestLibrary.class, options); + TestLibrary lib = Native.loadLibrary("testlib", TestLibrary.class, options); assertEquals("Failed to convert String argument to WString", new WString(MAGIC), lib.returnWStringArgument(MAGIC)); } @@ -101,8 +98,7 @@ public Class nativeType() { options.put(Library.OPTION_TYPE_MAPPER, mapper); final int MAGIC = 0x7BEDCF23; - TestLibrary lib = (TestLibrary) - Native.loadLibrary("testlib", TestLibrary.class, options); + TestLibrary lib = Native.loadLibrary("testlib", TestLibrary.class, options); assertEquals("Failed to convert String argument to Int", MAGIC, lib.returnInt32Argument(Integer.toHexString(MAGIC))); } @@ -120,8 +116,7 @@ public Class nativeType() { options.put(Library.OPTION_TYPE_MAPPER, mapper); final int MAGIC = 0x7BEDCF23; - TestLibrary lib = (TestLibrary) - Native.loadLibrary("testlib", TestLibrary.class, options); + TestLibrary lib = Native.loadLibrary("testlib", TestLibrary.class, options); assertEquals("Failed to convert Double argument to Int", MAGIC, lib.returnInt32Argument(new Double(MAGIC))); } @@ -141,8 +136,7 @@ public Class nativeType() { }); Map options = new HashMap(); options.put(Library.OPTION_TYPE_MAPPER, mapper); - TestLibrary lib = (TestLibrary) - Native.loadLibrary("testlib", TestLibrary.class, options); + TestLibrary lib = Native.loadLibrary("testlib", TestLibrary.class, options); assertEquals("Failed to convert WString result to String", MAGIC, lib.returnWStringArgument(new WString(MAGIC))); } @@ -171,8 +165,7 @@ public Class nativeType() { } }); options.put(Library.OPTION_TYPE_MAPPER, mapper); - BooleanTestLibrary lib = (BooleanTestLibrary) - Native.loadLibrary("testlib", BooleanTestLibrary.class, options); + BooleanTestLibrary lib = Native.loadLibrary("testlib", BooleanTestLibrary.class, options); assertEquals("Failed to convert integer return to boolean TRUE", true, lib.returnInt32Argument(true)); assertEquals("Failed to convert integer return to boolean FALSE", false, @@ -205,8 +198,7 @@ public Class nativeType() { mapper.addTypeConverter(Boolean.class, converter); Map options = new HashMap(); options.put(Library.OPTION_TYPE_MAPPER, mapper); - StructureTestLibrary lib = (StructureTestLibrary) - Native.loadLibrary("testlib", StructureTestLibrary.class, options); + StructureTestLibrary lib = Native.loadLibrary("testlib", StructureTestLibrary.class, options); StructureTestLibrary.TestStructure s = new StructureTestLibrary.TestStructure(mapper); assertEquals("Wrong native size", 4, s.size()); @@ -251,8 +243,7 @@ public Class nativeType() { mapper.addTypeConverter(Enumeration.class, converter); Map options = new HashMap(); options.put(Library.OPTION_TYPE_MAPPER, mapper); - EnumerationTestLibrary lib = (EnumerationTestLibrary) - Native.loadLibrary("testlib", EnumerationTestLibrary.class, options); + EnumerationTestLibrary lib = Native.loadLibrary("testlib", EnumerationTestLibrary.class, options); assertEquals("Enumeration improperly converted", Enumeration.STATUS_1, lib.returnInt32Argument(Enumeration.STATUS_1)); } diff --git a/test/com/sun/jna/VarArgsTest.java b/test/com/sun/jna/VarArgsTest.java index 2fdabd909f..043b6a0d53 100644 --- a/test/com/sun/jna/VarArgsTest.java +++ b/test/com/sun/jna/VarArgsTest.java @@ -8,7 +8,7 @@ * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna; @@ -24,8 +24,9 @@ public class VarArgsTest extends TestCase { public static interface TestLibrary extends Library { public static class TestStructure extends Structure { public int magic = 0; + @Override protected List getFieldOrder() { - return Arrays.asList(new String[] { "magic" }); + return Arrays.asList(new String[] { "magic" }); } } public int addInt32VarArgs(String fmt, Number... args); @@ -33,12 +34,14 @@ protected List getFieldOrder() { public void modifyStructureVarArgs(String fmt, Object arg1, Object... args); } TestLibrary lib; + @Override protected void setUp() { - lib = (TestLibrary)Native.loadLibrary("testlib", TestLibrary.class); + lib = Native.loadLibrary("testlib", TestLibrary.class); } + @Override protected void tearDown() { lib = null; - } + } public void testIntVarArgs() { int arg1 = 1; int arg2 = 2; @@ -62,24 +65,24 @@ public void testStringVarArgs() { assertEquals("Did not return correct string", args[0], lib.returnStringVarArgs("", args)); } - + public void testAppendNullToVarargs() { Number[] args = new Number[] { new Integer(1) }; assertEquals("No trailing NULL was appended to varargs list", 1, lib.addInt32VarArgs("dd", args)); } - + public void testModifyStructureInVarargs() { TestStructure arg1 = new TestStructure(); TestStructure[] varargs = new TestStructure[] { new TestStructure() }; lib.modifyStructureVarArgs("ss", arg1, varargs[0]); assertEquals("Structure memory not read in fixed arg w/varargs", - MAGIC32, arg1.magic); + MAGIC32, arg1.magic); assertEquals("Structure memory not read in varargs", - MAGIC32, varargs[0].magic); - + MAGIC32, varargs[0].magic); + } - + public static void main(String[] args) { junit.textui.TestRunner.run(VarArgsTest.class); } diff --git a/test/com/sun/jna/WebStartTest.java b/test/com/sun/jna/WebStartTest.java index 251878324f..62c9d013d2 100644 --- a/test/com/sun/jna/WebStartTest.java +++ b/test/com/sun/jna/WebStartTest.java @@ -290,8 +290,7 @@ private String findJWS() throws IOException { } // NOTE: win64 only includes javaws in the system path if (Platform.isWindows()) { - FolderInfo info = (FolderInfo) - Native.loadLibrary("shell32", FolderInfo.class); + FolderInfo info = Native.loadLibrary("shell32", FolderInfo.class); char[] buf = new char[FolderInfo.MAX_PATH]; //int result = info.SHGetFolderPathW(null, FolderInfo.CSIDL_WINDOWS, null, 0, buf); @@ -321,8 +320,7 @@ private File findDeploymentProperties() { vendor = vendor.substring(0, vendor.indexOf(" ")); } if (Platform.isWindows()) { - FolderInfo info = (FolderInfo) - Native.loadLibrary("shell32", FolderInfo.class); + FolderInfo info = Native.loadLibrary("shell32", FolderInfo.class); char[] buf = new char[FolderInfo.MAX_PATH]; info.SHGetFolderPathW(null, FolderInfo.CSIDL_APPDATA, null, 0, buf); diff --git a/test/com/sun/jna/win32/W32StdCallTest.java b/test/com/sun/jna/win32/W32StdCallTest.java index 5404c32a81..bfd4198062 100644 --- a/test/com/sun/jna/win32/W32StdCallTest.java +++ b/test/com/sun/jna/win32/W32StdCallTest.java @@ -8,7 +8,7 @@ * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. + * Lesser General Public License for more details. */ package com.sun.jna.win32; @@ -34,8 +34,9 @@ public class W32StdCallTest extends TestCase { public static interface TestLibrary extends StdCallLibrary { public static class Inner extends Structure { public double value; + @Override protected List getFieldOrder() { - return Arrays.asList(new String[] { "value" }); + return Arrays.asList(new String[] { "value" }); } } public static class TestStructure extends Structure { @@ -45,8 +46,9 @@ public static class ByValue extends TestStructure implements Structure.ByValue { public int i; public long j; public Inner inner; + @Override protected List getFieldOrder() { - return Arrays.asList(new String[] { "c", "s", "i", "j", "inner" }); + return Arrays.asList(new String[] { "c", "s", "i", "j", "inner" }); } } int returnInt32ArgumentStdCall(int arg); @@ -68,20 +70,23 @@ int callManyArgsStdCallCallback(ManyArgsStdCallCallback c, NativeLong arg1, int double arg8, NativeLong arg9, NativeLong arg10, NativeLong arg11); } - + public static void main(java.lang.String[] argList) { junit.textui.TestRunner.run(W32StdCallTest.class); } private TestLibrary testlib; - + + @Override protected void setUp() { - testlib = (TestLibrary) - Native.loadLibrary("testlib", TestLibrary.class, new HashMap() { - { put(Library.OPTION_FUNCTION_MAPPER, StdCallLibrary.FUNCTION_MAPPER); } - }); + testlib = Native.loadLibrary("testlib", TestLibrary.class, new HashMap() { + { + put(Library.OPTION_FUNCTION_MAPPER, StdCallLibrary.FUNCTION_MAPPER); + } + }); } - + + @Override protected void tearDown() { testlib = null; } @@ -113,22 +118,23 @@ public void testFunctionMapper() throws Exception { name, lib.getFunction(name, StdCallLibrary.STDCALL_CONVENTION).getName()); } } - + public void testStdCallReturnInt32Argument() { final int MAGIC = 0x12345678; assertEquals("Expect zero return", 0, testlib.returnInt32ArgumentStdCall(0)); assertEquals("Expect magic return", MAGIC, testlib.returnInt32ArgumentStdCall(MAGIC)); } - + public void testStdCallReturnStructureByValueArgument() { TestLibrary.TestStructure.ByValue s = new TestLibrary.TestStructure.ByValue(); assertTrue("Wrong struct value", s.dataEquals(testlib.returnStructureByValueArgumentStdCall(s))); } - + public void testStdCallCallback() { final int MAGIC = 0x11111111; final boolean[] called = { false }; TestLibrary.Int32Callback cb = new TestLibrary.Int32Callback() { + @Override public int callback(int arg, int arg2) { called[0] = true; return arg + arg2; @@ -140,9 +146,9 @@ public int callback(int arg, int arg2) { if (value == -1) { fail("stdcall callback did not restore the stack pointer"); } - assertEquals("Wrong stdcall callback value", Integer.toHexString(EXPECTED), + assertEquals("Wrong stdcall callback value", Integer.toHexString(EXPECTED), Integer.toHexString(value)); - + value = testlib.callInt32StdCallCallback(cb, -1, -2); if (value == -1) { fail("stdcall callback did not restore the stack pointer"); @@ -153,6 +159,7 @@ public int callback(int arg, int arg2) { public void testStdCallCallbackStackAlignment() { final boolean[] called = { false }; TestLibrary.ManyArgsStdCallCallback cb = new TestLibrary.ManyArgsStdCallCallback() { + @Override public void callback(NativeLong arg1, int arg2, double arg3, String arg4, String arg5, double arg6, NativeLong arg7, diff --git a/test/com/sun/jna/wince/CoreDLLTest.java b/test/com/sun/jna/wince/CoreDLLTest.java index 46c9986170..b1c0ba87c9 100644 --- a/test/com/sun/jna/wince/CoreDLLTest.java +++ b/test/com/sun/jna/wince/CoreDLLTest.java @@ -25,6 +25,8 @@ public static void main(java.lang.String[] argList) { } public interface CoreDLL extends StdCallLibrary { + CoreDLL INSTANCE = Native.loadLibrary("coredll", CoreDLL.class, W32APIOptions.UNICODE_OPTIONS); + public static class SECURITY_ATTRIBUTES extends Structure { public int dwLength; public Pointer lpSecurityDescriptor; @@ -88,8 +90,7 @@ protected List getFieldOrder() { return Arrays.asList(new String[] { "hProcess", "hThread", "dwProcessId", "dwThreadId" }); } } - CoreDLL INSTANCE = (CoreDLL)Native.loadLibrary("coredll", CoreDLL.class, - W32APIOptions.UNICODE_OPTIONS); + boolean CreateProcess(String lpApplicationName, String lpCommandLine, SECURITY_ATTRIBUTES lpProcessAttributes, SECURITY_ATTRIBUTES lpThreadAttributes,