From 579b36d8b22d1b4671254f851fd579f3ba995e4e Mon Sep 17 00:00:00 2001 From: Daniel Widdis Date: Mon, 20 Nov 2023 01:38:58 -0800 Subject: [PATCH 1/5] Use Diamond Operator except for anonymous inner classes --- src/com/sun/jna/CallbackReference.java | 22 +++++++------- src/com/sun/jna/DefaultTypeMapper.java | 4 +-- src/com/sun/jna/ELFAnalyser.java | 12 ++++---- src/com/sun/jna/Library.java | 6 ++-- src/com/sun/jna/Memory.java | 6 ++-- src/com/sun/jna/Native.java | 16 +++++----- src/com/sun/jna/NativeLibrary.java | 28 ++++++++--------- src/com/sun/jna/NativeMappedConverter.java | 4 +-- src/com/sun/jna/Pointer.java | 4 +-- src/com/sun/jna/StringArray.java | 2 +- src/com/sun/jna/Structure.java | 30 +++++++++---------- src/com/sun/jna/Union.java | 2 +- src/com/sun/jna/WeakMemoryHolder.java | 6 ++-- src/com/sun/jna/internal/Cleaner.java | 2 +- test/com/sun/jna/CallbacksTest.java | 14 ++++----- .../DirectArgumentsWrappersMarshalTest.java | 2 +- test/com/sun/jna/DirectTest.java | 7 +++-- test/com/sun/jna/JNALoadTest.java | 8 ++--- test/com/sun/jna/LastErrorTest.java | 2 +- test/com/sun/jna/MemoryTest.java | 6 ++-- test/com/sun/jna/NativeLibraryTest.java | 6 ++-- .../sun/jna/StructureFieldOrderInspector.java | 6 ++-- .../jna/StructureFieldOrderInspectorTest.java | 2 +- test/com/sun/jna/StructureTest.java | 4 +-- test/com/sun/jna/WebStartTest.java | 2 +- 25 files changed, 102 insertions(+), 101 deletions(-) diff --git a/src/com/sun/jna/CallbackReference.java b/src/com/sun/jna/CallbackReference.java index 6639300c95..cc2376b0d3 100644 --- a/src/com/sun/jna/CallbackReference.java +++ b/src/com/sun/jna/CallbackReference.java @@ -53,16 +53,16 @@ public class CallbackReference extends WeakReference implements Closea // Access to callbackMap, directCallbackMap, pointerCallbackMap is protected // by synchonizing on pointerCallbackMap - static final Map callbackMap = new WeakHashMap(); - static final Map directCallbackMap = new WeakHashMap(); + static final Map callbackMap = new WeakHashMap<>(); + static final Map directCallbackMap = new WeakHashMap<>(); //callbacks with different signatures sharing the same pointer - static final Map[]> pointerCallbackMap = new WeakHashMap[]>(); + static final Map[]> pointerCallbackMap = new WeakHashMap<>(); // Track memory allocations associated with this closure (usually String args) static final Map allocations = - Collections.synchronizedMap(new WeakHashMap()); + Collections.synchronizedMap(new WeakHashMap<>()); // Global map of allocated closures to facilitate centralized cleanup private static final Map> allocatedMemory = - new ConcurrentHashMap>(); + new ConcurrentHashMap<>(); private static final Method PROXY_CALLBACK_METHOD; static { @@ -87,7 +87,7 @@ public class CallbackReference extends WeakReference implements Closea } } - private static final Map initializers = new WeakHashMap(); + private static final Map initializers = new WeakHashMap<>(); /** * @param cb The {@link Callback} instance * @param initializer The {@link CallbackThreadInitializer} - if {@code null} then the @@ -211,14 +211,14 @@ private static Reference[] addCallbackToArray(Callback cb,Reference(cb); + newArray[nidx] = new WeakReference<>(cb); return newArray; } private static Callback createCallback(Class type, Pointer p) { int ctype = AltCallingConvention.class.isAssignableFrom(type) ? Function.ALT_CONVENTION : Function.C_CONVENTION; - Map foptions = new HashMap(Native.getLibraryOptions(type)); + Map foptions = new HashMap<>(Native.getLibraryOptions(type)); foptions.put(Function.OPTION_INVOKING_METHOD, getCallbackMethod(type)); NativeFunctionHandler h = new NativeFunctionHandler(p, ctype, foptions); return (Callback)Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, h); @@ -330,7 +330,7 @@ private CallbackReference(Callback callback, int callingConvention, boolean dire } cbstruct = peer != 0 ? new Pointer(peer) : null; if(peer != 0) { - allocatedMemory.put(peer, new WeakReference(this)); + allocatedMemory.put(peer, new WeakReference<>(this)); cleanable = Cleaner.getCleaner().register(this, new CallbackReferenceDisposer(cbstruct)); } } @@ -401,7 +401,7 @@ private static Method getCallbackMethod(Class cls) { // Look at only public methods defined by the Callback class Method[] pubMethods = cls.getDeclaredMethods(); Method[] classMethods = cls.getMethods(); - Set pmethods = new HashSet(Arrays.asList(pubMethods)); + Set pmethods = new HashSet<>(Arrays.asList(pubMethods)); pmethods.retainAll(Arrays.asList(classMethods)); // Remove Object methods disallowed as callback method names @@ -456,7 +456,7 @@ protected void dispose() { /** Dispose of all memory allocated for callbacks. */ static void disposeAll() { // use a copy since dispose() modifes the map - Collection> refs = new LinkedList>(allocatedMemory.values()); + Collection> refs = new LinkedList<>(allocatedMemory.values()); for (Reference r : refs) { CallbackReference ref = r.get(); if(ref != null) { diff --git a/src/com/sun/jna/DefaultTypeMapper.java b/src/com/sun/jna/DefaultTypeMapper.java index e0d41a01fd..5f1c9524c5 100644 --- a/src/com/sun/jna/DefaultTypeMapper.java +++ b/src/com/sun/jna/DefaultTypeMapper.java @@ -52,8 +52,8 @@ public Entry(Class type, Object converter) { } } - private List toNativeConverters = new ArrayList(); - private List fromNativeConverters = new ArrayList(); + private List toNativeConverters = new ArrayList<>(); + private List fromNativeConverters = new ArrayList<>(); private Class getAltClass(Class cls) { if (cls == Boolean.class) { diff --git a/src/com/sun/jna/ELFAnalyser.java b/src/com/sun/jna/ELFAnalyser.java index fc322ae098..7b30aad284 100644 --- a/src/com/sun/jna/ELFAnalyser.java +++ b/src/com/sun/jna/ELFAnalyser.java @@ -230,7 +230,7 @@ private void parseEabiAapcsVfp(ByteBuffer headerData, RandomAccessFile raf) thro } static class ELFSectionHeaders { - private final List entries = new ArrayList(); + private final List entries = new ArrayList<>(); public ELFSectionHeaders(boolean _64bit, boolean bigEndian, ByteBuffer headerData, RandomAccessFile raf) throws IOException { long shoff; @@ -401,9 +401,9 @@ public boolean equals(Object obj) { return true; } - private static final List tags = new LinkedList(); - private static final Map valueMap = new HashMap(); - private static final Map nameMap = new HashMap(); + private static final List tags = new LinkedList<>(); + private static final Map valueMap = new HashMap<>(); + private static final Map nameMap = new HashMap<>(); // Enumerated from ARM IHI 0045E, 2.5 Attributes summary and history public static final ArmAeabiAttributesTag File = addTag(1, "File", ParameterType.UINT32); @@ -520,7 +520,7 @@ private static Map> parseArmAttribut } private static Map> parseAEABI(ByteBuffer buffer) { - Map> data = new HashMap>(); + Map> data = new HashMap<>(); while (buffer.position() < buffer.limit()) { int pos = buffer.position(); int subsectionTag = readULEB128(buffer).intValue(); @@ -534,7 +534,7 @@ private static Map> parseAEABI(ByteB } private static Map parseFileAttribute(ByteBuffer bb) { - Map result = new HashMap(); + Map result = new HashMap<>(); while (bb.position() < bb.limit()) { int tagValue = readULEB128(bb).intValue(); ArmAeabiAttributesTag tag = ArmAeabiAttributesTag.getByValue(tagValue); diff --git a/src/com/sun/jna/Library.java b/src/com/sun/jna/Library.java index 3b79fabde0..71745ffd73 100644 --- a/src/com/sun/jna/Library.java +++ b/src/com/sun/jna/Library.java @@ -172,7 +172,7 @@ private static final class FunctionInfo { // Library invocation options private final Map options; private final InvocationMapper invocationMapper; - private final Map functions = new WeakHashMap(); + private final Map functions = new WeakHashMap<>(); public Handler(String libname, Class interfaceClass, Map options) { if (libname != null && "".equals(libname.trim())) { @@ -184,7 +184,7 @@ public Handler(String libname, Class interfaceClass, Map options) } this.interfaceClass = interfaceClass; - this.options = new HashMap(options); + this.options = new HashMap<>(options); int callingConvention = AltCallingConvention.class.isAssignableFrom(interfaceClass) ? Function.ALT_CONVENTION : Function.C_CONVENTION; @@ -247,7 +247,7 @@ public Object invoke(Object proxy, Method method, Object[] inArgs) // Find the function to invoke function = nativeLibrary.getFunction(method.getName(), method); parameterTypes = method.getParameterTypes(); - options = new HashMap(this.options); + options = new HashMap<>(this.options); options.put(Function.OPTION_INVOKING_METHOD, method); } f = new FunctionInfo(handler, function, parameterTypes, isVarArgs, options); diff --git a/src/com/sun/jna/Memory.java b/src/com/sun/jna/Memory.java index c83bfed9b5..cea967e617 100644 --- a/src/com/sun/jna/Memory.java +++ b/src/com/sun/jna/Memory.java @@ -54,7 +54,7 @@ public class Memory extends Pointer implements Closeable { /** Keep track of all allocated memory so we can dispose of it before unloading. */ private static final Map> allocatedMemory = - new ConcurrentHashMap>(); + new ConcurrentHashMap<>(); private static final WeakMemoryHolder buffers = new WeakMemoryHolder(); @@ -68,7 +68,7 @@ public static void purge() { /** Dispose of all allocated memory. */ public static void disposeAll() { // use a copy since dispose() modifies the map - Collection> refs = new ArrayList>(allocatedMemory.values()); + Collection> refs = new ArrayList<>(allocatedMemory.values()); for (Reference r : refs) { Memory m = r.get(); if(m != null) { @@ -118,7 +118,7 @@ public Memory(long size) { if (peer == 0) throw new OutOfMemoryError("Cannot allocate " + size + " bytes"); - allocatedMemory.put(peer, new WeakReference(this)); + allocatedMemory.put(peer, new WeakReference<>(this)); cleanable = Cleaner.getCleaner().register(this, new MemoryDisposer(peer)); } diff --git a/src/com/sun/jna/Native.java b/src/com/sun/jna/Native.java index e3c3d8ebef..d057031482 100644 --- a/src/com/sun/jna/Native.java +++ b/src/com/sun/jna/Native.java @@ -517,7 +517,7 @@ public static List toStringList(char[] buf) { * @return A {@link List} of all the strings in the buffer */ public static List toStringList(char[] buf, int offset, int len) { - List list = new ArrayList(); + List list = new ArrayList<>(); int lastPos = offset; int maxPos = offset + len; for (int curPos = offset; curPos < maxPos; curPos++) { @@ -691,7 +691,7 @@ private static void loadLibraryInstance(Class cls) { && Modifier.isStatic(field.getModifiers())) { // Ensure the field gets initialized by reading it field.setAccessible(true); // interface might be private - libraries.put(cls, new WeakReference(field.get(null))); + libraries.put(cls, new WeakReference<>(field.get(null))); break; } } @@ -785,7 +785,7 @@ public static Map getLibraryOptions(Class type) { throw new IllegalArgumentException("OPTIONS must be a public field of type java.util.Map (" + e + "): " + mappingClass); } // Make a clone of the original options - libraryOptions = new HashMap(libraryOptions); + libraryOptions = new HashMap<>(libraryOptions); if (!libraryOptions.containsKey(Library.OPTION_TYPE_MAPPER)) { libraryOptions.put(Library.OPTION_TYPE_MAPPER, lookupField(mappingClass, "TYPE_MAPPER", TypeMapper.class)); } @@ -1552,8 +1552,8 @@ public static void setCallbackThreadInitializer(Callback cb, CallbackThreadIniti CallbackReference.setCallbackThreadInitializer(cb, initializer); } - private static final Map, long[]> registeredClasses = new WeakHashMap, long[]>(); - private static final Map, NativeLibrary> registeredLibraries = new WeakHashMap, NativeLibrary>(); + private static final Map, long[]> registeredClasses = new WeakHashMap<>(); + private static final Map, NativeLibrary> registeredLibraries = new WeakHashMap<>(); private static void unregisterAll() { synchronized(registeredClasses) { @@ -1786,7 +1786,7 @@ public static void register(Class cls, String libName) { // method name, library name, call conv public static void register(Class cls, NativeLibrary lib) { Method[] methods = cls.getDeclaredMethods(); - List mlist = new ArrayList(); + List mlist = new ArrayList<>(); Map options = lib.getOptions(); TypeMapper mapper = (TypeMapper) options.get(Library.OPTION_TYPE_MAPPER); boolean allowObjects = Boolean.TRUE.equals(options.get(Library.OPTION_ALLOW_OBJECTS)); @@ -1926,11 +1926,11 @@ public static void register(Class cls, NativeLibrary lib) { * looking them up later. */ private static Map cacheOptions(Class cls, Map options, Object proxy) { - Map libOptions = new HashMap(options); + Map libOptions = new HashMap<>(options); libOptions.put(_OPTION_ENCLOSING_LIBRARY, cls); typeOptions.put(cls, libOptions); if (proxy != null) { - libraries.put(cls, new WeakReference(proxy)); + libraries.put(cls, new WeakReference<>(proxy)); } // If it's a direct mapping, AND implements a Library interface, diff --git a/src/com/sun/jna/NativeLibrary.java b/src/com/sun/jna/NativeLibrary.java index 27eb569423..4cfd9b0001 100644 --- a/src/com/sun/jna/NativeLibrary.java +++ b/src/com/sun/jna/NativeLibrary.java @@ -99,16 +99,16 @@ public long getSymbolAddress(long handle, String name, SymbolProvider parent) { private long handle; private final String libraryName; private final String libraryPath; - private final Map functions = new HashMap(); + private final Map functions = new HashMap<>(); private final SymbolProvider symbolProvider; final int callFlags; private String encoding; final Map options; - private static final Map> libraries = new HashMap>(); + private static final Map> libraries = new HashMap<>(); - private static final Map> searchPaths = new ConcurrentHashMap>(); - private static final LinkedHashSet librarySearchPath = new LinkedHashSet(); + private static final Map> searchPaths = new ConcurrentHashMap<>(); + private static final LinkedHashSet librarySearchPath = new LinkedHashSet<>(); static { // Force initialization of native library @@ -173,9 +173,9 @@ private static int openFlags(Map options) { private static NativeLibrary loadLibrary(final String libraryName, final Map options) { LOG.log(DEBUG_LOAD_LEVEL, "Looking for library '" + libraryName + "'"); - List exceptions = new ArrayList(); + List exceptions = new ArrayList<>(); boolean isAbsolutePath = new File(libraryName).isAbsolute(); - LinkedHashSet searchPath = new LinkedHashSet(); + LinkedHashSet searchPath = new LinkedHashSet<>(); int openFlags = openFlags(options); // @@ -361,7 +361,7 @@ private static void addSuppressedReflected(Throwable target, Throwable suppresse /** Look for a matching framework (OSX) */ static String[] matchFramework(String libraryName) { - Set paths = new LinkedHashSet(); + Set paths = new LinkedHashSet<>(); File framework = new File(libraryName); if (framework.isAbsolute()) { if (libraryName.contains(".framework")) { @@ -460,7 +460,7 @@ public static final NativeLibrary getInstance(String libraryName, ClassLoader cl * @param libraryOptions Native library options for the given library (see {@link Library}). */ public static final NativeLibrary getInstance(String libraryName, Map libraryOptions) { - Map options = new HashMap(libraryOptions); + Map options = new HashMap<>(libraryOptions); if (options.get(Library.OPTION_CALLING_CONVENTION) == null) { options.put(Library.OPTION_CALLING_CONVENTION, Integer.valueOf(Function.C_CONVENTION)); } @@ -482,7 +482,7 @@ public static final NativeLibrary getInstance(String libraryName, Map else { library = loadLibrary(libraryName, options); } - ref = new WeakReference(library); + ref = new WeakReference<>(library); libraries.put(library.getName() + options, ref); File file = library.getFile(); if (file != null) { @@ -675,7 +675,7 @@ public File getFile() { static void disposeAll() { Set> values; synchronized(libraries) { - values = new LinkedHashSet>(libraries.values()); + values = new LinkedHashSet<>(libraries.values()); } for (Reference ref : values) { NativeLibrary lib = ref.get(); @@ -687,7 +687,7 @@ static void disposeAll() { /** Close the native library we're mapped to. */ public void close() { - Set keys = new HashSet(); + Set keys = new HashSet<>(); synchronized(libraries) { for (Map.Entry> e : libraries.entrySet()) { Reference ref = e.getValue(); @@ -720,7 +720,7 @@ private static List initPaths(String key) { return Collections.emptyList(); } StringTokenizer st = new StringTokenizer(value, File.pathSeparator); - List list = new ArrayList(); + List list = new ArrayList<>(); while (st.hasMoreTokens()) { String path = st.nextToken(); if (!"".equals(path)) { @@ -852,7 +852,7 @@ public boolean accept(File dir, String filename) { } }; - Collection matches = new LinkedList(); + Collection matches = new LinkedList<>(); for (String path : searchPath) { File[] files = new File(path).listFiles(filter); if (files != null && files.length > 0) { @@ -1018,7 +1018,7 @@ else if (Platform.ARCH.equals("mips64el")) { * Get the library paths from ldconfig cache. Tested against ldconfig 2.13. */ private static ArrayList getLinuxLdPaths() { - ArrayList ldPaths = new ArrayList(); + ArrayList ldPaths = new ArrayList<>(); Process process = null; BufferedReader reader = null; try { diff --git a/src/com/sun/jna/NativeMappedConverter.java b/src/com/sun/jna/NativeMappedConverter.java index 0c54e43494..ee13fe1e57 100644 --- a/src/com/sun/jna/NativeMappedConverter.java +++ b/src/com/sun/jna/NativeMappedConverter.java @@ -32,7 +32,7 @@ /** Provides type conversion for instances of {@link NativeMapped}. */ public class NativeMappedConverter implements TypeConverter { private static final Map, Reference> converters = - new WeakHashMap, Reference>(); + new WeakHashMap<>(); private final Class type; private final Class nativeType; private final NativeMapped instance; @@ -43,7 +43,7 @@ public static NativeMappedConverter getInstance(Class cls) { NativeMappedConverter nmc = r != null ? r.get() : null; if (nmc == null) { nmc = new NativeMappedConverter(cls); - converters.put(cls, new SoftReference(nmc)); + converters.put(cls, new SoftReference<>(nmc)); } return nmc; } diff --git a/src/com/sun/jna/Pointer.java b/src/com/sun/jna/Pointer.java index 1a3fe5d60f..444035f51a 100644 --- a/src/com/sun/jna/Pointer.java +++ b/src/com/sun/jna/Pointer.java @@ -748,7 +748,7 @@ public double[] getDoubleArray(long offset, int arraySize) { * determined by a NULL-valued terminating element. */ public Pointer[] getPointerArray(long offset) { - List array = new ArrayList(); + List array = new ArrayList<>(); int addOffset = 0; Pointer p = getPointer(offset); while (p != null) { @@ -811,7 +811,7 @@ public String[] getWideStringArray(long offset, int length) { * @param encoding */ public String[] getStringArray(long offset, int length, String encoding) { - List strings = new ArrayList(); + List strings = new ArrayList<>(); Pointer p; int addOffset = 0; if (length != -1) { diff --git a/src/com/sun/jna/StringArray.java b/src/com/sun/jna/StringArray.java index daf4c108b0..d7096e8bba 100644 --- a/src/com/sun/jna/StringArray.java +++ b/src/com/sun/jna/StringArray.java @@ -34,7 +34,7 @@ */ public class StringArray extends Memory implements Function.PostCallRead { private String encoding; - private List natives = new ArrayList(); + private List natives = new ArrayList<>(); private Object[] original; /** Create a native array of strings. */ public StringArray(String[] strings) { diff --git a/src/com/sun/jna/Structure.java b/src/com/sun/jna/Structure.java index 39d3da0efa..0f1f3975d2 100644 --- a/src/com/sun/jna/Structure.java +++ b/src/com/sun/jna/Structure.java @@ -155,8 +155,8 @@ private static class NativeStringTracking { //public static final int ALIGN_8 = 6; protected static final int CALCULATE_SIZE = -1; - static final Map, LayoutInfo> layoutInfo = new WeakHashMap, LayoutInfo>(); - static final Map, List> fieldOrder = new WeakHashMap, List>(); + static final Map, LayoutInfo> layoutInfo = new WeakHashMap<>(); + static final Map, List> fieldOrder = new WeakHashMap<>(); // This field is accessed by native code private Pointer memory; @@ -168,7 +168,7 @@ private static class NativeStringTracking { private Map structFields; // Keep track of native C strings which have been allocated, // corresponding to String fields of this Structure - private final Map nativeStrings = new HashMap(8); + private final Map nativeStrings = new HashMap<>(8); private TypeMapper typeMapper; // This field is accessed by native code private long typeInfo; @@ -479,7 +479,7 @@ public Pointer getPointer() { private static final ThreadLocal> reads = new ThreadLocal>() { @Override protected synchronized Map initialValue() { - return new HashMap(); + return new HashMap<>(); } }; @@ -981,7 +981,7 @@ private void writeField(StructField structField, Object value) { */ // TODO(idosu 28 Apr 2018): Maybe deprecate this method to let users know they should use @FieldOrder protected List getFieldOrder() { - List fields = new LinkedList(); + List fields = new LinkedList<>(); for (Class clazz = getClass(); clazz != Structure.class; clazz = clazz.getSuperclass()) { FieldOrder order = clazz.getAnnotation(FieldOrder.class); if (order != null) { @@ -1015,11 +1015,11 @@ protected void sortFields(List fields, List names) { * this {@link Structure} class. */ protected List getFieldList() { - List flist = new ArrayList(); + List flist = new ArrayList<>(); for (Class cls = getClass(); !cls.equals(Structure.class); cls = cls.getSuperclass()) { - List classFields = new ArrayList(); + List classFields = new ArrayList<>(); Field[] fields = cls.getDeclaredFields(); for (int i=0;i < fields.length;i++) { int modifiers = fields[i].getModifiers(); @@ -1053,7 +1053,7 @@ public static List createFieldsOrder(List baseFields, String ... } public static List createFieldsOrder(List baseFields, List extraFields) { - List fields = new ArrayList(baseFields.size() + extraFields.size()); + List fields = new ArrayList<>(baseFields.size() + extraFields.size()); fields.addAll(baseFields); fields.addAll(extraFields); return Collections.unmodifiableList(fields); @@ -1076,7 +1076,7 @@ public static List createFieldsOrder(String ... fields) { } private static > List sort(Collection c) { - List list = new ArrayList(c); + List list = new ArrayList<>(c); Collections.sort(list); return list; } @@ -1090,7 +1090,7 @@ private static > List sort(Collection c) **/ protected List getFields(boolean force) { List flist = getFieldList(); - Set names = new HashSet(); + Set names = new HashSet<>(); for (Field f : flist) { names.add(f.getName()); } @@ -1113,7 +1113,7 @@ protected List getFields(boolean force) { return null; } - Set orderedNames = new HashSet(fieldOrder); + Set orderedNames = new HashSet<>(fieldOrder); if (!orderedNames.equals(names)) { throw new Error("Structure.getFieldOrder() on " + getClass() + " returns names (" @@ -1955,9 +1955,9 @@ public static class size_t extends IntegerType { public size_t(long value) { super(Native.SIZE_T_SIZE, value); } } - private static final Map> typeInfoMap = new WeakHashMap>(); - private static final Map unionHelper = new WeakHashMap(); - private static final Map ffiTypeInfo = new HashMap(); + private static final Map> typeInfoMap = new WeakHashMap<>(); + private static final Map unionHelper = new WeakHashMap<>(); + private static final Map ffiTypeInfo = new HashMap<>(); // Native.initIDs initializes these fields to their appropriate // pointer values. These are in a separate class from FFIType so that @@ -2206,7 +2206,7 @@ private static void storeTypeInfo(Class clazz, int elementCount, FFIType type) { synchronized (typeInfoMap) { Map typeMap = typeInfoMap.get(clazz); if(typeMap == null) { - typeMap = new HashMap(); + typeMap = new HashMap<>(); typeInfoMap.put(clazz, typeMap); } typeMap.put(elementCount, type); diff --git a/src/com/sun/jna/Union.java b/src/com/sun/jna/Union.java index 28ef5169f8..b21937385f 100644 --- a/src/com/sun/jna/Union.java +++ b/src/com/sun/jna/Union.java @@ -67,7 +67,7 @@ protected Union(Pointer p, int alignType, TypeMapper mapper) { @Override protected List getFieldOrder() { List flist = getFieldList(); - List list = new ArrayList(flist.size()); + List list = new ArrayList<>(flist.size()); for (Field f : flist) { list.add(f.getName()); } diff --git a/src/com/sun/jna/WeakMemoryHolder.java b/src/com/sun/jna/WeakMemoryHolder.java index 1526e8dc44..610b2d494d 100644 --- a/src/com/sun/jna/WeakMemoryHolder.java +++ b/src/com/sun/jna/WeakMemoryHolder.java @@ -38,12 +38,12 @@ * The references to the memory objects are released on access of WeakMemoryHolder. */ public class WeakMemoryHolder { - ReferenceQueue referenceQueue = new ReferenceQueue(); - IdentityHashMap, Memory> backingMap = new IdentityHashMap, Memory>(); + ReferenceQueue referenceQueue = new ReferenceQueue<>(); + IdentityHashMap, Memory> backingMap = new IdentityHashMap<>(); public synchronized void put(Object o, Memory m) { clean(); - Reference reference = new WeakReference(o, referenceQueue); + Reference reference = new WeakReference<>(o, referenceQueue); backingMap.put(reference, m); } diff --git a/src/com/sun/jna/internal/Cleaner.java b/src/com/sun/jna/internal/Cleaner.java index 3a1b0eac54..a2095937fc 100644 --- a/src/com/sun/jna/internal/Cleaner.java +++ b/src/com/sun/jna/internal/Cleaner.java @@ -49,7 +49,7 @@ public static Cleaner getCleaner() { private CleanerRef firstCleanable; private Cleaner() { - referenceQueue = new ReferenceQueue(); + referenceQueue = new ReferenceQueue<>(); } public synchronized Cleanable register(Object obj, Runnable cleanupTask) { diff --git a/test/com/sun/jna/CallbacksTest.java b/test/com/sun/jna/CallbacksTest.java index da6918e83a..ff801fb7e5 100644 --- a/test/com/sun/jna/CallbacksTest.java +++ b/test/com/sun/jna/CallbacksTest.java @@ -354,7 +354,7 @@ public void callback() { lib.callVoidCallback(cb); assertTrue("Callback not called", called[0]); - Map refs = new WeakHashMap(callbackCache()); + Map refs = new WeakHashMap<>(callbackCache()); assertTrue("Callback not cached", refs.containsKey(cb)); CallbackReference ref = refs.get(cb); refs = callbackCache(); @@ -694,7 +694,7 @@ public String callback(String arg, String arg2) { String arg = getName() + "1" + charset.decode(charset.encode(UNICODE)); String arg2 = getName() + "2" + charset.decode(charset.encode(UNICODE)); String value = lib.callStringCallback(cb, arg, arg2); - WeakReference ref = new WeakReference(value); + WeakReference ref = new WeakReference<>(value); arg = null; value = null; @@ -1331,7 +1331,7 @@ public void callback() { // as daemon to avoid VM having to wait for it. public void testCallbackThreadPersistence() throws Exception { final int[] called = {0}; - final Set threads = new HashSet(); + final Set threads = new HashSet<>(); final int COUNT = 5; CallbackThreadInitializer init = new CallbackThreadInitializer(true, false) { @@ -1360,12 +1360,12 @@ public void callback() { // Thread object is never GC'd on linux-amd64 and darwin-amd64 (w/openjdk7) public void testCleanupUndetachedThreadOnThreadExit() throws Exception { - final Set> threads = new HashSet>(); + 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())); + threads.add(new WeakReference<>(Thread.currentThread())); if (++called[0] == 1) { Thread.currentThread().setName(getName() + " (Thread to be cleaned up)"); } @@ -1414,7 +1414,7 @@ public String getName(Callback cb) { // but callback explicitly detaches it on final invocation. public void testCallbackIndicatedThreadDetach() throws Exception { final int[] called = {0}; - final Set threads = new HashSet(); + final Set threads = new HashSet<>(); final int COUNT = 5; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { @Override @@ -1477,7 +1477,7 @@ public void callback() { assertEquals("Wrong module HANDLE for DLL function pointer", handle, pref.getValue()); // Check slot re-use - Map refs = new WeakHashMap(callbackCache()); + Map refs = new WeakHashMap<>(callbackCache()); assertTrue("Callback not cached", refs.containsKey(cb)); CallbackReference ref = refs.get(cb); refs = callbackCache(); diff --git a/test/com/sun/jna/DirectArgumentsWrappersMarshalTest.java b/test/com/sun/jna/DirectArgumentsWrappersMarshalTest.java index ffa1383b56..960c361d81 100644 --- a/test/com/sun/jna/DirectArgumentsWrappersMarshalTest.java +++ b/test/com/sun/jna/DirectArgumentsWrappersMarshalTest.java @@ -92,7 +92,7 @@ public Object toNative(Object value, ToNativeContext context) { } } } - final Map converters = new HashMap(); + final Map converters = new HashMap<>(); converters.put(Boolean.class, new PrimitiveConverter(boolean.class)); converters.put(Byte.class, new PrimitiveConverter(byte.class)); converters.put(Short.class, new PrimitiveConverter(short.class)); diff --git a/test/com/sun/jna/DirectTest.java b/test/com/sun/jna/DirectTest.java index 3e2f4b563f..953a796ae9 100644 --- a/test/com/sun/jna/DirectTest.java +++ b/test/com/sun/jna/DirectTest.java @@ -23,9 +23,8 @@ */ package com.sun.jna; -import junit.framework.*; -import java.lang.reflect.Method; import java.io.File; +import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; @@ -35,6 +34,8 @@ import java.util.List; import java.util.Map; +import junit.framework.TestCase; + //@SuppressWarnings("unused") public class DirectTest extends TestCase implements Paths { @@ -203,7 +204,7 @@ public void testGetOptionsForDirectMappingWithMemberInitializer() { final TypeMapper mapper = new DefaultTypeMapper(); final int alignment = Structure.ALIGN_NONE; final String encoding = System.getProperty("file.encoding"); - Map options = new HashMap(); + Map options = new HashMap<>(); options.put(Library.OPTION_TYPE_MAPPER, mapper); options.put(Library.OPTION_STRUCTURE_ALIGNMENT, alignment); options.put(Library.OPTION_STRING_ENCODING, encoding); diff --git a/test/com/sun/jna/JNALoadTest.java b/test/com/sun/jna/JNALoadTest.java index 466b5baf5f..98c3f24051 100644 --- a/test/com/sun/jna/JNALoadTest.java +++ b/test/com/sun/jna/JNALoadTest.java @@ -136,8 +136,8 @@ public void testLoadAndUnloadFromJar() throws Exception { assertTrue("Native library not unpacked from jar: " + path, path.startsWith(Native.getTempDir().getAbsolutePath())); - Reference> ref = new WeakReference>(cls); - Reference clref = new WeakReference(loader); + Reference> ref = new WeakReference<>(cls); + Reference clref = new WeakReference<>(loader); loader = null; cls = null; field = null; @@ -191,8 +191,8 @@ public void testLoadAndUnloadFromResourcePath() throws Exception { String path = (String)field.get(null); assertNotNull("Native library not found", path); - Reference> ref = new WeakReference>(cls); - Reference clref = new WeakReference(loader); + Reference> ref = new WeakReference<>(cls); + Reference clref = new WeakReference<>(loader); loader = null; cls = null; field = null; diff --git a/test/com/sun/jna/LastErrorTest.java b/test/com/sun/jna/LastErrorTest.java index 7435f97f94..8356dba70e 100644 --- a/test/com/sun/jna/LastErrorTest.java +++ b/test/com/sun/jna/LastErrorTest.java @@ -69,7 +69,7 @@ public void testLastErrorPerThreadStorage() throws Exception { final TestLibrary lib = Native.load("testlib", TestLibrary.class); final int NTHREADS = 100; final int[] errors = new int[NTHREADS]; - List threads = new ArrayList(NTHREADS); + List threads = new ArrayList<>(NTHREADS); for (int i=0;i < NTHREADS;i++) { final int idx = i; Thread t = new Thread("tLastErrorSetter-" + i) { diff --git a/test/com/sun/jna/MemoryTest.java b/test/com/sun/jna/MemoryTest.java index b287c6e7a7..1e695cce73 100644 --- a/test/com/sun/jna/MemoryTest.java +++ b/test/com/sun/jna/MemoryTest.java @@ -42,7 +42,7 @@ public class MemoryTest extends TestCase { public void testAutoFreeMemory() throws Exception { Memory core = new Memory(10); Pointer shared = core.share(0, 5); - Reference ref = new WeakReference(core); + Reference ref = new WeakReference<>(core); core = null; System.gc(); @@ -133,8 +133,8 @@ public void testAvoidGCWithExtantBuffer() throws Exception { m.clear(); ByteBuffer b = m.getByteBuffer(0, m.size()); - Reference ref = new WeakReference(m); - Reference bref = new WeakReference(b); + Reference ref = new WeakReference<>(m); + Reference bref = new WeakReference<>(b); // Create a second byte buffer "equal" to the first m = new Memory(1024); diff --git a/test/com/sun/jna/NativeLibraryTest.java b/test/com/sun/jna/NativeLibraryTest.java index 46a15d7e90..6c3511d55f 100644 --- a/test/com/sun/jna/NativeLibraryTest.java +++ b/test/com/sun/jna/NativeLibraryTest.java @@ -69,7 +69,7 @@ public void testMapSharedLibraryName() { public void testGCNativeLibrary() throws Exception { NativeLibrary lib = NativeLibrary.getInstance("testlib"); - Reference ref = new WeakReference(lib); + Reference ref = new WeakReference<>(lib); lib = null; System.gc(); long start = System.currentTimeMillis(); @@ -131,7 +131,7 @@ public void testAliasLibraryFullPath() { public void testAliasSimpleLibraryName() throws Exception { NativeLibrary nl = NativeLibrary.getInstance("testlib"); File file = nl.getFile(); - Reference ref = new WeakReference(nl); + Reference ref = new WeakReference<>(nl); nl = null; System.gc(); long start = System.currentTimeMillis(); @@ -171,7 +171,7 @@ public void testIncludeSymbolNameInLookupError() { public void testFunctionHoldsLibraryReference() throws Exception { NativeLibrary lib = NativeLibrary.getInstance("testlib"); - Reference ref = new WeakReference(lib); + Reference ref = new WeakReference<>(lib); Function f = lib.getFunction("callCount"); lib = null; System.gc(); diff --git a/test/com/sun/jna/StructureFieldOrderInspector.java b/test/com/sun/jna/StructureFieldOrderInspector.java index 8ea1987eba..1ce040c301 100644 --- a/test/com/sun/jna/StructureFieldOrderInspector.java +++ b/test/com/sun/jna/StructureFieldOrderInspector.java @@ -74,7 +74,7 @@ public static void batchCheckStructureGetFieldOrder(final Class classDeclared final boolean onlyInnerClasses) { final Set> classes = StructureFieldOrderInspector.findSubTypesOfStructure(classDeclaredInSourceTreeToSearch, onlyInnerClasses); - final List problems = new ArrayList(); + final List problems = new ArrayList<>(); for (final Class structureSubType : classes) { try { @@ -121,7 +121,7 @@ public static Set> findSubTypesOfStructure(final Clas .setUrls(ClasspathHelper.forClass(classDeclaredInSourceTreeToSearch)) ); - Set> types = new HashSet>(reflections.getSubTypesOf(Structure.class)); + Set> types = new HashSet<>(reflections.getSubTypesOf(Structure.class)); if(onlyInnerClasses) { Iterator> it = types.iterator(); while(it.hasNext()) { @@ -192,7 +192,7 @@ public static void checkMethodGetFieldOrder(final Class str final List methodCallFieldOrder = structure.getFieldOrder(); final List actualFields = structure.getFieldList(); - final List actualFieldNames = new ArrayList(actualFields.size()); + final List actualFieldNames = new ArrayList<>(actualFields.size()); for (final Field field : actualFields) { // ignore static fields if (!Modifier.isStatic(field.getModifiers())) { diff --git a/test/com/sun/jna/StructureFieldOrderInspectorTest.java b/test/com/sun/jna/StructureFieldOrderInspectorTest.java index 5780e5274a..488af97e63 100644 --- a/test/com/sun/jna/StructureFieldOrderInspectorTest.java +++ b/test/com/sun/jna/StructureFieldOrderInspectorTest.java @@ -148,7 +148,7 @@ public void testCheckMethodGetFieldOrderWithAbstractSubtype() throws Exception { } public void testCheckMethodGetFieldOrderWithIgnoreCtorError() throws Exception { - final List ignoreConstructorError = new ArrayList(); + final List ignoreConstructorError = new ArrayList<>(); ignoreConstructorError.add(StructureFieldOrderInspectorTest.class.getName()); StructureFieldOrderInspector.checkMethodGetFieldOrder(MyStructExtraField.class, ignoreConstructorError); } diff --git a/test/com/sun/jna/StructureTest.java b/test/com/sun/jna/StructureTest.java index db7c1aeacd..0a6002a8df 100644 --- a/test/com/sun/jna/StructureTest.java +++ b/test/com/sun/jna/StructureTest.java @@ -1667,7 +1667,7 @@ protected List getFieldOrder() { public static class XTestStructureSub extends XTestStructure { public static final List EXTRA_FIELDS = createFieldsOrder("second"); - private static final AtomicReference> fieldsHolder = new AtomicReference>(null); + private static final AtomicReference> fieldsHolder = new AtomicReference<>(null); private static List resolveEffectiveFields(List baseFields) { List fields; synchronized (fieldsHolder) { @@ -1713,7 +1713,7 @@ class DerivedTestStructure extends TestStructure { public int four = 4; @Override protected List getFieldOrder() { - List list = new ArrayList(super.getFieldOrder()); + List list = new ArrayList<>(super.getFieldOrder()); list.addAll(Arrays.asList("four", "five")); return list; } diff --git a/test/com/sun/jna/WebStartTest.java b/test/com/sun/jna/WebStartTest.java index 25edd6d908..c3b6229355 100644 --- a/test/com/sun/jna/WebStartTest.java +++ b/test/com/sun/jna/WebStartTest.java @@ -291,7 +291,7 @@ private String findJWS() throws IOException { String JAVA_HOME = System.getProperty("java.home"); String BIN = new File(JAVA_HOME, "/bin").getAbsolutePath(); File javaws = new File(BIN, "javaws" + (Platform.isWindows()?".exe":"")); - List tried = new ArrayList(); + List tried = new ArrayList<>(); tried.add(javaws); if (!javaws.exists()) { // NOTE: OSX puts javaws somewhere else entirely From 7e1307e1fedbf8aa08c6b65fd009c924deb7bb8c Mon Sep 17 00:00:00 2001 From: Daniel Widdis Date: Mon, 20 Nov 2023 01:41:43 -0800 Subject: [PATCH 2/5] Use try-with-resources --- test/com/sun/jna/ELFAnalyserTest.java | 13 +++---------- test/com/sun/jna/WebStartTest.java | 5 +---- 2 files changed, 4 insertions(+), 14 deletions(-) diff --git a/test/com/sun/jna/ELFAnalyserTest.java b/test/com/sun/jna/ELFAnalyserTest.java index 16a7ef5fa2..a8da0b2c4f 100644 --- a/test/com/sun/jna/ELFAnalyserTest.java +++ b/test/com/sun/jna/ELFAnalyserTest.java @@ -128,16 +128,9 @@ public static void afterClass() throws IOException { private static void extractTestFile(File outputFile) throws IOException { String inputPath = "/com/sun/jna/data/" + outputFile.getName(); - InputStream is = ELFAnalyserTest.class.getResourceAsStream(inputPath); - try { - OutputStream os = new FileOutputStream(outputFile); - try { - copyStream(is, os); - } finally { - os.close(); - } - } finally { - is.close(); + try (InputStream is = ELFAnalyserTest.class.getResourceAsStream(inputPath); + OutputStream os = new FileOutputStream(outputFile)) { + copyStream(is, os); } } diff --git a/test/com/sun/jna/WebStartTest.java b/test/com/sun/jna/WebStartTest.java index c3b6229355..2e1b58e3f1 100644 --- a/test/com/sun/jna/WebStartTest.java +++ b/test/com/sun/jna/WebStartTest.java @@ -145,8 +145,7 @@ private void runTestUnderWebStart(String testClass, String testMethod) throws Ex String dir = System.getProperty("jna.builddir", BUILDDIR); String codebase = new File(dir, "jws").toURI().toURL().toString(); - ServerSocket s = new ServerSocket(0); - try { + try (ServerSocket s = new ServerSocket(0)) { s.setSoTimeout(SOCKET_TIMEOUT); int port = s.getLocalPort(); @@ -233,8 +232,6 @@ public void run() { finally { jnlp.delete(); } - } finally { - s.close(); } } From 59721330fa26608b2e4c9f4a4433b593d8141691 Mon Sep 17 00:00:00 2001 From: Daniel Widdis Date: Mon, 20 Nov 2023 01:42:42 -0800 Subject: [PATCH 3/5] Use Multi-catch --- src/com/sun/jna/CallbackReference.java | 5 +---- src/com/sun/jna/Klass.java | 18 +----------------- src/com/sun/jna/Native.java | 6 +----- src/com/sun/jna/NativeLibrary.java | 6 +----- src/com/sun/jna/Structure.java | 4 +--- src/com/sun/jna/VarArgsChecker.java | 4 +--- src/com/sun/jna/internal/ReflectionUtils.java | 4 +--- .../sun/jna/StructureFieldOrderInspector.java | 4 +--- 8 files changed, 8 insertions(+), 43 deletions(-) diff --git a/src/com/sun/jna/CallbackReference.java b/src/com/sun/jna/CallbackReference.java index cc2376b0d3..b452b94244 100644 --- a/src/com/sun/jna/CallbackReference.java +++ b/src/com/sun/jna/CallbackReference.java @@ -584,10 +584,7 @@ private Object invokeCallback(Object[] args) { try { result = convertResult(callbackMethod.invoke(cb, callbackArgs)); } - catch (IllegalArgumentException e) { - Native.getCallbackExceptionHandler().uncaughtException(cb, e); - } - catch (IllegalAccessException e) { + catch (IllegalArgumentException | IllegalAccessException e) { Native.getCallbackExceptionHandler().uncaughtException(cb, e); } catch (InvocationTargetException e) { diff --git a/src/com/sun/jna/Klass.java b/src/com/sun/jna/Klass.java index da16e6f8c6..aee4282a28 100644 --- a/src/com/sun/jna/Klass.java +++ b/src/com/sun/jna/Klass.java @@ -46,23 +46,7 @@ private Klass() { public static T newInstance(Class klass) { try { return klass.getDeclaredConstructor().newInstance(); - } catch (IllegalAccessException e) { - String msg = "Can't create an instance of " + klass - + ", requires a public no-arg constructor: " + e; - throw new IllegalArgumentException(msg, e); - } catch (IllegalArgumentException e) { - String msg = "Can't create an instance of " + klass - + ", requires a public no-arg constructor: " + e; - throw new IllegalArgumentException(msg, e); - } catch (InstantiationException e) { - String msg = "Can't create an instance of " + klass - + ", requires a public no-arg constructor: " + e; - throw new IllegalArgumentException(msg, e); - } catch (NoSuchMethodException e) { - String msg = "Can't create an instance of " + klass - + ", requires a public no-arg constructor: " + e; - throw new IllegalArgumentException(msg, e); - } catch (SecurityException e) { + } catch (IllegalAccessException | IllegalArgumentException | InstantiationException | NoSuchMethodException | SecurityException e) { String msg = "Can't create an instance of " + klass + ", requires a public no-arg constructor: " + e; throw new IllegalArgumentException(msg, e); diff --git a/src/com/sun/jna/Native.java b/src/com/sun/jna/Native.java index d057031482..8cfc033f92 100644 --- a/src/com/sun/jna/Native.java +++ b/src/com/sun/jna/Native.java @@ -397,11 +397,7 @@ private static Charset getCharset(String encoding) { try { charset = Charset.forName(encoding); } - catch(IllegalCharsetNameException e) { - LOG.log(Level.WARNING, "JNA Warning: Encoding ''{0}'' is unsupported ({1})", - new Object[]{encoding, e.getMessage()}); - } - catch(UnsupportedCharsetException e) { + catch(IllegalCharsetNameException | UnsupportedCharsetException e) { LOG.log(Level.WARNING, "JNA Warning: Encoding ''{0}'' is unsupported ({1})", new Object[]{encoding, e.getMessage()}); } diff --git a/src/com/sun/jna/NativeLibrary.java b/src/com/sun/jna/NativeLibrary.java index 4cfd9b0001..ae274fda15 100644 --- a/src/com/sun/jna/NativeLibrary.java +++ b/src/com/sun/jna/NativeLibrary.java @@ -350,11 +350,7 @@ private static void addSuppressedReflected(Throwable target, Throwable suppresse } try { addSuppressedMethod.invoke(target, suppressed); - } catch (IllegalAccessException ex) { - throw new RuntimeException("Failed to call addSuppressedMethod", ex); - } catch (IllegalArgumentException ex) { - throw new RuntimeException("Failed to call addSuppressedMethod", ex); - } catch (InvocationTargetException ex) { + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new RuntimeException("Failed to call addSuppressedMethod", ex); } } diff --git a/src/com/sun/jna/Structure.java b/src/com/sun/jna/Structure.java index 0f1f3975d2..cd2b7bd3d8 100644 --- a/src/com/sun/jna/Structure.java +++ b/src/com/sun/jna/Structure.java @@ -2325,9 +2325,7 @@ static void validate(Class cls) { try { cls.getConstructor(); return; - }catch(NoSuchMethodException e) { - } - catch(SecurityException e) { + }catch(NoSuchMethodException | SecurityException e) { } throw new IllegalArgumentException("No suitable constructor found for class: " + cls.getName()); } diff --git a/src/com/sun/jna/VarArgsChecker.java b/src/com/sun/jna/VarArgsChecker.java index ae3a5cdf29..7d25a7b0db 100644 --- a/src/com/sun/jna/VarArgsChecker.java +++ b/src/com/sun/jna/VarArgsChecker.java @@ -83,9 +83,7 @@ static VarArgsChecker create() { } else { return new NoVarArgsChecker(); } - } catch (NoSuchMethodException e) { - return new NoVarArgsChecker(); - } catch (SecurityException e) { + } catch (NoSuchMethodException | SecurityException e) { return new NoVarArgsChecker(); } } diff --git a/src/com/sun/jna/internal/ReflectionUtils.java b/src/com/sun/jna/internal/ReflectionUtils.java index ee85767da3..72e9cb3c4b 100644 --- a/src/com/sun/jna/internal/ReflectionUtils.java +++ b/src/com/sun/jna/internal/ReflectionUtils.java @@ -136,9 +136,7 @@ public static boolean isDefault(Method method) { } try { return (boolean) (Boolean) METHOD_IS_DEFAULT.invoke(method); - } catch (IllegalAccessException ex) { - throw new RuntimeException(ex); - } catch (IllegalArgumentException ex) { + } catch (IllegalAccessException | IllegalArgumentException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { Throwable cause = ex.getCause(); diff --git a/test/com/sun/jna/StructureFieldOrderInspector.java b/test/com/sun/jna/StructureFieldOrderInspector.java index 1ce040c301..a9c26fc92b 100644 --- a/test/com/sun/jna/StructureFieldOrderInspector.java +++ b/test/com/sun/jna/StructureFieldOrderInspector.java @@ -172,9 +172,7 @@ public static void checkMethodGetFieldOrder(final Class str final Structure structure; try { structure= structConstructor.newInstance(); - } catch (InstantiationException e) { - throw new RuntimeException("Could not instantiate Structure sub type: " + structureSubType.getName(), e); - } catch (IllegalAccessException e) { + } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("Could not instantiate Structure sub type: " + structureSubType.getName(), e); } catch (InvocationTargetException e) { // this is triggered by checks in Structure.getFields(), and static loadlibrary() failures From bfb4ddc2fef60c17e60fd64c272d4a305182bb85 Mon Sep 17 00:00:00 2001 From: Daniel Widdis Date: Mon, 20 Nov 2023 01:44:27 -0800 Subject: [PATCH 4/5] Use constants for system properties --- src/com/sun/jna/Native.java | 2 +- src/com/sun/jna/Structure.java | 2 +- test/com/sun/jna/DirectTest.java | 5 +++-- test/com/sun/jna/MemoryTest.java | 2 +- test/com/sun/jna/NativeTest.java | 4 ++-- test/com/sun/jna/StructureTest.java | 2 +- 6 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/com/sun/jna/Native.java b/src/com/sun/jna/Native.java index 8cfc033f92..0ebacfee59 100644 --- a/src/com/sun/jna/Native.java +++ b/src/com/sun/jna/Native.java @@ -221,7 +221,7 @@ static boolean isCompatibleVersion(String expectedVersion, String nativeVersion) loadNativeDispatchLibrary(); if (! isCompatibleVersion(VERSION_NATIVE, getNativeVersion())) { - String LS = System.getProperty("line.separator"); + String LS = System.lineSeparator(); throw new Error(LS + LS + "There is an incompatible JNA native library installed on this system" + LS + "Expected: " + VERSION_NATIVE + LS diff --git a/src/com/sun/jna/Structure.java b/src/com/sun/jna/Structure.java index cd2b7bd3d8..86a3acff85 100644 --- a/src/com/sun/jna/Structure.java +++ b/src/com/sun/jna/Structure.java @@ -1563,7 +1563,7 @@ private String format(Class type) { private String toString(int indent, boolean showContents, boolean dumpMemory) { ensureAllocated(); - String LS = System.getProperty("line.separator"); + String LS = System.lineSeparator(); String name = format(getClass()) + "(" + getPointer() + ")"; if (!(getPointer() instanceof Memory)) { name += " (" + size() + " bytes)"; diff --git a/test/com/sun/jna/DirectTest.java b/test/com/sun/jna/DirectTest.java index 953a796ae9..5f88c6f4e2 100644 --- a/test/com/sun/jna/DirectTest.java +++ b/test/com/sun/jna/DirectTest.java @@ -28,6 +28,7 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; +import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -203,7 +204,7 @@ public void testGetOptionsForDirectMappingWithMemberInitializer() { }; final TypeMapper mapper = new DefaultTypeMapper(); final int alignment = Structure.ALIGN_NONE; - final String encoding = System.getProperty("file.encoding"); + final String encoding = Charset.defaultCharset().displayName(); Map options = new HashMap<>(); options.put(Library.OPTION_TYPE_MAPPER, mapper); options.put(Library.OPTION_STRUCTURE_ALIGNMENT, alignment); @@ -224,7 +225,7 @@ public void testGetOptionsForDirectMappingWithMemberInitializer() { public static class DirectMappingStatic { final static TypeMapper TEST_MAPPER = new DefaultTypeMapper(); final static int TEST_ALIGNMENT = Structure.ALIGN_DEFAULT; - final static String TEST_ENCODING = System.getProperty("file.encoding"); + final static String TEST_ENCODING = Charset.defaultCharset().displayName(); final static Map TEST_OPTIONS = new HashMap() { private static final long serialVersionUID = 1L; // we're not serializing it diff --git a/test/com/sun/jna/MemoryTest.java b/test/com/sun/jna/MemoryTest.java index 1e695cce73..5cbbafff06 100644 --- a/test/com/sun/jna/MemoryTest.java +++ b/test/com/sun/jna/MemoryTest.java @@ -172,7 +172,7 @@ public void testDump() { m.setByte(i, (byte) i); } - String ls = System.getProperty("line.separator"); + String ls = System.lineSeparator(); assertEquals("memory dump" + ls + "[00010203]" + ls + diff --git a/test/com/sun/jna/NativeTest.java b/test/com/sun/jna/NativeTest.java index 7a9ffcb3fc..c29e6c14e0 100644 --- a/test/com/sun/jna/NativeTest.java +++ b/test/com/sun/jna/NativeTest.java @@ -85,7 +85,7 @@ public void testLongStringGeneration() { } public void testCustomStringEncoding() throws Exception { - final String ENCODING = System.getProperty("file.encoding"); + final String ENCODING = Charset.defaultCharset().displayName(); // 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"; @@ -477,7 +477,7 @@ public void testGetBytesWithCharset() throws Exception { public void testGetBytesBadEncoding() throws Exception { byte[] buf = Native.getBytes(getName(), "unsupported"); assertEquals("Incorrect fallback bytes with bad encoding", - getName(), new String(buf, System.getProperty("file.encoding"))); + getName(), new String(buf, Charset.defaultCharset().displayName())); } public void testFindDirectMappedClassFailure() { diff --git a/test/com/sun/jna/StructureTest.java b/test/com/sun/jna/StructureTest.java index 0a6002a8df..93918ea95f 100644 --- a/test/com/sun/jna/StructureTest.java +++ b/test/com/sun/jna/StructureTest.java @@ -1429,7 +1429,7 @@ protected List getFieldOrder() { } } TestStructure s = new TestStructure(); - final String LS = System.getProperty("line.separator"); + final String LS = System.lineSeparator(); System.setProperty("jna.dump_memory", "true"); final String EXPECTED = "(?m).*" + s.size() + " bytes.*\\{" + LS + " int intField@0x0=0x0000" + LS From e643f5f65aac5d0793d0594b5cdefe88ffbf26fe Mon Sep 17 00:00:00 2001 From: Daniel Widdis Date: Mon, 20 Nov 2023 14:11:45 -0800 Subject: [PATCH 5/5] Change Charset displayName to Name to use canonical encoding Signed-off-by: Daniel Widdis --- test/com/sun/jna/DirectTest.java | 4 ++-- test/com/sun/jna/NativeTest.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/com/sun/jna/DirectTest.java b/test/com/sun/jna/DirectTest.java index 5f88c6f4e2..203e9a2669 100644 --- a/test/com/sun/jna/DirectTest.java +++ b/test/com/sun/jna/DirectTest.java @@ -204,7 +204,7 @@ public void testGetOptionsForDirectMappingWithMemberInitializer() { }; final TypeMapper mapper = new DefaultTypeMapper(); final int alignment = Structure.ALIGN_NONE; - final String encoding = Charset.defaultCharset().displayName(); + final String encoding = Charset.defaultCharset().name(); Map options = new HashMap<>(); options.put(Library.OPTION_TYPE_MAPPER, mapper); options.put(Library.OPTION_STRUCTURE_ALIGNMENT, alignment); @@ -225,7 +225,7 @@ public void testGetOptionsForDirectMappingWithMemberInitializer() { public static class DirectMappingStatic { final static TypeMapper TEST_MAPPER = new DefaultTypeMapper(); final static int TEST_ALIGNMENT = Structure.ALIGN_DEFAULT; - final static String TEST_ENCODING = Charset.defaultCharset().displayName(); + final static String TEST_ENCODING = Charset.defaultCharset().name(); final static Map TEST_OPTIONS = new HashMap() { private static final long serialVersionUID = 1L; // we're not serializing it diff --git a/test/com/sun/jna/NativeTest.java b/test/com/sun/jna/NativeTest.java index c29e6c14e0..0dd7bf8d63 100644 --- a/test/com/sun/jna/NativeTest.java +++ b/test/com/sun/jna/NativeTest.java @@ -85,7 +85,7 @@ public void testLongStringGeneration() { } public void testCustomStringEncoding() throws Exception { - final String ENCODING = Charset.defaultCharset().displayName(); + final String ENCODING = Charset.defaultCharset().name(); // 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"; @@ -477,7 +477,7 @@ public void testGetBytesWithCharset() throws Exception { public void testGetBytesBadEncoding() throws Exception { byte[] buf = Native.getBytes(getName(), "unsupported"); assertEquals("Incorrect fallback bytes with bad encoding", - getName(), new String(buf, Charset.defaultCharset().displayName())); + getName(), new String(buf, Charset.defaultCharset().name())); } public void testFindDirectMappedClassFailure() {