diff options
author | Sven Gothel <[email protected]> | 2014-07-03 16:06:47 +0200 |
---|---|---|
committer | Sven Gothel <[email protected]> | 2014-07-03 16:06:47 +0200 |
commit | df9ff7f340a5ab4e07efc613f5f264eeae63d4c7 (patch) | |
tree | 239ae276b82024b140428e6c0fe5d739fdd686a4 /src/java/com | |
parent | eb47aaba63e3b1bf55f274a0f338f1010a017ae4 (diff) |
Code Clean-Up based on our Recommended Settings (jogamp-scripting c47bc86ae2ee268a1f38c5580d11f93d7f8d6e74)
Code Clean-Up based on our Recommended Settings (jogamp-scripting c47bc86ae2ee268a1f38c5580d11f93d7f8d6e74)
- Change non static accesses to static members using declaring type
- Change indirect accesses to static members to direct accesses (accesses through subtypes)
- Add final modifier to private fields
- Add final modifier to method parameters
- Add final modifier to local variables
- Remove unnecessary casts
- Remove unnecessary '$NON-NLS$' tags
- Remove trailing white spaces on all lines
Diffstat (limited to 'src/java/com')
99 files changed, 2022 insertions, 2019 deletions
diff --git a/src/java/com/jogamp/common/GlueGenVersion.java b/src/java/com/jogamp/common/GlueGenVersion.java index a20b153..f97aba6 100644 --- a/src/java/com/jogamp/common/GlueGenVersion.java +++ b/src/java/com/jogamp/common/GlueGenVersion.java @@ -36,7 +36,7 @@ public class GlueGenVersion extends JogampVersion { protected static volatile GlueGenVersion jogampCommonVersionInfo; - protected GlueGenVersion(String packageName, Manifest mf) { + protected GlueGenVersion(final String packageName, final Manifest mf) { super(packageName, mf); } @@ -59,7 +59,7 @@ public class GlueGenVersion extends JogampVersion { return jogampCommonVersionInfo; } - public static void main(String args[]) { + public static void main(final String args[]) { System.err.println(VersionUtil.getPlatformInfo()); System.err.println(GlueGenVersion.getInstance()); } diff --git a/src/java/com/jogamp/common/JogampRuntimeException.java b/src/java/com/jogamp/common/JogampRuntimeException.java index 7298812..d33d498 100644 --- a/src/java/com/jogamp/common/JogampRuntimeException.java +++ b/src/java/com/jogamp/common/JogampRuntimeException.java @@ -40,19 +40,19 @@ public class JogampRuntimeException extends RuntimeException { /** Constructs a JogampRuntimeException object with the specified detail message. */ - public JogampRuntimeException(String message) { + public JogampRuntimeException(final String message) { super(message); } /** Constructs a JogampRuntimeException object with the specified detail message and root cause. */ - public JogampRuntimeException(String message, Throwable cause) { + public JogampRuntimeException(final String message, final Throwable cause) { super(message, cause); } /** Constructs a JogampRuntimeException object with the specified root cause. */ - public JogampRuntimeException(Throwable cause) { + public JogampRuntimeException(final Throwable cause) { super(cause); } } diff --git a/src/java/com/jogamp/common/jvm/JNILibLoaderBase.java b/src/java/com/jogamp/common/jvm/JNILibLoaderBase.java index 673300d..1f11e9e 100644 --- a/src/java/com/jogamp/common/jvm/JNILibLoaderBase.java +++ b/src/java/com/jogamp/common/jvm/JNILibLoaderBase.java @@ -89,7 +89,7 @@ public class JNILibLoaderBase { private static class DefaultAction implements LoaderAction { @Override - public boolean loadLibrary(String libname, boolean ignoreError, ClassLoader cl) { + public boolean loadLibrary(final String libname, final boolean ignoreError, final ClassLoader cl) { boolean res = true; if(!isLoaded(libname)) { try { @@ -98,7 +98,7 @@ public class JNILibLoaderBase { if(DEBUG) { System.err.println("JNILibLoaderBase: loaded "+libname); } - } catch (UnsatisfiedLinkError e) { + } catch (final UnsatisfiedLinkError e) { res = false; if(DEBUG) { e.printStackTrace(); @@ -112,7 +112,7 @@ public class JNILibLoaderBase { } @Override - public void loadLibrary(String libname, String[] preload, boolean preloadIgnoreError, ClassLoader cl) { + public void loadLibrary(final String libname, final String[] preload, final boolean preloadIgnoreError, final ClassLoader cl) { if(!isLoaded(libname)) { if (null!=preload) { for (int i=0; i<preload.length; i++) { @@ -127,11 +127,11 @@ public class JNILibLoaderBase { private static final HashSet<String> loaded = new HashSet<String>(); private static LoaderAction loaderAction = new DefaultAction(); - public static boolean isLoaded(String libName) { + public static boolean isLoaded(final String libName) { return loaded.contains(libName); } - public static void addLoaded(String libName) { + public static void addLoaded(final String libName) { loaded.add(libName); if(DEBUG) { System.err.println("JNILibLoaderBase: Loaded Native Library: "+libName); @@ -146,7 +146,7 @@ public class JNILibLoaderBase { setLoadingAction(new DefaultAction()); } - public static synchronized void setLoadingAction(LoaderAction action) { + public static synchronized void setLoadingAction(final LoaderAction action) { loaderAction = action; } @@ -162,7 +162,7 @@ public class JNILibLoaderBase { * @throws SecurityException * @throws URISyntaxException */ - /* pp */ static final boolean addNativeJarLibsImpl(Class<?> classFromJavaJar, URI classJarURI, String jarBasename, String nativeJarBasename, StringBuilder msg) + /* pp */ static final boolean addNativeJarLibsImpl(final Class<?> classFromJavaJar, final URI classJarURI, final String jarBasename, final String nativeJarBasename, final StringBuilder msg) throws IOException, SecurityException, URISyntaxException { msg.setLength(0); // reset @@ -223,14 +223,14 @@ public class JNILibLoaderBase { * @param nativeJarBasename jogl-all * @return true if the native JAR file loaded successful or were loaded already, false in case of an error */ - public static final boolean addNativeJarLibs(Class<?> classFromJavaJar, String nativeJarBasename) { + public static final boolean addNativeJarLibs(final Class<?> classFromJavaJar, final String nativeJarBasename) { if(TempJarCache.isInitialized()) { final StringBuilder msg = new StringBuilder(); try { final URI classJarURI = JarUtil.getJarURI(classFromJavaJar.getName(), classFromJavaJar.getClassLoader()); final String jarName = JarUtil.getJarBasename(classJarURI); return addNativeJarLibsImpl(classFromJavaJar, classJarURI, jarName, nativeJarBasename+"-natives-"+PlatformPropsImpl.os_and_arch+".jar", msg); - } catch (Exception e0) { + } catch (final Exception e0) { // IllegalArgumentException, IOException System.err.println("Caught "+e0.getClass().getSimpleName()+": "+e0.getMessage()+", while "+msg.toString()); if(DEBUG) { @@ -345,7 +345,7 @@ public class JNILibLoaderBase { * @return true if either the 'all-in-one' native JAR or all native JARs loaded successful or were loaded already, * false in case of an error */ - public static boolean addNativeJarLibs(Class<?>[] classesFromJavaJars, String singleJarMarker, String[] stripBasenameSuffixes) { + public static boolean addNativeJarLibs(final Class<?>[] classesFromJavaJars, final String singleJarMarker, final String[] stripBasenameSuffixes) { if(DEBUG) { System.err.println("JNILibLoaderBase: addNativeJarLibs0(classesFromJavaJars "+Arrays.asList(classesFromJavaJars)+", singleJarMarker "+singleJarMarker+", stripBasenameSuffixes "+(null!=stripBasenameSuffixes?Arrays.asList(stripBasenameSuffixes):"none")); } @@ -372,7 +372,7 @@ public class JNILibLoaderBase { } } } - } catch (Exception e0) { + } catch (final Exception e0) { // IllegalArgumentException, IOException System.err.println("Caught "+e0.getClass().getSimpleName()+": "+e0.getMessage()+", while "+msg.toString()); if(DEBUG) { @@ -389,10 +389,10 @@ public class JNILibLoaderBase { return ok; } - private static final String stripName(String name, String[] suffixes) { + private static final String stripName(final String name, final String[] suffixes) { if(null != suffixes) { for(int i=0; i<suffixes.length && null != suffixes[i]; i++) { - int idx = name.indexOf(suffixes[i]); + final int idx = name.indexOf(suffixes[i]); if(0 < idx) { return name.substring(0, idx); } @@ -409,7 +409,7 @@ public class JNILibLoaderBase { * @param cl optional ClassLoader, used to locate the library * @return true if library loaded successful */ - protected static synchronized boolean loadLibrary(String libname, boolean ignoreError, ClassLoader cl) { + protected static synchronized boolean loadLibrary(final String libname, final boolean ignoreError, final ClassLoader cl) { if (loaderAction != null) { return loaderAction.loadLibrary(libname, ignoreError, cl); } @@ -425,7 +425,7 @@ public class JNILibLoaderBase { * @param preloadIgnoreError if true, errors during loading the preload-libraries should be ignored * @param cl optional ClassLoader, used to locate the library */ - protected static synchronized void loadLibrary(String libname, String[] preload, boolean preloadIgnoreError, ClassLoader cl) { + protected static synchronized void loadLibrary(final String libname, final String[] preload, final boolean preloadIgnoreError, final ClassLoader cl) { if (loaderAction != null) { loaderAction.loadLibrary(libname, preload, preloadIgnoreError, cl); } @@ -442,7 +442,7 @@ public class JNILibLoaderBase { @Override public Method run() { // FIXME: remove - final boolean usingJNLPAppletLauncher = Debug.getBooleanProperty(sunAppletLauncherProperty, true); + final boolean usingJNLPAppletLauncher = PropertyAccess.getBooleanProperty(sunAppletLauncherProperty, true); Class<?> launcherClass = null; Method loadLibraryMethod = null; @@ -450,18 +450,18 @@ public class JNILibLoaderBase { if (usingJNLPAppletLauncher) { try { launcherClass = Class.forName(sunAppletLauncherClassName); - } catch (ClassNotFoundException cnfe) { + } catch (final ClassNotFoundException cnfe) { // oops .. look like JNLPAppletLauncher doesn't exist, despite property // this may happen if a previous applet was using JNLPAppletLauncher in the same JVM System.err.println("JNILibLoaderBase: <"+sunAppletLauncherClassName+"> not found, despite enabled property <"+sunAppletLauncherProperty+">, JNLPAppletLauncher was probably used before"); System.setProperty(sunAppletLauncherProperty, Boolean.FALSE.toString()); - } catch (LinkageError le) { + } catch (final LinkageError le) { throw le; } if(null != launcherClass) { try { loadLibraryMethod = launcherClass.getDeclaredMethod("loadLibrary", new Class[] { String.class }); - } catch (NoSuchMethodException ex) { + } catch (final NoSuchMethodException ex) { if(DEBUG) { ex.printStackTrace(); } @@ -470,16 +470,16 @@ public class JNILibLoaderBase { } } if(null==launcherClass) { - String launcherClassName = PropertyAccess.getProperty("jnlp.launcher.class", false); + final String launcherClassName = PropertyAccess.getProperty("jnlp.launcher.class", false); if(null!=launcherClassName) { try { launcherClass = Class.forName(launcherClassName); loadLibraryMethod = launcherClass.getDeclaredMethod("loadLibrary", new Class[] { String.class }); - } catch (ClassNotFoundException ex) { + } catch (final ClassNotFoundException ex) { if(DEBUG) { ex.printStackTrace(); } - } catch (NoSuchMethodException ex) { + } catch (final NoSuchMethodException ex) { if(DEBUG) { ex.printStackTrace(); } @@ -492,7 +492,7 @@ public class JNILibLoaderBase { customLoadLibraryMethod = loadLibraryMethod; } - private static void loadLibraryInternal(String libraryName, ClassLoader cl) { + private static void loadLibraryInternal(final String libraryName, final ClassLoader cl) { // Note: special-casing JAWT which is built in to the JDK int mode = 0; // 1 - custom, 2 - System.load( TempJarCache ), 3 - System.loadLibrary( name ), 4 - System.load( enumLibNames ) if (null!=customLoadLibraryMethod && !libraryName.equals("jawt")) { @@ -503,7 +503,7 @@ public class JNILibLoaderBase { try { customLoadLibraryMethod.invoke(null, new Object[] { libraryName }); mode = 1; - } catch (Exception e) { + } catch (final Exception e) { Throwable t = e; if (t instanceof InvocationTargetException) { t = ((InvocationTargetException) t).getTargetException(); @@ -536,21 +536,21 @@ public class JNILibLoaderBase { try { System.loadLibrary(libraryName); mode = 3; - } catch (UnsatisfiedLinkError ex1) { + } catch (final UnsatisfiedLinkError ex1) { if(DEBUG) { System.err.println("ERROR (retry w/ enumLibPath) - "+ex1.getMessage()); } - List<String> possiblePaths = NativeLibrary.enumerateLibraryPaths(libraryName, libraryName, libraryName, true, cl); + final List<String> possiblePaths = NativeLibrary.enumerateLibraryPaths(libraryName, libraryName, libraryName, true, cl); // Iterate down these and see which one if any we can actually find. - for (Iterator<String> iter = possiblePaths.iterator(); 0 == mode && iter.hasNext(); ) { - String path = iter.next(); + for (final Iterator<String> iter = possiblePaths.iterator(); 0 == mode && iter.hasNext(); ) { + final String path = iter.next(); if (DEBUG) { System.err.println("JNILibLoaderBase: System.load("+path+") - mode 4"); } try { System.load(path); mode = 4; - } catch (UnsatisfiedLinkError ex2) { + } catch (final UnsatisfiedLinkError ex2) { if(DEBUG) { System.err.println("n/a - "+ex2.getMessage()); } diff --git a/src/java/com/jogamp/common/net/AssetURLConnection.java b/src/java/com/jogamp/common/net/AssetURLConnection.java index 4f2a412..908e329 100644 --- a/src/java/com/jogamp/common/net/AssetURLConnection.java +++ b/src/java/com/jogamp/common/net/AssetURLConnection.java @@ -71,7 +71,7 @@ import java.net.URL; */ public class AssetURLConnection extends PiggybackURLConnection<AssetURLContext> { - public AssetURLConnection(URL url, AssetURLContext implHelper) { + public AssetURLConnection(final URL url, final AssetURLContext implHelper) { super(url, implHelper); } diff --git a/src/java/com/jogamp/common/net/AssetURLContext.java b/src/java/com/jogamp/common/net/AssetURLContext.java index 38691e8..2ada3c6 100644 --- a/src/java/com/jogamp/common/net/AssetURLContext.java +++ b/src/java/com/jogamp/common/net/AssetURLContext.java @@ -59,7 +59,7 @@ public abstract class AssetURLContext implements PiggybackURLContext { * @return * @throws MalformedURLException */ - public static URL createURL(String path, ClassLoader cl) throws MalformedURLException { + public static URL createURL(final String path, final ClassLoader cl) throws MalformedURLException { return new URL(null, path.startsWith(asset_protocol_prefix) ? path : asset_protocol_prefix + path, createHandler(cl)); } @@ -75,7 +75,7 @@ public abstract class AssetURLContext implements PiggybackURLContext { * @return * @throws MalformedURLException */ - public static URL createURL(String path) throws MalformedURLException { + public static URL createURL(final String path) throws MalformedURLException { return new URL(path.startsWith(asset_protocol_prefix) ? path : asset_protocol_prefix + path); } @@ -94,7 +94,7 @@ public abstract class AssetURLContext implements PiggybackURLContext { * * @return true if successful, otherwise false */ - public static boolean registerHandler(ClassLoader cl) { + public static boolean registerHandler(final ClassLoader cl) { final GenericURLStreamHandlerFactory f = GenericURLStreamHandlerFactory.register(); if( null != f ) { f.setHandler(asset_protocol, createHandler(cl)); @@ -141,11 +141,11 @@ public abstract class AssetURLContext implements PiggybackURLContext { * </p> **/ @Override - public URLConnection resolve(String path) throws IOException { + public URLConnection resolve(final String path) throws IOException { return resolve(path, getClassLoader()); } - public static URLConnection resolve(String path, ClassLoader cl) throws IOException { + public static URLConnection resolve(String path, final ClassLoader cl) throws IOException { URL url = null; URLConnection conn = null; int type = -1; @@ -155,7 +155,7 @@ public abstract class AssetURLContext implements PiggybackURLContext { } try { path = IOUtil.cleanPathString(path); - } catch (URISyntaxException uriEx) { + } catch (final URISyntaxException uriEx) { throw new IOException(uriEx); } @@ -164,7 +164,7 @@ public abstract class AssetURLContext implements PiggybackURLContext { url = new URL(path); conn = open(url); type = null != conn ? 1 : -1; - } catch(MalformedURLException e1) { if(DEBUG) { System.err.println("ERR(0): "+e1.getMessage()); } } + } catch(final MalformedURLException e1) { if(DEBUG) { System.err.println("ERR(0): "+e1.getMessage()); } } if(null == conn && null != cl) { // lookup via ClassLoader .. cleanup leading '/' @@ -183,13 +183,13 @@ public abstract class AssetURLContext implements PiggybackURLContext { if(null == conn) { // lookup as File try { - File file = new File(path); + final File file = new File(path); if(file.exists()) { url = IOUtil.toURISimple(file).toURL(); conn = open(url); type = null != conn ? 3 : -1; } - } catch (Throwable e) { if(DEBUG) { System.err.println("ERR(1): "+e.getMessage()); } } + } catch (final Throwable e) { if(DEBUG) { System.err.println("ERR(1): "+e.getMessage()); } } } if(DEBUG) { @@ -201,7 +201,7 @@ public abstract class AssetURLContext implements PiggybackURLContext { return conn; } - private static URLConnection open(URL url) { + private static URLConnection open(final URL url) { if(null==url) { return null; } @@ -209,7 +209,7 @@ public abstract class AssetURLContext implements PiggybackURLContext { final URLConnection c = url.openConnection(); c.connect(); // redundant return c; - } catch (IOException ioe) { if(DEBUG) { System.err.println("ERR: "+ioe.getMessage()); } } + } catch (final IOException ioe) { if(DEBUG) { System.err.println("ERR: "+ioe.getMessage()); } } return null; } diff --git a/src/java/com/jogamp/common/net/AssetURLStreamHandler.java b/src/java/com/jogamp/common/net/AssetURLStreamHandler.java index 6760646..88cedbb 100644 --- a/src/java/com/jogamp/common/net/AssetURLStreamHandler.java +++ b/src/java/com/jogamp/common/net/AssetURLStreamHandler.java @@ -22,12 +22,12 @@ import com.jogamp.common.net.AssetURLConnection; public class AssetURLStreamHandler extends URLStreamHandler { AssetURLContext ctx; - public AssetURLStreamHandler(AssetURLContext ctx) { + public AssetURLStreamHandler(final AssetURLContext ctx) { this.ctx = ctx; } @Override - protected URLConnection openConnection(URL u) throws IOException { + protected URLConnection openConnection(final URL u) throws IOException { final AssetURLConnection c = new AssetURLConnection(u, ctx); c.connect(); return c; diff --git a/src/java/com/jogamp/common/net/GenericURLStreamHandlerFactory.java b/src/java/com/jogamp/common/net/GenericURLStreamHandlerFactory.java index b5c5177..185142f 100644 --- a/src/java/com/jogamp/common/net/GenericURLStreamHandlerFactory.java +++ b/src/java/com/jogamp/common/net/GenericURLStreamHandlerFactory.java @@ -22,7 +22,7 @@ public class GenericURLStreamHandlerFactory implements URLStreamHandlerFactory { * * @return the previous set <code>handler</code>, or null if none was set. */ - public synchronized final URLStreamHandler setHandler(String protocol, URLStreamHandler handler) { + public synchronized final URLStreamHandler setHandler(final String protocol, final URLStreamHandler handler) { return protocolHandlers.put(protocol, handler); } @@ -30,12 +30,12 @@ public class GenericURLStreamHandlerFactory implements URLStreamHandlerFactory { * Returns the <code>protocol</code> handler previously set via {@link #setHandler(String, URLStreamHandler)}, * or null if none was set. */ - public synchronized final URLStreamHandler getHandler(String protocol) { + public synchronized final URLStreamHandler getHandler(final String protocol) { return protocolHandlers.get(protocol); } @Override - public synchronized final URLStreamHandler createURLStreamHandler(String protocol) { + public synchronized final URLStreamHandler createURLStreamHandler(final String protocol) { return getHandler(protocol); } @@ -52,11 +52,11 @@ public class GenericURLStreamHandlerFactory implements URLStreamHandlerFactory { @Override public GenericURLStreamHandlerFactory run() { boolean ok = false; - GenericURLStreamHandlerFactory f = new GenericURLStreamHandlerFactory(); + final GenericURLStreamHandlerFactory f = new GenericURLStreamHandlerFactory(); try { URL.setURLStreamHandlerFactory(f); ok = true; - } catch (Throwable e) { + } catch (final Throwable e) { System.err.println("GenericURLStreamHandlerFactory: Setting URLStreamHandlerFactory failed: "+e.getMessage()); } return ok ? f : null; diff --git a/src/java/com/jogamp/common/net/PiggybackURLConnection.java b/src/java/com/jogamp/common/net/PiggybackURLConnection.java index 3b774e8..6f5f4f0 100644 --- a/src/java/com/jogamp/common/net/PiggybackURLConnection.java +++ b/src/java/com/jogamp/common/net/PiggybackURLConnection.java @@ -24,7 +24,7 @@ public abstract class PiggybackURLConnection<I extends PiggybackURLContext> exte * @param url the specific URL for this instance * @param context the piggyback context, defining state independent code and constants */ - protected PiggybackURLConnection(URL url, I context) { + protected PiggybackURLConnection(final URL url, final I context) { super(url); this.context = context; } diff --git a/src/java/com/jogamp/common/net/URIQueryProps.java b/src/java/com/jogamp/common/net/URIQueryProps.java index fd91b9b..138ff9b 100644 --- a/src/java/com/jogamp/common/net/URIQueryProps.java +++ b/src/java/com/jogamp/common/net/URIQueryProps.java @@ -53,7 +53,7 @@ public class URIQueryProps { private final HashMap<String, String> properties = new HashMap<String, String>(); - private URIQueryProps(char querySeparator) { + private URIQueryProps(final char querySeparator) { query_separator = String.valueOf(querySeparator); } @@ -72,7 +72,7 @@ public class URIQueryProps { needsSep = true; } } - Iterator<Entry<String, String>> entries = properties.entrySet().iterator(); + final Iterator<Entry<String, String>> entries = properties.entrySet().iterator(); while(entries.hasNext()) { if(needsSep) { sb.append(query_separator); @@ -87,7 +87,7 @@ public class URIQueryProps { return sb.toString(); } - public final URI appendQuery(URI base) throws URISyntaxException { + public final URI appendQuery(final URI base) throws URISyntaxException { return new URI(base.getScheme(), base.getRawUserInfo(), base.getHost(), base.getPort(), base.getRawPath(), appendQuery(base.getRawQuery()), base.getRawFragment()); @@ -100,7 +100,7 @@ public class URIQueryProps { * @return * @throws IllegalArgumentException if <code>querySeparator</code> is illegal, i.e. neither <i>;</i> nor <i>&</i> */ - public static final URIQueryProps create(URI uri, char querySeparator) throws IllegalArgumentException { + public static final URIQueryProps create(final URI uri, final char querySeparator) throws IllegalArgumentException { if( ';' != querySeparator && '&' != querySeparator ) { throw new IllegalArgumentException("querySeparator is invalid: "+querySeparator); } @@ -109,7 +109,7 @@ public class URIQueryProps { final int q_l = null != q ? q.length() : -1; int q_e = -1; while(q_e < q_l) { - int q_b = q_e + 1; // next term + final int q_b = q_e + 1; // next term q_e = q.indexOf(querySeparator, q_b); if(0 == q_e) { // single separator diff --git a/src/java/com/jogamp/common/net/asset/Handler.java b/src/java/com/jogamp/common/net/asset/Handler.java index d622221..74fb015 100644 --- a/src/java/com/jogamp/common/net/asset/Handler.java +++ b/src/java/com/jogamp/common/net/asset/Handler.java @@ -29,7 +29,7 @@ public class Handler extends URLStreamHandler { } @Override - protected URLConnection openConnection(URL u) throws IOException { + protected URLConnection openConnection(final URL u) throws IOException { final AssetURLConnection c = new AssetURLConnection(u, localCL); c.connect(); return c; diff --git a/src/java/com/jogamp/common/nio/AbstractBuffer.java b/src/java/com/jogamp/common/nio/AbstractBuffer.java index 1be279b..2da6440 100644 --- a/src/java/com/jogamp/common/nio/AbstractBuffer.java +++ b/src/java/com/jogamp/common/nio/AbstractBuffer.java @@ -60,7 +60,7 @@ public abstract class AbstractBuffer<B extends AbstractBuffer> implements Native * @param elementSize the target element size in bytes. * @param capacity the target capacity in elements of size <code>elementSize</code>. */ - protected AbstractBuffer(Buffer buffer, int elementSize, int capacity) { + protected AbstractBuffer(final Buffer buffer, final int elementSize, final int capacity) { this.buffer = buffer; this.elementSize = elementSize; this.capacity = capacity; @@ -89,7 +89,7 @@ public abstract class AbstractBuffer<B extends AbstractBuffer> implements Native } @Override - public final B position(int newPos) { + public final B position(final int newPos) { if (0 > newPos || newPos >= capacity) { throw new IndexOutOfBoundsException("Sorry to interrupt, but the position "+newPos+" was out of bounds. " + "My capacity is "+capacity()+"."); diff --git a/src/java/com/jogamp/common/nio/Buffers.java b/src/java/com/jogamp/common/nio/Buffers.java index 2a37e47..8fff30e 100644 --- a/src/java/com/jogamp/common/nio/Buffers.java +++ b/src/java/com/jogamp/common/nio/Buffers.java @@ -69,19 +69,19 @@ public class Buffers { * elements. The returned buffer will have its byte order set to * the host platform's native byte order. */ - public static ByteBuffer newDirectByteBuffer(int numElements) { + public static ByteBuffer newDirectByteBuffer(final int numElements) { return nativeOrder(ByteBuffer.allocateDirect(numElements)); } - public static ByteBuffer newDirectByteBuffer(byte[] values, int offset, int length) { + public static ByteBuffer newDirectByteBuffer(final byte[] values, final int offset, final int length) { return (ByteBuffer)newDirectByteBuffer(length).put(values, offset, length).rewind(); } - public static ByteBuffer newDirectByteBuffer(byte[] values, int offset) { + public static ByteBuffer newDirectByteBuffer(final byte[] values, final int offset) { return newDirectByteBuffer(values, offset, values.length-offset); } - public static ByteBuffer newDirectByteBuffer(byte[] values) { + public static ByteBuffer newDirectByteBuffer(final byte[] values) { return newDirectByteBuffer(values, 0); } @@ -90,19 +90,19 @@ public class Buffers { * elements. The returned buffer will have its byte order set to * the host platform's native byte order. */ - public static DoubleBuffer newDirectDoubleBuffer(int numElements) { + public static DoubleBuffer newDirectDoubleBuffer(final int numElements) { return newDirectByteBuffer(numElements * SIZEOF_DOUBLE).asDoubleBuffer(); } - public static DoubleBuffer newDirectDoubleBuffer(double[] values, int offset, int length) { + public static DoubleBuffer newDirectDoubleBuffer(final double[] values, final int offset, final int length) { return (DoubleBuffer)newDirectDoubleBuffer(length).put(values, offset, length).rewind(); } - public static DoubleBuffer newDirectDoubleBuffer(double[] values, int offset) { + public static DoubleBuffer newDirectDoubleBuffer(final double[] values, final int offset) { return newDirectDoubleBuffer(values, offset, values.length - offset); } - public static DoubleBuffer newDirectDoubleBuffer(double[] values) { + public static DoubleBuffer newDirectDoubleBuffer(final double[] values) { return newDirectDoubleBuffer(values, 0); } @@ -111,19 +111,19 @@ public class Buffers { * elements. The returned buffer will have its byte order set to * the host platform's native byte order. */ - public static FloatBuffer newDirectFloatBuffer(int numElements) { + public static FloatBuffer newDirectFloatBuffer(final int numElements) { return newDirectByteBuffer(numElements * SIZEOF_FLOAT).asFloatBuffer(); } - public static FloatBuffer newDirectFloatBuffer(float[] values, int offset, int length) { + public static FloatBuffer newDirectFloatBuffer(final float[] values, final int offset, final int length) { return (FloatBuffer)newDirectFloatBuffer(length).put(values, offset, length).rewind(); } - public static FloatBuffer newDirectFloatBuffer(float[] values, int offset) { + public static FloatBuffer newDirectFloatBuffer(final float[] values, final int offset) { return newDirectFloatBuffer(values, offset, values.length - offset); } - public static FloatBuffer newDirectFloatBuffer(float[] values) { + public static FloatBuffer newDirectFloatBuffer(final float[] values) { return newDirectFloatBuffer(values, 0); } @@ -132,19 +132,19 @@ public class Buffers { * elements. The returned buffer will have its byte order set to * the host platform's native byte order. */ - public static IntBuffer newDirectIntBuffer(int numElements) { + public static IntBuffer newDirectIntBuffer(final int numElements) { return newDirectByteBuffer(numElements * SIZEOF_INT).asIntBuffer(); } - public static IntBuffer newDirectIntBuffer(int[] values, int offset, int length) { + public static IntBuffer newDirectIntBuffer(final int[] values, final int offset, final int length) { return (IntBuffer)newDirectIntBuffer(length).put(values, offset, length).rewind(); } - public static IntBuffer newDirectIntBuffer(int[] values, int offset) { + public static IntBuffer newDirectIntBuffer(final int[] values, final int offset) { return newDirectIntBuffer(values, offset, values.length - offset); } - public static IntBuffer newDirectIntBuffer(int[] values) { + public static IntBuffer newDirectIntBuffer(final int[] values) { return newDirectIntBuffer(values, 0); } @@ -153,19 +153,19 @@ public class Buffers { * elements. The returned buffer will have its byte order set to * the host platform's native byte order. */ - public static LongBuffer newDirectLongBuffer(int numElements) { + public static LongBuffer newDirectLongBuffer(final int numElements) { return newDirectByteBuffer(numElements * SIZEOF_LONG).asLongBuffer(); } - public static LongBuffer newDirectLongBuffer(long[] values, int offset, int length) { + public static LongBuffer newDirectLongBuffer(final long[] values, final int offset, final int length) { return (LongBuffer)newDirectLongBuffer(length).put(values, offset, length).rewind(); } - public static LongBuffer newDirectLongBuffer(long[] values, int offset) { + public static LongBuffer newDirectLongBuffer(final long[] values, final int offset) { return newDirectLongBuffer(values, offset, values.length - offset); } - public static LongBuffer newDirectLongBuffer(long[] values) { + public static LongBuffer newDirectLongBuffer(final long[] values) { return newDirectLongBuffer(values, 0); } @@ -174,19 +174,19 @@ public class Buffers { * elements. The returned buffer will have its byte order set to * the host platform's native byte order. */ - public static ShortBuffer newDirectShortBuffer(int numElements) { + public static ShortBuffer newDirectShortBuffer(final int numElements) { return newDirectByteBuffer(numElements * SIZEOF_SHORT).asShortBuffer(); } - public static ShortBuffer newDirectShortBuffer(short[] values, int offset, int length) { + public static ShortBuffer newDirectShortBuffer(final short[] values, final int offset, final int length) { return (ShortBuffer)newDirectShortBuffer(length).put(values, offset, length).rewind(); } - public static ShortBuffer newDirectShortBuffer(short[] values, int offset) { + public static ShortBuffer newDirectShortBuffer(final short[] values, final int offset) { return newDirectShortBuffer(values, offset, values.length - offset); } - public static ShortBuffer newDirectShortBuffer(short[] values) { + public static ShortBuffer newDirectShortBuffer(final short[] values) { return newDirectShortBuffer(values, 0); } @@ -195,19 +195,19 @@ public class Buffers { * elements. The returned buffer will have its byte order set to * the host platform's native byte order. */ - public static CharBuffer newDirectCharBuffer(int numElements) { + public static CharBuffer newDirectCharBuffer(final int numElements) { return newDirectByteBuffer(numElements * SIZEOF_SHORT).asCharBuffer(); } - public static CharBuffer newDirectCharBuffer(char[] values, int offset, int length) { + public static CharBuffer newDirectCharBuffer(final char[] values, final int offset, final int length) { return (CharBuffer)newDirectCharBuffer(length).put(values, offset, length).rewind(); } - public static CharBuffer newDirectCharBuffer(char[] values, int offset) { + public static CharBuffer newDirectCharBuffer(final char[] values, final int offset) { return newDirectCharBuffer(values, offset, values.length - offset); } - public static CharBuffer newDirectCharBuffer(char[] values) { + public static CharBuffer newDirectCharBuffer(final char[] values) { return newDirectCharBuffer(values, 0); } @@ -216,7 +216,7 @@ public class Buffers { * @see #slice(java.nio.Buffer, int, int) */ @SuppressWarnings("unchecked") - public static <B extends Buffer> B slice(B buffer) { + public static <B extends Buffer> B slice(final B buffer) { if (buffer instanceof ByteBuffer) { final ByteBuffer bb = (ByteBuffer) buffer; return (B) bb.slice().order(bb.order()); // slice and duplicate may change byte order @@ -242,9 +242,9 @@ public class Buffers { * Concurrency warning: this method changes the buffers position and limit but * will restore it before return. */ - public static <B extends Buffer> B slice(B buffer, int offset, int size) { - int pos = buffer.position(); - int limit = buffer.limit(); + public static <B extends Buffer> B slice(final B buffer, final int offset, final int size) { + final int pos = buffer.position(); + final int limit = buffer.limit(); B slice = null; try { @@ -280,7 +280,7 @@ public class Buffers { * @param floatSize {@link Buffers#SIZEOF_FLOAT} size * @return FloatBuffer w/ native byte order as given ByteBuffer */ - public static final FloatBuffer slice2Float(Buffer buf, int floatStartPos, int floatSize) { + public static final FloatBuffer slice2Float(final Buffer buf, final int floatStartPos, final int floatSize) { final int pos; final int limit; if(null != buf) { @@ -293,12 +293,12 @@ public class Buffers { final FloatBuffer res; try { if(buf instanceof ByteBuffer) { - ByteBuffer bb = (ByteBuffer) buf; + final ByteBuffer bb = (ByteBuffer) buf; bb.position( floatStartPos * Buffers.SIZEOF_FLOAT ); bb.limit( (floatStartPos + floatSize) * Buffers.SIZEOF_FLOAT ); res = bb.slice().order(bb.order()).asFloatBuffer(); // slice and duplicate may change byte order } else if(buf instanceof FloatBuffer) { - FloatBuffer fb = (FloatBuffer) buf; + final FloatBuffer fb = (FloatBuffer) buf; fb.position( floatStartPos ); fb.limit( floatStartPos + floatSize ); res = fb.slice(); // slice and duplicate may change byte order @@ -335,7 +335,7 @@ public class Buffers { * @param floatSize {@link Buffers#SIZEOF_FLOAT} size * @return FloatBuffer w/ native byte order as given ByteBuffer */ - public static final FloatBuffer slice2Float(float[] backing, int floatStartPos, int floatSize) { + public static final FloatBuffer slice2Float(final float[] backing, final int floatStartPos, final int floatSize) { return (FloatBuffer) FloatBuffer.wrap(backing, floatStartPos, floatSize).mark(); } @@ -345,7 +345,7 @@ public class Buffers { * that operation is supported by the underlying NIO * implementation. */ - public static ByteBuffer nativeOrder(ByteBuffer buf) { + public static ByteBuffer nativeOrder(final ByteBuffer buf) { return buf.order(ByteOrder.nativeOrder()); } @@ -353,7 +353,7 @@ public class Buffers { * Returns the size of a single element of the given buffer in bytes * or <code>0</code> if the given buffer is <code>null</code>. */ - public static int sizeOfBufferElem(Object buffer) { + public static int sizeOfBufferElem(final Object buffer) { if (buffer == null) { return 0; } @@ -384,7 +384,7 @@ public class Buffers { * @return If <code>buffer</code> is null, returns <code>0<code>, otherwise the remaining size in elements. * @throws IllegalArgumentException if <code>buffer</code> is of invalid type. */ - public static int remainingElem(Object buffer) throws IllegalArgumentException { + public static int remainingElem(final Object buffer) throws IllegalArgumentException { if (buffer == null) { return 0; } @@ -404,13 +404,13 @@ public class Buffers { * @return If <code>buffer</code> is null, returns <code>0<code>, otherwise the remaining size in bytes. * @throws IllegalArgumentException if <code>buffer</code> is of invalid type. */ - public static int remainingBytes(Object buffer) throws IllegalArgumentException { + public static int remainingBytes(final Object buffer) throws IllegalArgumentException { if (buffer == null) { return 0; } final int bytesRemaining; if (buffer instanceof Buffer) { - int elementsRemaining = ((Buffer) buffer).remaining(); + final int elementsRemaining = ((Buffer) buffer).remaining(); if (buffer instanceof ByteBuffer) { bytesRemaining = elementsRemaining; } else if (buffer instanceof FloatBuffer) { @@ -441,7 +441,7 @@ public class Buffers { * Helper routine to tell whether a buffer is direct or not. Null * pointers <b>are</b> considered direct. */ - public static boolean isDirect(Object buf) { + public static boolean isDirect(final Object buf) { if (buf == null) { return true; } @@ -478,7 +478,7 @@ public class Buffers { * account the Buffer position and the underlying type. This is * the total offset for Direct Buffers. */ - public static int getDirectBufferByteOffset(Object buf) { + public static int getDirectBufferByteOffset(final Object buf) { if (buf == null) { return 0; } @@ -513,7 +513,7 @@ public class Buffers { * @throws UnsupportedOperationException if the passed Object does not have an array backing store * @throws IllegalArgumentException if the passed Object is neither of type {@link java.nio.Buffer} or {@link NativeBuffer}. */ - public static Object getArray(Object buf) throws UnsupportedOperationException, IllegalArgumentException { + public static Object getArray(final Object buf) throws UnsupportedOperationException, IllegalArgumentException { if (buf == null) { return null; } @@ -532,7 +532,7 @@ public class Buffers { * object. The array offset also includes the position offset * within the buffer, in addition to any array offset. */ - public static int getIndirectBufferByteOffset(Object buf) { + public static int getIndirectBufferByteOffset(final Object buf) { if (buf == null) { return 0; } @@ -573,9 +573,9 @@ public class Buffers { * order. The position of the newly-allocated buffer will be zero, * and the position of the passed buffer is unchanged. */ - public static ByteBuffer copyByteBuffer(ByteBuffer orig) { + public static ByteBuffer copyByteBuffer(final ByteBuffer orig) { final int op0 = orig.position(); - ByteBuffer dest = newDirectByteBuffer(orig.remaining()); + final ByteBuffer dest = newDirectByteBuffer(orig.remaining()); dest.put(orig); dest.rewind(); orig.position(op0); @@ -590,7 +590,7 @@ public class Buffers { * order. The position of the newly-allocated buffer will be zero, * and the position of the passed buffer is unchanged. */ - public static FloatBuffer copyFloatBuffer(FloatBuffer orig) { + public static FloatBuffer copyFloatBuffer(final FloatBuffer orig) { return copyFloatBufferAsByteBuffer(orig).asFloatBuffer(); } @@ -602,7 +602,7 @@ public class Buffers { * order. The position of the newly-allocated buffer will be zero, * and the position of the passed buffer is unchanged. */ - public static IntBuffer copyIntBuffer(IntBuffer orig) { + public static IntBuffer copyIntBuffer(final IntBuffer orig) { return copyIntBufferAsByteBuffer(orig).asIntBuffer(); } @@ -614,7 +614,7 @@ public class Buffers { * order. The position of the newly-allocated buffer will be zero, * and the position of the passed buffer is unchanged. */ - public static ShortBuffer copyShortBuffer(ShortBuffer orig) { + public static ShortBuffer copyShortBuffer(final ShortBuffer orig) { return copyShortBufferAsByteBuffer(orig).asShortBuffer(); } @@ -629,9 +629,9 @@ public class Buffers { * order. The position of the newly-allocated buffer will be zero, * and the position of the passed buffer is unchanged. */ - public static ByteBuffer copyFloatBufferAsByteBuffer(FloatBuffer orig) { + public static ByteBuffer copyFloatBufferAsByteBuffer(final FloatBuffer orig) { final int op0 = orig.position(); - ByteBuffer dest = newDirectByteBuffer(orig.remaining() * SIZEOF_FLOAT); + final ByteBuffer dest = newDirectByteBuffer(orig.remaining() * SIZEOF_FLOAT); dest.asFloatBuffer().put(orig); dest.rewind(); orig.position(op0); @@ -646,9 +646,9 @@ public class Buffers { * order. The position of the newly-allocated buffer will be zero, * and the position of the passed buffer is unchanged. */ - public static ByteBuffer copyIntBufferAsByteBuffer(IntBuffer orig) { + public static ByteBuffer copyIntBufferAsByteBuffer(final IntBuffer orig) { final int op0 = orig.position(); - ByteBuffer dest = newDirectByteBuffer(orig.remaining() * SIZEOF_INT); + final ByteBuffer dest = newDirectByteBuffer(orig.remaining() * SIZEOF_INT); dest.asIntBuffer().put(orig); dest.rewind(); orig.position(op0); @@ -663,9 +663,9 @@ public class Buffers { * order. The position of the newly-allocated buffer will be zero, * and the position of the passed buffer is unchanged. */ - public static ByteBuffer copyShortBufferAsByteBuffer(ShortBuffer orig) { + public static ByteBuffer copyShortBufferAsByteBuffer(final ShortBuffer orig) { final int op0 = orig.position(); - ByteBuffer dest = newDirectByteBuffer(orig.remaining() * SIZEOF_SHORT); + final ByteBuffer dest = newDirectByteBuffer(orig.remaining() * SIZEOF_SHORT); dest.asShortBuffer().put(orig); dest.rewind(); orig.position(op0); @@ -684,7 +684,7 @@ public class Buffers { * @param len the payload of elements to be copied, if <code>len < 0</code> then <code>len = source.length - soffset</code> * @return the passed or newly created target array */ - public static float[] getFloatArray(double[] source, int soffset, float[] dest, int doffset, int len) { + public static float[] getFloatArray(final double[] source, final int soffset, float[] dest, int doffset, int len) { if(0>len) { len = source.length - soffset; } @@ -710,7 +710,7 @@ public class Buffers { * @param dest the target buffer, if null, a new buffer is being created with size </code>source.remaining()</code> * @return the passed or newly created target buffer */ - public static FloatBuffer getFloatBuffer(DoubleBuffer source, FloatBuffer dest) { + public static FloatBuffer getFloatBuffer(final DoubleBuffer source, FloatBuffer dest) { if(null == dest) { dest = newDirectFloatBuffer(source.remaining()); } @@ -731,7 +731,7 @@ public class Buffers { * @param len the payload of elements to be copied, if <code>len < 0</code> then <code>len = source.length - soffset</code> * @return the passed or newly created target array */ - public static double[] getDoubleArray(float[] source, int soffset, double[] dest, int doffset, int len) { + public static double[] getDoubleArray(final float[] source, final int soffset, double[] dest, int doffset, int len) { if(0>len) { len = source.length - soffset; } @@ -757,7 +757,7 @@ public class Buffers { * @param dest the target buffer, if null, a new buffer is being created with size </code>source.remaining()</code> * @return the passed or newly created target buffer */ - public static DoubleBuffer getDoubleBuffer(FloatBuffer source, DoubleBuffer dest) { + public static DoubleBuffer getDoubleBuffer(final FloatBuffer source, DoubleBuffer dest) { if(null == dest) { dest = newDirectDoubleBuffer(source.remaining()); } @@ -776,7 +776,7 @@ public class Buffers { // @SuppressWarnings("unchecked") - public static <B extends Buffer> B put(B dest, Buffer src) { + public static <B extends Buffer> B put(final B dest, final Buffer src) { if ((dest instanceof ByteBuffer) && (src instanceof ByteBuffer)) { return (B) ((ByteBuffer) dest).put((ByteBuffer) src); } else if ((dest instanceof ShortBuffer) && (src instanceof ShortBuffer)) { @@ -796,7 +796,7 @@ public class Buffers { } @SuppressWarnings("unchecked") - public static <B extends Buffer> B putb(B dest, byte v) { + public static <B extends Buffer> B putb(final B dest, final byte v) { if (dest instanceof ByteBuffer) { return (B) ((ByteBuffer) dest).put(v); } else if (dest instanceof ShortBuffer) { @@ -817,7 +817,7 @@ public class Buffers { } @SuppressWarnings("unchecked") - public static <B extends Buffer> B puts(B dest, short v) { + public static <B extends Buffer> B puts(final B dest, final short v) { if (dest instanceof ShortBuffer) { return (B) ((ShortBuffer) dest).put(v); } else if (dest instanceof IntBuffer) { @@ -834,7 +834,7 @@ public class Buffers { } @SuppressWarnings("unchecked") - public static <B extends Buffer> B puti(B dest, int v) { + public static <B extends Buffer> B puti(final B dest, final int v) { if (dest instanceof IntBuffer) { return (B) ((IntBuffer) dest).put(v); } else if (dest instanceof FloatBuffer) { @@ -849,7 +849,7 @@ public class Buffers { } @SuppressWarnings("unchecked") - public static <B extends Buffer> B putf(B dest, float v) { + public static <B extends Buffer> B putf(final B dest, final float v) { if (dest instanceof FloatBuffer) { return (B) ((FloatBuffer) dest).put(v); } else if (dest instanceof DoubleBuffer) { @@ -864,7 +864,7 @@ public class Buffers { } @SuppressWarnings("unchecked") - public static <B extends Buffer> B putd(B dest, double v) { + public static <B extends Buffer> B putd(final B dest, final double v) { if (dest instanceof FloatBuffer) { return (B) ((FloatBuffer) dest).put((float) v); } else { @@ -886,7 +886,7 @@ public class Buffers { * @param sSigned true if source represents a signed value, false if source represents an unsigned value */ @SuppressWarnings("unchecked") - public static <B extends Buffer> B putNb(B dest, boolean dSigned, byte v, boolean sSigned) { + public static <B extends Buffer> B putNb(final B dest, final boolean dSigned, final byte v, final boolean sSigned) { if (dest instanceof ByteBuffer) { return (B) ((ByteBuffer) dest).put( v ); } else if (dest instanceof ShortBuffer) { @@ -910,7 +910,7 @@ public class Buffers { * @param sSigned true if source represents a signed value, false if source represents an unsigned value */ @SuppressWarnings("unchecked") - public static <B extends Buffer> B putNs(B dest, boolean dSigned, short v, boolean sSigned) { + public static <B extends Buffer> B putNs(final B dest, final boolean dSigned, final short v, final boolean sSigned) { if (dest instanceof ByteBuffer) { return (B) ((ByteBuffer) dest).put( ValueConv.short_to_byte(v, sSigned, dSigned) ); } else if (dest instanceof ShortBuffer) { @@ -934,7 +934,7 @@ public class Buffers { * @param sSigned true if source represents a signed value, false if source represents an unsigned value */ @SuppressWarnings("unchecked") - public static <B extends Buffer> B putNi(B dest, boolean dSigned, int v, boolean sSigned) { + public static <B extends Buffer> B putNi(final B dest, final boolean dSigned, final int v, final boolean sSigned) { if (dest instanceof ByteBuffer) { return (B) ((ByteBuffer) dest).put( ValueConv.int_to_byte(v, sSigned, dSigned) ); } else if (dest instanceof ShortBuffer) { @@ -957,7 +957,7 @@ public class Buffers { * @param v source float value to be put in dest buffer */ @SuppressWarnings("unchecked") - public static <B extends Buffer> B putNf(B dest, boolean dSigned, float v) { + public static <B extends Buffer> B putNf(final B dest, final boolean dSigned, final float v) { if (dest instanceof ByteBuffer) { return (B) ((ByteBuffer) dest).put( ValueConv.float_to_byte(v, dSigned) ); } else if (dest instanceof ShortBuffer) { @@ -975,7 +975,7 @@ public class Buffers { // Range check methods // - public static void rangeCheck(byte[] array, int offset, int minElementsRemaining) { + public static void rangeCheck(final byte[] array, final int offset, final int minElementsRemaining) { if (array == null) { return; } @@ -985,7 +985,7 @@ public class Buffers { } } - public static void rangeCheck(char[] array, int offset, int minElementsRemaining) { + public static void rangeCheck(final char[] array, final int offset, final int minElementsRemaining) { if (array == null) { return; } @@ -995,7 +995,7 @@ public class Buffers { } } - public static void rangeCheck(short[] array, int offset, int minElementsRemaining) { + public static void rangeCheck(final short[] array, final int offset, final int minElementsRemaining) { if (array == null) { return; } @@ -1005,7 +1005,7 @@ public class Buffers { } } - public static void rangeCheck(int[] array, int offset, int minElementsRemaining) { + public static void rangeCheck(final int[] array, final int offset, final int minElementsRemaining) { if (array == null) { return; } @@ -1015,7 +1015,7 @@ public class Buffers { } } - public static void rangeCheck(long[] array, int offset, int minElementsRemaining) { + public static void rangeCheck(final long[] array, final int offset, final int minElementsRemaining) { if (array == null) { return; } @@ -1025,7 +1025,7 @@ public class Buffers { } } - public static void rangeCheck(float[] array, int offset, int minElementsRemaining) { + public static void rangeCheck(final float[] array, final int offset, final int minElementsRemaining) { if (array == null) { return; } @@ -1035,7 +1035,7 @@ public class Buffers { } } - public static void rangeCheck(double[] array, int offset, int minElementsRemaining) { + public static void rangeCheck(final double[] array, final int offset, final int minElementsRemaining) { if (array == null) { return; } @@ -1045,7 +1045,7 @@ public class Buffers { } } - public static void rangeCheck(Buffer buffer, int minElementsRemaining) { + public static void rangeCheck(final Buffer buffer, final int minElementsRemaining) { if (buffer == null) { return; } @@ -1061,7 +1061,7 @@ public class Buffers { * @throws IllegalArgumentException if <code>buffer</code> is of invalid type. * @throws IndexOutOfBoundsException if {@link #remainingBytes(Object)} is < <code>minBytesRemaining<code>. */ - public static void rangeCheckBytes(Object buffer, int minBytesRemaining) throws IllegalArgumentException, IndexOutOfBoundsException { + public static void rangeCheckBytes(final Object buffer, final int minBytesRemaining) throws IllegalArgumentException, IndexOutOfBoundsException { if (buffer == null) { return; } @@ -1080,7 +1080,7 @@ public class Buffers { * @param buffer Any valid Buffer instance * @return the modified StringBuilder containing the Buffer details */ - public static StringBuilder toString(StringBuilder sb, String f, Buffer buffer) { + public static StringBuilder toString(StringBuilder sb, final String f, final Buffer buffer) { if(null == sb) { sb = new StringBuilder(); } diff --git a/src/java/com/jogamp/common/nio/CachedBufferFactory.java b/src/java/com/jogamp/common/nio/CachedBufferFactory.java index 6ddff4a..073659c 100644 --- a/src/java/com/jogamp/common/nio/CachedBufferFactory.java +++ b/src/java/com/jogamp/common/nio/CachedBufferFactory.java @@ -75,7 +75,7 @@ public class CachedBufferFactory { this(DEFAULT_ALLOCATION_SIZE, DEFAULT_ALLOCATION_SIZE); } - private CachedBufferFactory(int initialSize, int allocationSize) { + private CachedBufferFactory(final int initialSize, final int allocationSize) { currentBuffer = Buffers.newDirectByteBuffer(initialSize); ALLOCATION_SIZE = allocationSize; } @@ -93,7 +93,7 @@ public class CachedBufferFactory { * Creates a factory with the specified initial size. The allocation size is set to * {@link #DEFAULT_ALLOCATION_SIZE}. */ - public static CachedBufferFactory create(int initialSize) { + public static CachedBufferFactory create(final int initialSize) { return new CachedBufferFactory(initialSize, DEFAULT_ALLOCATION_SIZE); } @@ -103,14 +103,14 @@ public class CachedBufferFactory { * @param fixed Creates a fixed size factory which will handle overflows (initial size) * with RuntimeExceptions. */ - public static CachedBufferFactory create(int initialSize, boolean fixed) { + public static CachedBufferFactory create(final int initialSize, final boolean fixed) { return new CachedBufferFactory(initialSize, fixed?-1:DEFAULT_ALLOCATION_SIZE); } /** * Creates a factory with the specified initial size and allocation size. */ - public static CachedBufferFactory create(int initialSize, int allocationSize) { + public static CachedBufferFactory create(final int initialSize, final int allocationSize) { return new CachedBufferFactory(initialSize, allocationSize); } @@ -125,21 +125,21 @@ public class CachedBufferFactory { /** * Synchronized version of {@link #create(int)}. */ - public static CachedBufferFactory createSynchronized(int initialSize) { + public static CachedBufferFactory createSynchronized(final int initialSize) { return new SynchronizedCachedBufferFactory(initialSize, DEFAULT_ALLOCATION_SIZE); } /** * Synchronized version of {@link #create(int, boolean)}. */ - public static CachedBufferFactory createSynchronized(int initialSize, boolean fixed) { + public static CachedBufferFactory createSynchronized(final int initialSize, final boolean fixed) { return new SynchronizedCachedBufferFactory(initialSize, fixed?-1:DEFAULT_ALLOCATION_SIZE); } /** * Synchronized version of {@link #create(int, int)}. */ - public static CachedBufferFactory createSynchronized(int initialSize, int allocationSize) { + public static CachedBufferFactory createSynchronized(final int initialSize, final int allocationSize) { return new CachedBufferFactory(initialSize, allocationSize); } @@ -174,7 +174,7 @@ public class CachedBufferFactory { currentBuffer = null; } } - public ByteBuffer newDirectByteBuffer(int size) { + public ByteBuffer newDirectByteBuffer(final int size) { // if large enough... just create it if (size > currentBuffer.capacity()) { @@ -189,123 +189,123 @@ public class CachedBufferFactory { } currentBuffer.limit(currentBuffer.position() + size); - ByteBuffer result = currentBuffer.slice().order(currentBuffer.order()); + final ByteBuffer result = currentBuffer.slice().order(currentBuffer.order()); currentBuffer.position(currentBuffer.limit()); currentBuffer.limit(currentBuffer.capacity()); return result; } - public ByteBuffer newDirectByteBuffer(byte[] values, int offset, int lenght) { + public ByteBuffer newDirectByteBuffer(final byte[] values, final int offset, final int lenght) { return (ByteBuffer)newDirectByteBuffer(lenght).put(values, offset, lenght).rewind(); } - public ByteBuffer newDirectByteBuffer(byte[] values, int offset) { + public ByteBuffer newDirectByteBuffer(final byte[] values, final int offset) { return newDirectByteBuffer(values, offset, values.length-offset); } - public ByteBuffer newDirectByteBuffer(byte[] values) { + public ByteBuffer newDirectByteBuffer(final byte[] values) { return newDirectByteBuffer(values, 0); } - public DoubleBuffer newDirectDoubleBuffer(int numElements) { + public DoubleBuffer newDirectDoubleBuffer(final int numElements) { return newDirectByteBuffer(numElements * Buffers.SIZEOF_DOUBLE).asDoubleBuffer(); } - public DoubleBuffer newDirectDoubleBuffer(double[] values, int offset, int lenght) { + public DoubleBuffer newDirectDoubleBuffer(final double[] values, final int offset, final int lenght) { return (DoubleBuffer)newDirectDoubleBuffer(lenght).put(values, offset, lenght).rewind(); } - public DoubleBuffer newDirectDoubleBuffer(double[] values, int offset) { + public DoubleBuffer newDirectDoubleBuffer(final double[] values, final int offset) { return newDirectDoubleBuffer(values, offset, values.length - offset); } - public DoubleBuffer newDirectDoubleBuffer(double[] values) { + public DoubleBuffer newDirectDoubleBuffer(final double[] values) { return newDirectDoubleBuffer(values, 0); } - public FloatBuffer newDirectFloatBuffer(int numElements) { + public FloatBuffer newDirectFloatBuffer(final int numElements) { return newDirectByteBuffer(numElements * Buffers.SIZEOF_FLOAT).asFloatBuffer(); } - public FloatBuffer newDirectFloatBuffer(float[] values, int offset, int lenght) { + public FloatBuffer newDirectFloatBuffer(final float[] values, final int offset, final int lenght) { return (FloatBuffer)newDirectFloatBuffer(lenght).put(values, offset, lenght).rewind(); } - public FloatBuffer newDirectFloatBuffer(float[] values, int offset) { + public FloatBuffer newDirectFloatBuffer(final float[] values, final int offset) { return newDirectFloatBuffer(values, offset, values.length - offset); } - public FloatBuffer newDirectFloatBuffer(float[] values) { + public FloatBuffer newDirectFloatBuffer(final float[] values) { return newDirectFloatBuffer(values, 0); } - public IntBuffer newDirectIntBuffer(int numElements) { + public IntBuffer newDirectIntBuffer(final int numElements) { return newDirectByteBuffer(numElements * Buffers.SIZEOF_INT).asIntBuffer(); } - public IntBuffer newDirectIntBuffer(int[] values, int offset, int lenght) { + public IntBuffer newDirectIntBuffer(final int[] values, final int offset, final int lenght) { return (IntBuffer)newDirectIntBuffer(lenght).put(values, offset, lenght).rewind(); } - public IntBuffer newDirectIntBuffer(int[] values, int offset) { + public IntBuffer newDirectIntBuffer(final int[] values, final int offset) { return newDirectIntBuffer(values, offset, values.length - offset); } - public IntBuffer newDirectIntBuffer(int[] values) { + public IntBuffer newDirectIntBuffer(final int[] values) { return newDirectIntBuffer(values, 0); } - public LongBuffer newDirectLongBuffer(int numElements) { + public LongBuffer newDirectLongBuffer(final int numElements) { return newDirectByteBuffer(numElements * Buffers.SIZEOF_LONG).asLongBuffer(); } - public LongBuffer newDirectLongBuffer(long[] values, int offset, int lenght) { + public LongBuffer newDirectLongBuffer(final long[] values, final int offset, final int lenght) { return (LongBuffer)newDirectLongBuffer(lenght).put(values, offset, lenght).rewind(); } - public LongBuffer newDirectLongBuffer(long[] values, int offset) { + public LongBuffer newDirectLongBuffer(final long[] values, final int offset) { return newDirectLongBuffer(values, offset, values.length - offset); } - public LongBuffer newDirectLongBuffer(long[] values) { + public LongBuffer newDirectLongBuffer(final long[] values) { return newDirectLongBuffer(values, 0); } - public ShortBuffer newDirectShortBuffer(int numElements) { + public ShortBuffer newDirectShortBuffer(final int numElements) { return newDirectByteBuffer(numElements * Buffers.SIZEOF_SHORT).asShortBuffer(); } - public ShortBuffer newDirectShortBuffer(short[] values, int offset, int lenght) { + public ShortBuffer newDirectShortBuffer(final short[] values, final int offset, final int lenght) { return (ShortBuffer)newDirectShortBuffer(lenght).put(values, offset, lenght).rewind(); } - public ShortBuffer newDirectShortBuffer(short[] values, int offset) { + public ShortBuffer newDirectShortBuffer(final short[] values, final int offset) { return newDirectShortBuffer(values, offset, values.length - offset); } - public ShortBuffer newDirectShortBuffer(short[] values) { + public ShortBuffer newDirectShortBuffer(final short[] values) { return newDirectShortBuffer(values, 0); } - public CharBuffer newDirectCharBuffer(int numElements) { + public CharBuffer newDirectCharBuffer(final int numElements) { return newDirectByteBuffer(numElements * Buffers.SIZEOF_SHORT).asCharBuffer(); } - public CharBuffer newDirectCharBuffer(char[] values, int offset, int lenght) { + public CharBuffer newDirectCharBuffer(final char[] values, final int offset, final int lenght) { return (CharBuffer)newDirectCharBuffer(lenght).put(values, offset, lenght).rewind(); } - public CharBuffer newDirectCharBuffer(char[] values, int offset) { + public CharBuffer newDirectCharBuffer(final char[] values, final int offset) { return newDirectCharBuffer(values, offset, values.length - offset); } - public CharBuffer newDirectCharBuffer(char[] values) { + public CharBuffer newDirectCharBuffer(final char[] values) { return newDirectCharBuffer(values, 0); } @Override - public boolean equals(Object obj) { + public boolean equals(final Object obj) { if (obj == null) { return false; } @@ -335,12 +335,12 @@ public class CachedBufferFactory { super(); } - private SynchronizedCachedBufferFactory(int size, int step) { + private SynchronizedCachedBufferFactory(final int size, final int step) { super(size, step); } @Override - public synchronized ByteBuffer newDirectByteBuffer(int size) { + public synchronized ByteBuffer newDirectByteBuffer(final int size) { return super.newDirectByteBuffer(size); } diff --git a/src/java/com/jogamp/common/nio/PointerBuffer.java b/src/java/com/jogamp/common/nio/PointerBuffer.java index 5d470d5..e9138ac 100644 --- a/src/java/com/jogamp/common/nio/PointerBuffer.java +++ b/src/java/com/jogamp/common/nio/PointerBuffer.java @@ -57,17 +57,17 @@ public class PointerBuffer extends AbstractBuffer<PointerBuffer> { } /** no backup array, use for direct usage only */ - static PointerBuffer create(ByteBuffer bb) { + static PointerBuffer create(final ByteBuffer bb) { return Platform.is32Bit() ? new PointerBuffer( bb.asIntBuffer() ) : new PointerBuffer( bb.asLongBuffer() ); } /** supports backup array */ - PointerBuffer(IntBuffer b) { + PointerBuffer(final IntBuffer b) { super(b, ELEMENT_SIZE, b.capacity()); } /** supports backup array */ - PointerBuffer(LongBuffer b) { + PointerBuffer(final LongBuffer b) { super(b, ELEMENT_SIZE, b.capacity()); } @@ -79,7 +79,7 @@ public class PointerBuffer extends AbstractBuffer<PointerBuffer> { } /** Returns a non direct PointerBuffer in native order, having a backup array */ - public static PointerBuffer allocate(int size) { + public static PointerBuffer allocate(final int size) { if (Platform.is32Bit()) { return new PointerBuffer(IntBuffer.wrap(new int[size])); } else { @@ -88,11 +88,11 @@ public class PointerBuffer extends AbstractBuffer<PointerBuffer> { } /** Returns a direct PointerBuffer in native order, w/o backup array */ - public static PointerBuffer allocateDirect(int size) { + public static PointerBuffer allocateDirect(final int size) { return create(Buffers.newDirectByteBuffer(ELEMENT_SIZE * size)); } - public static PointerBuffer wrap(ByteBuffer src) { + public static PointerBuffer wrap(final ByteBuffer src) { return create(src); } @@ -118,7 +118,7 @@ public class PointerBuffer extends AbstractBuffer<PointerBuffer> { * Relative bulk get method. Copy the source values <code> src[position .. capacity] [</code> * to this buffer and increment the position by <code>capacity-position</code>. */ @Override - public final PointerBuffer put(PointerBuffer src) { + public final PointerBuffer put(final PointerBuffer src) { if (remaining() < src.remaining()) { throw new IndexOutOfBoundsException(); } @@ -132,7 +132,7 @@ public class PointerBuffer extends AbstractBuffer<PointerBuffer> { final long addr = src.get(); put(addr); if( null != src.dataMap) { - Buffer bb = (Buffer) src.dataMap.get(addr); + final Buffer bb = (Buffer) src.dataMap.get(addr); if(null!=bb) { validateDataMap(); dataMap.put(addr, bb); @@ -150,19 +150,19 @@ public class PointerBuffer extends AbstractBuffer<PointerBuffer> { /** Relative get method. Get the pointer value at the current position and increment the position by one. */ @Override public final long get() { - long r = get(position); + final long r = get(position); position++; return r; } /** Absolute get method. Get the pointer value at the given index */ @Override - public final long get(int idx) { + public final long get(final int idx) { if (0 > idx || idx >= capacity) { throw new IndexOutOfBoundsException(); } if (Platform.is32Bit()) { - return (long) ((IntBuffer) buffer).get(idx) & 0x00000000FFFFFFFFL; + return ((IntBuffer) buffer).get(idx) & 0x00000000FFFFFFFFL; } else { return ((LongBuffer) buffer).get(idx); } @@ -172,7 +172,7 @@ public class PointerBuffer extends AbstractBuffer<PointerBuffer> { * Relative bulk get method. Copy the pointer values <code> [ position .. position+length [</code> * to the destination array <code> [ dest[offset] .. dest[offset+length] [ </code> * and increment the position by <code>length</code>. */ - public final PointerBuffer get(long[] dest, int offset, int length) { + public final PointerBuffer get(final long[] dest, int offset, int length) { if (dest.length<offset+length) { throw new IndexOutOfBoundsException(); } @@ -188,7 +188,7 @@ public class PointerBuffer extends AbstractBuffer<PointerBuffer> { /** Absolute put method. Put the pointer value at the given index */ @Override - public final PointerBuffer put(int idx, long v) { + public final PointerBuffer put(final int idx, final long v) { if (0 > idx || idx >= capacity) { throw new IndexOutOfBoundsException(); } @@ -202,7 +202,7 @@ public class PointerBuffer extends AbstractBuffer<PointerBuffer> { /** Relative put method. Put the pointer value at the current position and increment the position by one. */ @Override - public final PointerBuffer put(long value) { + public final PointerBuffer put(final long value) { put(position, value); position++; return this; @@ -211,7 +211,7 @@ public class PointerBuffer extends AbstractBuffer<PointerBuffer> { /** * Relative bulk put method. Put the pointer values <code> [ src[offset] .. src[offset+length] [</code> * at the current position and increment the position by <code>length</code>. */ - public final PointerBuffer put(long[] src, int offset, int length) { + public final PointerBuffer put(final long[] src, int offset, int length) { if (src.length<offset+length) { throw new IndexOutOfBoundsException(); } @@ -231,15 +231,15 @@ public class PointerBuffer extends AbstractBuffer<PointerBuffer> { @throws IllegalArgumentException if bb is null or not a direct buffer */ - public final PointerBuffer referenceBuffer(int index, Buffer bb) { + public final PointerBuffer referenceBuffer(final int index, final Buffer bb) { if(null==bb) { throw new IllegalArgumentException("Buffer is null"); } if(!Buffers.isDirect(bb)) { throw new IllegalArgumentException("Buffer is not direct"); } - long mask = Platform.is32Bit() ? 0x00000000FFFFFFFFL : 0xFFFFFFFFFFFFFFFFL ; - long bbAddr = getDirectBufferAddressImpl(bb) & mask; + final long mask = Platform.is32Bit() ? 0x00000000FFFFFFFFL : 0xFFFFFFFFFFFFFFFFL ; + final long bbAddr = getDirectBufferAddressImpl(bb) & mask; if(0==bbAddr) { throw new RuntimeException("Couldn't determine native address of given Buffer: "+bb); } @@ -252,22 +252,22 @@ public class PointerBuffer extends AbstractBuffer<PointerBuffer> { /** Put the address of the given direct Buffer at the end of this pointer array. Adding a reference of the given direct Buffer to this object. */ - public final PointerBuffer referenceBuffer(Buffer bb) { + public final PointerBuffer referenceBuffer(final Buffer bb) { referenceBuffer(position, bb); position++; return this; } - public final Buffer getReferencedBuffer(int index) { + public final Buffer getReferencedBuffer(final int index) { if(null != dataMap) { - long addr = get(index); + final long addr = get(index); return (Buffer) dataMap.get(addr); } return null; } public final Buffer getReferencedBuffer() { - Buffer bb = getReferencedBuffer(position); + final Buffer bb = getReferencedBuffer(position); position++; return bb; } diff --git a/src/java/com/jogamp/common/nio/StructAccessor.java b/src/java/com/jogamp/common/nio/StructAccessor.java index b1593fe..af7b6d1 100644 --- a/src/java/com/jogamp/common/nio/StructAccessor.java +++ b/src/java/com/jogamp/common/nio/StructAccessor.java @@ -48,7 +48,7 @@ public class StructAccessor { private final ByteBuffer bb; - public StructAccessor(ByteBuffer bb) { + public StructAccessor(final ByteBuffer bb) { // Setting of byte order is concession to native code which needs // to instantiate these this.bb = bb.order(ByteOrder.nativeOrder()); @@ -64,7 +64,7 @@ public class StructAccessor { * bytes. Note that this method is not thread-safe with respect to * the other methods in this class. */ - public final ByteBuffer slice(int byteOffset, int byteLength) { + public final ByteBuffer slice(final int byteOffset, final int byteLength) { bb.position(byteOffset); bb.limit(byteOffset + byteLength); final ByteBuffer newBuf = bb.slice().order(bb.order()); // slice and duplicate may change byte order @@ -74,47 +74,47 @@ public class StructAccessor { } /** Retrieves the byte at the specified byteOffset. */ - public final byte getByteAt(int byteOffset) { + public final byte getByteAt(final int byteOffset) { return bb.get(byteOffset); } /** Puts a byte at the specified byteOffset. */ - public final void setByteAt(int byteOffset, byte v) { + public final void setByteAt(final int byteOffset, final byte v) { bb.put(byteOffset, v); } /** Retrieves the char at the specified byteOffset. */ - public final char getCharAt(int byteOffset) { + public final char getCharAt(final int byteOffset) { return bb.getChar(byteOffset); } /** Puts a char at the specified byteOffset. */ - public final void setCharAt(int byteOffset, char v) { + public final void setCharAt(final int byteOffset, final char v) { bb.putChar(byteOffset, v); } /** Retrieves the short at the specified byteOffset. */ - public final short getShortAt(int byteOffset) { + public final short getShortAt(final int byteOffset) { return bb.getShort(byteOffset); } /** Puts a short at the specified byteOffset. */ - public final void setShortAt(int byteOffset, short v) { + public final void setShortAt(final int byteOffset, final short v) { bb.putShort(byteOffset, v); } /** Retrieves the int at the specified byteOffset. */ - public final int getIntAt(int byteOffset) { + public final int getIntAt(final int byteOffset) { return bb.getInt(byteOffset); } /** Puts a int at the specified byteOffset. */ - public final void setIntAt(int byteOffset, int v) { + public final void setIntAt(final int byteOffset, final int v) { bb.putInt(byteOffset, v); } /** Retrieves the int at the specified byteOffset. */ - public final int getIntAt(int byteOffset, int nativeSizeInBytes) { + public final int getIntAt(final int byteOffset, final int nativeSizeInBytes) { switch(nativeSizeInBytes) { case 2: return bb.getShort(byteOffset) & 0x0000FFFF ; @@ -128,7 +128,7 @@ public class StructAccessor { } /** Puts a int at the specified byteOffset. */ - public final void setIntAt(int byteOffset, int v, int nativeSizeInBytes) { + public final void setIntAt(final int byteOffset, final int v, final int nativeSizeInBytes) { switch(nativeSizeInBytes) { case 2: bb.putShort(byteOffset, (short) ( v & 0x0000FFFF ) ); @@ -145,37 +145,37 @@ public class StructAccessor { } /** Retrieves the float at the specified byteOffset. */ - public final float getFloatAt(int byteOffset) { + public final float getFloatAt(final int byteOffset) { return bb.getFloat(byteOffset); } /** Puts a float at the specified byteOffset. */ - public final void setFloatAt(int byteOffset, float v) { + public final void setFloatAt(final int byteOffset, final float v) { bb.putFloat(byteOffset, v); } /** Retrieves the double at the specified byteOffset. */ - public final double getDoubleAt(int byteOffset) { + public final double getDoubleAt(final int byteOffset) { return bb.getDouble(byteOffset); } /** Puts a double at the specified byteOffset. */ - public final void setDoubleAt(int byteOffset, double v) { + public final void setDoubleAt(final int byteOffset, final double v) { bb.putDouble(byteOffset, v); } /** Retrieves the long at the specified byteOffset. */ - public final long getLongAt(int byteOffset) { + public final long getLongAt(final int byteOffset) { return bb.getLong(byteOffset); } /** Puts a long at the specified byteOffset. */ - public final void setLongAt(int byteOffset, long v) { + public final void setLongAt(final int byteOffset, final long v) { bb.putLong(byteOffset, v); } /** Retrieves the long at the specified byteOffset. */ - public final long getLongAt(int byteOffset, int nativeSizeInBytes) { + public final long getLongAt(final int byteOffset, final int nativeSizeInBytes) { switch(nativeSizeInBytes) { case 4: return bb.getInt(byteOffset) & 0x00000000FFFFFFFFL; @@ -187,7 +187,7 @@ public class StructAccessor { } /** Puts a long at the specified byteOffset. */ - public final void setLongAt(int byteOffset, long v, int nativeSizeInBytes) { + public final void setLongAt(final int byteOffset, final long v, final int nativeSizeInBytes) { switch(nativeSizeInBytes) { case 4: bb.putInt(byteOffset, (int) ( v & 0x00000000FFFFFFFFL ) ); @@ -200,91 +200,91 @@ public class StructAccessor { } } - public final void setBytesAt(int byteOffset, byte[] v) { + public final void setBytesAt(int byteOffset, final byte[] v) { for (int i = 0; i < v.length; i++) { bb.put(byteOffset++, v[i]); } } - public final byte[] getBytesAt(int byteOffset, byte[] v) { + public final byte[] getBytesAt(int byteOffset, final byte[] v) { for (int i = 0; i < v.length; i++) { v[i] = bb.get(byteOffset++); } return v; } - public final void setCharsAt(int byteOffset, char[] v) { + public final void setCharsAt(int byteOffset, final char[] v) { for (int i = 0; i < v.length; i++, byteOffset+=2) { bb.putChar(byteOffset, v[i]); } } - public final char[] getCharsAt(int byteOffset, char[] v) { + public final char[] getCharsAt(int byteOffset, final char[] v) { for (int i = 0; i < v.length; i++, byteOffset+=2) { v[i] = bb.getChar(byteOffset); } return v; } - public final void setShortsAt(int byteOffset, short[] v) { + public final void setShortsAt(int byteOffset, final short[] v) { for (int i = 0; i < v.length; i++, byteOffset+=2) { bb.putShort(byteOffset, v[i]); } } - public final short[] getShortsAt(int byteOffset, short[] v) { + public final short[] getShortsAt(int byteOffset, final short[] v) { for (int i = 0; i < v.length; i++, byteOffset+=2) { v[i] = bb.getShort(byteOffset); } return v; } - public final void setIntsAt(int byteOffset, int[] v) { + public final void setIntsAt(int byteOffset, final int[] v) { for (int i = 0; i < v.length; i++, byteOffset+=4) { bb.putInt(byteOffset, v[i]); } } - public final int[] getIntsAt(int byteOffset, int[] v) { + public final int[] getIntsAt(int byteOffset, final int[] v) { for (int i = 0; i < v.length; i++, byteOffset+=4) { v[i] = bb.getInt(byteOffset); } return v; } - public final void setFloatsAt(int byteOffset, float[] v) { + public final void setFloatsAt(int byteOffset, final float[] v) { for (int i = 0; i < v.length; i++, byteOffset+=4) { bb.putFloat(byteOffset, v[i]); } } - public final float[] getFloatsAt(int byteOffset, float[] v) { + public final float[] getFloatsAt(int byteOffset, final float[] v) { for (int i = 0; i < v.length; i++, byteOffset+=4) { v[i] = bb.getFloat(byteOffset); } return v; } - public final void setDoublesAt(int byteOffset, double[] v) { + public final void setDoublesAt(int byteOffset, final double[] v) { for (int i = 0; i < v.length; i++, byteOffset+=8) { bb.putDouble(byteOffset, v[i]); } } - public final double[] getDoublesAt(int byteOffset, double[] v) { + public final double[] getDoublesAt(int byteOffset, final double[] v) { for (int i = 0; i < v.length; i++, byteOffset+=8) { v[i] = bb.getDouble(byteOffset); } return v; } - public final void setLongsAt(int byteOffset, long[] v) { + public final void setLongsAt(int byteOffset, final long[] v) { for (int i = 0; i < v.length; i++, byteOffset+=8) { bb.putLong(byteOffset, v[i]); } } - public final long[] getLongsAt(int byteOffset, long[] v) { + public final long[] getLongsAt(int byteOffset, final long[] v) { for (int i = 0; i < v.length; i++, byteOffset+=8) { v[i] = bb.getLong(byteOffset); } diff --git a/src/java/com/jogamp/common/os/AndroidVersion.java b/src/java/com/jogamp/common/os/AndroidVersion.java index edf2229..adfb1ef 100644 --- a/src/java/com/jogamp/common/os/AndroidVersion.java +++ b/src/java/com/jogamp/common/os/AndroidVersion.java @@ -82,7 +82,7 @@ public class AndroidVersion { * </pre> * </p> */ - private static final CPUType getCPUTypeImpl(String cpuABI) { + private static final CPUType getCPUTypeImpl(final String cpuABI) { if( null == cpuABI ) { return null; } else if( cpuABI.equals("armeabi-v7a") ) { @@ -98,7 +98,7 @@ public class AndroidVersion { return null; } } - private static final ABIType getABITypeImpl(final CPUType cpuType, String cpuABI) { + private static final ABIType getABITypeImpl(final CPUType cpuType, final String cpuABI) { if( null == cpuType || null == cpuABI ) { return null; } else if( CPUFamily.ARM != cpuType.family ) { @@ -122,7 +122,7 @@ public class AndroidVersion { abvObject = abvClass.newInstance(); abvcClass = ReflectionUtil.getClass(androidBuildVersionCodes, true, cl); abvcObject = abvcClass.newInstance(); - } catch (Exception e) { /* n/a */ } + } catch (final Exception e) { /* n/a */ } isAvailable = null != abObject && null != abvObject && null != abvcObject; if(isAvailable) { CPU_ABI = getString(abClass, abObject, "CPU_ABI", true); @@ -149,38 +149,38 @@ public class AndroidVersion { ABI_TYPE2 = getABITypeImpl(CPU_TYPE2, CPU_ABI2); } - private static final IntObjectHashMap getVersionCodes(Class<?> cls, Object obj) { + private static final IntObjectHashMap getVersionCodes(final Class<?> cls, final Object obj) { final Field[] fields = cls.getFields(); - IntObjectHashMap map = new IntObjectHashMap( 3 * fields.length / 2, 0.75f ); + final IntObjectHashMap map = new IntObjectHashMap( 3 * fields.length / 2, 0.75f ); for(int i=0; i<fields.length; i++) { try { final int version = fields[i].getInt(obj); final String version_name = fields[i].getName(); // System.err.println(i+": "+version+": "+version_name); map.put(new Integer(version), version_name); - } catch (Exception e) { e.printStackTrace(); /* n/a */ } + } catch (final Exception e) { e.printStackTrace(); /* n/a */ } } return map; } - private static final String getString(Class<?> cls, Object obj, String name, boolean lowerCase) { + private static final String getString(final Class<?> cls, final Object obj, final String name, final boolean lowerCase) { try { - Field f = cls.getField(name); + final Field f = cls.getField(name); final String s = (String) f.get(obj); if( lowerCase && null != s ) { return s.toLowerCase(); } else { return s; } - } catch (Exception e) { e.printStackTrace(); /* n/a */ } + } catch (final Exception e) { e.printStackTrace(); /* n/a */ } return null; } - private static final int getInt(Class<?> cls, Object obj, String name) { + private static final int getInt(final Class<?> cls, final Object obj, final String name) { try { - Field f = cls.getField(name); + final Field f = cls.getField(name); return f.getInt(obj); - } catch (Exception e) { e.printStackTrace(); /* n/a */ } + } catch (final Exception e) { e.printStackTrace(); /* n/a */ } return -1; } diff --git a/src/java/com/jogamp/common/os/DynamicLibraryBundle.java b/src/java/com/jogamp/common/os/DynamicLibraryBundle.java index 4013203..ec76154 100644 --- a/src/java/com/jogamp/common/os/DynamicLibraryBundle.java +++ b/src/java/com/jogamp/common/os/DynamicLibraryBundle.java @@ -88,7 +88,7 @@ public class DynamicLibraryBundle implements DynamicLookupHelper { * is being used to help locating the native libraries. * </p> */ - public DynamicLibraryBundle(DynamicLibraryBundleInfo info) { + public DynamicLibraryBundle(final DynamicLibraryBundleInfo info) { if(null==info) { throw new RuntimeException("Null DynamicLibraryBundleInfo"); } @@ -191,7 +191,7 @@ public class DynamicLibraryBundle implements DynamicLookupHelper { return 0 < toolLibLoadedNumber; } - public final boolean isToolLibLoaded(int i) { + public final boolean isToolLibLoaded(final int i) { if(0 <= i && i < toolLibLoaded.length) { return toolLibLoaded[i]; } @@ -217,7 +217,7 @@ public class DynamicLibraryBundle implements DynamicLookupHelper { return 0 == getGlueLibNumber() || isGlueLibLoaded(getGlueLibNumber() - 1); } - public final boolean isGlueLibLoaded(int i) { + public final boolean isGlueLibLoaded(final int i) { if(0 <= i && i < glueLibLoaded.length) { return glueLibLoaded[i]; } @@ -241,7 +241,7 @@ public class DynamicLibraryBundle implements DynamicLookupHelper { return aptr; } - protected final NativeLibrary loadFirstAvailable(List<String> libNames, ClassLoader loader, boolean global) { + protected final NativeLibrary loadFirstAvailable(final List<String> libNames, final ClassLoader loader, final boolean global) { for (int i=0; i < libNames.size(); i++) { final NativeLibrary lib = NativeLibrary.open(libNames.get(i), loader, global); if (lib != null) { @@ -285,14 +285,14 @@ public class DynamicLibraryBundle implements DynamicLookupHelper { glueLibLoadedNumber = 0; for (i=0; i < glueLibNames.size(); i++) { final String libName = glueLibNames.get(i); - boolean ignoreError = true; + final boolean ignoreError = true; boolean res; try { res = GlueJNILibLoader.loadLibrary(libName, ignoreError, cl); if(DEBUG && !res) { System.err.println("Info: Could not load JNI/Glue library: "+libName); } - } catch (UnsatisfiedLinkError e) { + } catch (final UnsatisfiedLinkError e) { res = false; if(DEBUG) { System.err.println("Unable to load JNI/Glue library: "+libName); @@ -306,7 +306,7 @@ public class DynamicLibraryBundle implements DynamicLookupHelper { } } - private final long dynamicLookupFunctionOnLibs(String funcName) { + private final long dynamicLookupFunctionOnLibs(final String funcName) { if(!isToolLibLoaded() || null==funcName) { if(DEBUG_LOOKUP && !isToolLibLoaded()) { System.err.println("Lookup-Native: <" + funcName + "> ** FAILED ** Tool native library not loaded"); @@ -326,7 +326,7 @@ public class DynamicLibraryBundle implements DynamicLookupHelper { addr = lib.dynamicLookupFunction(funcName); } if(DEBUG_LOOKUP) { - String libName = ( null == lib ) ? "GLOBAL" : lib.toString(); + final String libName = ( null == lib ) ? "GLOBAL" : lib.toString(); if(0!=addr) { System.err.println("Lookup-Native: <" + funcName + "> 0x" + Long.toHexString(addr) + " in lib " + libName ); } else { @@ -336,9 +336,9 @@ public class DynamicLibraryBundle implements DynamicLookupHelper { return addr; } - private final long toolDynamicLookupFunction(String funcName) { + private final long toolDynamicLookupFunction(final String funcName) { if(0 != toolGetProcAddressHandle) { - long addr = info.toolGetProcAddress(toolGetProcAddressHandle, funcName); + final long addr = info.toolGetProcAddress(toolGetProcAddressHandle, funcName); if(DEBUG_LOOKUP) { if(0!=addr) { System.err.println("Lookup-Tool: <"+funcName+"> 0x"+Long.toHexString(addr)); @@ -350,7 +350,7 @@ public class DynamicLibraryBundle implements DynamicLookupHelper { } @Override - public final long dynamicLookupFunction(String funcName) { + public final long dynamicLookupFunction(final String funcName) { if(!isToolLibLoaded() || null==funcName) { if(DEBUG_LOOKUP && !isToolLibLoaded()) { System.err.println("Lookup: <" + funcName + "> ** FAILED ** Tool native library not loaded"); @@ -378,13 +378,13 @@ public class DynamicLibraryBundle implements DynamicLookupHelper { } @Override - public final boolean isFunctionAvailable(String funcName) { + public final boolean isFunctionAvailable(final String funcName) { return 0 != dynamicLookupFunction(funcName); } /** Inherit access */ static final class GlueJNILibLoader extends JNILibLoaderBase { - protected static synchronized boolean loadLibrary(String libname, boolean ignoreError, ClassLoader cl) { + protected static synchronized boolean loadLibrary(final String libname, final boolean ignoreError, final ClassLoader cl) { return JNILibLoaderBase.loadLibrary(libname, ignoreError, cl); } } diff --git a/src/java/com/jogamp/common/os/MachineDescription.java b/src/java/com/jogamp/common/os/MachineDescription.java index 8ff3ff7..ca9819a 100644 --- a/src/java/com/jogamp/common/os/MachineDescription.java +++ b/src/java/com/jogamp/common/os/MachineDescription.java @@ -64,7 +64,7 @@ public class MachineDescription { public final Platform.CPUType cpu; - ID(Platform.CPUType cpu){ + ID(final Platform.CPUType cpu){ this.cpu = cpu; } } @@ -106,7 +106,7 @@ public class MachineDescription { public final ID id; public final MachineDescription md; - StaticConfig(ID id, boolean littleEndian, int[] sizes, int[] alignments) { + StaticConfig(final ID id, final boolean littleEndian, final int[] sizes, final int[] alignments) { this.id = id; int i=0, j=0; this.md = new MachineDescription(false, littleEndian, @@ -174,27 +174,27 @@ public class MachineDescription { final private int ldoubleAlignmentInBytes; final private int pointerAlignmentInBytes; - public MachineDescription(boolean runtimeValidated, - boolean littleEndian, - - int intSizeInBytes, - int longSizeInBytes, - int floatSizeInBytes, - int doubleSizeInBytes, - int ldoubleSizeInBytes, - int pointerSizeInBytes, - int pageSizeInBytes, - - int int8AlignmentInBytes, - int int16AlignmentInBytes, - int int32AlignmentInBytes, - int int64AlignmentInBytes, - int intAlignmentInBytes, - int longAlignmentInBytes, - int floatAlignmentInBytes, - int doubleAlignmentInBytes, - int ldoubleAlignmentInBytes, - int pointerAlignmentInBytes) { + public MachineDescription(final boolean runtimeValidated, + final boolean littleEndian, + + final int intSizeInBytes, + final int longSizeInBytes, + final int floatSizeInBytes, + final int doubleSizeInBytes, + final int ldoubleSizeInBytes, + final int pointerSizeInBytes, + final int pageSizeInBytes, + + final int int8AlignmentInBytes, + final int int16AlignmentInBytes, + final int int32AlignmentInBytes, + final int int64AlignmentInBytes, + final int intAlignmentInBytes, + final int longAlignmentInBytes, + final int floatAlignmentInBytes, + final int doubleAlignmentInBytes, + final int ldoubleAlignmentInBytes, + final int pointerAlignmentInBytes) { this.runtimeValidated = runtimeValidated; this.littleEndian = littleEndian; @@ -273,14 +273,14 @@ public class MachineDescription { /** * @return number of pages required for size in bytes */ - public int pageCount(int size) { + public int pageCount(final int size) { return ( size + ( pageSizeInBytes - 1) ) / pageSizeInBytes ; // integer arithmetic } /** * @return page aligned size in bytes */ - public int pageAlignedSize(int size) { + public int pageAlignedSize(final int size) { return pageCount(size) * pageSizeInBytes; } @@ -292,7 +292,7 @@ public class MachineDescription { * otherwise <code>false</code>. */ @Override - public final boolean equals(Object obj) { + public final boolean equals(final Object obj) { if (this == obj) { return true; } if ( !(obj instanceof MachineDescription) ) { return false; } final MachineDescription md = (MachineDescription) obj; @@ -308,7 +308,7 @@ public class MachineDescription { * @return <code>true</code> if the two MachineDescription are equal; * otherwise <code>false</code>. */ - public final boolean compatible(MachineDescription md) { + public final boolean compatible(final MachineDescription md) { return littleEndian == md.littleEndian && intSizeInBytes == md.intSizeInBytes && diff --git a/src/java/com/jogamp/common/os/NativeLibrary.java b/src/java/com/jogamp/common/os/NativeLibrary.java index b6ed7ad..e54f5e6 100644 --- a/src/java/com/jogamp/common/os/NativeLibrary.java +++ b/src/java/com/jogamp/common/os/NativeLibrary.java @@ -123,7 +123,7 @@ public final class NativeLibrary implements DynamicLookupHelper { private final boolean global; // Private constructor to prevent arbitrary instances from floating around - private NativeLibrary(long libraryHandle, String libraryPath, boolean global) { + private NativeLibrary(final long libraryHandle, final String libraryPath, final boolean global) { this.libraryHandle = libraryHandle; this.libraryPath = libraryPath; this.global = global; @@ -141,7 +141,7 @@ public final class NativeLibrary implements DynamicLookupHelper { name on all platforms, looking first in the system's search path, and in the context of the specified ClassLoader, which is used to help find the library in the case of e.g. Java Web Start. */ - public static final NativeLibrary open(String libName, ClassLoader loader) { + public static final NativeLibrary open(final String libName, final ClassLoader loader) { return open(libName, libName, libName, true, loader, true); } @@ -149,7 +149,7 @@ public final class NativeLibrary implements DynamicLookupHelper { name on all platforms, looking first in the system's search path, and in the context of the specified ClassLoader, which is used to help find the library in the case of e.g. Java Web Start. */ - public static final NativeLibrary open(String libName, ClassLoader loader, boolean global) { + public static final NativeLibrary open(final String libName, final ClassLoader loader, final boolean global) { return open(libName, libName, libName, true, loader, global); } @@ -168,27 +168,27 @@ public final class NativeLibrary implements DynamicLookupHelper { dynamic loading facility is used correctly the version number will be irrelevant. */ - public static final NativeLibrary open(String windowsLibName, - String unixLibName, - String macOSXLibName, - boolean searchSystemPathFirst, - ClassLoader loader) { + public static final NativeLibrary open(final String windowsLibName, + final String unixLibName, + final String macOSXLibName, + final boolean searchSystemPathFirst, + final ClassLoader loader) { return open(windowsLibName, unixLibName, macOSXLibName, searchSystemPathFirst, loader, true); } - public static final NativeLibrary open(String windowsLibName, - String unixLibName, - String macOSXLibName, - boolean searchSystemPathFirst, - ClassLoader loader, boolean global) { - List<String> possiblePaths = enumerateLibraryPaths(windowsLibName, + public static final NativeLibrary open(final String windowsLibName, + final String unixLibName, + final String macOSXLibName, + final boolean searchSystemPathFirst, + final ClassLoader loader, final boolean global) { + final List<String> possiblePaths = enumerateLibraryPaths(windowsLibName, unixLibName, macOSXLibName, searchSystemPathFirst, loader); Platform.initSingleton(); // loads native gluegen-rt library // Iterate down these and see which one if any we can actually find. - for (Iterator<String> iter = possiblePaths.iterator(); iter.hasNext(); ) { + for (final Iterator<String> iter = possiblePaths.iterator(); iter.hasNext(); ) { final String path = iter.next(); if (DEBUG) { System.err.println("NativeLibrary.open(global "+global+"): Trying to load " + path); @@ -201,7 +201,7 @@ public final class NativeLibrary implements DynamicLookupHelper { } else { res = dynLink.openLibraryLocal(path, DEBUG); } - } catch (Throwable t1) { + } catch (final Throwable t1) { t = t1; res = 0; } @@ -214,7 +214,7 @@ public final class NativeLibrary implements DynamicLookupHelper { String errstr; try { errstr = dynLink.getLastError(); - } catch (Throwable t2) { errstr=null; } + } catch (final Throwable t2) { errstr=null; } System.err.println("NativeLibrary.open: Last error "+errstr); if( null != t ) { t.printStackTrace(); @@ -233,7 +233,7 @@ public final class NativeLibrary implements DynamicLookupHelper { } @Override - public final long dynamicLookupFunction(String funcName) { + public final long dynamicLookupFunction(final String funcName) { if ( 0 == libraryHandle ) { throw new RuntimeException("Library is not open"); } @@ -241,7 +241,7 @@ public final class NativeLibrary implements DynamicLookupHelper { } @Override - public final boolean isFunctionAvailable(String funcName) { + public final boolean isFunctionAvailable(final String funcName) { if ( 0 == libraryHandle ) { throw new RuntimeException("Library is not open"); } @@ -249,12 +249,12 @@ public final class NativeLibrary implements DynamicLookupHelper { } /** Looks up the given function name in all loaded libraries. */ - public static final long dynamicLookupFunctionGlobal(String funcName) { + public static final long dynamicLookupFunctionGlobal(final String funcName) { return dynLink.lookupSymbolGlobal(funcName); } /** Looks up the given function name in all loaded libraries. */ - public static final boolean isFunctionAvailableGlobal(String funcName) { + public static final boolean isFunctionAvailableGlobal(final String funcName) { return 0 != dynLink.lookupSymbolGlobal(funcName); } @@ -279,7 +279,7 @@ public final class NativeLibrary implements DynamicLookupHelper { if ( 0 == libraryHandle ) { throw new RuntimeException("Library already closed"); } - long handle = libraryHandle; + final long handle = libraryHandle; libraryHandle = 0; dynLink.closeLibrary(handle); if (DEBUG) { @@ -297,11 +297,11 @@ public final class NativeLibrary implements DynamicLookupHelper { * * @return basename of libName w/o path, ie. /usr/lib/libDrinkBeer.so -> DrinkBeer on Unix systems, but null on Windows. */ - public static final String isValidNativeLibraryName(String libName, boolean isLowerCaseAlready) { + public static final String isValidNativeLibraryName(final String libName, final boolean isLowerCaseAlready) { final String libBaseName; try { libBaseName = IOUtil.getBasename(libName); - } catch (URISyntaxException uriEx) { + } catch (final URISyntaxException uriEx) { throw new IllegalArgumentException(uriEx); } final String libBaseNameLC = isLowerCaseAlready ? libBaseName : libBaseName.toLowerCase(); @@ -331,20 +331,20 @@ public final class NativeLibrary implements DynamicLookupHelper { final String macOSXLibName, final boolean searchSystemPathFirst, final ClassLoader loader) { - List<String> paths = new ArrayList<String>(); - String libName = selectName(windowsLibName, unixLibName, macOSXLibName); + final List<String> paths = new ArrayList<String>(); + final String libName = selectName(windowsLibName, unixLibName, macOSXLibName); if (libName == null) { return paths; } // Allow user's full path specification to override our building of paths - File file = new File(libName); + final File file = new File(libName); if (file.isAbsolute()) { paths.add(libName); return paths; } - String[] baseNames = buildNames(libName); + final String[] baseNames = buildNames(libName); if (searchSystemPathFirst) { // Add just the library names to use the OS's search algorithm @@ -402,7 +402,7 @@ public final class NativeLibrary implements DynamicLookupHelper { } // Add current working directory - String userDir = + final String userDir = AccessController.doPrivileged(new PrivilegedAction<String>() { @Override public String run() { @@ -430,9 +430,9 @@ public final class NativeLibrary implements DynamicLookupHelper { } - private static final String selectName(String windowsLibName, - String unixLibName, - String macOSXLibName) { + private static final String selectName(final String windowsLibName, + final String unixLibName, + final String macOSXLibName) { switch (PlatformPropsImpl.OS_TYPE) { case WINDOWS: return windowsLibName; @@ -452,14 +452,14 @@ public final class NativeLibrary implements DynamicLookupHelper { } } - private static final String[] buildNames(String libName) { + private static final String[] buildNames(final String libName) { // If the library name already has the prefix / suffix added // (principally because we want to force a version number on Unix // operating systems) then just return the library name. final String libBaseNameLC; try { libBaseNameLC = IOUtil.getBasename(libName).toLowerCase(); - } catch (URISyntaxException uriEx) { + } catch (final URISyntaxException uriEx) { throw new IllegalArgumentException(uriEx); } @@ -485,7 +485,7 @@ public final class NativeLibrary implements DynamicLookupHelper { for (int i = suffixIdx + suffixes[0].length(); i < libName.length(); i++) { - char c = libName.charAt(i); + final char c = libName.charAt(i); if (!(c == '.' || (c >= '0' && c <= '9'))) { ok = false; break; @@ -497,7 +497,7 @@ public final class NativeLibrary implements DynamicLookupHelper { } } - String[] res = new String[prefixes.length * suffixes.length + + final String[] res = new String[prefixes.length * suffixes.length + ( PlatformPropsImpl.OS_TYPE == Platform.OSType.MACOS ? 1 : 0 )]; int idx = 0; for (int i = 0; i < prefixes.length; i++) { @@ -512,7 +512,7 @@ public final class NativeLibrary implements DynamicLookupHelper { return res; } - private static final void addPaths(String path, String[] baseNames, List<String> paths) { + private static final void addPaths(final String path, final String[] baseNames, final List<String> paths) { for (int j = 0; j < baseNames.length; j++) { paths.add(path + File.separator + baseNames[j]); } @@ -532,7 +532,7 @@ public final class NativeLibrary implements DynamicLookupHelper { findLibraryMethod = ClassLoader.class.getDeclaredMethod("findLibrary", new Class[] { String.class }); findLibraryMethod.setAccessible(true); - } catch (Exception e) { + } catch (final Exception e) { // Fail silently disabling this functionality } initializedFindLibraryMethod = true; @@ -547,12 +547,12 @@ public final class NativeLibrary implements DynamicLookupHelper { public String run() { try { return (String) findLibraryMethod.invoke(loader, new Object[] { libName }); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException(e); } } }); - } catch (Exception e) { + } catch (final Exception e) { if (DEBUG) { e.printStackTrace(); } diff --git a/src/java/com/jogamp/common/os/Platform.java b/src/java/com/jogamp/common/os/Platform.java index 518c772..933947c 100644 --- a/src/java/com/jogamp/common/os/Platform.java +++ b/src/java/com/jogamp/common/os/Platform.java @@ -35,6 +35,7 @@ import java.util.concurrent.TimeUnit; import com.jogamp.common.jvm.JNILibLoaderBase; import com.jogamp.common.util.JarUtil; +import com.jogamp.common.util.PropertyAccess; import com.jogamp.common.util.ReflectionUtil; import com.jogamp.common.util.VersionNumber; import com.jogamp.common.util.cache.TempJarCache; @@ -62,7 +63,7 @@ public class Platform extends PlatformPropsImpl { public final int id; - OSType(int id){ + OSType(final int id){ this.id = id; } } @@ -85,7 +86,7 @@ public class Platform extends PlatformPropsImpl { public final int id; - CPUFamily(int id){ + CPUFamily(final int id){ this.id = id; } } @@ -121,7 +122,7 @@ public class Platform extends PlatformPropsImpl { public final int id; public final CPUFamily family; - CPUType(CPUFamily type, int id){ + CPUType(final CPUFamily type, final int id){ this.family = type; this.id = id; } @@ -138,7 +139,7 @@ public class Platform extends PlatformPropsImpl { public final int id; - ABIType(int id){ + ABIType(final int id){ this.id = id; } } @@ -189,19 +190,19 @@ public class Platform extends PlatformPropsImpl { URI _platformClassJarURI = null; try { _platformClassJarURI = JarUtil.getJarURI(Platform.class.getName(), cl); - } catch (Exception e) { } + } catch (final Exception e) { } platformClassJarURI = _platformClassJarURI; } _isRunningFromJarURL[0] = null != platformClassJarURI; _USE_TEMP_JAR_CACHE[0] = ( OS_TYPE != OSType.ANDROID ) && ( null != platformClassJarURI ) && - Debug.getBooleanProperty(useTempJarCachePropName, true, true); + PropertyAccess.getBooleanProperty(useTempJarCachePropName, true, true); // load GluegenRT native library if(_USE_TEMP_JAR_CACHE[0] && TempJarCache.initSingleton()) { try { JNILibLoaderBase.addNativeJarLibs(new Class<?>[] { Platform.class }, null, null ); - } catch (Exception e0) { + } catch (final Exception e0) { // IllegalArgumentException, IOException System.err.println("Caught "+e0.getClass().getSimpleName()+": "+e0.getMessage()+", while JNILibLoaderBase.addNativeJarLibs(..)"); } @@ -212,12 +213,12 @@ public class Platform extends PlatformPropsImpl { JVMUtil.initSingleton(); // requires gluegen-rt, one-time init. // AWT Headless determination - if( !Debug.getBooleanProperty("java.awt.headless", true) && + if( !PropertyAccess.getBooleanProperty("java.awt.headless", true) && ReflectionUtil.isClassAvailable(ReflectionUtil.AWTNames.ComponentClass, cl) && ReflectionUtil.isClassAvailable(ReflectionUtil.AWTNames.GraphicsEnvironmentClass, cl) ) { try { _AWT_AVAILABLE[0] = false == ((Boolean)ReflectionUtil.callStaticMethod(ReflectionUtil.AWTNames.GraphicsEnvironmentClass, ReflectionUtil.AWTNames.isHeadlessMethod, null, null, cl)).booleanValue(); - } catch (Throwable t) { } + } catch (final Throwable t) { } } return null; } } ); @@ -227,11 +228,11 @@ public class Platform extends PlatformPropsImpl { MachineDescription md = MachineDescriptionRuntime.getRuntime(); if(null == md) { - MachineDescription.StaticConfig smd = MachineDescriptionRuntime.getStatic(); + final MachineDescription.StaticConfig smd = MachineDescriptionRuntime.getStatic(); md = smd.md; System.err.println("Warning: Using static MachineDescription: "+smd); } else { - MachineDescription.StaticConfig smd = MachineDescriptionRuntime.getStatic(); + final MachineDescription.StaticConfig smd = MachineDescriptionRuntime.getStatic(); if(!md.compatible(smd.md)) { throw new RuntimeException("Incompatible MachineDescriptions:"+PlatformPropsImpl.NEWLINE+ " Static "+smd+PlatformPropsImpl.NEWLINE+ @@ -476,7 +477,7 @@ public class Platform extends PlatformPropsImpl { final long nsPeriod = nsDuration / splitInLoops; final long t0_ns = System.nanoTime(); for(int i=splitInLoops; i>0; i--) { - try { TimeUnit.NANOSECONDS.sleep(nsPeriod); } catch (InterruptedException e) { } + try { TimeUnit.NANOSECONDS.sleep(nsPeriod); } catch (final InterruptedException e) { } } return ( ( System.nanoTime() - t0_ns ) - nsDuration ) / splitInLoops; } diff --git a/src/java/com/jogamp/common/util/ArrayHashSet.java b/src/java/com/jogamp/common/util/ArrayHashSet.java index a125580..34e84c4 100644 --- a/src/java/com/jogamp/common/util/ArrayHashSet.java +++ b/src/java/com/jogamp/common/util/ArrayHashSet.java @@ -76,12 +76,12 @@ public class ArrayHashSet<E> data = new ArrayList<E>(); } - public ArrayHashSet(int initialCapacity) { + public ArrayHashSet(final int initialCapacity) { map = new HashMap<E,E>(initialCapacity); data = new ArrayList<E>(initialCapacity); } - public ArrayHashSet(int initialCapacity, float loadFactor) { + public ArrayHashSet(final int initialCapacity, final float loadFactor) { map = new HashMap<E,E>(initialCapacity, loadFactor); data = new ArrayList<E>(initialCapacity); } @@ -130,7 +130,7 @@ public class ArrayHashSet<E> * otherwise false (already contained). */ @Override - public final boolean add(E element) { + public final boolean add(final E element) { final boolean exists = map.containsKey(element); if(!exists) { if(null != map.put(element, element)) { @@ -153,7 +153,7 @@ public class ArrayHashSet<E> * otherwise false (not contained). */ @Override - public final boolean remove(Object element) { + public final boolean remove(final Object element) { if ( null != map.remove(element) ) { if ( ! data.remove(element) ) { throw new InternalError("Couldn't remove prev mapped element: "+element); @@ -172,9 +172,9 @@ public class ArrayHashSet<E> * otherwise false (completely container). */ @Override - public final boolean addAll(Collection<? extends E> c) { + public final boolean addAll(final Collection<? extends E> c) { boolean mod = false; - for (E o : c) { + for (final E o : c) { mod |= add(o); } return mod; @@ -189,7 +189,7 @@ public class ArrayHashSet<E> * otherwise false. */ @Override - public final boolean contains(Object element) { + public final boolean contains(final Object element) { return map.containsKey(element); } @@ -202,8 +202,8 @@ public class ArrayHashSet<E> * otherwise false. */ @Override - public final boolean containsAll(Collection<?> c) { - for (Object o : c) { + public final boolean containsAll(final Collection<?> c) { + for (final Object o : c) { if (!this.contains(o)) { return false; } @@ -220,9 +220,9 @@ public class ArrayHashSet<E> * otherwise false. */ @Override - public final boolean removeAll(Collection<?> c) { + public final boolean removeAll(final Collection<?> c) { boolean mod = false; - for (Object o : c) { + for (final Object o : c) { mod |= this.remove(o); } return mod; @@ -238,9 +238,9 @@ public class ArrayHashSet<E> * otherwise false. */ @Override - public final boolean retainAll(Collection<?> c) { + public final boolean retainAll(final Collection<?> c) { boolean mod = false; - for (Object o : c) { + for (final Object o : c) { if (!c.contains(o)) { mod |= this.remove(o); } @@ -255,7 +255,7 @@ public class ArrayHashSet<E> * Performance: arrayHashSet(1) */ @Override - public final boolean equals(Object arrayHashSet) { + public final boolean equals(final Object arrayHashSet) { if ( !(arrayHashSet instanceof ArrayHashSet) ) { return false; } @@ -294,7 +294,7 @@ public class ArrayHashSet<E> } @Override - public final <T> T[] toArray(T[] a) { + public final <T> T[] toArray(final T[] a) { return data.toArray(a); } @@ -303,12 +303,12 @@ public class ArrayHashSet<E> // @Override - public final E get(int index) { + public final E get(final int index) { return data.get(index); } @Override - public final int indexOf(Object element) { + public final int indexOf(final Object element) { return data.indexOf(element); } @@ -320,7 +320,7 @@ public class ArrayHashSet<E> * @throws IllegalArgumentException if the given element was already contained */ @Override - public final void add(int index, E element) { + public final void add(final int index, final E element) { if ( map.containsKey(element) ) { throw new IllegalArgumentException("Element "+element+" is already contained"); } @@ -334,7 +334,7 @@ public class ArrayHashSet<E> * @throws UnsupportedOperationException */ @Override - public final boolean addAll(int index, Collection<? extends E> c) { + public final boolean addAll(final int index, final Collection<? extends E> c) { throw new UnsupportedOperationException("Not supported yet."); } @@ -342,7 +342,7 @@ public class ArrayHashSet<E> * @throws UnsupportedOperationException */ @Override - public final E set(int index, E element) { + public final E set(final int index, final E element) { final E old = remove(index); if(null!=old) { add(index, element); @@ -358,7 +358,7 @@ public class ArrayHashSet<E> * @return the removed object */ @Override - public final E remove(int index) { + public final E remove(final int index) { final E o = get(index); if( null!=o && remove(o) ) { return o; @@ -374,7 +374,7 @@ public class ArrayHashSet<E> * @return index of element, or -1 if not found */ @Override - public final int lastIndexOf(Object o) { + public final int lastIndexOf(final Object o) { return indexOf(o); } @@ -384,12 +384,12 @@ public class ArrayHashSet<E> } @Override - public final ListIterator<E> listIterator(int index) { + public final ListIterator<E> listIterator(final int index) { return data.listIterator(index); } @Override - public final List<E> subList(int fromIndex, int toIndex) { + public final List<E> subList(final int fromIndex, final int toIndex) { return data.subList(fromIndex, toIndex); } @@ -413,7 +413,7 @@ public class ArrayHashSet<E> * @return object from this list, identical to the given <code>key</code> hash code, * or null if not contained */ - public final E get(Object key) { + public final E get(final Object key) { return map.get(key); } @@ -427,7 +427,7 @@ public class ArrayHashSet<E> * @return object from this list, identical to the given <code>key</code> hash code, * or add the given <code>key</code> and return it. */ - public final E getOrAdd(E key) { + public final E getOrAdd(final E key) { final E identity = get(key); if(null == identity) { // object not contained yet, add it @@ -451,7 +451,7 @@ public class ArrayHashSet<E> * @return true if the given element is contained by this list using slow equals operation, * otherwise false. */ - public final boolean containsSafe(Object element) { + public final boolean containsSafe(final Object element) { return data.contains(element); } diff --git a/src/java/com/jogamp/common/util/Bitstream.java b/src/java/com/jogamp/common/util/Bitstream.java index 393108b..7d9c4fd 100644 --- a/src/java/com/jogamp/common/util/Bitstream.java +++ b/src/java/com/jogamp/common/util/Bitstream.java @@ -595,7 +595,7 @@ public class Bitstream<T> { * Default behavior for I/O methods is not to throw an {@link IOException}, but to return {@link #EOS}. * </p> */ - public final void setThrowIOExceptionOnEOF(boolean enable) { + public final void setThrowIOExceptionOnEOF(final boolean enable) { throwIOExceptionOnEOF = enable; } diff --git a/src/java/com/jogamp/common/util/FloatStack.java b/src/java/com/jogamp/common/util/FloatStack.java index 8cb2e5b..b9be29c 100644 --- a/src/java/com/jogamp/common/util/FloatStack.java +++ b/src/java/com/jogamp/common/util/FloatStack.java @@ -50,7 +50,7 @@ public class /*name*/FloatStack/*name*/ implements PrimitiveStack { * @param growSize grow size if {@link #position()} is reached, maybe <code>0</code> * in which case an {@link IndexOutOfBoundsException} is thrown. */ - public /*name*/FloatStack/*name*/(int initialSize, int growSize) { + public /*name*/FloatStack/*name*/(final int initialSize, final int growSize) { this.position = 0; this.growSize = growSize; this.buffer = new /*value*/float/*value*/[initialSize]; @@ -63,7 +63,7 @@ public class /*name*/FloatStack/*name*/ implements PrimitiveStack { public final int position() { return position; } @Override - public final void position(int newPosition) throws IndexOutOfBoundsException { + public final void position(final int newPosition) throws IndexOutOfBoundsException { if( 0 > position || position >= buffer.length ) { throw new IndexOutOfBoundsException("Invalid new position "+newPosition+", "+this.toString()); } @@ -77,7 +77,7 @@ public class /*name*/FloatStack/*name*/ implements PrimitiveStack { public final int getGrowSize() { return growSize; } @Override - public final void setGrowSize(int newGrowSize) { growSize = newGrowSize; } + public final void setGrowSize(final int newGrowSize) { growSize = newGrowSize; } @Override public final String toString() { @@ -86,12 +86,12 @@ public class /*name*/FloatStack/*name*/ implements PrimitiveStack { public final /*value*/float/*value*/[] buffer() { return buffer; } - private final void growIfNecessary(int length) throws IndexOutOfBoundsException { + private final void growIfNecessary(final int length) throws IndexOutOfBoundsException { if( position + length > buffer.length ) { if( 0 >= growSize ) { throw new IndexOutOfBoundsException("Out of fixed stack size: "+this); } - /*value*/float/*value*/[] newBuffer = + final /*value*/float/*value*/[] newBuffer = new /*value*/float/*value*/[buffer.length + growSize]; System.arraycopy(buffer, 0, newBuffer, 0, position); buffer = newBuffer; @@ -108,7 +108,7 @@ public class /*name*/FloatStack/*name*/ implements PrimitiveStack { * @throws IndexOutOfBoundsException if stack cannot grow due to zero grow-size or offset+length exceeds src. */ public final /*value*/float/*value*/[] - putOnTop(/*value*/float/*value*/[] src, int srcOffset, int length) throws IndexOutOfBoundsException { + putOnTop(final /*value*/float/*value*/[] src, final int srcOffset, final int length) throws IndexOutOfBoundsException { growIfNecessary(length); System.arraycopy(src, srcOffset, buffer, position, length); position += length; @@ -125,7 +125,7 @@ public class /*name*/FloatStack/*name*/ implements PrimitiveStack { * @throws BufferUnderflowException if <code>src</code> FloatBuffer has less remaining elements than <code>length</code>. */ public final /*value2*/FloatBuffer/*value2*/ - putOnTop(/*value2*/FloatBuffer/*value2*/ src, int length) throws IndexOutOfBoundsException, BufferUnderflowException { + putOnTop(final /*value2*/FloatBuffer/*value2*/ src, final int length) throws IndexOutOfBoundsException, BufferUnderflowException { growIfNecessary(length); src.get(buffer, position, length); position += length; @@ -142,7 +142,7 @@ public class /*name*/FloatStack/*name*/ implements PrimitiveStack { * @throws IndexOutOfBoundsException if stack or <code>dest</code> has less elements than <code>length</code>. */ public final /*value*/float/*value*/[] - getFromTop(/*value*/float/*value*/[] dest, int destOffset, int length) throws IndexOutOfBoundsException { + getFromTop(final /*value*/float/*value*/[] dest, final int destOffset, final int length) throws IndexOutOfBoundsException { System.arraycopy(buffer, position-length, dest, destOffset, length); position -= length; return dest; @@ -158,7 +158,7 @@ public class /*name*/FloatStack/*name*/ implements PrimitiveStack { * @throws BufferOverflowException if <code>src</code> FloatBuffer has less remaining elements than <code>length</code>. */ public final /*value2*/FloatBuffer/*value2*/ - getFromTop(/*value2*/FloatBuffer/*value2*/ dest, int length) throws IndexOutOfBoundsException, BufferOverflowException { + getFromTop(final /*value2*/FloatBuffer/*value2*/ dest, final int length) throws IndexOutOfBoundsException, BufferOverflowException { dest.put(buffer, position-length, length); position -= length; return dest; diff --git a/src/java/com/jogamp/common/util/FunctionTask.java b/src/java/com/jogamp/common/util/FunctionTask.java index b742d73..4ac64d3 100644 --- a/src/java/com/jogamp/common/util/FunctionTask.java +++ b/src/java/com/jogamp/common/util/FunctionTask.java @@ -46,7 +46,7 @@ public class FunctionTask<R,A> extends TaskBase implements Function<R,A> { * @param args the {@link Function} arguments * @return the {@link Function} return value */ - public static <U,V> U invoke(boolean waitUntilDone, Function<U,V> func, V... args) { + public static <U,V> U invoke(final boolean waitUntilDone, final Function<U,V> func, final V... args) { Throwable throwable = null; final Object sync = new Object(); final FunctionTask<U,V> rt = new FunctionTask<U,V>( func, waitUntilDone ? sync : null, true, waitUntilDone ? null : System.err ); @@ -56,7 +56,7 @@ public class FunctionTask<R,A> extends TaskBase implements Function<R,A> { if( waitUntilDone ) { try { sync.wait(); - } catch (InterruptedException ie) { + } catch (final InterruptedException ie) { throwable = ie; } if(null==throwable) { @@ -82,7 +82,7 @@ public class FunctionTask<R,A> extends TaskBase implements Function<R,A> { * otherwise the exception is thrown. * @param exceptionOut If not <code>null</code>, exceptions are written to this {@link PrintStream}. */ - public FunctionTask(Function<R,A> runnable, Object syncObject, boolean catchExceptions, PrintStream exceptionOut) { + public FunctionTask(final Function<R,A> runnable, final Object syncObject, final boolean catchExceptions, final PrintStream exceptionOut) { super(syncObject, catchExceptions, exceptionOut); this.runnable = runnable ; result = null; @@ -98,7 +98,7 @@ public class FunctionTask<R,A> extends TaskBase implements Function<R,A> { * Sets the arguments for {@link #run()}. * They will be cleared after calling {@link #run()} or {@link #eval(Object...)}. */ - public final void setArgs(A... args) { + public final void setArgs(final A... args) { this.args = args; } @@ -132,7 +132,7 @@ public class FunctionTask<R,A> extends TaskBase implements Function<R,A> { if(null == syncObject) { try { this.result = runnable.eval(args); - } catch (Throwable t) { + } catch (final Throwable t) { runnableException = t; if(null != exceptionOut) { exceptionOut.println("FunctionTask.run(): "+getExceptionOutIntro()+" exception occured on thread "+Thread.currentThread().getName()+": "+toString()); @@ -149,7 +149,7 @@ public class FunctionTask<R,A> extends TaskBase implements Function<R,A> { synchronized (syncObject) { try { this.result = runnable.eval(args); - } catch (Throwable t) { + } catch (final Throwable t) { runnableException = t; if(null != exceptionOut) { exceptionOut.println("FunctionTask.run(): "+getExceptionOutIntro()+" exception occured on thread "+Thread.currentThread().getName()+": "+toString()); @@ -168,7 +168,7 @@ public class FunctionTask<R,A> extends TaskBase implements Function<R,A> { } @Override - public final R eval(A... args) { + public final R eval(final A... args) { this.args = args; run(); final R res = result; diff --git a/src/java/com/jogamp/common/util/HashUtil.java b/src/java/com/jogamp/common/util/HashUtil.java index 5ce2332..b567bca 100644 --- a/src/java/com/jogamp/common/util/HashUtil.java +++ b/src/java/com/jogamp/common/util/HashUtil.java @@ -32,10 +32,10 @@ public class HashUtil { * Generates a 32bit equally distributed identity hash value * from <code>addr</code> avoiding XOR collision. */ - public static int getAddrHash32_EqualDist(long addr) { + public static int getAddrHash32_EqualDist(final long addr) { // avoid xor collisions of low/high parts // 31 * x == (x << 5) - x - int hash = 31 + (int) addr ; // lo addr + final int hash = 31 + (int) addr ; // lo addr return ((hash << 5) - hash) + (int) ( addr >>> 32 ) ; // hi addr } @@ -43,7 +43,7 @@ public class HashUtil { * Generates a 32bit equally distributed identity hash value * from <code>addr</code> and <code>size</code> avoiding XOR collision. */ - public static int getAddrSizeHash32_EqualDist(long addr, long size) { + public static int getAddrSizeHash32_EqualDist(final long addr, final long size) { // avoid xor collisions of low/high parts // 31 * x == (x << 5) - x int hash = 31 + (int) addr ; // lo addr @@ -56,7 +56,7 @@ public class HashUtil { * Generates a 64bit equally distributed hash value * from <code>addr</code> and <code>size</code> avoiding XOR collisions. */ - public static long getHash64(long addr, long size) { + public static long getHash64(final long addr, final long size) { // 31 * x == (x << 5) - x final long hash = 31 + addr; return ((hash << 5) - hash) + size; diff --git a/src/java/com/jogamp/common/util/IOUtil.java b/src/java/com/jogamp/common/util/IOUtil.java index c70fa92..3b145af 100644 --- a/src/java/com/jogamp/common/util/IOUtil.java +++ b/src/java/com/jogamp/common/util/IOUtil.java @@ -98,7 +98,7 @@ public class IOUtil { try { _fosCtor = ReflectionUtil.getConstructor("java.io.FileOutputStream", new Class<?>[] { File.class }, true, IOUtil.class.getClassLoader()); _t = null; - } catch (Throwable t) { + } catch (final Throwable t) { _fosCtor = null; _t = t; } @@ -126,11 +126,11 @@ public class IOUtil { * @return * @throws IOException */ - public static int copyURLConn2File(URLConnection conn, File outFile) throws IOException { + public static int copyURLConn2File(final URLConnection conn, final File outFile) throws IOException { conn.connect(); // redundant int totalNumBytes = 0; - InputStream in = new BufferedInputStream(conn.getInputStream()); + final InputStream in = new BufferedInputStream(conn.getInputStream()); try { totalNumBytes = copyStream2File(in, outFile, conn.getContentLength()); } finally { @@ -149,8 +149,8 @@ public class IOUtil { * @return * @throws IOException */ - public static int copyStream2File(InputStream in, File outFile, int totalNumBytes) throws IOException { - OutputStream out = new BufferedOutputStream(new FileOutputStream(outFile)); + public static int copyStream2File(final InputStream in, final File outFile, int totalNumBytes) throws IOException { + final OutputStream out = new BufferedOutputStream(new FileOutputStream(outFile)); try { totalNumBytes = copyStream2Stream(in, out, totalNumBytes); } finally { @@ -169,7 +169,7 @@ public class IOUtil { * @return * @throws IOException */ - public static int copyStream2Stream(InputStream in, OutputStream out, int totalNumBytes) throws IOException { + public static int copyStream2Stream(final InputStream in, final OutputStream out, final int totalNumBytes) throws IOException { return copyStream2Stream(Platform.getMachineDescription().pageSizeInBytes(), in, out, totalNumBytes); } @@ -184,7 +184,7 @@ public class IOUtil { * @return * @throws IOException */ - public static int copyStream2Stream(int bufferSize, InputStream in, OutputStream out, int totalNumBytes) throws IOException { + public static int copyStream2Stream(final int bufferSize, final InputStream in, final OutputStream out, final int totalNumBytes) throws IOException { final byte[] buf = new byte[bufferSize]; int numBytes = 0; while (true) { @@ -238,7 +238,7 @@ public class IOUtil { * * @param stream input stream, which will be wrapped into a BufferedInputStream, if not already done. */ - public static ByteBuffer copyStream2ByteBuffer(InputStream stream) throws IOException { + public static ByteBuffer copyStream2ByteBuffer(final InputStream stream) throws IOException { return copyStream2ByteBuffer(stream, -1); } @@ -259,7 +259,7 @@ public class IOUtil { } final MachineDescription machine = Platform.getMachineDescription(); ByteBuffer data = Buffers.newDirectByteBuffer( machine.pageAlignedSize( initialCapacity ) ); - byte[] chunk = new byte[machine.pageSizeInBytes()]; + final byte[] chunk = new byte[machine.pageSizeInBytes()]; int chunk2Read = Math.min(machine.pageSizeInBytes(), avail); int numRead = 0; do { @@ -296,7 +296,7 @@ public class IOUtil { * @return * @throws URISyntaxException if path is empty or has no parent directory available while resolving <code>../</code> */ - public static String slashify(String path, boolean startWithSlash, boolean endWithSlash) throws URISyntaxException { + public static String slashify(final String path, final boolean startWithSlash, final boolean endWithSlash) throws URISyntaxException { String p = path.replace('\\', '/'); // unify file separator if (startWithSlash && !p.startsWith("/")) { p = "/" + p; @@ -312,7 +312,7 @@ public class IOUtil { * @throws URISyntaxException if path is empty or has no parent directory available while resolving <code>../</code> * @throws URISyntaxException if the resulting string does not comply w/ an RFC 2396 URI */ - public static URI toURISimple(File file) throws URISyntaxException { + public static URI toURISimple(final File file) throws URISyntaxException { return new URI(FILE_SCHEME, null, slashify(file.getAbsolutePath(), true /* startWithSlash */, file.isDirectory() /* endWithSlash */), null); } @@ -321,7 +321,7 @@ public class IOUtil { * @throws URISyntaxException if path is empty or has no parent directory available while resolving <code>../</code> * @throws URISyntaxException if the resulting string does not comply w/ an RFC 2396 URI */ - public static URI toURISimple(String protocol, String path, boolean isDirectory) throws URISyntaxException { + public static URI toURISimple(final String protocol, final String path, final boolean isDirectory) throws URISyntaxException { return new URI(protocol, null, slashify(new File(path).getAbsolutePath(), true /* startWithSlash */, isDirectory /* endWithSlash */), null); } @@ -336,7 +336,7 @@ public class IOUtil { * @throws NullPointerException if file is null */ - public static String getFileSuffix(File file) { + public static String getFileSuffix(final File file) { return getFileSuffix(file.getName()); } @@ -350,14 +350,14 @@ public class IOUtil { * @return lowercase suffix of the file name * @throws NullPointerException if filename is null */ - public static String getFileSuffix(String filename) { - int lastDot = filename.lastIndexOf('.'); + public static String getFileSuffix(final String filename) { + final int lastDot = filename.lastIndexOf('.'); if (lastDot < 0) { return null; } return toLowerCase(filename.substring(lastDot + 1)); } - private static String toLowerCase(String arg) { + private static String toLowerCase(final String arg) { if (arg == null) { return null; } @@ -373,7 +373,7 @@ public class IOUtil { * the class {@link java.io.FileOutputStream} is not accessible or * the user does not have sufficient rights to access the local filesystem. */ - public static FileOutputStream getFileOutputStream(File file, boolean allowOverwrite) throws IOException { + public static FileOutputStream getFileOutputStream(final File file, final boolean allowOverwrite) throws IOException { final Constructor<?> fosCtor = getFOSCtor(); if(null == fosCtor) { throw new IOException("Cannot open file (" + file + ") for writing, FileOutputStream feature not available."); @@ -383,12 +383,12 @@ public class IOUtil { } try { return (FileOutputStream) fosCtor.newInstance(new Object[] { file }); - } catch (Exception e) { + } catch (final Exception e) { throw new IOException("error opening " + file + " for write. ", e); } } - public static String getClassFileName(String clazzBinName) { + public static String getClassFileName(final String clazzBinName) { // or return clazzBinName.replace('.', File.separatorChar) + ".class"; ? return clazzBinName.replace('.', '/') + ".class"; } @@ -399,7 +399,7 @@ public class IOUtil { * @return jar:file:/usr/local/projects/JOGL/gluegen/build-x86_64/gluegen-rt.jar!/com/jogamp/common/util/cache/TempJarCache.class * @throws IOException if the jar file could not been found by the ClassLoader */ - public static URL getClassURL(String clazzBinName, ClassLoader cl) throws IOException { + public static URL getClassURL(final String clazzBinName, final ClassLoader cl) throws IOException { final URL url = cl.getResource(getClassFileName(clazzBinName)); if(null == url) { throw new IOException("Cannot not find: "+clazzBinName); @@ -413,7 +413,7 @@ public class IOUtil { */ public static String getBasename(String fname) throws URISyntaxException { fname = slashify(fname, false /* startWithSlash */, false /* endWithSlash */); - int lios = fname.lastIndexOf('/'); // strip off dirname + final int lios = fname.lastIndexOf('/'); // strip off dirname if(lios>=0) { fname = fname.substring(lios+1); } @@ -426,7 +426,7 @@ public class IOUtil { */ public static String getDirname(String fname) throws URISyntaxException { fname = slashify(fname, false /* startWithSlash */, false /* endWithSlash */); - int lios = fname.lastIndexOf('/'); // strip off dirname + final int lios = fname.lastIndexOf('/'); // strip off dirname if(lios>=0) { fname = fname.substring(0, lios+1); } @@ -445,11 +445,11 @@ public class IOUtil { * @throws IllegalArgumentException if the URI doesn't match the expected formatting, or is null * @throws URISyntaxException */ - public static URI getURIDirname(URI uri) throws IllegalArgumentException, URISyntaxException { + public static URI getURIDirname(final URI uri) throws IllegalArgumentException, URISyntaxException { if(null == uri) { throw new IllegalArgumentException("URI is null"); } - String uriS = uri.toString(); + final String uriS = uri.toString(); if( DEBUG ) { System.err.println("getURIDirname "+uri+", extForm: "+uriS); } @@ -556,7 +556,7 @@ public class IOUtil { File f; try { f = new File( decodeFromURI( specificURI.getPath() ) ); // validates uri, uses decoded uri.getPath() and normalizes it - } catch(Exception iae) { + } catch(final Exception iae) { if( DEBUG ) { System.err.println("Caught "+iae.getClass().getSimpleName()+": new File("+decodeFromURI( specificURI.getPath() )+") failed: "+iae.getMessage()); iae.printStackTrace(); @@ -584,7 +584,7 @@ public class IOUtil { final URL fUrl = fUri.toURL(); System.err.println("IOUtil.toURL.1b: fUri "+fUri+PlatformPropsImpl.NEWLINE+ "\t, fUrl "+fUrl); - } catch (Exception ee) { + } catch (final Exception ee) { System.err.println("Caught "+ee.getClass().getSimpleName()+": f.toURI().toURL() failed: "+ee.getMessage()); ee.printStackTrace(); } @@ -612,7 +612,7 @@ public class IOUtil { url = new URL(urlS); mode = 2; } - } catch (Exception mue) { + } catch (final Exception mue) { if( DEBUG ) { System.err.println("Caught "+mue.getClass().getSimpleName()+": new URL("+urlS+") failed: "+mue.getMessage()); mue.printStackTrace(); @@ -624,7 +624,7 @@ public class IOUtil { try { url = uri.toURL(); mode = 3; - } catch (Exception e) { + } catch (final Exception e) { if( DEBUG ) { System.err.println("Caught "+e.getClass().getSimpleName()+": "+uri+".toURL() failed: "+e.getMessage()); e.printStackTrace(); @@ -662,7 +662,7 @@ public class IOUtil { * @param contextCL class instance to {@link #resolve(int)} {@link #resourcePaths}. * @param resourcePaths array of strings denominating multiple resource paths. None shall be null. */ - public ClassResources(Class<?> contextCL, String[] resourcePaths) { + public ClassResources(final Class<?> contextCL, final String[] resourcePaths) { for(int i=resourcePaths.length-1; i>=0; i--) { if( null == resourcePaths[i] ) { throw new IllegalArgumentException("resourcePath["+i+"] is null"); @@ -676,7 +676,7 @@ public class IOUtil { * Resolving one of the {@link #resourcePaths} indexed by <code>uriIndex</code> using {@link #contextCL} and {@link IOUtil#getResource(Class, String)}. * @throws ArrayIndexOutOfBoundsException if <code>uriIndex</code> is < 0 or >= {@link #resourceCount()}. */ - public URLConnection resolve(int uriIndex) throws ArrayIndexOutOfBoundsException { + public URLConnection resolve(final int uriIndex) throws ArrayIndexOutOfBoundsException { return getResource(contextCL, resourcePaths[uriIndex]); } } @@ -698,11 +698,11 @@ public class IOUtil { * @see ClassLoader#getResource(String) * @see ClassLoader#getSystemResource(String) */ - public static URLConnection getResource(Class<?> context, String resourcePath) { + public static URLConnection getResource(final Class<?> context, final String resourcePath) { if(null == resourcePath) { return null; } - ClassLoader contextCL = (null!=context)?context.getClassLoader():IOUtil.class.getClassLoader(); + final ClassLoader contextCL = (null!=context)?context.getClassLoader():IOUtil.class.getClassLoader(); URLConnection conn = null; if(null != context) { // scoping the path within the class's package @@ -738,7 +738,7 @@ public class IOUtil { * @see URL#URL(String) * @see File#File(String) */ - public static URLConnection getResource(String resourcePath, ClassLoader cl) { + public static URLConnection getResource(final String resourcePath, final ClassLoader cl) { if(null == resourcePath) { return null; } @@ -748,7 +748,7 @@ public class IOUtil { if(resourcePath.startsWith(AssetURLContext.asset_protocol_prefix)) { try { return AssetURLContext.createURL(resourcePath, cl).openConnection(); - } catch (IOException ioe) { + } catch (final IOException ioe) { if(DEBUG) { System.err.println("IOUtil: Caught Exception:"); ioe.printStackTrace(); @@ -758,7 +758,7 @@ public class IOUtil { } else { try { return AssetURLContext.resolve(resourcePath, cl); - } catch (IOException ioe) { + } catch (final IOException ioe) { if(DEBUG) { System.err.println("IOUtil: Caught Exception:"); ioe.printStackTrace(); @@ -775,7 +775,7 @@ public class IOUtil { * @param relativeFile denotes a relative file to the baseLocation * @throws URISyntaxException if path is empty or has no parent directory available while resolving <code>../</code> */ - public static String getRelativeOf(File baseLocation, String relativeFile) throws URISyntaxException { + public static String getRelativeOf(final File baseLocation, final String relativeFile) throws URISyntaxException { if(null == relativeFile) { return null; } @@ -793,7 +793,7 @@ public class IOUtil { * @return parent of path * @throws URISyntaxException if path is empty or has no parent directory available */ - public static String getParentOf(String path) throws URISyntaxException { + public static String getParentOf(final String path) throws URISyntaxException { final int pl = null!=path ? path.length() : 0; if(pl == 0) { throw new IllegalArgumentException("path is empty <"+path+">"); @@ -850,7 +850,7 @@ public class IOUtil { * @param relativePath denotes a relative file to the baseLocation's parent directory * @throws URISyntaxException if path is empty or has no parent directory available while resolving <code>../</code> */ - public static URI getRelativeOf(URI baseURI, String relativePath) throws URISyntaxException { + public static URI getRelativeOf(final URI baseURI, final String relativePath) throws URISyntaxException { return compose(baseURI.getScheme(), baseURI.getSchemeSpecificPart(), relativePath, baseURI.getFragment()); } @@ -858,10 +858,10 @@ public class IOUtil { * Wraps {@link #getRelativeOf(URI, String)} for convenience. * @throws IOException */ - public static URL getRelativeOf(URL baseURL, String relativePath) throws IOException { + public static URL getRelativeOf(final URL baseURL, final String relativePath) throws IOException { try { return getRelativeOf(baseURL.toURI(), relativePath).toURL(); - } catch (URISyntaxException e) { + } catch (final URISyntaxException e) { throw new IOException(e); } } @@ -883,7 +883,7 @@ public class IOUtil { * @throws URISyntaxException if path is empty or has no parent directory available while resolving <code>../</code> * @see #encodeToURI(String) */ - public static URI compose(String scheme, String schemeSpecificPart, String relativePath, String fragment) throws URISyntaxException { + public static URI compose(final String scheme, String schemeSpecificPart, final String relativePath, final String fragment) throws URISyntaxException { // cut off optional query in scheme-specific-part final String query; final int queryI = schemeSpecificPart.lastIndexOf('?'); @@ -912,7 +912,7 @@ public class IOUtil { * <li>SPACE -> %20</li> * </ul> */ - public static String encodeToURI(String s) { + public static String encodeToURI(final String s) { return patternSpaceRaw.matcher(s).replaceAll("%20"); } @@ -922,7 +922,7 @@ public class IOUtil { * <li>%20 -> SPACE</li> * </ul> */ - public static String decodeFromURI(String s) { + public static String decodeFromURI(final String s) { return patternSpaceEnc.matcher(s).replaceAll(" "); } @@ -1019,14 +1019,14 @@ public class IOUtil { /** * Returns the connected URLConnection, or null if not url is not available */ - public static URLConnection openURL(URL url) { + public static URLConnection openURL(final URL url) { return openURL(url, "."); } /** * Returns the connected URLConnection, or null if not url is not available */ - public static URLConnection openURL(URL url, String dbgmsg) { + public static URLConnection openURL(final URL url, final String dbgmsg) { if(null!=url) { try { final URLConnection c = url.openConnection(); @@ -1035,7 +1035,7 @@ public class IOUtil { System.err.println("IOUtil: urlExists("+url+") ["+dbgmsg+"] - true"); } return c; - } catch (IOException ioe) { + } catch (final IOException ioe) { if(DEBUG) { System.err.println("IOUtil: urlExists("+url+") ["+dbgmsg+"] - false - "+ioe.getClass().getSimpleName()+": "+ioe.getMessage()); ioe.printStackTrace(); @@ -1092,7 +1092,7 @@ public class IOUtil { * @param shallBeWritable * @return */ - public static boolean testFile(File file, boolean shallBeDir, boolean shallBeWritable) { + public static boolean testFile(final File file, final boolean shallBeDir, final boolean shallBeWritable) { if (!file.exists()) { if(DEBUG) { System.err.println("IOUtil.testFile: <"+file.getAbsolutePath()+">: does not exist"); @@ -1126,7 +1126,7 @@ public class IOUtil { * @throws SecurityException if file creation and process execution is not allowed within the current security context * @param dir */ - public static boolean testDirExec(File dir) + public static boolean testDirExec(final File dir) throws SecurityException { if (!testFile(dir, true, true)) { @@ -1145,9 +1145,9 @@ public class IOUtil { File exetst; try { exetst = File.createTempFile("jogamp_exe_tst", getShellSuffix(), dir); - } catch (SecurityException se) { + } catch (final SecurityException se) { throw se; // fwd Security exception - } catch (IOException e) { + } catch (final IOException e) { if(DEBUG) { e.printStackTrace(); } @@ -1156,12 +1156,12 @@ public class IOUtil { int res = -1; if(exetst.setExecutable(true /* exec */, true /* ownerOnly */)) { try { - Process pr = Runtime.getRuntime().exec(exetst.getCanonicalPath()); + final Process pr = Runtime.getRuntime().exec(exetst.getCanonicalPath()); pr.waitFor() ; res = pr.exitValue(); - } catch (SecurityException se) { + } catch (final SecurityException se) { throw se; // fwd Security exception - } catch (Throwable t) { + } catch (final Throwable t) { res = -2; if(DEBUG) { System.err.println("IOUtil.testDirExec: <"+exetst.getAbsolutePath()+">: Caught "+t.getClass().getSimpleName()+": "+t.getMessage()); @@ -1176,7 +1176,7 @@ public class IOUtil { return 0 == res; } - private static File testDirImpl(File dir, boolean create, boolean executable, String dbgMsg) + private static File testDirImpl(final File dir, final boolean create, final boolean executable, final String dbgMsg) throws SecurityException { final File res; @@ -1214,7 +1214,7 @@ public class IOUtil { return testDirImpl(dir, create, executable, "testDir"); } - private static boolean isStringSet(String s) { return null != s && 0 < s.length(); } + private static boolean isStringSet(final String s) { return null != s && 0 < s.length(); } /** * This methods finds [and creates] an available temporary sub-directory: @@ -1240,7 +1240,7 @@ public class IOUtil { * @return a temporary directory, writable by this user * @throws SecurityException */ - private static File getSubTempDir(File tmpRoot, String tmpSubDirPrefix, boolean executable, String dbgMsg) + private static File getSubTempDir(final File tmpRoot, final String tmpSubDirPrefix, final boolean executable, final String dbgMsg) throws SecurityException { File tmpBaseDir = null; @@ -1411,17 +1411,17 @@ public class IOUtil { * @throws IOException * @throws SecurityException */ - public static File createTempFile(String prefix, String suffix, boolean executable) + public static File createTempFile(final String prefix, final String suffix, final boolean executable) throws IllegalArgumentException, IOException, SecurityException { return File.createTempFile( prefix, suffix, getTempDir(executable) ); } - public static void close(Closeable stream, boolean throwRuntimeException) throws RuntimeException { + public static void close(final Closeable stream, final boolean throwRuntimeException) throws RuntimeException { if(null != stream) { try { stream.close(); - } catch (IOException e) { + } catch (final IOException e) { if(throwRuntimeException) { throw new RuntimeException(e); } else if(DEBUG) { diff --git a/src/java/com/jogamp/common/util/IntBitfield.java b/src/java/com/jogamp/common/util/IntBitfield.java index 2d2f1ef..74e37ac 100644 --- a/src/java/com/jogamp/common/util/IntBitfield.java +++ b/src/java/com/jogamp/common/util/IntBitfield.java @@ -50,7 +50,7 @@ public class IntBitfield { /** * @param bitCount */ - public IntBitfield(long bitCount) { + public IntBitfield(final long bitCount) { final int units = (int) Math.max(1L, ( bitCount + 7L ) >>> UNIT_SHIFT_L); this.storage = new int[units]; this.bitsCountL = (long)units << UNIT_SHIFT_L ; @@ -60,19 +60,19 @@ public class IntBitfield { /** * @param bitCount */ - public IntBitfield(int bitCount) { + public IntBitfield(final int bitCount) { final int units = Math.max(1, ( bitCount + 7 ) >>> UNIT_SHIFT_I); this.storage = new int[units]; this.bitsCountI = units << UNIT_SHIFT_I; this.bitsCountL = bitsCountI; } - private final void check(long bitnum) { + private final void check(final long bitnum) { if( 0 > bitnum || bitnum >= bitsCountL ) { throw new ArrayIndexOutOfBoundsException("Bitnum should be within [0.."+(bitsCountL-1)+"], but is "+bitnum); } } - private final void check(int bitnum) { + private final void check(final int bitnum) { if( 0 > bitnum || bitnum >= bitsCountI ) { throw new ArrayIndexOutOfBoundsException("Bitnum should be within [0.."+(bitsCountI-1)+"], but is "+bitnum); } @@ -82,7 +82,7 @@ public class IntBitfield { public final long capacity() { return bitsCountL; } /** Return <code>true</code> if the bit at position <code>bitnum</code> is set, otherwise <code>false</code>. */ - public final boolean get(long bitnum) { + public final boolean get(final long bitnum) { check(bitnum); final int u = (int) ( bitnum >>> UNIT_SHIFT_L ); final int b = (int) ( bitnum - ( (long)u << UNIT_SHIFT_L ) ); @@ -90,7 +90,7 @@ public class IntBitfield { } /** Return <code>true</code> if the bit at position <code>bitnum</code> is set, otherwise <code>false</code>. */ - public final boolean get(int bitnum) { + public final boolean get(final int bitnum) { check(bitnum); final int u = bitnum >>> UNIT_SHIFT_I; final int b = bitnum - ( u << UNIT_SHIFT_I ); @@ -101,7 +101,7 @@ public class IntBitfield { * Set or clear the bit at position <code>bitnum</code> according to <code>bit</code> * and return the previous value. */ - public final boolean put(long bitnum, boolean bit) { + public final boolean put(final long bitnum, final boolean bit) { check(bitnum); final int u = (int) ( bitnum >>> UNIT_SHIFT_L ); final int b = (int) ( bitnum - ( (long)u << UNIT_SHIFT_L ) ); @@ -121,7 +121,7 @@ public class IntBitfield { * Set or clear the bit at position <code>bitnum</code> according to <code>bit</code> * and return the previous value. */ - public final boolean put(int bitnum, boolean bit) { + public final boolean put(final int bitnum, final boolean bit) { check(bitnum); final int u = bitnum >>> UNIT_SHIFT_I; final int b = bitnum - ( u << UNIT_SHIFT_I ); diff --git a/src/java/com/jogamp/common/util/IntIntHashMap.java b/src/java/com/jogamp/common/util/IntIntHashMap.java index ef6159b..4cb2329 100644 --- a/src/java/com/jogamp/common/util/IntIntHashMap.java +++ b/src/java/com/jogamp/common/util/IntIntHashMap.java @@ -88,13 +88,13 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, @Override @SuppressWarnings("unchecked") public EntryCM run() { - EntryCM r = new EntryCM(); + final EntryCM r = new EntryCM(); r.c = (Constructor<Entry>) ReflectionUtil.getConstructor(Entry.class, new Class[] { keyClazz, valueClazz, Entry.class } ); try { r.m1 = valueClazz.getDeclaredMethod("equals", Object.class); - } catch (NoSuchMethodException ex) { + } catch (final NoSuchMethodException ex) { throw new JogampRuntimeException("Class "+valueClazz+" doesn't support equals(Object)"); } return r; @@ -111,11 +111,11 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, this(16, 0.75f); } - public /*name*/IntIntHashMap/*name*/(int initialCapacity) { + public /*name*/IntIntHashMap/*name*/(final int initialCapacity) { this(initialCapacity, 0.75f); } - public /*name*/IntIntHashMap/*name*/(int initialCapacity, float loadFactor) { + public /*name*/IntIntHashMap/*name*/(final int initialCapacity, final float loadFactor) { if (initialCapacity > 1 << 30) { throw new IllegalArgumentException("initialCapacity is too large."); } @@ -135,9 +135,9 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, this.mask = capacity - 1; } - private /*name*/IntIntHashMap/*name*/(float loadFactor, int table_size, int size, - int mask, int capacity, int threshold, - /*value*/int/*value*/ keyNotFoundValue) { + private /*name*/IntIntHashMap/*name*/(final float loadFactor, final int table_size, final int size, + final int mask, final int capacity, final int threshold, + final /*value*/int/*value*/ keyNotFoundValue) { this.loadFactor = loadFactor; this.table = new Entry[table_size]; this.size = size; @@ -157,7 +157,7 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, */ @Override public Object clone() { - /*name*/IntIntHashMap/*name*/ n = + final /*name*/IntIntHashMap/*name*/ n = new /*name*/IntIntHashMap/*name*/(loadFactor, table.length, size, mask, capacity, threshold, keyNotFoundValue); @@ -187,8 +187,8 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, return n; } - public boolean containsValue(/*value*/int/*value*/ value) { - Entry[] t = this.table; + public boolean containsValue(final /*value*/int/*value*/ value) { + final Entry[] t = this.table; for (int i = t.length; i-- > 0;) { for (Entry e = t[i]; e != null; e = e.next) { if( isPrimitive ) { @@ -207,7 +207,7 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, } // @SuppressWarnings(value="cast") - public boolean containsKey(/*key*/int/*key*/ key) { + public boolean containsKey(final /*key*/int/*key*/ key) { final Entry[] t = this.table; final int index = /*keyHash*/key/*keyHash*/ & mask; for (Entry e = t[index]; e != null; e = e.next) { @@ -223,7 +223,7 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, * or {@link #getKeyNotFoundValue} if this map contains no mapping for the key. */ // @SuppressWarnings(value="cast") - public /*value*/int/*value*/ get(/*key*/int/*key*/ key) { + public /*value*/int/*value*/ get(final /*key*/int/*key*/ key) { final Entry[] t = this.table; final int index = /*keyHash*/key/*keyHash*/ & mask; for (Entry e = t[index]; e != null; e = e.next) { @@ -239,7 +239,7 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, * the previous value will be returned (otherwise {@link #getKeyNotFoundValue}). */ // @SuppressWarnings(value="cast") - public /*value*/int/*value*/ put(/*key*/int/*key*/ key, /*value*/int/*value*/ value) { + public /*value*/int/*value*/ put(final /*key*/int/*key*/ key, final /*value*/int/*value*/ value) { final Entry[] t = this.table; final int index = /*keyHash*/key/*keyHash*/ & mask; // Check if key already exists. @@ -247,7 +247,7 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, if (e.key != key) { continue; } - /*value*/int/*value*/ oldValue = e.value; + final /*value*/int/*value*/ oldValue = e.value; e.value = value; return oldValue; } @@ -263,7 +263,7 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, if (e != null) { t[j] = null; do { - Entry next = e.next; + final Entry next = e.next; final int index2 = /*keyHash*/e.key/*keyHash*/ & newMask; e.next = newTable[index2]; newTable[index2] = e; @@ -282,7 +282,7 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, /** * Copies all of the mappings from the specified map to this map. */ - public void putAll(/*name*/IntIntHashMap/*name*/ source) { + public void putAll(final /*name*/IntIntHashMap/*name*/ source) { final Iterator<Entry> itr = source.iterator(); while(itr.hasNext()) { final Entry e = itr.next(); @@ -295,14 +295,14 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, * Returns the previously mapped value or {@link #getKeyNotFoundValue} if no such mapping exists. */ // @SuppressWarnings(value="cast") - public /*value*/int/*value*/ remove(/*key*/int/*key*/ key) { + public /*value*/int/*value*/ remove(final /*key*/int/*key*/ key) { final Entry[] t = this.table; final int index = /*keyHash*/key/*keyHash*/ & mask; Entry prev = t[index]; Entry e = prev; while (e != null) { - Entry next = e.next; + final Entry next = e.next; if (e.key == key) { size--; if (prev == e) { @@ -358,8 +358,8 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, * @see #get * @see #put */ - public /*value*/int/*value*/ setKeyNotFoundValue(/*value*/int/*value*/ newKeyNotFoundValue) { - /*value*/int/*value*/ t = keyNotFoundValue; + public /*value*/int/*value*/ setKeyNotFoundValue(final /*value*/int/*value*/ newKeyNotFoundValue) { + final /*value*/int/*value*/ t = keyNotFoundValue; keyNotFoundValue = newKeyNotFoundValue; return t; } @@ -382,7 +382,7 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, sb = new StringBuilder(); } sb.append("{"); - Iterator<Entry> itr = iterator(); + final Iterator<Entry> itr = iterator(); while(itr.hasNext()) { itr.next().toString(sb); if(itr.hasNext()) { @@ -405,7 +405,7 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, private int index; private Entry next; - private EntryIterator(Entry[] entries){ + private EntryIterator(final Entry[] entries){ this.entries = entries; // load next next(); @@ -424,7 +424,7 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, next = current.next; }else{ while(index < entries.length) { - Entry e = entries[index++]; + final Entry e = entries[index++]; if(e != null) { next = e; return current; @@ -453,7 +453,7 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, private Entry next; - Entry(/*key*/int/*key*/ k, /*value*/int/*value*/ v, Entry n) { + Entry(final /*key*/int/*key*/ k, final /*value*/int/*value*/ v, final Entry n) { key = k; value = v; next = n; @@ -476,7 +476,7 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, /** * Sets the value for this entry. */ - public void setValue(/*value*/int/*value*/ value) { + public void setValue(final /*value*/int/*value*/ value) { this.value = value; } @@ -499,14 +499,14 @@ public class /*name*/IntIntHashMap/*name*/ implements Cloneable, } - private static Method getCloneMethod(Object obj) { + private static Method getCloneMethod(final Object obj) { final Class<?> clazz = obj.getClass(); return AccessController.doPrivileged(new PrivilegedAction<Method>() { @Override public Method run() { try { return clazz.getDeclaredMethod("clone"); - } catch (NoSuchMethodException ex) { + } catch (final NoSuchMethodException ex) { throw new JogampRuntimeException("Class "+clazz+" doesn't support clone()", ex); } } } ); diff --git a/src/java/com/jogamp/common/util/JarUtil.java b/src/java/com/jogamp/common/util/JarUtil.java index 77f1a84..eeee82a 100644 --- a/src/java/com/jogamp/common/util/JarUtil.java +++ b/src/java/com/jogamp/common/util/JarUtil.java @@ -83,7 +83,7 @@ public class JarUtil { * @throws SecurityException if the security manager doesn't have the setFactory * permission */ - public static void setResolver(Resolver r) throws IllegalArgumentException, IllegalStateException, SecurityException { + public static void setResolver(final Resolver r) throws IllegalArgumentException, IllegalStateException, SecurityException { if(r == null) { throw new IllegalArgumentException("Null Resolver passed"); } @@ -113,10 +113,10 @@ public class JarUtil { * @return true if the class is loaded from a Jar file, otherwise false. * @see {@link #getJarURI(String, ClassLoader)} */ - public static boolean hasJarURI(String clazzBinName, ClassLoader cl) { + public static boolean hasJarURI(final String clazzBinName, final ClassLoader cl) { try { return null != getJarURI(clazzBinName, cl); - } catch (Exception e) { /* ignore */ } + } catch (final Exception e) { /* ignore */ } return false; } @@ -136,7 +136,7 @@ public class JarUtil { * @throws URISyntaxException if the URI could not be translated into a RFC 2396 URI * @see {@link IOUtil#getClassURL(String, ClassLoader)} */ - public static URI getJarURI(String clazzBinName, ClassLoader cl) throws IllegalArgumentException, IOException, URISyntaxException { + public static URI getJarURI(final String clazzBinName, final ClassLoader cl) throws IllegalArgumentException, IOException, URISyntaxException { if(null == clazzBinName || null == cl) { throw new IllegalArgumentException("null arguments: clazzBinName "+clazzBinName+", cl "+cl); } @@ -187,7 +187,7 @@ public class JarUtil { * @throws IllegalArgumentException if the URI doesn't match the expected formatting or is null * @see {@link IOUtil#getClassURL(String, ClassLoader)} */ - public static String getJarBasename(URI classJarURI) throws IllegalArgumentException { + public static String getJarBasename(final URI classJarURI) throws IllegalArgumentException { if(null == classJarURI) { throw new IllegalArgumentException("URI is null"); } @@ -246,7 +246,7 @@ public class JarUtil { * @throws URISyntaxException if the URI could not be translated into a RFC 2396 URI * @see {@link IOUtil#getClassURL(String, ClassLoader)} */ - public static String getJarBasename(String clazzBinName, ClassLoader cl) throws IllegalArgumentException, IOException, URISyntaxException { + public static String getJarBasename(final String clazzBinName, final ClassLoader cl) throws IllegalArgumentException, IOException, URISyntaxException { return getJarBasename( getJarURI(clazzBinName, cl) ); } @@ -264,7 +264,7 @@ public class JarUtil { * @throws URISyntaxException if the URI could not be translated into a RFC 2396 URI * @see {@link IOUtil#getClassURL(String, ClassLoader)} */ - public static URI getJarSubURI(URI classJarURI) throws IllegalArgumentException, URISyntaxException { + public static URI getJarSubURI(final URI classJarURI) throws IllegalArgumentException, URISyntaxException { if(null == classJarURI) { throw new IllegalArgumentException("URI is null"); } @@ -277,7 +277,7 @@ public class JarUtil { // to // file:/some/path/gluegen-rt.jar final String uriS0 = classJarURI.getSchemeSpecificPart(); - int idx = uriS0.lastIndexOf(IOUtil.JAR_SCHEME_SEPARATOR); + final int idx = uriS0.lastIndexOf(IOUtil.JAR_SCHEME_SEPARATOR); final String uriS1; if (0 <= idx) { uriS1 = uriS0.substring(0, idx); // exclude '!/' @@ -303,7 +303,7 @@ public class JarUtil { * @return <code>/com/jogamp/common/GlueGenVersion.class</code> * @see {@link IOUtil#getClassURL(String, ClassLoader)} */ - public static String getJarEntry(URI classJarURI) { + public static String getJarEntry(final URI classJarURI) { if(null == classJarURI) { throw new IllegalArgumentException("URI is null"); } @@ -345,7 +345,7 @@ public class JarUtil { * @throws URISyntaxException if the URI could not be translated into a RFC 2396 URI * @see {@link IOUtil#getClassURL(String, ClassLoader)} */ - public static URI getJarSubURI(String clazzBinName, ClassLoader cl) throws IllegalArgumentException, IOException, URISyntaxException { + public static URI getJarSubURI(final String clazzBinName, final ClassLoader cl) throws IllegalArgumentException, IOException, URISyntaxException { return getJarSubURI( getJarURI(clazzBinName, cl) ); } @@ -365,7 +365,7 @@ public class JarUtil { * @throws URISyntaxException if the URI could not be translated into a RFC 2396 URI * @see {@link IOUtil#getClassURL(String, ClassLoader)} */ - public static URI getJarFileURI(String clazzBinName, ClassLoader cl) throws IllegalArgumentException, IOException, URISyntaxException { + public static URI getJarFileURI(final String clazzBinName, final ClassLoader cl) throws IllegalArgumentException, IOException, URISyntaxException { if(null == clazzBinName || null == cl) { throw new IllegalArgumentException("null arguments: clazzBinName "+clazzBinName+", cl "+cl); } @@ -383,7 +383,7 @@ public class JarUtil { * @throws URISyntaxException * @throws IllegalArgumentException null arguments */ - public static URI getJarFileURI(URI baseUri, String jarFileName) throws IllegalArgumentException, URISyntaxException { + public static URI getJarFileURI(final URI baseUri, final String jarFileName) throws IllegalArgumentException, URISyntaxException { if(null == baseUri || null == jarFileName) { throw new IllegalArgumentException("null arguments: baseURI "+baseUri+", jarFileName "+jarFileName); } @@ -396,7 +396,7 @@ public class JarUtil { * @throws IllegalArgumentException null arguments * @throws URISyntaxException */ - public static URI getJarFileURI(URI jarSubUri) throws IllegalArgumentException, URISyntaxException { + public static URI getJarFileURI(final URI jarSubUri) throws IllegalArgumentException, URISyntaxException { if(null == jarSubUri) { throw new IllegalArgumentException("jarSubURI is null"); } @@ -409,7 +409,7 @@ public class JarUtil { * @throws IllegalArgumentException null arguments * @throws URISyntaxException */ - public static URI getJarFileURI(String jarSubUriS) throws IllegalArgumentException, URISyntaxException { + public static URI getJarFileURI(final String jarSubUriS) throws IllegalArgumentException, URISyntaxException { if(null == jarSubUriS) { throw new IllegalArgumentException("jarSubURIS is null"); } @@ -423,7 +423,7 @@ public class JarUtil { * @throws IllegalArgumentException null arguments * @throws URISyntaxException */ - public static URI getJarEntryURI(URI jarFileURI, String jarEntry) throws IllegalArgumentException, URISyntaxException { + public static URI getJarEntryURI(final URI jarFileURI, final String jarEntry) throws IllegalArgumentException, URISyntaxException { if(null == jarEntry) { throw new IllegalArgumentException("jarEntry is null"); } @@ -439,7 +439,7 @@ public class JarUtil { * @throws URISyntaxException if the URI could not be translated into a RFC 2396 URI * @see {@link #getJarFileURI(String, ClassLoader)} */ - public static JarFile getJarFile(String clazzBinName, ClassLoader cl) throws IOException, IllegalArgumentException, URISyntaxException { + public static JarFile getJarFile(final String clazzBinName, final ClassLoader cl) throws IOException, IllegalArgumentException, URISyntaxException { return getJarFile( getJarFileURI(clazzBinName, cl) ); } @@ -450,7 +450,7 @@ public class JarUtil { * @throws IOException if the Jar file could not been found * @throws URISyntaxException */ - public static JarFile getJarFile(URI jarFileURI) throws IOException, IllegalArgumentException, URISyntaxException { + public static JarFile getJarFile(final URI jarFileURI) throws IOException, IllegalArgumentException, URISyntaxException { if(null == jarFileURI) { throw new IllegalArgumentException("null jarFileURI"); } @@ -464,8 +464,8 @@ public class JarUtil { // final URL jarFileURL = jarFileURI.toURL(); // doesn't work due to encoded path even w/ file schema! final URLConnection urlc = jarFileURL.openConnection(); if(urlc instanceof JarURLConnection) { - JarURLConnection jarConnection = (JarURLConnection)jarFileURL.openConnection(); - JarFile jarFile = jarConnection.getJarFile(); + final JarURLConnection jarConnection = (JarURLConnection)jarFileURL.openConnection(); + final JarFile jarFile = jarConnection.getJarFile(); if(DEBUG) { System.err.println("getJarFile res: "+jarFile.getName()); } @@ -509,7 +509,7 @@ public class JarUtil { * @throws IOException * @throws URISyntaxException */ - public static URI getRelativeOf(Class<?> classFromJavaJar, String cutOffInclSubDir, String relResPath) throws IllegalArgumentException, IOException, URISyntaxException { + public static URI getRelativeOf(final Class<?> classFromJavaJar, final String cutOffInclSubDir, final String relResPath) throws IllegalArgumentException, IOException, URISyntaxException { final ClassLoader cl = classFromJavaJar.getClassLoader(); final URI classJarURI = JarUtil.getJarURI(classFromJavaJar.getName(), cl); if( DEBUG ) { @@ -546,7 +546,7 @@ public class JarUtil { /** * Return a map from native-lib-base-name to entry-name. */ - public static Map<String, String> getNativeLibNames(JarFile jarFile) { + public static Map<String, String> getNativeLibNames(final JarFile jarFile) { if (DEBUG) { System.err.println("JarUtil: getNativeLibNames: "+jarFile); } @@ -602,11 +602,11 @@ public class JarUtil { * @return * @throws IOException */ - public static final int extract(File dest, Map<String, String> nativeLibMap, - JarFile jarFile, - String nativeLibraryPath, - boolean extractNativeLibraries, - boolean extractClassFiles, boolean extractOtherFiles) throws IOException { + public static final int extract(final File dest, final Map<String, String> nativeLibMap, + final JarFile jarFile, + final String nativeLibraryPath, + final boolean extractNativeLibraries, + final boolean extractClassFiles, final boolean extractOtherFiles) throws IOException { if (DEBUG) { System.err.println("JarUtil: extract: "+jarFile.getName()+" -> "+dest+ @@ -616,10 +616,10 @@ public class JarUtil { } int num = 0; - Enumeration<JarEntry> entries = jarFile.entries(); + final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { - JarEntry entry = entries.nextElement(); - String entryName = entry.getName(); + final JarEntry entry = entries.nextElement(); + final String entryName = entry.getName(); // Match entries with correct prefix and suffix (ignoring case) final String libBaseName = NativeLibrary.isValidNativeLibraryName(entryName, false); @@ -637,7 +637,7 @@ public class JarUtil { try { nativeLibraryPathS = IOUtil.slashify(nativeLibraryPath, false /* startWithSlash */, true /* endWithSlash */); dirnameS = IOUtil.getDirname(entryName); - } catch (URISyntaxException e) { + } catch (final URISyntaxException e) { throw new IOException(e); } if( !nativeLibraryPathS.equals(dirnameS) ) { @@ -721,7 +721,7 @@ public class JarUtil { * <li>Bug 865: Safari >= 6.1 [OSX]: May employ xattr on 'com.apple.quarantine' on 'PluginProcess.app'</li> * </ul> */ - private final static void fixNativeLibAttribs(File file) { + private final static void fixNativeLibAttribs(final File file) { // We tolerate UnsatisfiedLinkError (and derived) to solve the chicken and egg problem // of loading gluegen's native library. // On Safari(OSX), Bug 865, we simply hope the destination folder is executable. @@ -732,7 +732,7 @@ public class JarUtil { if( DEBUG ) { System.err.println("JarUtil.fixNativeLibAttribs: "+fileAbsPath+" - OK"); } - } catch (Throwable t) { + } catch (final Throwable t) { if( DEBUG ) { System.err.println("JarUtil.fixNativeLibAttribs: "+fileAbsPath+" - "+t.getClass().getSimpleName()+": "+t.getMessage()); } @@ -749,7 +749,7 @@ public class JarUtil { getCodeSource().getCertificates(); </pre> */ - public static final void validateCertificates(Certificate[] rootCerts, JarFile jarFile) + public static final void validateCertificates(final Certificate[] rootCerts, final JarFile jarFile) throws IOException, SecurityException { if (DEBUG) { @@ -760,8 +760,8 @@ public class JarUtil { throw new IllegalArgumentException("Null certificates passed"); } - byte[] buf = new byte[1024]; - Enumeration<JarEntry> entries = jarFile.entries(); + final byte[] buf = new byte[1024]; + final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); if( ! entry.isDirectory() && ! entry.getName().startsWith("META-INF/") ) { @@ -775,8 +775,8 @@ public class JarUtil { * Check the certificates with the ones in the jar file * (all must match). */ - private static final void validateCertificate(Certificate[] rootCerts, - JarFile jar, JarEntry entry, byte[] buf) throws IOException, SecurityException { + private static final void validateCertificate(final Certificate[] rootCerts, + final JarFile jar, final JarEntry entry, final byte[] buf) throws IOException, SecurityException { if (DEBUG) { System.err.println("JarUtil: validate JarEntry : " + entry.getName()); @@ -785,7 +785,7 @@ public class JarUtil { // API states that we must read all of the data from the entry's // InputStream in order to be able to get its certificates - InputStream is = jar.getInputStream(entry); + final InputStream is = jar.getInputStream(entry); try { while (is.read(buf) > 0) { } } finally { diff --git a/src/java/com/jogamp/common/util/JogampVersion.java b/src/java/com/jogamp/common/util/JogampVersion.java index 2789de7..2ff7d81 100644 --- a/src/java/com/jogamp/common/util/JogampVersion.java +++ b/src/java/com/jogamp/common/util/JogampVersion.java @@ -47,15 +47,15 @@ public class JogampVersion { /** See {@link #getImplementationCommit()} */ public static final Attributes.Name IMPLEMENTATION_COMMIT = new Attributes.Name("Implementation-Commit"); - private String packageName; - private Manifest mf; - private int hash; - private Attributes mainAttributes; - private Set<?>/*<Attributes.Name>*/ mainAttributeNames; + private final String packageName; + private final Manifest mf; + private final int hash; + private final Attributes mainAttributes; + private final Set<?>/*<Attributes.Name>*/ mainAttributeNames; private final String androidPackageVersionName; - protected JogampVersion(String packageName, Manifest mf) { + protected JogampVersion(final String packageName, final Manifest mf) { this.packageName = packageName; this.mf = ( null != mf ) ? mf : new Manifest(); this.hash = this.mf.hashCode(); @@ -70,7 +70,7 @@ public class JogampVersion { } @Override - public final boolean equals(Object o) { + public final boolean equals(final Object o) { if (o instanceof JogampVersion) { return mf.equals(((JogampVersion) o).getManifest()); } @@ -85,17 +85,17 @@ public class JogampVersion { return packageName; } - public final String getAttribute(Attributes.Name attributeName) { + public final String getAttribute(final Attributes.Name attributeName) { return (null != attributeName) ? (String) mainAttributes.get(attributeName) : null; } - public final String getAttribute(String attributeName) { + public final String getAttribute(final String attributeName) { return getAttribute(getAttributeName(attributeName)); } - public final Attributes.Name getAttributeName(String attributeName) { - for (Iterator<?> iter = mainAttributeNames.iterator(); iter.hasNext();) { - Attributes.Name an = (Attributes.Name) iter.next(); + public final Attributes.Name getAttributeName(final String attributeName) { + for (final Iterator<?> iter = mainAttributeNames.iterator(); iter.hasNext();) { + final Attributes.Name an = (Attributes.Name) iter.next(); if (an.toString().equals(attributeName)) { return an; } @@ -121,21 +121,21 @@ public class JogampVersion { * Returns the implementation build number, e.g. <code>2.0-b456-20130328</code>. */ public final String getImplementationBuild() { - return this.getAttribute(GlueGenVersion.IMPLEMENTATION_BUILD); + return this.getAttribute(JogampVersion.IMPLEMENTATION_BUILD); } /** * Returns the SCM branch name */ public final String getImplementationBranch() { - return this.getAttribute(GlueGenVersion.IMPLEMENTATION_BRANCH); + return this.getAttribute(JogampVersion.IMPLEMENTATION_BRANCH); } /** * Returns the SCM version of the last commit, e.g. git's sha1 */ public final String getImplementationCommit() { - return this.getAttribute(GlueGenVersion.IMPLEMENTATION_COMMIT); + return this.getAttribute(JogampVersion.IMPLEMENTATION_COMMIT); } public final String getImplementationTitle() { @@ -181,7 +181,7 @@ public class JogampVersion { return this.getAttribute(Attributes.Name.SPECIFICATION_VERSION); } - public final StringBuilder getFullManifestInfo(StringBuilder sb) { + public final StringBuilder getFullManifestInfo(final StringBuilder sb) { return VersionUtil.getFullManifestInfo(getManifest(), sb); } @@ -189,7 +189,7 @@ public class JogampVersion { if(null==sb) { sb = new StringBuilder(); } - String nl = Platform.getNewline(); + final String nl = Platform.getNewline(); sb.append("Package: ").append(getPackageName()).append(nl); sb.append("Extension Name: ").append(getExtensionName()).append(nl); sb.append("Specification Title: ").append(getSpecificationTitle()).append(nl); diff --git a/src/java/com/jogamp/common/util/LFRingbuffer.java b/src/java/com/jogamp/common/util/LFRingbuffer.java index a0418c5..685c529 100644 --- a/src/java/com/jogamp/common/util/LFRingbuffer.java +++ b/src/java/com/jogamp/common/util/LFRingbuffer.java @@ -87,7 +87,7 @@ public class LFRingbuffer<T> implements Ringbuffer<T> { } @Override - public final void dump(PrintStream stream, String prefix) { + public final void dump(final PrintStream stream, final String prefix) { stream.println(prefix+" "+toString()+" {"); for(int i=0; i<capacityPlusOne; i++) { stream.println("\t["+i+"]: "+array[i]); @@ -116,7 +116,7 @@ public class LFRingbuffer<T> implements Ringbuffer<T> { * @throws IllegalArgumentException if <code>copyFrom</code> is <code>null</code> */ @SuppressWarnings("unchecked") - public LFRingbuffer(T[] copyFrom) throws IllegalArgumentException { + public LFRingbuffer(final T[] copyFrom) throws IllegalArgumentException { capacityPlusOne = copyFrom.length + 1; array = (T[]) newArray(copyFrom.getClass(), capacityPlusOne); resetImpl(true, copyFrom); @@ -139,9 +139,9 @@ public class LFRingbuffer<T> implements Ringbuffer<T> { * @param arrayType the array type of the created empty internal array. * @param capacity the initial net capacity of the ring buffer */ - public LFRingbuffer(Class<? extends T[]> arrayType, int capacity) { + public LFRingbuffer(final Class<? extends T[]> arrayType, final int capacity) { capacityPlusOne = capacity+1; - array = (T[]) newArray(arrayType, capacityPlusOne); + array = newArray(arrayType, capacityPlusOne); resetImpl(false, null /* empty, nothing to copy */ ); } @@ -162,11 +162,11 @@ public class LFRingbuffer<T> implements Ringbuffer<T> { } @Override - public final void resetFull(T[] copyFrom) throws IllegalArgumentException { + public final void resetFull(final T[] copyFrom) throws IllegalArgumentException { resetImpl(true, copyFrom); } - private final void resetImpl(boolean full, T[] copyFrom) throws IllegalArgumentException { + private final void resetImpl(final boolean full, final T[] copyFrom) throws IllegalArgumentException { synchronized ( syncGlobal ) { if( null != copyFrom ) { if( copyFrom.length != capacityPlusOne-1 ) { @@ -210,7 +210,7 @@ public class LFRingbuffer<T> implements Ringbuffer<T> { public final T get() { try { return getImpl(false, false); - } catch (InterruptedException ie) { throw new RuntimeException(ie); } + } catch (final InterruptedException ie) { throw new RuntimeException(ie); } } /** @@ -228,14 +228,14 @@ public class LFRingbuffer<T> implements Ringbuffer<T> { public final T peek() { try { return getImpl(false, true); - } catch (InterruptedException ie) { throw new RuntimeException(ie); } + } catch (final InterruptedException ie) { throw new RuntimeException(ie); } } @Override public final T peekBlocking() throws InterruptedException { return getImpl(true, true); } - private final T getImpl(boolean blocking, boolean peek) throws InterruptedException { + private final T getImpl(final boolean blocking, final boolean peek) throws InterruptedException { int localReadPos = readPos; if( localReadPos == writePos ) { if( blocking ) { @@ -268,10 +268,10 @@ public class LFRingbuffer<T> implements Ringbuffer<T> { * </p> */ @Override - public final boolean put(T e) { + public final boolean put(final T e) { try { return putImpl(e, false, false); - } catch (InterruptedException ie) { throw new RuntimeException(ie); } + } catch (final InterruptedException ie) { throw new RuntimeException(ie); } } /** @@ -281,7 +281,7 @@ public class LFRingbuffer<T> implements Ringbuffer<T> { * </p> */ @Override - public final void putBlocking(T e) throws InterruptedException { + public final void putBlocking(final T e) throws InterruptedException { if( !putImpl(e, false, true) ) { throw new InternalError("Blocking put failed: "+this); } @@ -294,11 +294,11 @@ public class LFRingbuffer<T> implements Ringbuffer<T> { * </p> */ @Override - public final boolean putSame(boolean blocking) throws InterruptedException { + public final boolean putSame(final boolean blocking) throws InterruptedException { return putImpl(null, true, blocking); } - private final boolean putImpl(T e, boolean sameRef, boolean blocking) throws InterruptedException { + private final boolean putImpl(final T e, final boolean sameRef, final boolean blocking) throws InterruptedException { int localWritePos = writePos; localWritePos = (localWritePos + 1) % capacityPlusOne; if( localWritePos == readPos ) { @@ -325,7 +325,7 @@ public class LFRingbuffer<T> implements Ringbuffer<T> { @Override - public final void waitForFreeSlots(int count) throws InterruptedException { + public final void waitForFreeSlots(final int count) throws InterruptedException { synchronized ( syncRead ) { if( capacityPlusOne - 1 - size < count ) { while( capacityPlusOne - 1 - size < count ) { @@ -361,7 +361,7 @@ public class LFRingbuffer<T> implements Ringbuffer<T> { final int growAmount = newElements.length; final int newCapacity = capacityPlusOne + growAmount; final T[] oldArray = array; - final T[] newArray = (T[]) newArray(arrayTypeInternal, newCapacity); + final T[] newArray = newArray(arrayTypeInternal, newCapacity); // writePos == readPos writePos += growAmount; // warp writePos to the end of the new data location @@ -401,7 +401,7 @@ public class LFRingbuffer<T> implements Ringbuffer<T> { final int newCapacity = capacityPlusOne + growAmount; final T[] oldArray = array; - final T[] newArray = (T[]) newArray(arrayTypeInternal, newCapacity); + final T[] newArray = newArray(arrayTypeInternal, newCapacity); // writePos == readPos - 1 readPos = ( writePos + 1 + growAmount ) % newCapacity; // warp readPos to the end of the new data location @@ -420,7 +420,7 @@ public class LFRingbuffer<T> implements Ringbuffer<T> { } @SuppressWarnings("unchecked") - private static <T> T[] newArray(Class<? extends T[]> arrayType, int length) { + private static <T> T[] newArray(final Class<? extends T[]> arrayType, final int length) { return ((Object)arrayType == (Object)Object[].class) ? (T[]) new Object[length] : (T[]) Array.newInstance(arrayType.getComponentType(), length); diff --git a/src/java/com/jogamp/common/util/PropertyAccess.java b/src/java/com/jogamp/common/util/PropertyAccess.java index a2e3690..b6e9bdd 100644 --- a/src/java/com/jogamp/common/util/PropertyAccess.java +++ b/src/java/com/jogamp/common/util/PropertyAccess.java @@ -59,12 +59,12 @@ public class PropertyAccess { * @param prefix New prefix to be registered as trusted. * @throws AccessControlException as thrown by {@link SecurityUtil#checkAllPermissions()}. */ - protected static final void addTrustedPrefix(String prefix) throws AccessControlException { + protected static final void addTrustedPrefix(final String prefix) throws AccessControlException { SecurityUtil.checkAllPermissions(); trustedPrefixes.add(prefix); } - public static final boolean isTrusted(String propertyKey) { + public static final boolean isTrusted(final String propertyKey) { final int dot1 = propertyKey.indexOf('.'); if(0<=dot1) { return trustedPrefixes.contains(propertyKey.substring(0, dot1+1)) || trusted.contains(propertyKey); @@ -74,26 +74,26 @@ public class PropertyAccess { } /** @see #getProperty(String, boolean) */ - public static final int getIntProperty(final String property, final boolean jnlpAlias, int defaultValue) { + public static final int getIntProperty(final String property, final boolean jnlpAlias, final int defaultValue) { int i=defaultValue; try { final String sv = PropertyAccess.getProperty(property, jnlpAlias); if(null!=sv) { i = Integer.parseInt(sv); } - } catch (NumberFormatException nfe) {} + } catch (final NumberFormatException nfe) {} return i; } /** @see #getProperty(String, boolean) */ - public static final long getLongProperty(final String property, final boolean jnlpAlias, long defaultValue) { + public static final long getLongProperty(final String property, final boolean jnlpAlias, final long defaultValue) { long l=defaultValue; try { final String sv = PropertyAccess.getProperty(property, jnlpAlias); if(null!=sv) { l = Long.parseLong(sv); } - } catch (NumberFormatException nfe) {} + } catch (final NumberFormatException nfe) {} return l; } @@ -103,7 +103,7 @@ public class PropertyAccess { } /** @see #getProperty(String, boolean) */ - public static final boolean getBooleanProperty(final String property, final boolean jnlpAlias, boolean defaultValue) { + public static final boolean getBooleanProperty(final String property, final boolean jnlpAlias, final boolean defaultValue) { final String valueS = PropertyAccess.getProperty(property, jnlpAlias); if(null != valueS) { return Boolean.valueOf(valueS).booleanValue(); @@ -164,7 +164,7 @@ public class PropertyAccess { } /** See {@link #getProperty(String, boolean)}, additionally allows a <code>defaultValue</code> if property value is <code>null</code>. */ - public static final String getProperty(final String propertyKey, final boolean jnlpAlias, String defaultValue) + public static final String getProperty(final String propertyKey, final boolean jnlpAlias, final String defaultValue) throws SecurityException, NullPointerException, IllegalArgumentException { final String s = PropertyAccess.getProperty(propertyKey, jnlpAlias); if( null != s ) { @@ -180,7 +180,7 @@ public class PropertyAccess { public String run() { try { return System.getProperty(propertyKey); - } catch (SecurityException se) { + } catch (final SecurityException se) { throw new SecurityException("Could not access trusted property '"+propertyKey+"'", se); } } diff --git a/src/java/com/jogamp/common/util/ReflectionUtil.java b/src/java/com/jogamp/common/util/ReflectionUtil.java index 949df1d..7117f56 100644 --- a/src/java/com/jogamp/common/util/ReflectionUtil.java +++ b/src/java/com/jogamp/common/util/ReflectionUtil.java @@ -63,7 +63,7 @@ public final class ReflectionUtil { static { Debug.initSingleton(); DEBUG = Debug.debug("ReflectionUtil"); - DEBUG_STATS_FORNAME = Debug.isPropertyDefined("jogamp.debug.ReflectionUtil.forNameStats", true); + DEBUG_STATS_FORNAME = PropertyAccess.isPropertyDefined("jogamp.debug.ReflectionUtil.forNameStats", true); if(DEBUG_STATS_FORNAME) { forNameLock = new Object(); forNameStats = new HashMap<String, ClassNameLookup>(); @@ -81,7 +81,7 @@ public final class ReflectionUtil { private static final Class<?>[] zeroTypes = new Class[0]; private static class ClassNameLookup { - public ClassNameLookup(String name) { + public ClassNameLookup(final String name) { this.name = name; this.nanoCosts = 0; this.count = 0; @@ -111,7 +111,7 @@ public final class ReflectionUtil { sb.append(String.format("ReflectionUtil.forName: %8.3f ms, %03d invoc%n", forNameNanoCosts/1e6, forNameCount)); final Set<Entry<String, ClassNameLookup>> entries = forNameStats.entrySet(); int entryNum = 0; - for(Iterator<Entry<String, ClassNameLookup>> iter = entries.iterator(); iter.hasNext(); entryNum++) { + for(final Iterator<Entry<String, ClassNameLookup>> iter = entries.iterator(); iter.hasNext(); entryNum++) { final Entry<String, ClassNameLookup> entry = iter.next(); sb.append(String.format("ReflectionUtil.forName[%03d]: %s%n", entryNum, entry.getValue())); } @@ -120,7 +120,7 @@ public final class ReflectionUtil { return sb; } - private static Class<?> getClassImpl(String clazzName, boolean initializeClazz, ClassLoader cl) throws ClassNotFoundException { + private static Class<?> getClassImpl(final String clazzName, final boolean initializeClazz, final ClassLoader cl) throws ClassNotFoundException { if(DEBUG_STATS_FORNAME) { final long t0 = System.nanoTime(); final Class<?> res = Class.forName(clazzName, initializeClazz, cl); @@ -151,10 +151,10 @@ public final class ReflectionUtil { /** * Returns true only if the class could be loaded. */ - public static final boolean isClassAvailable(String clazzName, ClassLoader cl) { + public static final boolean isClassAvailable(final String clazzName, final ClassLoader cl) { try { return null != getClassImpl(clazzName, false, cl); - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { return false; } } @@ -163,11 +163,11 @@ public final class ReflectionUtil { * Loads and returns the class or null. * @see Class#forName(java.lang.String, boolean, java.lang.ClassLoader) */ - public static final Class<?> getClass(String clazzName, boolean initializeClazz, ClassLoader cl) + public static final Class<?> getClass(final String clazzName, final boolean initializeClazz, final ClassLoader cl) throws JogampRuntimeException { try { return getClassImpl(clazzName, initializeClazz, cl); - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { throw new JogampRuntimeException(clazzName + " not available", e); } } @@ -176,17 +176,17 @@ public final class ReflectionUtil { * @param initializeClazz TODO * @throws JogampRuntimeException if the constructor can not be delivered. */ - public static final Constructor<?> getConstructor(String clazzName, Class<?>[] cstrArgTypes, boolean initializeClazz, ClassLoader cl) + public static final Constructor<?> getConstructor(final String clazzName, final Class<?>[] cstrArgTypes, final boolean initializeClazz, final ClassLoader cl) throws JogampRuntimeException { try { return getConstructor(getClassImpl(clazzName, initializeClazz, cl), cstrArgTypes); - } catch (ClassNotFoundException ex) { + } catch (final ClassNotFoundException ex) { throw new JogampRuntimeException(clazzName + " not available", ex); } } - static final String asString(Class<?>[] argTypes) { - StringBuilder args = new StringBuilder(); + static final String asString(final Class<?>[] argTypes) { + final StringBuilder args = new StringBuilder(); boolean coma = false; if(null != argTypes) { for (int i = 0; i < argTypes.length; i++) { @@ -213,7 +213,7 @@ public final class ReflectionUtil { * * @throws JogampRuntimeException if the constructor can not be delivered. */ - public static final Constructor<?> getConstructor(Class<?> clazz, Class<?> ... cstrArgTypes) + public static final Constructor<?> getConstructor(final Class<?> clazz, Class<?> ... cstrArgTypes) throws JogampRuntimeException { if(null == cstrArgTypes) { cstrArgTypes = zeroTypes; @@ -221,7 +221,7 @@ public final class ReflectionUtil { Constructor<?> cstr = null; try { cstr = clazz.getDeclaredConstructor(cstrArgTypes); - } catch (NoSuchMethodException ex) { + } catch (final NoSuchMethodException ex) { // ok, cont. w/ 'isAssignableFrom()' validation } if(null == cstr) { @@ -248,7 +248,7 @@ public final class ReflectionUtil { return cstr; } - public static final Constructor<?> getConstructor(String clazzName, ClassLoader cl) + public static final Constructor<?> getConstructor(final String clazzName, final ClassLoader cl) throws JogampRuntimeException { return getConstructor(clazzName, null, true, cl); } @@ -256,12 +256,12 @@ public final class ReflectionUtil { /** * @throws JogampRuntimeException if the instance can not be created. */ - public static final Object createInstance(Constructor<?> cstr, Object ... cstrArgs) + public static final Object createInstance(final Constructor<?> cstr, final Object ... cstrArgs) throws JogampRuntimeException, RuntimeException { try { return cstr.newInstance(cstrArgs); - } catch (Exception e) { + } catch (final Exception e) { Throwable t = e; if (t instanceof InvocationTargetException) { t = ((InvocationTargetException) t).getTargetException(); @@ -279,13 +279,13 @@ public final class ReflectionUtil { /** * @throws JogampRuntimeException if the instance can not be created. */ - public static final Object createInstance(Class<?> clazz, Class<?>[] cstrArgTypes, Object ... cstrArgs) + public static final Object createInstance(final Class<?> clazz, final Class<?>[] cstrArgTypes, final Object ... cstrArgs) throws JogampRuntimeException, RuntimeException { return createInstance(getConstructor(clazz, cstrArgTypes), cstrArgs); } - public static final Object createInstance(Class<?> clazz, Object ... cstrArgs) + public static final Object createInstance(final Class<?> clazz, final Object ... cstrArgs) throws JogampRuntimeException, RuntimeException { Class<?>[] cstrArgTypes = null; @@ -298,17 +298,17 @@ public final class ReflectionUtil { return createInstance(clazz, cstrArgTypes, cstrArgs); } - public static final Object createInstance(String clazzName, Class<?>[] cstrArgTypes, Object[] cstrArgs, ClassLoader cl) + public static final Object createInstance(final String clazzName, final Class<?>[] cstrArgTypes, final Object[] cstrArgs, final ClassLoader cl) throws JogampRuntimeException, RuntimeException { try { return createInstance(getClassImpl(clazzName, true, cl), cstrArgTypes, cstrArgs); - } catch (ClassNotFoundException ex) { + } catch (final ClassNotFoundException ex) { throw new JogampRuntimeException(clazzName + " not available", ex); } } - public static final Object createInstance(String clazzName, Object[] cstrArgs, ClassLoader cl) + public static final Object createInstance(final String clazzName, final Object[] cstrArgs, final ClassLoader cl) throws JogampRuntimeException, RuntimeException { Class<?>[] cstrArgTypes = null; @@ -321,16 +321,16 @@ public final class ReflectionUtil { return createInstance(clazzName, cstrArgTypes, cstrArgs, cl); } - public static final Object createInstance(String clazzName, ClassLoader cl) + public static final Object createInstance(final String clazzName, final ClassLoader cl) throws JogampRuntimeException, RuntimeException { return createInstance(clazzName, null, null, cl); } - public static final boolean instanceOf(Object obj, String clazzName) { + public static final boolean instanceOf(final Object obj, final String clazzName) { return instanceOf(obj.getClass(), clazzName); } - public static final boolean instanceOf(Class<?> clazz, String clazzName) { + public static final boolean instanceOf(Class<?> clazz, final String clazzName) { do { if(clazz.getName().equals(clazzName)) { return true; @@ -340,14 +340,14 @@ public final class ReflectionUtil { return false; } - public static final boolean implementationOf(Object obj, String faceName) { + public static final boolean implementationOf(final Object obj, final String faceName) { return implementationOf(obj.getClass(), faceName); } - public static final boolean implementationOf(Class<?> clazz, String faceName) { + public static final boolean implementationOf(Class<?> clazz, final String faceName) { do { - Class<?>[] clazzes = clazz.getInterfaces(); + final Class<?>[] clazzes = clazz.getInterfaces(); for(int i=clazzes.length-1; i>=0; i--) { - Class<?> face = clazzes[i]; + final Class<?> face = clazzes[i]; if(face.getName().equals(faceName)) { return true; } @@ -357,27 +357,27 @@ public final class ReflectionUtil { return false; } - public static boolean isAWTComponent(Object target) { + public static boolean isAWTComponent(final Object target) { return instanceOf(target, AWTNames.ComponentClass); } - public static boolean isAWTComponent(Class<?> clazz) { + public static boolean isAWTComponent(final Class<?> clazz) { return instanceOf(clazz, AWTNames.ComponentClass); } /** * @throws JogampRuntimeException if the Method can not be found. */ - public static final Method getMethod(Class<?> clazz, String methodName, Class<?> ... argTypes) + public static final Method getMethod(final Class<?> clazz, final String methodName, final Class<?> ... argTypes) throws JogampRuntimeException, RuntimeException { Throwable t = null; Method m = null; try { m = clazz.getDeclaredMethod(methodName, argTypes); - } catch (NoClassDefFoundError ex0) { + } catch (final NoClassDefFoundError ex0) { t = ex0; - } catch (NoSuchMethodException ex1) { + } catch (final NoSuchMethodException ex1) { t = ex1; } if(null != t) { @@ -389,12 +389,12 @@ public final class ReflectionUtil { /** * @throws JogampRuntimeException if the Method can not be found. */ - public static final Method getMethod(String clazzName, String methodName, Class<?>[] argTypes, ClassLoader cl) + public static final Method getMethod(final String clazzName, final String methodName, final Class<?>[] argTypes, final ClassLoader cl) throws JogampRuntimeException, RuntimeException { try { return getMethod(getClassImpl(clazzName, true, cl), methodName, argTypes); - } catch (ClassNotFoundException ex) { + } catch (final ClassNotFoundException ex) { throw new JogampRuntimeException(clazzName + " not available", ex); } } @@ -407,12 +407,12 @@ public final class ReflectionUtil { * @throws JogampRuntimeException if call fails * @throws RuntimeException if call fails */ - public static final Object callMethod(Object instance, Method method, Object ... args) + public static final Object callMethod(final Object instance, final Method method, final Object ... args) throws JogampRuntimeException, RuntimeException { try { return method.invoke(instance, args); - } catch (Exception e) { + } catch (final Exception e) { Throwable t = e; if (t instanceof InvocationTargetException) { t = ((InvocationTargetException) t).getTargetException(); @@ -430,7 +430,7 @@ public final class ReflectionUtil { /** * @throws JogampRuntimeException if the instance can not be created. */ - public static final Object callStaticMethod(String clazzName, String methodName, Class<?>[] argTypes, Object[] args, ClassLoader cl) + public static final Object callStaticMethod(final String clazzName, final String methodName, final Class<?>[] argTypes, final Object[] args, final ClassLoader cl) throws JogampRuntimeException, RuntimeException { return callMethod(null, getMethod(clazzName, methodName, argTypes, cl), args); @@ -441,10 +441,10 @@ public final class ReflectionUtil { Method m = null; /** Check {@link #available()} before using instance. */ - public MethodAccessor(Class<?> clazz, String methodName, Class<?> ... argTypes) { + public MethodAccessor(final Class<?> clazz, final String methodName, final Class<?> ... argTypes) { try { m = ReflectionUtil.getMethod(clazz, methodName, argTypes); - } catch (JogampRuntimeException jre) { /* method n/a */ } + } catch (final JogampRuntimeException jre) { /* method n/a */ } } /** Returns true if method is available, otherwise false. */ @@ -456,7 +456,7 @@ public final class ReflectionUtil { * Check {@link #available()} before calling to avoid throwing a JogampRuntimeException. * @throws JogampRuntimeException if method is not available */ - public Object callMethod(Object instance, Object ... args) { + public Object callMethod(final Object instance, final Object ... args) { if(null == m) { throw new JogampRuntimeException("Method not available. Instance: "+instance); } diff --git a/src/java/com/jogamp/common/util/RunnableExecutor.java b/src/java/com/jogamp/common/util/RunnableExecutor.java index 629bc8c..9358a06 100644 --- a/src/java/com/jogamp/common/util/RunnableExecutor.java +++ b/src/java/com/jogamp/common/util/RunnableExecutor.java @@ -43,7 +43,7 @@ public interface RunnableExecutor { private CurrentThreadExecutor() {} @Override - public void invoke(boolean wait, Runnable r) { + public void invoke(final boolean wait, final Runnable r) { r.run(); } } diff --git a/src/java/com/jogamp/common/util/RunnableTask.java b/src/java/com/jogamp/common/util/RunnableTask.java index 97adf04..6fb98de 100644 --- a/src/java/com/jogamp/common/util/RunnableTask.java +++ b/src/java/com/jogamp/common/util/RunnableTask.java @@ -42,7 +42,7 @@ public class RunnableTask extends TaskBase { * @param waitUntilDone if <code>true</code>, waits until <code>runnable</code> execution is completed, otherwise returns immediately. * @param runnable the {@link Runnable} to execute. */ - public static void invoke(boolean waitUntilDone, Runnable runnable) { + public static void invoke(final boolean waitUntilDone, final Runnable runnable) { Throwable throwable = null; final Object sync = new Object(); final RunnableTask rt = new RunnableTask( runnable, waitUntilDone ? sync : null, true, waitUntilDone ? null : System.err ); @@ -51,7 +51,7 @@ public class RunnableTask extends TaskBase { if( waitUntilDone ) { try { sync.wait(); - } catch (InterruptedException ie) { + } catch (final InterruptedException ie) { throwable = ie; } if(null==throwable) { @@ -85,7 +85,7 @@ public class RunnableTask extends TaskBase { if( waitUntilDone ) { try { sync.wait(); - } catch (InterruptedException ie) { + } catch (final InterruptedException ie) { throwable = ie; } if(null==throwable) { @@ -114,7 +114,7 @@ public class RunnableTask extends TaskBase { * otherwise the exception is thrown. * @param exceptionOut If not <code>null</code>, exceptions are written to this {@link PrintStream}. */ - public RunnableTask(Runnable runnable, Object syncObject, boolean catchExceptions, PrintStream exceptionOut) { + public RunnableTask(final Runnable runnable, final Object syncObject, final boolean catchExceptions, final PrintStream exceptionOut) { super(syncObject, catchExceptions, exceptionOut); this.runnable = runnable ; } @@ -131,7 +131,7 @@ public class RunnableTask extends TaskBase { if(null == syncObject) { try { runnable.run(); - } catch (Throwable t) { + } catch (final Throwable t) { runnableException = t; if(null != exceptionOut) { exceptionOut.println("RunnableTask.run(): "+getExceptionOutIntro()+" exception occured on thread "+Thread.currentThread().getName()+": "+toString()); @@ -148,7 +148,7 @@ public class RunnableTask extends TaskBase { synchronized (syncObject) { try { runnable.run(); - } catch (Throwable t) { + } catch (final Throwable t) { runnableException = t; if(null != exceptionOut) { exceptionOut.println("RunnableTask.run(): "+getExceptionOutIntro()+" exception occured on thread "+Thread.currentThread().getName()+": "+toString()); diff --git a/src/java/com/jogamp/common/util/SecurityUtil.java b/src/java/com/jogamp/common/util/SecurityUtil.java index 4586d22..1b8b7c2 100644 --- a/src/java/com/jogamp/common/util/SecurityUtil.java +++ b/src/java/com/jogamp/common/util/SecurityUtil.java @@ -56,7 +56,7 @@ public class SecurityUtil { try { insecPD.implies(allPermissions); _hasAllPermissions = true; - } catch( SecurityException ace ) { + } catch( final SecurityException ace ) { _hasAllPermissions = false; } hasAllPermissions = _hasAllPermissions; @@ -92,11 +92,11 @@ public class SecurityUtil { * or the installed {@link SecurityManager}'s <code>checkPermission(perm)</code> * passes. Otherwise method returns <code>false</code>. */ - public static final boolean hasPermission(Permission perm) { + public static final boolean hasPermission(final Permission perm) { try { checkPermission(perm); return true; - } catch( SecurityException ace ) { + } catch( final SecurityException ace ) { return false; } } @@ -113,7 +113,7 @@ public class SecurityUtil { * Throws an {@link SecurityException} if an installed {@link SecurityManager} * does not permit the requested {@link Permission}. */ - public static final void checkPermission(Permission perm) throws SecurityException { + public static final void checkPermission(final Permission perm) throws SecurityException { if( null != securityManager ) { securityManager.checkPermission(perm); } @@ -124,11 +124,11 @@ public class SecurityUtil { * or the installed {@link SecurityManager}'s <code>checkLink(libName)</code> * passes. Otherwise method returns <code>false</code>. */ - public static final boolean hasLinkPermission(String libName) { + public static final boolean hasLinkPermission(final String libName) { try { checkLinkPermission(libName); return true; - } catch( SecurityException ace ) { + } catch( final SecurityException ace ) { return false; } } @@ -137,7 +137,7 @@ public class SecurityUtil { * Throws an {@link SecurityException} if an installed {@link SecurityManager} * does not permit to dynamically link the given libName. */ - public static final void checkLinkPermission(String libName) throws SecurityException { + public static final void checkLinkPermission(final String libName) throws SecurityException { if( null != securityManager ) { securityManager.checkLink(libName); } @@ -166,7 +166,7 @@ public class SecurityUtil { return (null != certs && certs.length>0) ? certs : null; } - public static final boolean equals(Certificate[] a, Certificate[] b) { + public static final boolean equals(final Certificate[] a, final Certificate[] b) { if(a == b) { return true; } diff --git a/src/java/com/jogamp/common/util/SyncedRingbuffer.java b/src/java/com/jogamp/common/util/SyncedRingbuffer.java index 8ef2970..7f4a878 100644 --- a/src/java/com/jogamp/common/util/SyncedRingbuffer.java +++ b/src/java/com/jogamp/common/util/SyncedRingbuffer.java @@ -63,7 +63,7 @@ public class SyncedRingbuffer<T> implements Ringbuffer<T> { } @Override - public final void dump(PrintStream stream, String prefix) { + public final void dump(final PrintStream stream, final String prefix) { stream.println(prefix+" "+toString()+" {"); for(int i=0; i<capacity; i++) { stream.println("\t["+i+"]: "+array[i]); @@ -92,7 +92,7 @@ public class SyncedRingbuffer<T> implements Ringbuffer<T> { * @throws IllegalArgumentException if <code>copyFrom</code> is <code>null</code> */ @SuppressWarnings("unchecked") - public SyncedRingbuffer(T[] copyFrom) throws IllegalArgumentException { + public SyncedRingbuffer(final T[] copyFrom) throws IllegalArgumentException { capacity = copyFrom.length; array = (T[]) newArray(copyFrom.getClass(), capacity); resetImpl(true, copyFrom); @@ -115,9 +115,9 @@ public class SyncedRingbuffer<T> implements Ringbuffer<T> { * @param arrayType the array type of the created empty internal array. * @param capacity the initial net capacity of the ring buffer */ - public SyncedRingbuffer(Class<? extends T[]> arrayType, int capacity) { + public SyncedRingbuffer(final Class<? extends T[]> arrayType, final int capacity) { this.capacity = capacity; - this.array = (T[]) newArray(arrayType, capacity); + this.array = newArray(arrayType, capacity); resetImpl(false, null /* empty, nothing to copy */ ); } @@ -144,11 +144,11 @@ public class SyncedRingbuffer<T> implements Ringbuffer<T> { } @Override - public final void resetFull(T[] copyFrom) throws IllegalArgumentException { + public final void resetFull(final T[] copyFrom) throws IllegalArgumentException { resetImpl(true, copyFrom); } - private final void resetImpl(boolean full, T[] copyFrom) throws IllegalArgumentException { + private final void resetImpl(final boolean full, final T[] copyFrom) throws IllegalArgumentException { synchronized ( syncGlobal ) { if( null != copyFrom ) { if( copyFrom.length != capacity() ) { @@ -202,7 +202,7 @@ public class SyncedRingbuffer<T> implements Ringbuffer<T> { public final T get() { try { return getImpl(false, false); - } catch (InterruptedException ie) { throw new RuntimeException(ie); } + } catch (final InterruptedException ie) { throw new RuntimeException(ie); } } /** @@ -220,14 +220,14 @@ public class SyncedRingbuffer<T> implements Ringbuffer<T> { public final T peek() { try { return getImpl(false, true); - } catch (InterruptedException ie) { throw new RuntimeException(ie); } + } catch (final InterruptedException ie) { throw new RuntimeException(ie); } } @Override public final T peekBlocking() throws InterruptedException { return getImpl(true, true); } - private final T getImpl(boolean blocking, boolean peek) throws InterruptedException { + private final T getImpl(final boolean blocking, final boolean peek) throws InterruptedException { synchronized( syncGlobal ) { if( 0 == size ) { if( blocking ) { @@ -257,10 +257,10 @@ public class SyncedRingbuffer<T> implements Ringbuffer<T> { * </p> */ @Override - public final boolean put(T e) { + public final boolean put(final T e) { try { return putImpl(e, false, false); - } catch (InterruptedException ie) { throw new RuntimeException(ie); } + } catch (final InterruptedException ie) { throw new RuntimeException(ie); } } /** @@ -270,7 +270,7 @@ public class SyncedRingbuffer<T> implements Ringbuffer<T> { * </p> */ @Override - public final void putBlocking(T e) throws InterruptedException { + public final void putBlocking(final T e) throws InterruptedException { if( !putImpl(e, false, true) ) { throw new InternalError("Blocking put failed: "+this); } @@ -283,11 +283,11 @@ public class SyncedRingbuffer<T> implements Ringbuffer<T> { * </p> */ @Override - public final boolean putSame(boolean blocking) throws InterruptedException { + public final boolean putSame(final boolean blocking) throws InterruptedException { return putImpl(null, true, blocking); } - private final boolean putImpl(T e, boolean sameRef, boolean blocking) throws InterruptedException { + private final boolean putImpl(final T e, final boolean sameRef, final boolean blocking) throws InterruptedException { synchronized( syncGlobal ) { if( capacity == size ) { if( blocking ) { @@ -310,7 +310,7 @@ public class SyncedRingbuffer<T> implements Ringbuffer<T> { } @Override - public final void waitForFreeSlots(int count) throws InterruptedException { + public final void waitForFreeSlots(final int count) throws InterruptedException { synchronized ( syncGlobal ) { if( capacity - size < count ) { while( capacity - size < count ) { @@ -344,7 +344,7 @@ public class SyncedRingbuffer<T> implements Ringbuffer<T> { final int growAmount = newElements.length; final int newCapacity = capacity + growAmount; final T[] oldArray = array; - final T[] newArray = (T[]) newArray(arrayTypeInternal, newCapacity); + final T[] newArray = newArray(arrayTypeInternal, newCapacity); // writePos == readPos writePos += growAmount; // warp writePos to the end of the new data location @@ -383,7 +383,7 @@ public class SyncedRingbuffer<T> implements Ringbuffer<T> { final int newCapacity = capacity + growAmount; final T[] oldArray = array; - final T[] newArray = (T[]) newArray(arrayTypeInternal, newCapacity); + final T[] newArray = newArray(arrayTypeInternal, newCapacity); // writePos == readPos readPos += growAmount; // warp readPos to the end of the new data location @@ -402,7 +402,7 @@ public class SyncedRingbuffer<T> implements Ringbuffer<T> { } @SuppressWarnings("unchecked") - private static <T> T[] newArray(Class<? extends T[]> arrayType, int length) { + private static <T> T[] newArray(final Class<? extends T[]> arrayType, final int length) { return ((Object)arrayType == (Object)Object[].class) ? (T[]) new Object[length] : (T[]) Array.newInstance(arrayType.getComponentType(), length); diff --git a/src/java/com/jogamp/common/util/TaskBase.java b/src/java/com/jogamp/common/util/TaskBase.java index db437f8..b688ba6 100644 --- a/src/java/com/jogamp/common/util/TaskBase.java +++ b/src/java/com/jogamp/common/util/TaskBase.java @@ -42,7 +42,7 @@ public abstract class TaskBase implements Runnable { static { Debug.initSingleton(); - TRACE_SOURCE = Debug.isPropertyDefined("jogamp.debug.TaskBase.TraceSource", true); + TRACE_SOURCE = PropertyAccess.isPropertyDefined("jogamp.debug.TaskBase.TraceSource", true); } protected final Object syncObject; @@ -56,7 +56,7 @@ public abstract class TaskBase implements Runnable { protected volatile long tExecuted; protected volatile boolean isFlushed; - protected TaskBase(Object syncObject, boolean catchExceptions, PrintStream exceptionOut) { + protected TaskBase(final Object syncObject, final boolean catchExceptions, final PrintStream exceptionOut) { this.syncObject = syncObject; this.catchExceptions = catchExceptions; this.exceptionOut = exceptionOut; @@ -88,7 +88,7 @@ public abstract class TaskBase implements Runnable { * Attach a custom object to this task. * Useful to piggybag further information, ie tag a task final. */ - public final void setAttachment(Object o) { + public final void setAttachment(final Object o) { attachment = o; } @@ -113,7 +113,7 @@ public abstract class TaskBase implements Runnable { * @see #isFlushed() * @see #isInQueue() */ - public final void flush(Throwable t) { + public final void flush(final Throwable t) { if(!isExecuted() && hasWaiter()) { runnableException = t; synchronized (syncObject) { diff --git a/src/java/com/jogamp/common/util/ValueConv.java b/src/java/com/jogamp/common/util/ValueConv.java index 9a16b64..2ad002a 100644 --- a/src/java/com/jogamp/common/util/ValueConv.java +++ b/src/java/com/jogamp/common/util/ValueConv.java @@ -37,7 +37,7 @@ package com.jogamp.common.util; * </p> */ public class ValueConv { - public static final byte float_to_byte(float v, boolean dSigned) { + public static final byte float_to_byte(final float v, final boolean dSigned) { // lossy if( dSigned ) { return (byte) ( v * ( v > 0 ? 127.0f : 128.0f ) ); @@ -45,14 +45,14 @@ public class ValueConv { return (byte) ( v * 255.0f ); } } - public static final short float_to_short(float v, boolean dSigned) { + public static final short float_to_short(final float v, final boolean dSigned) { if( dSigned ) { return (short) ( v * ( v > 0 ? 32767.0f : 32768.0f ) ); } else { return (short) ( v * 65535.0f ); } } - public static final int float_to_int(float v, boolean dSigned) { + public static final int float_to_int(final float v, final boolean dSigned) { // float significand 0x007fffff // double significand 0x000fffffffffffffL // int min = 0x80000000 = -2147483648 @@ -64,7 +64,7 @@ public class ValueConv { } } - public static final byte double_to_byte(double v, boolean dSigned) { + public static final byte double_to_byte(final double v, final boolean dSigned) { // lossy if( dSigned ) { return (byte) ( v * ( v > 0 ? 127.0 : 128.0 ) ); @@ -72,7 +72,7 @@ public class ValueConv { return (byte) ( v * 255.0 ); } } - public static final short double_to_short(double v, boolean dSigned) { + public static final short double_to_short(final double v, final boolean dSigned) { // lossy if( dSigned ) { return (short) ( v * ( v > 0 ? 32767.0 : 32768.0 ) ); @@ -80,7 +80,7 @@ public class ValueConv { return (short) ( v * 65535.0 ); } } - public static final int double_to_int(double v, boolean dSigned) { + public static final int double_to_int(final double v, final boolean dSigned) { // lossy if( dSigned ) { return (int) ( v * ( v > 0 ? 2147483647.0 : 2147483648.0 ) ); @@ -89,28 +89,28 @@ public class ValueConv { } } - public static final float byte_to_float(byte v, boolean sSigned) { + public static final float byte_to_float(final byte v, final boolean sSigned) { if( sSigned ) { return (v & 0xff) / ( v > 0 ? 127.0f : -128.0f ) ; } else { return (v & 0xff) / 255.0f ; } } - public static final double byte_to_double(byte v, boolean sSigned) { + public static final double byte_to_double(final byte v, final boolean sSigned) { if( sSigned ) { return (v & 0xff) / ( v > 0 ? 127.0 : -128.0 ) ; } else { return (v & 0xff) / 255.0 ; } } - public static final float short_to_float(short v, boolean sSigned) { + public static final float short_to_float(final short v, final boolean sSigned) { if( sSigned ) { return (v & 0xffff) / ( v > 0 ? 32767.0f : -32768.0f ) ; } else { return (v & 0xffff) / 65535.0f ; } } - public static final double short_to_double(short v, boolean sSigned) { + public static final double short_to_double(final short v, final boolean sSigned) { // lossy if( sSigned ) { return (v & 0xffff) / ( v > 0 ? 32767.0 : -32768.0 ) ; @@ -118,7 +118,7 @@ public class ValueConv { return (v & 0xffff) / 65535.0 ; } } - public static final float int_to_float(int v, boolean sSigned) { + public static final float int_to_float(final int v, final boolean sSigned) { // lossy // float significand 0x007fffff // double significand 0x000fffffffffffffL @@ -127,35 +127,35 @@ public class ValueConv { if( sSigned ) { return (float) ( v / ( v > 0 ? 2147483647.0 : 2147483648.0 ) ); } else { - return (float) ( ((long)v & 0xffffffffL) / 4294967295.0 ); + return (float) ( (v & 0xffffffffL) / 4294967295.0 ); } } - public static final double int_to_double(int v, boolean sSigned) { + public static final double int_to_double(final int v, final boolean sSigned) { if( sSigned ) { return v / ( v > 0 ? 2147483647.0 : 2147483648.0 ) ; } else { - return ((long)v & 0xffffffffL) / 4294967295.0 ; + return (v & 0xffffffffL) / 4294967295.0 ; } } - public static final short byte_to_short(byte v, boolean sSigned, boolean dSigned) { + public static final short byte_to_short(final byte v, final boolean sSigned, final boolean dSigned) { return float_to_short(byte_to_float(v, sSigned), dSigned); } - public static final int byte_to_int(byte v, boolean sSigned, boolean dSigned) { + public static final int byte_to_int(final byte v, final boolean sSigned, final boolean dSigned) { return float_to_int(byte_to_float(v, sSigned), dSigned); } - public static final byte short_to_byte(short v, boolean sSigned, boolean dSigned) { + public static final byte short_to_byte(final short v, final boolean sSigned, final boolean dSigned) { return float_to_byte(short_to_float(v, sSigned), dSigned); } - public static final int short_to_int(short v, boolean sSigned, boolean dSigned) { + public static final int short_to_int(final short v, final boolean sSigned, final boolean dSigned) { return float_to_int(short_to_float(v, sSigned), dSigned); } - public static final byte int_to_byte(int v, boolean sSigned, boolean dSigned) { + public static final byte int_to_byte(final int v, final boolean sSigned, final boolean dSigned) { return float_to_byte(int_to_float(v, sSigned), dSigned); } - public static final short int_to_short(int v, boolean sSigned, boolean dSigned) { + public static final short int_to_short(final int v, final boolean sSigned, final boolean dSigned) { return float_to_short(int_to_float(v, sSigned), dSigned); } } diff --git a/src/java/com/jogamp/common/util/VersionNumber.java b/src/java/com/jogamp/common/util/VersionNumber.java index addc879..b212fd0 100644 --- a/src/java/com/jogamp/common/util/VersionNumber.java +++ b/src/java/com/jogamp/common/util/VersionNumber.java @@ -72,7 +72,7 @@ public class VersionNumber implements Comparable<Object> { * </p> * @param delim the delimiter, e.g. "." */ - public static java.util.regex.Pattern getVersionNumberPattern(String delim) { + public static java.util.regex.Pattern getVersionNumberPattern(final String delim) { return java.util.regex.Pattern.compile("\\D*(\\d+)[^\\"+delim+"\\s]*(?:\\"+delim+"\\D*(\\d+)[^\\"+delim+"\\s]*(?:\\"+delim+"\\D*(\\d+))?)?"); } @@ -102,7 +102,7 @@ public class VersionNumber implements Comparable<Object> { protected final static short HAS_MINOR = 1 << 1 ; protected final static short HAS_SUB = 1 << 2 ; - protected VersionNumber(int majorRev, int minorRev, int subMinorRev, int _strEnd, short _state) { + protected VersionNumber(final int majorRev, final int minorRev, final int subMinorRev, final int _strEnd, final short _state) { major = majorRev; minor = minorRev; sub = subMinorRev; @@ -116,7 +116,7 @@ public class VersionNumber implements Comparable<Object> { * @see #hasMinor() * @see #hasSub() */ - public VersionNumber(int majorRev, int minorRev, int subMinorRev) { + public VersionNumber(final int majorRev, final int minorRev, final int subMinorRev) { this(majorRev, minorRev, subMinorRev, -1, (short)(HAS_MAJOR | HAS_MINOR | HAS_SUB)); } @@ -197,7 +197,7 @@ public class VersionNumber implements Comparable<Object> { } } } - } catch (Exception e) { } + } catch (final Exception e) { } major = val[0]; minor = val[1]; @@ -233,7 +233,7 @@ public class VersionNumber implements Comparable<Object> { } @Override - public final boolean equals(Object o) { + public final boolean equals(final Object o) { if ( o instanceof VersionNumber ) { return 0 == compareTo( (VersionNumber) o ); } @@ -241,15 +241,15 @@ public class VersionNumber implements Comparable<Object> { } @Override - public final int compareTo(Object o) { + public final int compareTo(final Object o) { if ( ! ( o instanceof VersionNumber ) ) { - Class<?> c = (null != o) ? o.getClass() : null ; + final Class<?> c = (null != o) ? o.getClass() : null ; throw new ClassCastException("Not a VersionNumber object: " + c); } return compareTo( (VersionNumber) o ); } - public final int compareTo(VersionNumber vo) { + public final int compareTo(final VersionNumber vo) { if (major > vo.major) { return 1; } else if (major < vo.major) { diff --git a/src/java/com/jogamp/common/util/VersionNumberString.java b/src/java/com/jogamp/common/util/VersionNumberString.java index e23300c..6644f65 100644 --- a/src/java/com/jogamp/common/util/VersionNumberString.java +++ b/src/java/com/jogamp/common/util/VersionNumberString.java @@ -44,7 +44,7 @@ public class VersionNumberString extends VersionNumber { protected final String strVal; - protected VersionNumberString(int majorRev, int minorRev, int subMinorRev, int strEnd, short _state, String versionString) { + protected VersionNumberString(final int majorRev, final int minorRev, final int subMinorRev, final int strEnd, final short _state, final String versionString) { super(majorRev, minorRev, subMinorRev, strEnd, _state); strVal = versionString; } @@ -52,7 +52,7 @@ public class VersionNumberString extends VersionNumber { /** * See {@link VersionNumber#VersionNumber(int, int, int)}. */ - public VersionNumberString(int majorRev, int minorRev, int subMinorRev, String versionString) { + public VersionNumberString(final int majorRev, final int minorRev, final int subMinorRev, final String versionString) { this(majorRev, minorRev, subMinorRev, -1, (short)(HAS_MAJOR | HAS_MINOR | HAS_SUB), versionString); } diff --git a/src/java/com/jogamp/common/util/VersionUtil.java b/src/java/com/jogamp/common/util/VersionUtil.java index c4451ac..6949d62 100644 --- a/src/java/com/jogamp/common/util/VersionUtil.java +++ b/src/java/com/jogamp/common/util/VersionUtil.java @@ -40,6 +40,8 @@ import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; +import jogamp.common.os.PlatformPropsImpl; + public class VersionUtil { public static final String SEPERATOR = "-----------------------------------------------------------------------------------------------------"; @@ -68,7 +70,7 @@ public class VersionUtil { Platform.getMachineDescription().toString(sb).append(Platform.getNewline()); // JVM/JRE - sb.append("Platform: Java Version: ").append(Platform.getJavaVersion()).append(" (").append(Platform.getJavaVersionNumber()).append("u").append(Platform.JAVA_VERSION_UPDATE).append("), VM: ").append(Platform.getJavaVMName()); + sb.append("Platform: Java Version: ").append(Platform.getJavaVersion()).append(" (").append(Platform.getJavaVersionNumber()).append("u").append(PlatformPropsImpl.JAVA_VERSION_UPDATE).append("), VM: ").append(Platform.getJavaVMName()); sb.append(", Runtime: ").append(Platform.getJavaRuntimeName()).append(Platform.getNewline()); sb.append("Platform: Java Vendor: ").append(Platform.getJavaVendor()).append(", ").append(Platform.getJavaVendorURL()); sb.append(", JavaSE: ").append(Platform.isJavaSE()); @@ -94,7 +96,7 @@ public class VersionUtil { * @param extension The value of the 'Extension-Name' jar-manifest attribute; used to identify the manifest. * @return the requested manifest or null when not found. */ - public static Manifest getManifest(ClassLoader cl, String extension) { + public static Manifest getManifest(final ClassLoader cl, final String extension) { return getManifest(cl, new String[] { extension } ); } @@ -106,10 +108,10 @@ public class VersionUtil { * Matching is applied in decreasing order, i.e. first element is favored over the second, etc. * @return the requested manifest or null when not found. */ - public static Manifest getManifest(ClassLoader cl, String[] extensions) { + public static Manifest getManifest(final ClassLoader cl, final String[] extensions) { final Manifest[] extManifests = new Manifest[extensions.length]; try { - Enumeration<URL> resources = cl.getResources("META-INF/MANIFEST.MF"); + final Enumeration<URL> resources = cl.getResources("META-INF/MANIFEST.MF"); while (resources.hasMoreElements()) { final InputStream is = resources.nextElement().openStream(); final Manifest manifest; @@ -118,7 +120,7 @@ public class VersionUtil { } finally { IOUtil.close(is, false); } - Attributes attributes = manifest.getMainAttributes(); + final Attributes attributes = manifest.getMainAttributes(); if(attributes != null) { for(int i=0; i < extensions.length && null == extManifests[i]; i++) { final String extension = extensions[i]; @@ -131,7 +133,7 @@ public class VersionUtil { } } } - } catch (IOException ex) { + } catch (final IOException ex) { throw new RuntimeException("Unable to read manifest.", ex); } for(int i=1; i<extManifests.length; i++) { @@ -142,7 +144,7 @@ public class VersionUtil { return null; } - public static StringBuilder getFullManifestInfo(Manifest mf, StringBuilder sb) { + public static StringBuilder getFullManifestInfo(final Manifest mf, StringBuilder sb) { if(null==mf) { return sb; } @@ -151,11 +153,11 @@ public class VersionUtil { sb = new StringBuilder(); } - Attributes attr = mf.getMainAttributes(); - Set<Object> keys = attr.keySet(); - for(Iterator<Object> iter=keys.iterator(); iter.hasNext(); ) { - Attributes.Name key = (Attributes.Name) iter.next(); - String val = attr.getValue(key); + final Attributes attr = mf.getMainAttributes(); + final Set<Object> keys = attr.keySet(); + for(final Iterator<Object> iter=keys.iterator(); iter.hasNext(); ) { + final Attributes.Name key = (Attributes.Name) iter.next(); + final String val = attr.getValue(key); sb.append(" "); sb.append(key); sb.append(" = "); diff --git a/src/java/com/jogamp/common/util/awt/AWTEDTExecutor.java b/src/java/com/jogamp/common/util/awt/AWTEDTExecutor.java index e98478e..ec9348d 100644 --- a/src/java/com/jogamp/common/util/awt/AWTEDTExecutor.java +++ b/src/java/com/jogamp/common/util/awt/AWTEDTExecutor.java @@ -44,7 +44,7 @@ public class AWTEDTExecutor implements RunnableExecutor { private AWTEDTExecutor() {} @Override - public void invoke(boolean wait, Runnable r) { + public void invoke(final boolean wait, final Runnable r) { if(EventQueue.isDispatchThread()) { r.run(); } else { @@ -54,9 +54,9 @@ public class AWTEDTExecutor implements RunnableExecutor { } else { EventQueue.invokeLater(r); } - } catch (InvocationTargetException e) { + } catch (final InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { throw new RuntimeException(e); } } @@ -83,7 +83,7 @@ public class AWTEDTExecutor implements RunnableExecutor { * @param r the {@link Runnable} to be executed. * @return <code>true</code> if the {@link Runnable} has been issued for execution, otherwise <code>false</code> */ - public boolean invoke(Object treeLock, boolean allowOnNonEDT, boolean wait, Runnable r) { + public boolean invoke(final Object treeLock, final boolean allowOnNonEDT, final boolean wait, final Runnable r) { if( EventQueue.isDispatchThread() ) { r.run(); return true; @@ -94,9 +94,9 @@ public class AWTEDTExecutor implements RunnableExecutor { } else { EventQueue.invokeLater(r); } - } catch (InvocationTargetException e) { + } catch (final InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { throw new RuntimeException(e); } return true; diff --git a/src/java/com/jogamp/common/util/cache/TempFileCache.java b/src/java/com/jogamp/common/util/cache/TempFileCache.java index e1b1aab..b58ea28 100644 --- a/src/java/com/jogamp/common/util/cache/TempFileCache.java +++ b/src/java/com/jogamp/common/util/cache/TempFileCache.java @@ -79,7 +79,7 @@ public class TempFileCache { try { _tmpBaseDir = new File(IOUtil.getTempDir(true /* executable */), tmpDirPrefix); _tmpBaseDir = IOUtil.testDir(_tmpBaseDir, true /* create */, false /* executable */); // executable already checked - } catch (Exception ex) { + } catch (final Exception ex) { System.err.println("Warning: Caught Exception while retrieving executable temp base directory:"); ex.printStackTrace(); staticInitError = true; @@ -94,7 +94,7 @@ public class TempFileCache { if(!staticInitError) { try { initTmpRoot(); - } catch (Exception ex) { + } catch (final Exception ex) { System.err.println("Warning: Caught Exception due to initializing TmpRoot:"); ex.printStackTrace(); staticInitError = true; @@ -200,7 +200,7 @@ public class TempFileCache { if (tmpRootPropValue == null) { // Create ${tmpbase}/jlnNNNN.tmp then lock the file - File tmpFile = File.createTempFile("jln", ".tmp", tmpBaseDir); + final File tmpFile = File.createTempFile("jln", ".tmp", tmpBaseDir); if (DEBUG) { System.err.println("TempFileCache: tmpFile = " + tmpFile.getAbsolutePath()); } @@ -209,12 +209,12 @@ public class TempFileCache { final FileLock tmpLock = tmpChannel.lock(); // Strip off the ".tmp" to get the name of the tmprootdir - String tmpFileName = tmpFile.getAbsolutePath(); - String tmpRootName = tmpFileName.substring(0, tmpFileName.lastIndexOf(".tmp")); + final String tmpFileName = tmpFile.getAbsolutePath(); + final String tmpRootName = tmpFileName.substring(0, tmpFileName.lastIndexOf(".tmp")); // create ${tmpbase}/jlnNNNN.lck then lock the file - String lckFileName = tmpRootName + ".lck"; - File lckFile = new File(lckFileName); + final String lckFileName = tmpRootName + ".lck"; + final File lckFile = new File(lckFileName); if (DEBUG) { System.err.println("TempFileCache: lckFile = " + lckFile.getAbsolutePath()); } @@ -248,7 +248,7 @@ public class TempFileCache { tmpLock.release(); lckOut.close(); lckLock.release(); - } catch (IOException ex) { + } catch (final IOException ex) { // Do nothing } } @@ -262,7 +262,7 @@ public class TempFileCache { } // Start a new Reaper thread to do stuff... - Thread reaperThread = new Thread() { + final Thread reaperThread = new Thread() { /* @Override */ @Override public void run() { @@ -286,10 +286,10 @@ public class TempFileCache { // enumerate list of jnl*.lck files, ignore our own jlnNNNN file final String ourLockFile = tmpRootPropValue + ".lck"; - FilenameFilter lckFilter = new FilenameFilter() { + final FilenameFilter lckFilter = new FilenameFilter() { /* @Override */ @Override - public boolean accept(File dir, String name) { + public boolean accept(final File dir, final String name) { return name.endsWith(".lck") && !name.equals(ourLockFile); } }; @@ -299,16 +299,16 @@ public class TempFileCache { // (which should always succeed unless there is a problem). If we can // get the lock on both files, then it must be an old installation, and // we will delete it. - String[] fileNames = tmpBaseDir.list(lckFilter); + final String[] fileNames = tmpBaseDir.list(lckFilter); if (fileNames != null) { for (int i = 0; i < fileNames.length; i++) { - String lckFileName = fileNames[i]; - String tmpDirName = lckFileName.substring(0, lckFileName.lastIndexOf(".lck")); - String tmpFileName = tmpDirName + ".tmp"; + final String lckFileName = fileNames[i]; + final String tmpDirName = lckFileName.substring(0, lckFileName.lastIndexOf(".lck")); + final String tmpFileName = tmpDirName + ".tmp"; - File lckFile = new File(tmpBaseDir, lckFileName); - File tmpFile = new File(tmpBaseDir, tmpFileName); - File tmpDir = new File(tmpBaseDir, tmpDirName); + final File lckFile = new File(tmpBaseDir, lckFileName); + final File tmpFile = new File(tmpBaseDir, tmpFileName); + final File tmpDir = new File(tmpBaseDir, tmpDirName); if (lckFile.exists() && tmpFile.exists() && tmpDir.isDirectory()) { FileOutputStream tmpOut = null; @@ -319,7 +319,7 @@ public class TempFileCache { tmpOut = new FileOutputStream(tmpFile); tmpChannel = tmpOut.getChannel(); tmpLock = tmpChannel.tryLock(); - } catch (Exception ex) { + } catch (final Exception ex) { // Ignore exceptions if (DEBUG) { ex.printStackTrace(); @@ -335,7 +335,7 @@ public class TempFileCache { lckOut = new FileOutputStream(lckFile); lckChannel = lckOut.getChannel(); lckLock = lckChannel.tryLock(); - } catch (Exception ex) { + } catch (final Exception ex) { if (DEBUG) { ex.printStackTrace(); } @@ -355,12 +355,12 @@ public class TempFileCache { // occasional 0-byte .lck or .tmp file left around try { lckOut.close(); - } catch (IOException ex) { + } catch (final IOException ex) { } lckFile.delete(); try { tmpOut.close(); - } catch (IOException ex) { + } catch (final IOException ex) { } tmpFile.delete(); } else { @@ -373,7 +373,7 @@ public class TempFileCache { // on the *.tmp file tmpOut.close(); tmpLock.release(); - } catch (IOException ex) { + } catch (final IOException ex) { if (DEBUG) { ex.printStackTrace(); } @@ -393,14 +393,14 @@ public class TempFileCache { * Remove the specified file or directory. If "path" is a directory, then * recursively remove all entries, then remove the directory itself. */ - private static void removeAll(File path) { + private static void removeAll(final File path) { if (DEBUG) { System.err.println("TempFileCache: removeAll(" + path + ")"); } if (path.isDirectory()) { // Recursively remove all files/directories in this directory - File[] list = path.listFiles(); + final File[] list = path.listFiles(); if (list != null) { for (int i = 0; i < list.length; i++) { removeAll(list[i]); @@ -419,7 +419,7 @@ public class TempFileCache { if(!staticInitError) { try { createTmpDir(); - } catch (Exception ex) { + } catch (final Exception ex) { ex.printStackTrace(); initError = true; } @@ -439,7 +439,7 @@ public class TempFileCache { if(!staticInitError) { try { removeAll(individualTmpDir); - } catch (Exception ex) { + } catch (final Exception ex) { ex.printStackTrace(); } } @@ -525,9 +525,9 @@ public class TempFileCache { * We avoid deleteOnExit, because it doesn't work reliably. */ private void createTmpDir() throws IOException { - File tmpFile = File.createTempFile("jln", ".tmp", tmpRootDir); - String tmpFileName = tmpFile.getAbsolutePath(); - String tmpDirName = tmpFileName.substring(0, tmpFileName.lastIndexOf(".tmp")); + final File tmpFile = File.createTempFile("jln", ".tmp", tmpRootDir); + final String tmpFileName = tmpFile.getAbsolutePath(); + final String tmpDirName = tmpFileName.substring(0, tmpFileName.lastIndexOf(".tmp")); individualTmpDir = new File(tmpDirName); if (!individualTmpDir.mkdir()) { throw new IOException("Cannot create " + individualTmpDir); diff --git a/src/java/com/jogamp/common/util/cache/TempJarCache.java b/src/java/com/jogamp/common/util/cache/TempJarCache.java index 99bb272..1b322d7 100644 --- a/src/java/com/jogamp/common/util/cache/TempJarCache.java +++ b/src/java/com/jogamp/common/util/cache/TempJarCache.java @@ -56,11 +56,11 @@ public class TempJarCache { public enum LoadState { LOOKED_UP, LOADED; - public boolean compliesWith(LoadState o2) { + public boolean compliesWith(final LoadState o2) { return null != o2 ? compareTo(o2) >= 0 : false; } } - private static boolean testLoadState(LoadState has, LoadState exp) { + private static boolean testLoadState(final LoadState has, final LoadState exp) { if(null == has) { return null == exp; } @@ -182,7 +182,7 @@ public class TempJarCache { return tmpFileCache; } - public synchronized static boolean checkNativeLibs(URI jarURI, LoadState exp) throws IOException { + public synchronized static boolean checkNativeLibs(final URI jarURI, final LoadState exp) throws IOException { checkInitialized(); if(null == jarURI) { throw new IllegalArgumentException("jarURI is null"); @@ -190,7 +190,7 @@ public class TempJarCache { return testLoadState(nativeLibJars.get(jarURI), exp); } - public synchronized static boolean checkClasses(URI jarURI, LoadState exp) throws IOException { + public synchronized static boolean checkClasses(final URI jarURI, final LoadState exp) throws IOException { checkInitialized(); if(null == jarURI) { throw new IllegalArgumentException("jarURI is null"); @@ -198,7 +198,7 @@ public class TempJarCache { return testLoadState(classFileJars.get(jarURI), exp); } - public synchronized static boolean checkResources(URI jarURI, LoadState exp) throws IOException { + public synchronized static boolean checkResources(final URI jarURI, final LoadState exp) throws IOException { checkInitialized(); if(null == jarURI) { throw new IllegalArgumentException("jarURI is null"); @@ -218,7 +218,7 @@ public class TempJarCache { * @throws URISyntaxException * @throws IllegalArgumentException */ - public synchronized static final boolean addNativeLibs(Class<?> certClass, URI jarURI, String nativeLibraryPath) throws IOException, SecurityException, IllegalArgumentException, URISyntaxException { + public synchronized static final boolean addNativeLibs(final Class<?> certClass, final URI jarURI, final String nativeLibraryPath) throws IOException, SecurityException, IllegalArgumentException, URISyntaxException { checkInitialized(); final LoadState nativeLibJarsLS = nativeLibJars.get(jarURI); if( !testLoadState(nativeLibJarsLS, LoadState.LOOKED_UP) ) { @@ -253,7 +253,7 @@ public class TempJarCache { * @throws URISyntaxException * @throws IllegalArgumentException */ - public synchronized static final void addClasses(Class<?> certClass, URI jarURI) throws IOException, SecurityException, IllegalArgumentException, URISyntaxException { + public synchronized static final void addClasses(final Class<?> certClass, final URI jarURI) throws IOException, SecurityException, IllegalArgumentException, URISyntaxException { checkInitialized(); final LoadState classFileJarsLS = classFileJars.get(jarURI); if( !testLoadState(classFileJarsLS, LoadState.LOOKED_UP) ) { @@ -282,7 +282,7 @@ public class TempJarCache { * @throws URISyntaxException * @throws IllegalArgumentException */ - public synchronized static final void addResources(Class<?> certClass, URI jarURI) throws IOException, SecurityException, IllegalArgumentException, URISyntaxException { + public synchronized static final void addResources(final Class<?> certClass, final URI jarURI) throws IOException, SecurityException, IllegalArgumentException, URISyntaxException { checkInitialized(); final LoadState resourceFileJarsLS = resourceFileJars.get(jarURI); if( !testLoadState(resourceFileJarsLS, LoadState.LOOKED_UP) ) { @@ -314,7 +314,7 @@ public class TempJarCache { * @throws URISyntaxException * @throws IllegalArgumentException */ - public synchronized static final void addAll(Class<?> certClass, URI jarURI) throws IOException, SecurityException, IllegalArgumentException, URISyntaxException { + public synchronized static final void addAll(final Class<?> certClass, final URI jarURI) throws IOException, SecurityException, IllegalArgumentException, URISyntaxException { checkInitialized(); if(null == jarURI) { throw new IllegalArgumentException("jarURI is null"); @@ -366,7 +366,7 @@ public class TempJarCache { } } - public synchronized static final String findLibrary(String libName) { + public synchronized static final String findLibrary(final String libName) { checkInitialized(); // try with mapped library basename first String path = nativeLibMap.get(libName); @@ -398,7 +398,7 @@ public class TempJarCache { } */ /** Similar to {@link ClassLoader#getResource(String)}. */ - public synchronized static final String findResource(String name) { + public synchronized static final String findResource(final String name) { checkInitialized(); final File f = new File(tmpFileCache.getTempDir(), name); if(f.exists()) { @@ -408,7 +408,7 @@ public class TempJarCache { } /** Similar to {@link ClassLoader#getResource(String)}. */ - public synchronized static final URI getResource(String name) throws URISyntaxException { + public synchronized static final URI getResource(final String name) throws URISyntaxException { checkInitialized(); final File f = new File(tmpFileCache.getTempDir(), name); if(f.exists()) { @@ -417,7 +417,7 @@ public class TempJarCache { return null; } - private static void validateCertificates(Class<?> certClass, JarFile jarFile) throws IOException, SecurityException { + private static void validateCertificates(final Class<?> certClass, final JarFile jarFile) throws IOException, SecurityException { if(null == certClass) { throw new IllegalArgumentException("certClass is null"); } diff --git a/src/java/com/jogamp/common/util/locks/LockFactory.java b/src/java/com/jogamp/common/util/locks/LockFactory.java index e1ec2d7..dd8d25b 100644 --- a/src/java/com/jogamp/common/util/locks/LockFactory.java +++ b/src/java/com/jogamp/common/util/locks/LockFactory.java @@ -39,7 +39,7 @@ public class LockFactory { public final int id; - ImplType(int id){ + ImplType(final int id){ this.id = id; } } @@ -54,7 +54,7 @@ public class LockFactory { return new RecursiveThreadGroupLockImpl01Unfairish(); } - public static RecursiveLock createRecursiveLock(ImplType t, boolean fair) { + public static RecursiveLock createRecursiveLock(final ImplType t, final boolean fair) { switch(t) { case Int01: return fair ? new RecursiveLockImpl01CompleteFair() : new RecursiveLockImpl01Unfairish(); diff --git a/src/java/com/jogamp/common/util/locks/SingletonInstance.java b/src/java/com/jogamp/common/util/locks/SingletonInstance.java index f016d4b..ee703cd 100644 --- a/src/java/com/jogamp/common/util/locks/SingletonInstance.java +++ b/src/java/com/jogamp/common/util/locks/SingletonInstance.java @@ -37,11 +37,11 @@ public abstract class SingletonInstance implements Lock { protected static final boolean DEBUG = true; - public static SingletonInstance createFileLock(long poll_ms, String lockFileBasename) { + public static SingletonInstance createFileLock(final long poll_ms, final String lockFileBasename) { return new SingletonInstanceFileLock(poll_ms, lockFileBasename); } - public static SingletonInstance createFileLock(long poll_ms, File lockFile) { + public static SingletonInstance createFileLock(final long poll_ms, final File lockFile) { return new SingletonInstanceFileLock(poll_ms, lockFile); } @@ -58,11 +58,11 @@ public abstract class SingletonInstance implements Lock { * @param pollPeriod * @param portNumber to be used for this single instance server socket. */ - public static SingletonInstance createServerSocket(long poll_ms, int portNumber) { + public static SingletonInstance createServerSocket(final long poll_ms, final int portNumber) { return new SingletonInstanceServerSocket(poll_ms, portNumber); } - protected SingletonInstance(long poll_ms) { + protected SingletonInstance(final long poll_ms) { this.poll_ms = Math.max(10, poll_ms); } @@ -79,7 +79,7 @@ public abstract class SingletonInstance implements Lock { return; } } while ( true ) ; - } catch ( RuntimeException ie ) { + } catch ( final RuntimeException ie ) { throw new RuntimeException(ie); } } @@ -109,7 +109,7 @@ public abstract class SingletonInstance implements Lock { maxwait -= System.currentTimeMillis()-t1; i++; } while ( 0 < maxwait ) ; - } catch ( InterruptedException ie ) { + } catch ( final InterruptedException ie ) { final long t2 = System.currentTimeMillis(); throw new RuntimeException(infoPrefix(t2)+" EEE (1) "+getName()+" - couldn't get lock within "+(t2-t0)+" ms, "+i+" attempts", ie); } @@ -139,7 +139,7 @@ public abstract class SingletonInstance implements Lock { return locked; } - protected String infoPrefix(long currentMillis) { + protected String infoPrefix(final long currentMillis) { return "SLOCK [T "+Thread.currentThread().getName()+" @ "+currentMillis+" ms"; } protected String infoPrefix() { diff --git a/src/java/com/jogamp/gluegen/CMethodBindingEmitter.java b/src/java/com/jogamp/gluegen/CMethodBindingEmitter.java index 810046b..5673aac 100644 --- a/src/java/com/jogamp/gluegen/CMethodBindingEmitter.java +++ b/src/java/com/jogamp/gluegen/CMethodBindingEmitter.java @@ -116,15 +116,15 @@ public class CMethodBindingEmitter extends FunctionEmitter { * comment emitter that will emit the signature of the C function that is * being bound. */ - public CMethodBindingEmitter(MethodBinding binding, - PrintWriter output, - String javaPackageName, - String javaClassName, - boolean isOverloadedBinding, - boolean isJavaMethodStatic, - boolean forImplementingMethodCall, - boolean forIndirectBufferAndArrayImplementation, - MachineDescription machDesc) + public CMethodBindingEmitter(final MethodBinding binding, + final PrintWriter output, + final String javaPackageName, + final String javaClassName, + final boolean isOverloadedBinding, + final boolean isJavaMethodStatic, + final boolean forImplementingMethodCall, + final boolean forIndirectBufferAndArrayImplementation, + final MachineDescription machDesc) { super(output, false); @@ -176,7 +176,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { * binding.getJavaReturnType().isCompoundTypeWrapper() == false * </code> */ - public final void setReturnValueCapacityExpression(MessageFormat expression) { + public final void setReturnValueCapacityExpression(final MessageFormat expression) { returnValueCapacityExpression = expression; if (!binding.getJavaReturnType().isNIOBuffer() && @@ -209,7 +209,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { * binding.getJavaReturnType().isNIOBuffer() == false * </code> */ - public final void setReturnValueLengthExpression(MessageFormat expression) { + public final void setReturnValueLengthExpression(final MessageFormat expression) { returnValueLengthExpression = expression; if (!binding.getJavaReturnType().isArray() && @@ -233,7 +233,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { * variables to be assigned to after the underlying function call. A * null argument indicates that no manual declarations are to be made. */ - public final void setTemporaryCVariableDeclarations(List<String> arg) { + public final void setTemporaryCVariableDeclarations(final List<String> arg) { temporaryCVariableDeclarations = arg; } @@ -252,7 +252,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { * variables which are made after the underlying function call. A * null argument indicates that no manual assignments are to be made. */ - public final void setTemporaryCVariableAssignments(List<String> arg) { + public final void setTemporaryCVariableAssignments(final List<String> arg) { temporaryCVariableAssignments = arg; } @@ -293,14 +293,14 @@ public class CMethodBindingEmitter extends FunctionEmitter { @Override - protected void emitReturnType(PrintWriter writer) { + protected void emitReturnType(final PrintWriter writer) { writer.print("JNIEXPORT "); writer.print(binding.getJavaReturnType().jniTypeName()); writer.print(" JNICALL"); } @Override - protected void emitName(PrintWriter writer) { + protected void emitName(final PrintWriter writer) { writer.println(); // start name on new line writer.print(JavaEmitter.getJNIMethodNamePrefix(getJavaPackageName(), getJavaClassName())); writer.print("_"); @@ -327,7 +327,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { } @Override - protected int emitArguments(PrintWriter writer) { + protected int emitArguments(final PrintWriter writer) { writer.print("JNIEnv *env, "); int numEmitted = 1; // initially just the JNIEnv if (isJavaMethodStatic && !binding.hasContainingType()) { @@ -343,7 +343,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { writer.print(", jobject " + JavaMethodBindingEmitter.javaThisArgumentName()); } for (int i = 0; i < binding.getNumArguments(); i++) { - JavaType javaArgType = binding.getJavaArgumentType(i); + final JavaType javaArgType = binding.getJavaArgumentType(i); // Handle case where only param is void if (javaArgType.isVoid()) { // Make sure this is the only param to the method; if it isn't, @@ -376,7 +376,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { @Override - protected void emitBody(PrintWriter writer) { + protected void emitBody(final PrintWriter writer) { writer.println(" {"); // writer.println("printf(\" - - - - "+ getName() + getImplSuffix() +" - - - -\\n\");"); emitBodyVariableDeclarations(writer); @@ -390,7 +390,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { writer.println(); } - protected void emitBodyVariableDeclarations(PrintWriter writer) { + protected void emitBodyVariableDeclarations(final PrintWriter writer) { // Emit declarations for all pointer and String conversion variables if (binding.hasContainingType()) { emitPointerDeclaration(writer, @@ -402,16 +402,16 @@ public class CMethodBindingEmitter extends FunctionEmitter { boolean emittedDataCopyTemps = false; for (int i = 0; i < binding.getNumArguments(); i++) { - JavaType type = binding.getJavaArgumentType(i); + final JavaType type = binding.getJavaArgumentType(i); if (type.isJNIEnv() || binding.isArgumentThisPointer(i)) { continue; } if (type.isArray() || type.isNIOBuffer() || type.isCompoundTypeWrapper() || type.isArrayOfCompoundTypeWrappers()) { - String javaArgName = binding.getArgumentName(i); - String convName = pointerConversionArgumentName(javaArgName); + final String javaArgName = binding.getArgumentName(i); + final String convName = pointerConversionArgumentName(javaArgName); // handle array/buffer argument types - boolean needsDataCopy = + final boolean needsDataCopy = emitPointerDeclaration(writer, type, binding.getCArgumentType(i), @@ -431,7 +431,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { emittedDataCopyTemps = true; } } else if (type.isString()) { - Type cType = binding.getCArgumentType(i); + final Type cType = binding.getCArgumentType(i); if (isUTF8Type(cType)) { writer.print(" const char* "); } else { @@ -445,9 +445,9 @@ public class CMethodBindingEmitter extends FunctionEmitter { } // Emit declaration for return value if necessary - Type cReturnType = binding.getCReturnType(); + final Type cReturnType = binding.getCReturnType(); - JavaType javaReturnType = binding.getJavaReturnType(); + final JavaType javaReturnType = binding.getJavaReturnType(); if (!cReturnType.isVoid()) { writer.print(" "); // Note we must respect const/volatile for return argument @@ -469,13 +469,13 @@ public class CMethodBindingEmitter extends FunctionEmitter { writer.print(arrayResLength); writer.println(";"); - Class<?> componentType = javaReturnType.getJavaClass().getComponentType(); + final Class<?> componentType = javaReturnType.getJavaClass().getComponentType(); if (componentType.isArray()) { throw new RuntimeException("Multi-dimensional arrays not supported yet"); } - String javaTypeName = componentType.getName(); - String javaArrayTypeName = "j" + javaTypeName + "Array"; + final String javaTypeName = componentType.getName(); + final String javaArrayTypeName = "j" + javaTypeName + "Array"; writer.print(" "); writer.print(javaArrayTypeName); writer.print(" "); @@ -487,9 +487,9 @@ public class CMethodBindingEmitter extends FunctionEmitter { /** Emits the user-defined C variable declarations from the TemporaryCVariableDeclarations directive in the .cfg file. */ - protected void emitBodyUserVariableDeclarations(PrintWriter writer) { + protected void emitBodyUserVariableDeclarations(final PrintWriter writer) { if (temporaryCVariableDeclarations != null) { - for (String val : temporaryCVariableDeclarations) { + for (final String val : temporaryCVariableDeclarations) { writer.print(" "); writer.println(val); } @@ -500,14 +500,14 @@ public class CMethodBindingEmitter extends FunctionEmitter { (i.e., "const char *", "const char **"). False implies that this type is for a Unicode pointer type ("jchar *", "jchar **"). */ protected boolean isUTF8Type(Type type) { - int i = 0; + final int i = 0; // Try to dereference the type at most two levels while (!type.isInt() && !type.isVoid() && (i < 2)) { - PointerType pt = type.asPointer(); + final PointerType pt = type.asPointer(); if (pt != null) { type = pt.getTargetType(); } else { - ArrayType arrt = type.asArray(); + final ArrayType arrt = type.asArray(); if (arrt == null) { throw new IllegalArgumentException("Type " + type + " should have been a pointer or array type"); } @@ -532,7 +532,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { * emitBodyVariableDeclarations(), PRIOR TO calling the actual C * function. */ - protected void emitBodyVariablePreCallSetup(PrintWriter writer) { + protected void emitBodyVariablePreCallSetup(final PrintWriter writer) { // Convert all Buffers to pointers first so we don't have to // call ReleasePrimitiveArrayCritical for any arrays if any @@ -548,12 +548,12 @@ public class CMethodBindingEmitter extends FunctionEmitter { // Convert all arrays to pointers, and get UTF-8 versions of jstring args for (int i = 0; i < binding.getNumArguments(); i++) { - JavaType javaArgType = binding.getJavaArgumentType(i); + final JavaType javaArgType = binding.getJavaArgumentType(i); if (javaArgType.isJNIEnv() || binding.isArgumentThisPointer(i)) { continue; } - String javaArgName = binding.getArgumentName(i); + final String javaArgName = binding.getArgumentName(i); if (javaArgType.isCompoundTypeWrapper() || (javaArgType.isNIOBuffer() && !forIndirectBufferAndArrayImplementation ) ) { @@ -564,14 +564,14 @@ public class CMethodBindingEmitter extends FunctionEmitter { } else if (javaArgType.isArray() || javaArgType.isArrayOfCompoundTypeWrappers() || ( javaArgType.isNIOBuffer() && forIndirectBufferAndArrayImplementation ) ) { - boolean needsDataCopy = javaArgTypeNeedsDataCopy(javaArgType); + final boolean needsDataCopy = javaArgTypeNeedsDataCopy(javaArgType); writer.println(" if ( NULL != " + javaArgName + " ) {"); - Type cArgType = binding.getCArgumentType(i); + final Type cArgType = binding.getCArgumentType(i); String cArgTypeName = cArgType.getName(); - String convName = pointerConversionArgumentName(javaArgName); + final String convName = pointerConversionArgumentName(javaArgName); if (!needsDataCopy) { writer.print(" "); @@ -609,7 +609,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { writer.println(" /* Copy contents of " + javaArgName + " into " + convName + "_copy */"); // get length of array being copied - String arrayLenName = "_tmpArrayLen"; + final String arrayLenName = "_tmpArrayLen"; writer.print(" "); writer.print(arrayLenName); writer.print(" = (*env)->GetArrayLength(env, "); @@ -758,24 +758,24 @@ public class CMethodBindingEmitter extends FunctionEmitter { * Code to clean up any variables that were declared in * emitBodyVariableDeclarations(), AFTER calling the actual C function. */ - protected void emitBodyVariablePostCallCleanup(PrintWriter writer) { + protected void emitBodyVariablePostCallCleanup(final PrintWriter writer) { // Release primitive arrays and temporary UTF8 strings if necessary for (int i = 0; i < binding.getNumArguments(); i++) { - JavaType javaArgType = binding.getJavaArgumentType(i); + final JavaType javaArgType = binding.getJavaArgumentType(i); if (javaArgType.isJNIEnv() || binding.isArgumentThisPointer(i)) { continue; } - Type cArgType = binding.getCArgumentType(i); - String javaArgName = binding.getArgumentName(i); + final Type cArgType = binding.getCArgumentType(i); + final String javaArgName = binding.getArgumentName(i); if (javaArgType.isArray() || (javaArgType.isNIOBuffer() && forIndirectBufferAndArrayImplementation) || javaArgType.isArrayOfCompoundTypeWrappers()) { - boolean needsDataCopy = javaArgTypeNeedsDataCopy(javaArgType); + final boolean needsDataCopy = javaArgTypeNeedsDataCopy(javaArgType); - String convName = pointerConversionArgumentName(javaArgName); + final String convName = pointerConversionArgumentName(javaArgName); if (!needsDataCopy) { writer.println(" if ( JNI_FALSE == " + isNIOArgName(i) + " && NULL != " + javaArgName + " ) {"); @@ -823,7 +823,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { if (!javaArgType.isNIOBufferArray() && !javaArgType.isArrayOfCompoundTypeWrappers()) { // Re-fetch length of array that was copied - String arrayLenName = "_tmpArrayLen"; + final String arrayLenName = "_tmpArrayLen"; writer.print(" "); writer.print(arrayLenName); writer.print(" = (*env)->GetArrayLength(env, "); @@ -831,7 +831,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { writer.println(");"); // free each element - PointerType cArgPtrType = cArgType.asPointer(); + final PointerType cArgPtrType = cArgType.asPointer(); if (cArgPtrType == null) { throw new RuntimeException( "Could not copy data for type \"" + cArgType + @@ -889,12 +889,12 @@ public class CMethodBindingEmitter extends FunctionEmitter { /** Returns the number of arguments passed so calling code knows whether to print a comma */ - protected int emitBodyPassCArguments(PrintWriter writer) { + protected int emitBodyPassCArguments(final PrintWriter writer) { for (int i = 0; i < binding.getNumArguments(); i++) { if (i != 0) { writer.print(", "); } - JavaType javaArgType = binding.getJavaArgumentType(i); + final JavaType javaArgType = binding.getJavaArgumentType(i); // Handle case where only param is void. if (javaArgType.isVoid()) { // Make sure this is the only param to the method; if it isn't, @@ -910,8 +910,8 @@ public class CMethodBindingEmitter extends FunctionEmitter { } else { writer.print("("); final Type cArgType = binding.getCArgumentType(i); - boolean needsDataCopy = javaArgTypeNeedsDataCopy(javaArgType); - boolean needsArrayOffset = !needsDataCopy && ( + final boolean needsDataCopy = javaArgTypeNeedsDataCopy(javaArgType); + final boolean needsArrayOffset = !needsDataCopy && ( javaArgType.isArray() || javaArgType.isArrayOfCompoundTypeWrappers() || ( javaArgType.isNIOBuffer() && forIndirectBufferAndArrayImplementation ) ); @@ -966,13 +966,13 @@ public class CMethodBindingEmitter extends FunctionEmitter { isCStructFunctionPointer = v; } - protected void emitBodyCallCFunction(PrintWriter writer) { + protected void emitBodyCallCFunction(final PrintWriter writer) { // Make the call to the actual C function writer.print(" "); // WARNING: this code assumes that the return type has already been // typedef-resolved. - Type cReturnType = binding.getCReturnType(); + final Type cReturnType = binding.getCReturnType(); if (!cReturnType.isVoid()) { writer.print("_res = "); @@ -989,24 +989,24 @@ public class CMethodBindingEmitter extends FunctionEmitter { /** Emits the user-defined C variable assignments from the TemporaryCVariableAssignments directive in the .cfg file. */ - protected void emitBodyUserVariableAssignments(PrintWriter writer) { + protected void emitBodyUserVariableAssignments(final PrintWriter writer) { if (temporaryCVariableAssignments != null) { - for (String val : temporaryCVariableAssignments) { + for (final String val : temporaryCVariableAssignments) { writer.print(" "); writer.println(val); } } } - protected void emitBodyReturnResult(PrintWriter writer) + protected void emitBodyReturnResult(final PrintWriter writer) { // WARNING: this code assumes that the return type has already been // typedef-resolved. - Type cReturnType = binding.getCReturnType(); + final Type cReturnType = binding.getCReturnType(); // Return result if necessary if (!cReturnType.isVoid()) { - JavaType javaReturnType = binding.getJavaReturnType(); + final JavaType javaReturnType = binding.getJavaReturnType(); if (javaReturnType.isPrimitive()) { writer.print(" return "); if (cReturnType.isPointer()) { @@ -1063,7 +1063,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { writer.println(" " + arrayResLength + " = " + returnValueLengthExpression.format(argumentNameArray()) + ";"); writer.println(" " + arrayRes + " = (*env)->NewObjectArray(env, " + arrayResLength + ", (*env)->FindClass(env, \"java/nio/ByteBuffer\"), NULL);"); writer.println(" for (" + arrayIdx + " = 0; " + arrayIdx + " < " + arrayResLength + "; " + arrayIdx + "++) {"); - Type retType = binding.getCSymbol().getReturnType(); + final Type retType = binding.getCSymbol().getReturnType(); Type pointerType; if (retType.isPointer()) { pointerType = retType.asPointer().getTargetType(); @@ -1114,8 +1114,8 @@ public class CMethodBindingEmitter extends FunctionEmitter { return "this0"; } - protected String jniMangle(MethodBinding binding) { - StringBuilder buf = new StringBuilder(); + protected String jniMangle(final MethodBinding binding) { + final StringBuilder buf = new StringBuilder(); buf.append(JavaEmitter.jniMangle(getName())); buf.append(getImplSuffix()); buf.append("__"); @@ -1127,7 +1127,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { if (binding.isArgumentThisPointer(i)) { continue; } - JavaType type = binding.getJavaArgumentType(i); + final JavaType type = binding.getJavaArgumentType(i); if (type.isVoid()) { // We should only see "void" as the first argument of a 1-argument function // FIXME: should normalize this in the parser @@ -1146,7 +1146,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { jniMangle(Boolean.TYPE, buf, false); } } else if (type.isNIOBufferArray()) { - int[] intArrayType = new int[0]; + final int[] intArrayType = new int[0]; c = intArrayType.getClass(); jniMangle(c , buf, true); } @@ -1158,7 +1158,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { jniMangle(java.nio.ByteBuffer.class, buf, true); } else if (type.isArrayOfCompoundTypeWrappers()) { // Mangle arrays of C structs as ByteBuffer[] - java.nio.ByteBuffer[] tmp = new java.nio.ByteBuffer[0]; + final java.nio.ByteBuffer[] tmp = new java.nio.ByteBuffer[0]; jniMangle(tmp.getClass(), buf, true); } else if (type.isJNIEnv()) { // These are not exposed at the Java level @@ -1172,7 +1172,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { return buf.toString(); } - protected void jniMangle(Class<?> c, StringBuilder res, boolean syntheticArgument) { + protected void jniMangle(final Class<?> c, final StringBuilder res, final boolean syntheticArgument) { if (c.isPrimitive()) { if (c == Boolean.TYPE) res.append("Z"); else if (c == Byte.TYPE) res.append("B"); @@ -1193,7 +1193,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { if (syntheticArgument) { if (c.isArray()) { res.append("_3"); - Class<?> componentType = c.getComponentType(); + final Class<?> componentType = c.getComponentType(); // Handle arrays of compound type wrappers differently for // convenience of the Java-level glue code generation jniMangle(componentType, res, @@ -1220,7 +1220,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { } } - private void emitOutOfMemoryCheck(PrintWriter writer, String varName, String errorMessage) { + private void emitOutOfMemoryCheck(final PrintWriter writer, final String varName, final String errorMessage) { writer.println(" if ( NULL == " + varName + " ) {"); writer.println(" (*env)->ThrowNew(env, (*env)->FindClass(env, \"java/lang/OutOfMemoryError\"),"); writer.print(" \"" + errorMessage); @@ -1235,12 +1235,12 @@ public class CMethodBindingEmitter extends FunctionEmitter { writer.println(" }"); } - private void emitMalloc(PrintWriter writer, - String targetVarName, - String elementTypeString, - boolean elementTypeIsConst, - String numElementsExpression, - String mallocFailureErrorString) { + private void emitMalloc(final PrintWriter writer, + final String targetVarName, + final String elementTypeString, + final boolean elementTypeIsConst, + final String numElementsExpression, + final String mallocFailureErrorString) { writer.print(" "); writer.print(targetVarName); writer.print(" = ("); @@ -1257,11 +1257,11 @@ public class CMethodBindingEmitter extends FunctionEmitter { emitOutOfMemoryCheck( writer, targetVarName, mallocFailureErrorString); } - private void emitCalloc(PrintWriter writer, - String targetVarName, - String elementTypeString, - String numElementsExpression, - String mallocFailureErrorString) { + private void emitCalloc(final PrintWriter writer, + final String targetVarName, + final String elementTypeString, + final String numElementsExpression, + final String mallocFailureErrorString) { writer.print(" "); writer.print(targetVarName); writer.print(" = ("); @@ -1275,11 +1275,11 @@ public class CMethodBindingEmitter extends FunctionEmitter { emitOutOfMemoryCheck( writer, targetVarName, mallocFailureErrorString); } - private void emitGetStringChars(PrintWriter writer, - String sourceVarName, - String receivingVarName, - boolean isUTF8, - boolean emitElseClause) { + private void emitGetStringChars(final PrintWriter writer, + final String sourceVarName, + final String receivingVarName, + final boolean isUTF8, + final boolean emitElseClause) { writer.println(" if ( NULL != " + sourceVarName + " ) {"); if (isUTF8) { @@ -1318,12 +1318,12 @@ public class CMethodBindingEmitter extends FunctionEmitter { } } - private void emitGetDirectBufferAddress(PrintWriter writer, - String sourceVarName, - String receivingVarTypeString, - String receivingVarName, - boolean receivingIsPtrPtr, - String byteOffsetVarName, boolean emitElseClause) { + private void emitGetDirectBufferAddress(final PrintWriter writer, + final String sourceVarName, + final String receivingVarTypeString, + final String receivingVarName, + final boolean receivingIsPtrPtr, + final String byteOffsetVarName, final boolean emitElseClause) { writer.println(" if ( NULL != " + sourceVarName + " ) {"); writer.print(" "); writer.print(" "); @@ -1350,12 +1350,12 @@ public class CMethodBindingEmitter extends FunctionEmitter { writer.println(); } - private void emitReturnDirectBufferAddress(PrintWriter writer, - String sourceVarName, - String receivingVarTypeString, - String receivingVarName, - boolean receivingIsPtrPtr, - String byteOffsetVarName) { + private void emitReturnDirectBufferAddress(final PrintWriter writer, + final String sourceVarName, + final String receivingVarTypeString, + final String receivingVarName, + final boolean receivingIsPtrPtr, + final String byteOffsetVarName) { writer.print(" "); writer.print(" "); if( receivingIsPtrPtr ) { @@ -1373,11 +1373,11 @@ public class CMethodBindingEmitter extends FunctionEmitter { // model to the C memory model prior to calling any C-side functions, then // an extra variable named XXX_copy (where XXX is the value of the // cVariableName argument) will be emitted and TRUE will be returned. - private boolean emitPointerDeclaration(PrintWriter writer, - JavaType javaType, - Type cType, - String cVariableName, - String javaArgumentName) { + private boolean emitPointerDeclaration(final PrintWriter writer, + final JavaType javaType, + final Type cType, + final String cVariableName, + final String javaArgumentName) { String ptrTypeString = null; boolean needsDataCopy = false; @@ -1394,9 +1394,9 @@ public class CMethodBindingEmitter extends FunctionEmitter { javaType.isArrayOfCompoundTypeWrappers()) { ptrTypeString = cType.getName(); } else if (!javaType.isStringArray()) { - Class<?> elementType = javaType.getJavaClass().getComponentType(); + final Class<?> elementType = javaType.getJavaClass().getComponentType(); if (elementType.isArray()) { - Class<?> subElementType = elementType.getComponentType(); + final Class<?> subElementType = elementType.getComponentType(); if (subElementType.isPrimitive()) { // type is pointer to pointer to primitive ptrTypeString = cType.getName(); @@ -1432,7 +1432,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { // memory model if (javaType.isStringArray()) { String cElementTypeName = "char *"; - PointerType cPtrType = cType.asPointer(); + final PointerType cPtrType = cType.asPointer(); if (cPtrType != null) { cElementTypeName = cPtrType.getTargetType().asPointer().getName(); } @@ -1456,12 +1456,12 @@ public class CMethodBindingEmitter extends FunctionEmitter { return needsDataCopy; } - private void emitPointerConversion(PrintWriter writer, - MethodBinding binding, - JavaType type, - Type cType, - String incomingArgumentName, - String cVariableName, + private void emitPointerConversion(final PrintWriter writer, + final MethodBinding binding, + final JavaType type, + final Type cType, + final String incomingArgumentName, + final String cVariableName, String byteOffsetVarName) { // Compound type wrappers do not get byte offsets added on if (type.isCompoundTypeWrapper()) { @@ -1482,24 +1482,24 @@ public class CMethodBindingEmitter extends FunctionEmitter { byteOffsetVarName, false); } - protected String byteOffsetArgName(int i) { + protected String byteOffsetArgName(final int i) { return JavaMethodBindingEmitter.byteOffsetArgName(binding.getArgumentName(i)); } - protected String isNIOArgName(int i) { + protected String isNIOArgName(final int i) { return isNIOArgName(binding.getArgumentName(i)); } - protected String isNIOArgName(String s) { + protected String isNIOArgName(final String s) { return s + "_is_nio"; } - protected String byteOffsetArrayArgName(int i) { + protected String byteOffsetArrayArgName(final int i) { return binding.getArgumentName(i) + "_byte_offset_array"; } protected String[] argumentNameArray() { - String[] argumentNames = new String[binding.getNumArguments()]; + final String[] argumentNames = new String[binding.getNumArguments()]; for (int i = 0; i < binding.getNumArguments(); i++) { argumentNames[i] = binding.getArgumentName(i); if (binding.getJavaArgumentType(i).isPrimitiveArray()) { @@ -1510,7 +1510,7 @@ public class CMethodBindingEmitter extends FunctionEmitter { return argumentNames; } - protected String pointerConversionArgumentName(String argName) { + protected String pointerConversionArgumentName(final String argName) { return "_" + argName + "_ptr"; } @@ -1521,26 +1521,26 @@ public class CMethodBindingEmitter extends FunctionEmitter { */ protected static class DefaultCommentEmitter implements CommentEmitter { @Override - public void emit(FunctionEmitter emitter, PrintWriter writer) { + public void emit(final FunctionEmitter emitter, final PrintWriter writer) { emitBeginning((CMethodBindingEmitter)emitter, writer); emitEnding((CMethodBindingEmitter)emitter, writer); } - protected void emitBeginning(CMethodBindingEmitter emitter, PrintWriter writer) { + protected void emitBeginning(final CMethodBindingEmitter emitter, final PrintWriter writer) { writer.println(" Java->C glue code:"); writer.print(" * Java package: "); writer.print(emitter.getJavaPackageName()); writer.print("."); writer.println(emitter.getJavaClassName()); writer.print(" * Java method: "); - MethodBinding binding = emitter.getBinding(); + final MethodBinding binding = emitter.getBinding(); writer.println(binding); writer.println(" * C function: " + binding.getCSymbol()); } - protected void emitEnding(CMethodBindingEmitter emitter, PrintWriter writer) { + protected void emitEnding(final CMethodBindingEmitter emitter, final PrintWriter writer) { } } - protected boolean javaArgTypeNeedsDataCopy(JavaType javaArgType) { + protected boolean javaArgTypeNeedsDataCopy(final JavaType javaArgType) { if (javaArgType.isArray()) { return (javaArgType.isNIOBufferArray() || javaArgType.isStringArray() || diff --git a/src/java/com/jogamp/gluegen/CodeGenUtils.java b/src/java/com/jogamp/gluegen/CodeGenUtils.java index 4c96915..221256b 100644 --- a/src/java/com/jogamp/gluegen/CodeGenUtils.java +++ b/src/java/com/jogamp/gluegen/CodeGenUtils.java @@ -47,8 +47,8 @@ public class CodeGenUtils { * Given a java package name (e.g., "java.lang"), return the package as a * directory path (i.e., "java/lang"). */ - public static String packageAsPath(String packageName) { - String path = packageName.replace('.', File.separatorChar); + public static String packageAsPath(final String packageName) { + final String path = packageName.replace('.', File.separatorChar); //System.out.println("Converted package [" + packageName + "] to path [" + path +"]"); return path; } @@ -57,7 +57,7 @@ public class CodeGenUtils { * @param generator the object that is emitting the autogenerated code. If * null, the generator will not be mentioned in the warning message. */ - public static void emitAutogeneratedWarning(PrintWriter w, Object generator) { + public static void emitAutogeneratedWarning(final PrintWriter w, final Object generator) { w.print("/* !---- DO NOT EDIT: This file autogenerated "); if (generator != null) { w.print("by "); @@ -73,19 +73,19 @@ public class CodeGenUtils { /** * Emit the opening headers for one java class/interface file. */ - public static void emitJavaHeaders(PrintWriter w, - String packageName, - String className, - boolean isClassNotInterface, - List<String> imports, - String[] accessModifiers, - String[] interfaces, - String classExtended, - EmissionCallback classDocComment) throws IOException { + public static void emitJavaHeaders(final PrintWriter w, + final String packageName, + final String className, + final boolean isClassNotInterface, + final List<String> imports, + final String[] accessModifiers, + final String[] interfaces, + final String classExtended, + final EmissionCallback classDocComment) throws IOException { w.println("package " + packageName + ";"); w.println(); - for (String imp : imports) { + for (final String imp : imports) { w.print("import "); w.print(imp); w.println(';'); diff --git a/src/java/com/jogamp/gluegen/ConstantDefinition.java b/src/java/com/jogamp/gluegen/ConstantDefinition.java index 9edb827..ca67001 100644 --- a/src/java/com/jogamp/gluegen/ConstantDefinition.java +++ b/src/java/com/jogamp/gluegen/ConstantDefinition.java @@ -39,18 +39,18 @@ import java.util.*; via a #define statement or through an enum definition. */ public class ConstantDefinition { - private String origName; - private HashSet<String> aliasedNames; + private final String origName; + private final HashSet<String> aliasedNames; private String name; - private String value; - private boolean isEnum; - private String enumName; + private final String value; + private final boolean isEnum; + private final String enumName; private Set<String> aliases; - public ConstantDefinition(String name, - String value, - boolean isEnum, - String enumName) { + public ConstantDefinition(final String name, + final String value, + final boolean isEnum, + final String enumName) { this.origName = name; this.name = name; this.value = value; @@ -59,13 +59,13 @@ public class ConstantDefinition { this.aliasedNames=new HashSet<String>(); } - public boolean equals(ConstantDefinition other) { + public boolean equals(final ConstantDefinition other) { return (equals(name, other.name) && equals(value, other.value) && equals(enumName, other.enumName)); } - private boolean equals(String s1, String s2) { + private boolean equals(final String s1, final String s2) { if (s1 == null || s2 == null) { if (s1 == null && s2 == null) { return true; @@ -82,14 +82,14 @@ public class ConstantDefinition { } /** Supports renaming in Java binding. */ - public void rename(String name) { + public void rename(final String name) { if(null!=name) { this.name = name; aliasedNames.add(origName); } } - public void addAliasedName(String name) { + public void addAliasedName(final String name) { aliasedNames.add(name); } public Collection<String> getAliasedNames() { @@ -115,7 +115,7 @@ public class ConstantDefinition { return aliases; } - public void addAlias(String alias) { + public void addAlias(final String alias) { if (aliases == null) { aliases = new LinkedHashSet<String>(); } diff --git a/src/java/com/jogamp/gluegen/DebugEmitter.java b/src/java/com/jogamp/gluegen/DebugEmitter.java index 8773f1b..6381c8c 100644 --- a/src/java/com/jogamp/gluegen/DebugEmitter.java +++ b/src/java/com/jogamp/gluegen/DebugEmitter.java @@ -48,10 +48,10 @@ import com.jogamp.gluegen.cgram.types.*; public class DebugEmitter implements GlueEmitter { @Override - public void readConfigurationFile(String filename) {} + public void readConfigurationFile(final String filename) {} @Override - public void beginEmission(GlueEmitterControls controls) { + public void beginEmission(final GlueEmitterControls controls) { System.out.println("----- BEGIN EMISSION OF GLUE CODE -----"); } @@ -64,9 +64,9 @@ public class DebugEmitter implements GlueEmitter { public void beginDefines() {} @Override - public void emitDefine(ConstantDefinition def, String optionalComment) { - String name = def.getName(); - String value = def.getValue(); + public void emitDefine(final ConstantDefinition def, final String optionalComment) { + final String name = def.getName(); + final String value = def.getValue(); System.out.println("#define " + name + " " + value + (optionalComment != null ? ("// " + optionalComment) : "")); } @@ -74,24 +74,24 @@ public class DebugEmitter implements GlueEmitter { public void endDefines() {} @Override - public void beginFunctions(TypeDictionary typedefDictionary, - TypeDictionary structDictionary, - Map<Type, Type> canonMap) { - Set<String> keys = typedefDictionary.keySet(); - for (String key: keys) { - Type value = typedefDictionary.get(key); + public void beginFunctions(final TypeDictionary typedefDictionary, + final TypeDictionary structDictionary, + final Map<Type, Type> canonMap) { + final Set<String> keys = typedefDictionary.keySet(); + for (final String key: keys) { + final Type value = typedefDictionary.get(key); System.out.println("typedef " + value + " " + key + ";"); } } @Override - public Iterator<FunctionSymbol> emitFunctions(List<FunctionSymbol> originalCFunctions) throws Exception { - for (FunctionSymbol sym : originalCFunctions) { + public Iterator<FunctionSymbol> emitFunctions(final List<FunctionSymbol> originalCFunctions) throws Exception { + for (final FunctionSymbol sym : originalCFunctions) { emitSingleFunction(sym); } return originalCFunctions.iterator(); } - public void emitSingleFunction(FunctionSymbol sym) { + public void emitSingleFunction(final FunctionSymbol sym) { System.out.println(sym); System.out.println(" -> " + sym.toString()); } @@ -101,16 +101,16 @@ public class DebugEmitter implements GlueEmitter { @Override public void beginStructLayout() throws Exception {} @Override - public void layoutStruct(CompoundType t) throws Exception {} + public void layoutStruct(final CompoundType t) throws Exception {} @Override public void endStructLayout() throws Exception {} @Override - public void beginStructs(TypeDictionary typedefDictionary, TypeDictionary structDictionary, Map<Type, Type> canonMap) { + public void beginStructs(final TypeDictionary typedefDictionary, final TypeDictionary structDictionary, final Map<Type, Type> canonMap) { } @Override - public void emitStruct(CompoundType t, String alternateName) { + public void emitStruct(final CompoundType t, final String alternateName) { String name = t.getName(); if (name == null && alternateName != null) { name = alternateName; diff --git a/src/java/com/jogamp/gluegen/FunctionEmitter.java b/src/java/com/jogamp/gluegen/FunctionEmitter.java index d193ec2..8e9d306 100644 --- a/src/java/com/jogamp/gluegen/FunctionEmitter.java +++ b/src/java/com/jogamp/gluegen/FunctionEmitter.java @@ -56,7 +56,7 @@ public abstract class FunctionEmitter { /** * Constructs the FunctionEmitter with a CommentEmitter that emits nothing. */ - public FunctionEmitter(PrintWriter defaultOutput, boolean isInterface) { + public FunctionEmitter(final PrintWriter defaultOutput, final boolean isInterface) { assert(defaultOutput != null); this.modifiers = new ArrayList<EmissionModifier>(); this.defaultOutput = defaultOutput; @@ -66,7 +66,7 @@ public abstract class FunctionEmitter { /** * Makes this FunctionEmitter a copy of the passed one. */ - public FunctionEmitter(FunctionEmitter arg) { + public FunctionEmitter(final FunctionEmitter arg) { modifiers = new ArrayList<EmissionModifier>(arg.modifiers); commentEmitter = arg.commentEmitter; defaultOutput = arg.defaultOutput; @@ -82,7 +82,7 @@ public abstract class FunctionEmitter { * Intermediate 'const' qualifier are not considered, e.g. const pointer. * </p> */ - protected final boolean isBaseTypeConst(Type type) { + protected final boolean isBaseTypeConst(final Type type) { if ( 2 == type.pointerDepth() ) { return type.asPointer().getTargetType().asPointer().getTargetType().isConst(); } else if ( 1 == type.pointerDepth() ) { @@ -96,18 +96,18 @@ public abstract class FunctionEmitter { public PrintWriter getDefaultOutput() { return defaultOutput; } - public void addModifiers(Iterator<EmissionModifier> mi) { + public void addModifiers(final Iterator<EmissionModifier> mi) { while (mi.hasNext()) { modifiers.add(mi.next()); } } - public void addModifier(EmissionModifier m) { modifiers.add(m); } + public void addModifier(final EmissionModifier m) { modifiers.add(m); } - public boolean removeModifier(EmissionModifier m) { return modifiers.remove(m); } + public boolean removeModifier(final EmissionModifier m) { return modifiers.remove(m); } public void clearModifiers() { modifiers.clear(); } - public boolean hasModifier(EmissionModifier m) { return modifiers.contains(m); } + public boolean hasModifier(final EmissionModifier m) { return modifiers.contains(m); } public Iterator<EmissionModifier> getModifiers() { return modifiers.iterator(); } @@ -117,7 +117,7 @@ public abstract class FunctionEmitter { * Emit the function to the specified output (instead of the default * output). */ - public void emit(PrintWriter output) { + public void emit(final PrintWriter output) { emitDocComment(output); //output.println(" // Emitter: " + getClass().getName()); emitSignature(output); @@ -135,8 +135,8 @@ public abstract class FunctionEmitter { /** Returns, as a String, whatever {@link #emit} would output. */ @Override public String toString() { - StringWriter sw = new StringWriter(500); - PrintWriter w = new PrintWriter(sw); + final StringWriter sw = new StringWriter(500); + final PrintWriter w = new PrintWriter(sw); emit(w); return sw.toString(); } @@ -145,7 +145,7 @@ public abstract class FunctionEmitter { * Set the object that will emit the comment for this function. If the * parameter is null, no comment will be emitted. */ - public void setCommentEmitter(CommentEmitter cEmitter) { + public void setCommentEmitter(final CommentEmitter cEmitter) { commentEmitter = cEmitter; } @@ -155,7 +155,7 @@ public abstract class FunctionEmitter { */ public CommentEmitter getCommentEmitter() { return commentEmitter; } - protected void emitDocComment(PrintWriter writer) { + protected void emitDocComment(final PrintWriter writer) { if (commentEmitter != null) { writer.print(getBaseIndentString()); //indent @@ -170,11 +170,11 @@ public abstract class FunctionEmitter { } } - protected void emitSignature(PrintWriter writer) { + protected void emitSignature(final PrintWriter writer) { writer.print(getBaseIndentString()); // indent method - int numEmitted = emitModifiers(writer); + final int numEmitted = emitModifiers(writer); if (numEmitted > 0) { writer.print(" "); } @@ -189,9 +189,9 @@ public abstract class FunctionEmitter { writer.print(")"); } - protected int emitModifiers(PrintWriter writer) { + protected int emitModifiers(final PrintWriter writer) { int numEmitted = 0; - for (Iterator<EmissionModifier> it = getModifiers(); it.hasNext(); ) { + for (final Iterator<EmissionModifier> it = getModifiers(); it.hasNext(); ) { writer.print(it.next()); ++numEmitted; if (it.hasNext()) { @@ -225,7 +225,7 @@ public abstract class FunctionEmitter { } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == null || (!(arg instanceof EmissionModifier))) { return false; } @@ -233,7 +233,7 @@ public abstract class FunctionEmitter { return emittedForm.equals(((EmissionModifier) arg).emittedForm); } - protected EmissionModifier(String emittedForm) { this.emittedForm = emittedForm; } + protected EmissionModifier(final String emittedForm) { this.emittedForm = emittedForm; } } } diff --git a/src/java/com/jogamp/gluegen/GlueGen.java b/src/java/com/jogamp/gluegen/GlueGen.java index 891878b..e123910 100644 --- a/src/java/com/jogamp/gluegen/GlueGen.java +++ b/src/java/com/jogamp/gluegen/GlueGen.java @@ -60,7 +60,7 @@ public class GlueGen implements GlueEmitterControls { Logging.init(); } - private List<String> forcedStructNames = new ArrayList<String>(); + private final List<String> forcedStructNames = new ArrayList<String>(); private PCPP preprocessor; // State for SymbolFilters @@ -72,20 +72,20 @@ public class GlueGen implements GlueEmitterControls { public static boolean debug() { return debug; } @Override - public void forceStructEmission(String typedefName) { + public void forceStructEmission(final String typedefName) { forcedStructNames.add(typedefName); } @Override - public String findHeaderFile(String headerFileName) { + public String findHeaderFile(final String headerFileName) { return preprocessor.findFile(headerFileName); } @Override - public void runSymbolFilter(SymbolFilter filter) { + public void runSymbolFilter(final SymbolFilter filter) { filter.filterSymbols(constants, functions); - List<ConstantDefinition> newConstants = filter.getConstants(); - List<FunctionSymbol> newFunctions = filter.getFunctions(); + final List<ConstantDefinition> newConstants = filter.getConstants(); + final List<FunctionSymbol> newFunctions = filter.getFunctions(); if (newConstants != null) { constants = newConstants; } @@ -96,11 +96,11 @@ public class GlueGen implements GlueEmitterControls { @SuppressWarnings("unchecked") - public void run(final Reader reader, final String filename, Class<?> emitterClass, List<String> includePaths, List<String> cfgFiles, String outputRootDir, boolean copyPCPPOutput2Stderr) { + public void run(final Reader reader, final String filename, final Class<?> emitterClass, final List<String> includePaths, final List<String> cfgFiles, final String outputRootDir, final boolean copyPCPPOutput2Stderr) { try { - File out = File.createTempFile("PCPPTemp", ".pcpp"); - FileOutputStream outStream = new FileOutputStream(out); + final File out = File.createTempFile("PCPPTemp", ".pcpp"); + final FileOutputStream outStream = new FileOutputStream(out); if(debug) { System.err.println("PCPP output at (persistent): " + out.getAbsolutePath()); @@ -116,14 +116,14 @@ public class GlueGen implements GlueEmitterControls { outStream.flush(); outStream.close(); - FileInputStream inStream = new FileInputStream(out); - DataInputStream dis = new DataInputStream(inStream); + final FileInputStream inStream = new FileInputStream(out); + final DataInputStream dis = new DataInputStream(inStream); - GnuCLexer lexer = new GnuCLexer(dis); + final GnuCLexer lexer = new GnuCLexer(dis); lexer.setTokenObjectClass(CToken.class.getName()); lexer.initialize(); // Parse the input expression. - GnuCParser parser = new GnuCParser(lexer); + final GnuCParser parser = new GnuCParser(lexer); // set AST node type to TNode or get nasty cast class errors parser.setASTNodeClass(TNode.class.getName()); @@ -132,17 +132,17 @@ public class GlueGen implements GlueEmitterControls { // invoke parser try { parser.translationUnit(); - } catch (RecognitionException e) { + } catch (final RecognitionException e) { throw new RuntimeException("Fatal IO error", e); - } catch (TokenStreamException e) { + } catch (final TokenStreamException e) { throw new RuntimeException("Fatal IO error", e); } - HeaderParser headerParser = new HeaderParser(); + final HeaderParser headerParser = new HeaderParser(); headerParser.setDebug(debug); - TypeDictionary td = new TypeDictionary(); + final TypeDictionary td = new TypeDictionary(); headerParser.setTypedefDictionary(td); - TypeDictionary sd = new TypeDictionary(); + final TypeDictionary sd = new TypeDictionary(); headerParser.setStructDictionary(sd); // set AST node type to TNode or get nasty cast class errors headerParser.setASTNodeClass(TNode.class.getName()); @@ -168,19 +168,19 @@ public class GlueGen implements GlueEmitterControls { } else { try { emit = (GlueEmitter) emitterClass.newInstance(); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Exception occurred while instantiating emitter class.", e); } } - for (String config : cfgFiles) { + for (final String config : cfgFiles) { emit.readConfigurationFile(config); } if (null != outputRootDir && outputRootDir.trim().length() > 0) { if (emit instanceof JavaEmitter) { // FIXME: hack to interfere with the *Configuration setting via commandlines - JavaEmitter jemit = (JavaEmitter) emit; + final JavaEmitter jemit = (JavaEmitter) emit; if (null != jemit.getConfig()) { jemit.getConfig().setOutputRootDir(outputRootDir); } @@ -190,20 +190,20 @@ public class GlueGen implements GlueEmitterControls { // Repackage the enum and #define statements from the parser into a common format // so that SymbolFilters can operate upon both identically constants = new ArrayList<ConstantDefinition>(); - for (EnumType enumeration : headerParser.getEnums()) { + for (final EnumType enumeration : headerParser.getEnums()) { String enumName = enumeration.getName(); if (enumName.equals("<anonymous>")) { enumName = null; } // iterate over all values in the enumeration for (int i = 0; i < enumeration.getNumEnumerates(); ++i) { - String enumElementName = enumeration.getEnumName(i); - String value = String.valueOf(enumeration.getEnumValue(i)); + final String enumElementName = enumeration.getEnumName(i); + final String value = String.valueOf(enumeration.getEnumValue(i)); constants.add(new ConstantDefinition(enumElementName, value, true, enumName)); } } - for (Object elem : lexer.getDefines()) { - Define def = (Define) elem; + for (final Object elem : lexer.getDefines()) { + final Define def = (Define) elem; constants.add(new ConstantDefinition(def.getName(), def.getValue(), false, null)); } @@ -213,16 +213,16 @@ public class GlueGen implements GlueEmitterControls { emit.beginEmission(this); emit.beginDefines(); - Set<String> emittedDefines = new HashSet<String>(100); + final Set<String> emittedDefines = new HashSet<String>(100); // emit java equivalent of enum { ... } statements - StringBuilder comment = new StringBuilder(); - for (ConstantDefinition def : constants) { + final StringBuilder comment = new StringBuilder(); + for (final ConstantDefinition def : constants) { if (!emittedDefines.contains(def.getName())) { emittedDefines.add(def.getName()); - Set<String> aliases = def.getAliases(); + final Set<String> aliases = def.getAliases(); if (aliases != null) { comment.append("Alias for: <code>"); - for (String alias : aliases) { + for (final String alias : aliases) { comment.append(" ").append(alias); } comment.append("</code>"); @@ -248,8 +248,8 @@ public class GlueGen implements GlueEmitterControls { // Iterate through the functions finding structs that are referenced in // the function signatures; these will be remembered for later emission - ReferencedStructs referencedStructs = new ReferencedStructs(); - for (FunctionSymbol sym : functions) { + final ReferencedStructs referencedStructs = new ReferencedStructs(); + for (final FunctionSymbol sym : functions) { // FIXME: this doesn't take into account the possibility that some of // the functions we send to emitMethodBindings() might not actually be // emitted (e.g., if an Ignore directive in the JavaEmitter causes it @@ -260,8 +260,8 @@ public class GlueGen implements GlueEmitterControls { // Normally only referenced types will be emitted. The user can force a // type to be emitted via a .cfg file directive. Those directives are // processed here. - for (String name : forcedStructNames) { - Type type = td.get(name); + for (final String name : forcedStructNames) { + final Type type = td.get(name); if (type == null) { err.println("WARNING: during forced struct emission: struct \"" + name + "\" not found"); } else if (!type.isCompound()) { @@ -273,13 +273,13 @@ public class GlueGen implements GlueEmitterControls { // Lay out structs emit.beginStructLayout(); - for (Iterator<Type> iter = referencedStructs.results(); iter.hasNext();) { - Type t = iter.next(); + for (final Iterator<Type> iter = referencedStructs.results(); iter.hasNext();) { + final Type t = iter.next(); if (t.isCompound()) { emit.layoutStruct(t.asCompound()); } else if (t.isPointer()) { - PointerType p = t.asPointer(); - CompoundType c = p.getTargetType().asCompound(); + final PointerType p = t.asPointer(); + final CompoundType c = p.getTargetType().asCompound(); emit.layoutStruct(c); } } @@ -287,13 +287,13 @@ public class GlueGen implements GlueEmitterControls { // Emit structs emit.beginStructs(td, sd, headerParser.getCanonMap()); - for (Iterator<Type> iter = referencedStructs.results(); iter.hasNext();) { - Type t = iter.next(); + for (final Iterator<Type> iter = referencedStructs.results(); iter.hasNext();) { + final Type t = iter.next(); if (t.isCompound()) { emit.emitStruct(t.asCompound(), null); } else if (t.isPointer()) { - PointerType p = t.asPointer(); - CompoundType c = p.getTargetType().asCompound(); + final PointerType p = t.asPointer(); + final CompoundType c = p.getTargetType().asCompound(); assert p.hasTypedefedName() && c.getName() == null : "ReferencedStructs incorrectly recorded pointer type " + p; emit.emitStruct(c, p.getName()); } @@ -308,12 +308,12 @@ public class GlueGen implements GlueEmitterControls { // end emission of glue code emit.endEmission(); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Exception occurred while generating glue code.", e); } } - public static void main(String... args) { + public static void main(final String... args) { if (args.length == 0) { System.err.println(GlueGenVersion.getInstance()); @@ -324,15 +324,15 @@ public class GlueGen implements GlueEmitterControls { String filename = null; String emitterFQN = null; String outputRootDir = null; - List<String> cfgFiles = new ArrayList<String>(); + final List<String> cfgFiles = new ArrayList<String>(); boolean copyCPPOutput2Stderr = false; - List<String> includePaths = new ArrayList<String>(); + final List<String> includePaths = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { if (i < args.length - 1) { - String arg = args[i]; + final String arg = args[i]; if (arg.startsWith("-I")) { - String[] paths = arg.substring(2).split(getProperty("path.separator")); + final String[] paths = arg.substring(2).split(getProperty("path.separator")); includePaths.addAll(Arrays.asList(paths)); } else if (arg.startsWith("-O")) { outputRootDir = arg.substring(2); @@ -348,7 +348,7 @@ public class GlueGen implements GlueEmitterControls { usage(); } } else { - String arg = args[i]; + final String arg = args[i]; if (arg.equals("-")) { reader = new InputStreamReader(in); filename = "standard input"; @@ -359,7 +359,7 @@ public class GlueGen implements GlueEmitterControls { filename = arg; try { reader = new BufferedReader(new FileReader(filename)); - } catch (FileNotFoundException ex) { + } catch (final FileNotFoundException ex) { throw new RuntimeException("input file not found", ex); } } @@ -367,9 +367,9 @@ public class GlueGen implements GlueEmitterControls { } try { - Class<?> emitterClass = emitterFQN == null ? null : Class.forName(emitterFQN); + final Class<?> emitterClass = emitterFQN == null ? null : Class.forName(emitterFQN); new GlueGen().run(reader, filename, emitterClass, includePaths, cfgFiles, outputRootDir, copyCPPOutput2Stderr); - } catch (ClassNotFoundException ex) { + } catch (final ClassNotFoundException ex) { throw new RuntimeException("specified emitter class was not in the classpath", ex); } diff --git a/src/java/com/jogamp/gluegen/JavaConfiguration.java b/src/java/com/jogamp/gluegen/JavaConfiguration.java index 771576e..53af4fc 100644 --- a/src/java/com/jogamp/gluegen/JavaConfiguration.java +++ b/src/java/com/jogamp/gluegen/JavaConfiguration.java @@ -180,7 +180,7 @@ public class JavaConfiguration { /** Reads the configuration file. @param filename path to file that should be read */ - public final void read(String filename) throws IOException { + public final void read(final String filename) throws IOException { read(filename, null); } @@ -190,18 +190,18 @@ public class JavaConfiguration { @param linePrefix if not null, treat each line read as if it were prefixed with the specified string. */ - protected final void read(String filename, String linePrefix) throws IOException { - File file = new File(filename); + protected final void read(final String filename, final String linePrefix) throws IOException { + final File file = new File(filename); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); } - catch (FileNotFoundException fnfe) { + catch (final FileNotFoundException fnfe) { throw new RuntimeException("Could not read file \"" + file + "\"", fnfe); } int lineNo = 0; String line = null; - boolean hasPrefix = linePrefix != null && linePrefix.length() > 0; + final boolean hasPrefix = linePrefix != null && linePrefix.length() > 0; try { ++nestedReads; while ((line = reader.readLine()) != null) { @@ -215,10 +215,10 @@ public class JavaConfiguration { continue; } - StringTokenizer tok = new StringTokenizer(line); + final StringTokenizer tok = new StringTokenizer(line); if (tok.hasMoreTokens()) { // always reset delimiters in case of CustomJavaCode, etc. - String cmd = tok.nextToken(" \t\n\r\f"); + final String cmd = tok.nextToken(" \t\n\r\f"); dispatch(cmd, tok, file, filename, lineNo); } @@ -268,7 +268,7 @@ public class JavaConfiguration { } } - public void setOutputRootDir(String s) { outputRootDir=s; } + public void setOutputRootDir(final String s) { outputRootDir=s; } /** Returns the package name parsed from the configuration file. */ public String packageName() { @@ -320,8 +320,8 @@ public class JavaConfiguration { } /** Returns the access control for the emitted Java method. Returns one of JavaEmitter.ACC_PUBLIC, JavaEmitter.ACC_PROTECTED, JavaEmitter.ACC_PRIVATE, or JavaEmitter.ACC_PACKAGE_PRIVATE. */ - public MethodAccess accessControl(String methodName) { - MethodAccess ret = accessControl.get(methodName); + public MethodAccess accessControl(final String methodName) { + final MethodAccess ret = accessControl.get(methodName); if (ret != null) { return ret; } @@ -355,13 +355,13 @@ public class JavaConfiguration { /** If this type should be considered opaque, returns the TypeInfo describing the replacement type. Returns null if this type should not be considered opaque. */ - public TypeInfo typeInfo(Type type, TypeDictionary typedefDictionary) { + public TypeInfo typeInfo(Type type, final TypeDictionary typedefDictionary) { // Because typedefs of pointer types can show up at any point, // walk the pointer chain looking for a typedef name that is in // the TypeInfo map. if (DEBUG_TYPE_INFO) System.err.println("Incoming type = " + type); - int pointerDepth = type.pointerDepth(); + final int pointerDepth = type.pointerDepth(); for (int i = 0; i <= pointerDepth; i++) { String name = type.getName(); if (DEBUG_TYPE_INFO) { @@ -369,7 +369,7 @@ public class JavaConfiguration { System.err.println(" Name = " + name); } if (name != null) { - TypeInfo info = closestTypeInfo(name, i + type.pointerDepth()); + final TypeInfo info = closestTypeInfo(name, i + type.pointerDepth()); if (info != null) { if (DEBUG_TYPE_INFO) { System.err.println(" info.name=" + info.name() + ", name=" + name + @@ -384,7 +384,7 @@ public class JavaConfiguration { // Try struct name as well name = type.asCompound().getStructName(); if (name != null) { - TypeInfo info = closestTypeInfo(name, i + type.pointerDepth()); + final TypeInfo info = closestTypeInfo(name, i + type.pointerDepth()); if (info != null) { if (DEBUG_TYPE_INFO) { System.err.println(" info.name=" + info.name() + ", name=" + name + @@ -397,15 +397,15 @@ public class JavaConfiguration { } // Try all typedef names that map to this type - Set<Entry<String, Type>> entrySet = typedefDictionary.entrySet(); - for (Map.Entry<String, Type> entry : entrySet) { + final Set<Entry<String, Type>> entrySet = typedefDictionary.entrySet(); + for (final Map.Entry<String, Type> entry : entrySet) { // "eq" equality is OK to use here since all types have been canonicalized if (entry.getValue() == type) { name = entry.getKey(); if (DEBUG_TYPE_INFO) { System.err.println("Looking under typedef name " + name); } - TypeInfo info = closestTypeInfo(name, i + type.pointerDepth()); + final TypeInfo info = closestTypeInfo(name, i + type.pointerDepth()); if (info != null) { if (DEBUG_TYPE_INFO) { System.err.println(" info.name=" + info.name() + ", name=" + name + @@ -426,7 +426,7 @@ public class JavaConfiguration { } // Helper functions for above - private TypeInfo closestTypeInfo(String name, int pointerDepth) { + private TypeInfo closestTypeInfo(final String name, final int pointerDepth) { TypeInfo info = typeInfoMap.get(name); TypeInfo closest = null; while (info != null) { @@ -443,7 +443,7 @@ public class JavaConfiguration { } // Promotes a TypeInfo to a higher pointer type (if necessary) - private TypeInfo promoteTypeInfo(TypeInfo info, int numPointersStripped) { + private TypeInfo promoteTypeInfo(final TypeInfo info, final int numPointersStripped) { int diff = numPointersStripped - info.pointerDepth(); if (diff == 0) { return info; @@ -456,7 +456,7 @@ public class JavaConfiguration { } Class<?> c = info.javaType().getJavaClass(); - int pd = info.pointerDepth(); + final int pd = info.pointerDepth(); // Handle single-pointer stripping for types compatible with C // integral and floating-point types specially so we end up @@ -488,7 +488,7 @@ public class JavaConfiguration { /** Indicates whether the given function (which returns a <code>char*</code> in C) should be translated as returning a <code>java.lang.String</code>. */ - public boolean returnsString(String functionName) { + public boolean returnsString(final String functionName) { return returnsString.contains(functionName); } @@ -507,7 +507,7 @@ public class JavaConfiguration { * either {@link #returnValueCapacity(String)} or {@link #returnValueLength(String)}! * </p> */ - public String returnedArrayLength(String functionName) { + public String returnedArrayLength(final String functionName) { return returnedArrayLengths.get(functionName); } @@ -515,23 +515,23 @@ public class JavaConfiguration { arguments that should be converted to <code>String</code>s. Returns null if there are no such hints for the given function name. */ - public List<Integer> stringArguments(String functionName) { + public List<Integer> stringArguments(final String functionName) { return argumentsAreString.get(functionName); } public boolean isForceUsingNIOOnly4All() { return forceUseNIOOnly4All; } - public void addUseNIOOnly(String fname ) { + public void addUseNIOOnly(final String fname ) { useNIOOnly.add(fname); } /** Returns true if the given function should only create a java.nio variant, and no array variants, for <code>void*</code> and other C primitive pointers. NIO only still allows usage of array backed not direct Buffers. */ - public boolean useNIOOnly(String functionName) { + public boolean useNIOOnly(final String functionName) { return useNIODirectOnly(functionName) || forceUseNIOOnly4All || useNIOOnly.contains(functionName); } - public void addUseNIODirectOnly(String fname ) { + public void addUseNIODirectOnly(final String fname ) { useNIODirectOnly.add(fname); } /** Returns true if the given function should only create a java.nio @@ -539,13 +539,13 @@ public class JavaConfiguration { C primitive pointers. NIO direct only does only allow direct Buffers. Implies useNIOOnly ! */ - public boolean useNIODirectOnly(String functionName) { + public boolean useNIODirectOnly(final String functionName) { return forceUseNIODirectOnly4All || useNIODirectOnly.contains(functionName); } /** Returns true if the glue code for the given function will be manually implemented by the end user. */ - public boolean manuallyImplement(String functionName) { + public boolean manuallyImplement(final String functionName) { return manuallyImplement.contains(functionName); } @@ -554,7 +554,7 @@ public class JavaConfiguration { * for the given class will be manually implemented by the end user * as requested via configuration directive <code>ManualStaticInitCall 'class-name'</code>. */ - public boolean manualStaticInitCall(String clazzName) { + public boolean manualStaticInitCall(final String clazzName) { return manualStaticInitCall.contains(clazzName); } @@ -571,7 +571,7 @@ public class JavaConfiguration { * to call <code>initializeImpl()</code>, see {@link #manualStaticInitCall(String)}. * </p> */ - public boolean forceStaticInitCode(String clazzName) { + public boolean forceStaticInitCode(final String clazzName) { return forceStaticInitCode.contains(clazzName); } @@ -579,7 +579,7 @@ public class JavaConfiguration { the given Java type name (not fully-qualified, only the class name); returns either null or an empty list if there is no custom code for the class. */ - public List<String> customJavaCodeForClass(String className) { + public List<String> customJavaCodeForClass(final String className) { List<String> res = customJavaCode.get(className); if (res == null) { res = new ArrayList<String>(); @@ -588,7 +588,7 @@ public class JavaConfiguration { return res; } - public List<String> javadocForMethod(String methodName) { + public List<String> javadocForMethod(final String methodName) { List<String> res = methodJavadoc.get(methodName); if (res == null) { res = new ArrayList<String>(); @@ -601,7 +601,7 @@ public class JavaConfiguration { the given Java type name (not fully-qualified, only the class name); returns either null or an empty list if there is no Javadoc documentation for the class. */ - public List<String> javadocForClass(String className) { + public List<String> javadocForClass(final String className) { List<String> res = classJavadoc.get(className); if (res == null) { res = new ArrayList<String>(); @@ -613,7 +613,7 @@ public class JavaConfiguration { /** Returns the package into which to place the glue code for accessing the specified struct. Defaults to emitting into the regular package (i.e., the result of {@link #packageName}). */ - public String packageForStruct(String structName) { + public String packageForStruct(final String structName) { String res = structPackages.get(structName); if (res == null) { res = packageName; @@ -642,7 +642,7 @@ public class JavaConfiguration { * it describes field's array-length or element-count referenced by a pointer. * </p> */ - public String returnValueCapacity(String functionName) { + public String returnValueCapacity(final String functionName) { return returnValueCapacities.get(functionName); } @@ -654,27 +654,27 @@ public class JavaConfiguration { * it describes field's array-length or element-count referenced by a pointer. * </p> */ - public String returnValueLength(String symbol) { + public String returnValueLength(final String symbol) { return returnValueLengths.get(symbol); } /** Returns a List of Strings of expressions declaring temporary C variables in the glue code for the specified function. */ - public List<String> temporaryCVariableDeclarations(String functionName) { + public List<String> temporaryCVariableDeclarations(final String functionName) { return temporaryCVariableDeclarations.get(functionName); } /** Returns a List of Strings of expressions containing assignments to temporary C variables in the glue code for the specified function. */ - public List<String> temporaryCVariableAssignments(String functionName) { + public List<String> temporaryCVariableAssignments(final String functionName) { return temporaryCVariableAssignments.get(functionName); } /** Returns a List of Strings indicating the interfaces the passed interface should declare it extends. May return null or a list of zero length if there are none. */ - public List<String> extendedInterfaces(String interfaceName) { + public List<String> extendedInterfaces(final String interfaceName) { List<String> res = extendedInterfaces.get(interfaceName); if (res == null) { res = new ArrayList<String>(); @@ -686,7 +686,7 @@ public class JavaConfiguration { /** Returns a List of Strings indicating the interfaces the passed class should declare it implements. May return null or a list of zero length if there are none. */ - public List<String> implementedInterfaces(String className) { + public List<String> implementedInterfaces(final String className) { List<String> res = implementedInterfaces.get(className); if (res == null) { res = new ArrayList<String>(); @@ -698,7 +698,7 @@ public class JavaConfiguration { /** Returns a List of Strings indicating the interfaces the passed class should declare it implements. May return null or a list of zero length if there are none. */ - public String extendedParentClass(String className) { + public String extendedParentClass(final String className) { return parentClass.get(className); } @@ -712,15 +712,15 @@ public class JavaConfiguration { public void dumpIgnores() { System.err.println("Extended Intf: "); - for (String str : extendedIntfSymbolsIgnore) { + for (final String str : extendedIntfSymbolsIgnore) { System.err.println("\t"+str); } System.err.println("Extended Impl: "); - for (String str : extendedImplSymbolsIgnore) { + for (final String str : extendedImplSymbolsIgnore) { System.err.println("\t"+str); } System.err.println("Ignores (All): "); - for (Pattern pattern : ignores) { + for (final Pattern pattern : ignores) { System.err.println("\t"+pattern); } } @@ -735,13 +735,13 @@ public class JavaConfiguration { public void dumpRenames() { System.err.println("Symbol Renames: "); - for (String key : javaSymbolRenames.keySet()) { + for (final String key : javaSymbolRenames.keySet()) { System.err.println("\t"+key+" -> "+javaSymbolRenames.get(key)); } System.err.println("Symbol Aliasing (through renaming): "); - for(String newName : javaSymbolRenames.values()) { - Set<String> origNames = javaRenamedSymbols.get(newName); + for(final String newName : javaSymbolRenames.values()) { + final Set<String> origNames = javaRenamedSymbols.get(newName); if(null!=origNames) { System.err.println("\t"+newName+" <- "+origNames); } @@ -752,7 +752,7 @@ public class JavaConfiguration { * Returns the canonical configuration name for a struct field name, * i.e. 'struct-name'.'field-name' */ - public static String canonicalStructFieldSymbol(String structName, String fieldName) { + public static String canonicalStructFieldSymbol(final String structName, final String fieldName) { return structName+"."+fieldName; } @@ -763,7 +763,7 @@ public class JavaConfiguration { * For struct fields see {@link #canonicalStructFieldSymbol(String, String)}. * </p> */ - public boolean shouldIgnoreInInterface(String symbol) { + public boolean shouldIgnoreInInterface(final String symbol) { if(DEBUG_IGNORES) { dumpIgnoresOnce(); } @@ -795,11 +795,11 @@ public class JavaConfiguration { * For struct fields see {@link #canonicalStructFieldSymbol(String, String)}. * </p> */ - public boolean shouldIgnoreInImpl(String symbol) { + public boolean shouldIgnoreInImpl(final String symbol) { return shouldIgnoreInImpl_Int(symbol); } - private boolean shouldIgnoreInImpl_Int(String symbol) { + private boolean shouldIgnoreInImpl_Int(final String symbol) { if(DEBUG_IGNORES) { dumpIgnoresOnce(); @@ -826,8 +826,8 @@ public class JavaConfiguration { // Ok, the slow case. We need to check the entire table, in case the table // contains an regular expression that matches the symbol. - for (Pattern regexp : ignores) { - Matcher matcher = regexp.matcher(symbol); + for (final Pattern regexp : ignores) { + final Matcher matcher = regexp.matcher(symbol); if (matcher.matches()) { if(DEBUG_IGNORES) { System.err.println("Ignore Impl RegEx: "+symbol); @@ -840,8 +840,8 @@ public class JavaConfiguration { if (ignoreNots.size() > 0) { // Ok, the slow case. We need to check the entire table, in case the table // contains an regular expression that matches the symbol. - for (Pattern regexp : ignoreNots) { - Matcher matcher = regexp.matcher(symbol); + for (final Pattern regexp : ignoreNots) { + final Matcher matcher = regexp.matcher(symbol); if (!matcher.matches()) { // Special case as this is most often likely to be the case. // Unignores are not used very often. @@ -853,8 +853,8 @@ public class JavaConfiguration { } boolean unignoreFound = false; - for (Pattern unignoreRegexp : unignores) { - Matcher unignoreMatcher = unignoreRegexp.matcher(symbol); + for (final Pattern unignoreRegexp : unignores) { + final Matcher unignoreMatcher = unignoreRegexp.matcher(symbol); if (unignoreMatcher.matches()) { unignoreFound = true; break; @@ -876,11 +876,11 @@ public class JavaConfiguration { /** Returns true if this function should be given a body which throws a run-time exception with an "unimplemented" message during glue code generation. */ - public boolean isUnimplemented(String symbol) { + public boolean isUnimplemented(final String symbol) { // Ok, the slow case. We need to check the entire table, in case the table // contains an regular expression that matches the symbol. - for (Pattern regexp : unimplemented) { - Matcher matcher = regexp.matcher(symbol); + for (final Pattern regexp : unimplemented) { + final Matcher matcher = regexp.matcher(symbol); if (matcher.matches()) { return true; } @@ -893,8 +893,8 @@ public class JavaConfiguration { name of a Java wrapper class for a C struct, or the name unchanged if no RenameJavaType directive was specified for this type. */ - public String renameJavaType(String javaTypeName) { - String rename = javaTypeRenames.get(javaTypeName); + public String renameJavaType(final String javaTypeName) { + final String rename = javaTypeRenames.get(javaTypeName); if (rename != null) { return rename; } @@ -906,7 +906,7 @@ public class JavaConfiguration { constant. If a function, it still calls the originally-named C function under the hood. Returns null if this symbol has not been explicitly renamed. */ - public String getJavaSymbolRename(String origName) { + public String getJavaSymbolRename(final String origName) { if(DEBUG_RENAMES) { dumpRenamesOnce(); } @@ -914,16 +914,16 @@ public class JavaConfiguration { } /** Returns a set of replaced names to the given <code>aliasedName</code>. */ - public Set<String> getRenamedJavaSymbols(String aliasedName) { + public Set<String> getRenamedJavaSymbols(final String aliasedName) { return javaRenamedSymbols.get(aliasedName); } /** Programmatically adds a rename directive for the given symbol. */ - public void addJavaSymbolRename(String origName, String newName) { + public void addJavaSymbolRename(final String origName, final String newName) { if(DEBUG_RENAMES) { System.err.print("\tRename "+origName+" -> "+newName); } - String prevValue = javaSymbolRenames.put(origName, newName); + final String prevValue = javaSymbolRenames.put(origName, newName); if(null != prevValue && !prevValue.equals(newName)) { throw new RuntimeException("Rename-Override Attampt: "+origName+" -> "+newName+ ", but "+origName+" -> "+prevValue+" already exist. Run in 'debug' mode to analyze!"); @@ -958,9 +958,9 @@ public class JavaConfiguration { /** Returns a list of Strings which should be emitted as a prologue to the body for the Java-side glue code for the given method. Returns null if no prologue was specified. */ - public List<String> javaPrologueForMethod(MethodBinding binding, - boolean forImplementingMethodCall, - boolean eraseBufferAndArrayTypes) { + public List<String> javaPrologueForMethod(final MethodBinding binding, + final boolean forImplementingMethodCall, + final boolean eraseBufferAndArrayTypes) { List<String> res = javaPrologues.get(binding.getName()); if (res == null) { // Try again with method name and descriptor @@ -972,9 +972,9 @@ public class JavaConfiguration { /** Returns a list of Strings which should be emitted as an epilogue to the body for the Java-side glue code for the given method. Returns null if no epilogue was specified. */ - public List<String> javaEpilogueForMethod(MethodBinding binding, - boolean forImplementingMethodCall, - boolean eraseBufferAndArrayTypes) { + public List<String> javaEpilogueForMethod(final MethodBinding binding, + final boolean forImplementingMethodCall, + final boolean eraseBufferAndArrayTypes) { List<String> res = javaEpilogues.get(binding.getName()); if (res == null) { // Try again with method name and descriptor @@ -987,7 +987,7 @@ public class JavaConfiguration { // Internals only below this point // - protected void dispatch(String cmd, StringTokenizer tok, File file, String filename, int lineNo) throws IOException { + protected void dispatch(final String cmd, final StringTokenizer tok, final File file, final String filename, final int lineNo) throws IOException { //System.err.println("read cmd = [" + cmd + "]"); if (cmd.equalsIgnoreCase("Package")) { packageName = readString("package", tok, filename, lineNo); @@ -1004,14 +1004,14 @@ public class JavaConfiguration { } else if (cmd.equalsIgnoreCase("NativeOutputDir")) { nativeOutputDir = readString("NativeOutputDir", tok, filename, lineNo); } else if (cmd.equalsIgnoreCase("HierarchicalNativeOutput")) { - String tmp = readString("HierarchicalNativeOutput", tok, filename, lineNo); + final String tmp = readString("HierarchicalNativeOutput", tok, filename, lineNo); nativeOutputUsesJavaHierarchy = Boolean.valueOf(tmp).booleanValue(); } else if (cmd.equalsIgnoreCase("TagNativeBinding")) { tagNativeBinding = readBoolean("TagNativeBinding", tok, filename, lineNo).booleanValue(); } else if (cmd.equalsIgnoreCase("Style")) { try{ emissionStyle = EmissionStyle.valueOf(readString("Style", tok, filename, lineNo)); - }catch(IllegalArgumentException ex) { + }catch(final IllegalArgumentException ex) { LOG.log(WARNING, "Error parsing \"style\" command at line {0} in file \"{1}\"", new Object[]{lineNo, filename}); } } else if (cmd.equalsIgnoreCase("AccessControl")) { @@ -1073,14 +1073,14 @@ public class JavaConfiguration { // Warning: make sure delimiters are reset at the top of this loop // because readClassJavadoc changes them. } else if (cmd.equalsIgnoreCase("NIOOnly")) { - String funcName = readString("NIOOnly", tok, filename, lineNo); + final String funcName = readString("NIOOnly", tok, filename, lineNo); if(funcName.equals("__ALL__")) { forceUseNIOOnly4All=true; } else { addUseNIOOnly( funcName ); } } else if (cmd.equalsIgnoreCase("NIODirectOnly")) { - String funcName = readString("NIODirectOnly", tok, filename, lineNo); + final String funcName = readString("NIODirectOnly", tok, filename, lineNo); if(funcName.equals("__ALL__")) { forceUseNIODirectOnly4All=true; } else { @@ -1149,25 +1149,25 @@ public class JavaConfiguration { } } - protected String readString(String cmd, StringTokenizer tok, String filename, int lineNo) { + protected String readString(final String cmd, final StringTokenizer tok, final String filename, final int lineNo) { try { return tok.nextToken(); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"" + cmd + "\" command at line " + lineNo + " in file \"" + filename + "\": missing expected parameter", e); } } - protected Boolean readBoolean(String cmd, StringTokenizer tok, String filename, int lineNo) { + protected Boolean readBoolean(final String cmd, final StringTokenizer tok, final String filename, final int lineNo) { try { return Boolean.valueOf(tok.nextToken()); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"" + cmd + "\" command at line " + lineNo + " in file \"" + filename + "\": missing expected boolean value", e); } } - protected Class<?> stringToPrimitiveType(String type) throws ClassNotFoundException { + protected Class<?> stringToPrimitiveType(final String type) throws ClassNotFoundException { if (type.equals("boolean")) return Boolean.TYPE; if (type.equals("byte")) return Byte.TYPE; if (type.equals("char")) return Character.TYPE; @@ -1179,21 +1179,21 @@ public class JavaConfiguration { throw new RuntimeException("Only primitive types are supported here"); } - protected void readAccessControl(StringTokenizer tok, String filename, int lineNo) { + protected void readAccessControl(final StringTokenizer tok, final String filename, final int lineNo) { try { - String methodName = tok.nextToken(); - String style = tok.nextToken(); - MethodAccess access = MethodAccess.valueOf(style.toUpperCase()); + final String methodName = tok.nextToken(); + final String style = tok.nextToken(); + final MethodAccess access = MethodAccess.valueOf(style.toUpperCase()); accessControl.put(methodName, access); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Error parsing \"AccessControl\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readOpaque(StringTokenizer tok, String filename, int lineNo) { + protected void readOpaque(final StringTokenizer tok, final String filename, final int lineNo) { try { - JavaType javaType = JavaType.createForClass(stringToPrimitiveType(tok.nextToken())); + final JavaType javaType = JavaType.createForClass(stringToPrimitiveType(tok.nextToken())); String cType = null; while (tok.hasMoreTokens()) { if (cType == null) { @@ -1206,55 +1206,55 @@ public class JavaConfiguration { throw new RuntimeException("No C type for \"Opaque\" command at line " + lineNo + " in file \"" + filename + "\""); } - TypeInfo info = parseTypeInfo(cType, javaType); + final TypeInfo info = parseTypeInfo(cType, javaType); addTypeInfo(info); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Error parsing \"Opaque\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readReturnsString(StringTokenizer tok, String filename, int lineNo) { + protected void readReturnsString(final StringTokenizer tok, final String filename, final int lineNo) { try { - String name = tok.nextToken(); + final String name = tok.nextToken(); returnsString.add(name); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"ReturnsString\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readReturnedArrayLength(StringTokenizer tok, String filename, int lineNo) { + protected void readReturnedArrayLength(final StringTokenizer tok, final String filename, final int lineNo) { try { - String functionName = tok.nextToken(); + final String functionName = tok.nextToken(); String restOfLine = tok.nextToken("\n\r\f"); restOfLine = restOfLine.trim(); returnedArrayLengths.put(functionName, restOfLine); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"ReturnedArrayLength\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readExtendedIntfImplSymbols(StringTokenizer tok, String filename, int lineNo, boolean forInterface, boolean forImplementation, boolean onlyList) { + protected void readExtendedIntfImplSymbols(final StringTokenizer tok, final String filename, final int lineNo, final boolean forInterface, final boolean forImplementation, final boolean onlyList) { File javaFile; BufferedReader javaReader; try { javaFile = new File(tok.nextToken()); javaReader = new BufferedReader(new FileReader(javaFile)); - } catch (FileNotFoundException e) { + } catch (final FileNotFoundException e) { throw new RuntimeException(e); } - JavaLexer lexer = new JavaLexer(javaReader); + final JavaLexer lexer = new JavaLexer(javaReader); lexer.setFilename(javaFile.getName()); - JavaParser parser = new JavaParser(lexer); + final JavaParser parser = new JavaParser(lexer); parser.setFilename(javaFile.getName()); try { parser.compilationUnit(); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException(e); } @@ -1281,22 +1281,22 @@ public class JavaConfiguration { } } - protected void readIgnore(StringTokenizer tok, String filename, int lineNo) { + protected void readIgnore(final StringTokenizer tok, final String filename, final int lineNo) { try { - String regex = tok.nextToken(); - Pattern pattern = Pattern.compile(regex); + final String regex = tok.nextToken(); + final Pattern pattern = Pattern.compile(regex); ignores.add(pattern); ignoreMap.put(regex, pattern); //System.err.println("IGNORING " + regex + " / " + ignores.get(regex)); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"Ignore\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readUnignore(StringTokenizer tok, String filename, int lineNo) { + protected void readUnignore(final StringTokenizer tok, final String filename, final int lineNo) { try { - String regex = tok.nextToken(); + final String regex = tok.nextToken(); Pattern pattern = ignoreMap.get(regex); ignoreMap.remove(regex); ignores.remove(pattern); @@ -1308,129 +1308,129 @@ public class JavaConfiguration { unignores.add(pattern); //System.err.println("UN-IGNORING " + regex + " / " + ignores.get(regex)); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"Unignore\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readIgnoreNot(StringTokenizer tok, String filename, int lineNo) { + protected void readIgnoreNot(final StringTokenizer tok, final String filename, final int lineNo) { try { - String regex = tok.nextToken(); + final String regex = tok.nextToken(); ignoreNots.add(Pattern.compile(regex)); //System.err.println("IGNORING NEGATION OF " + regex + " / " + ignores.get(regex)); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"IgnoreNot\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readUnimplemented(StringTokenizer tok, String filename, int lineNo) { + protected void readUnimplemented(final StringTokenizer tok, final String filename, final int lineNo) { try { - String regex = tok.nextToken(); + final String regex = tok.nextToken(); unimplemented.add(Pattern.compile(regex)); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"Unimplemented\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readIgnoreField(StringTokenizer tok, String filename, int lineNo) { + protected void readIgnoreField(final StringTokenizer tok, final String filename, final int lineNo) { try { - String containingStruct = tok.nextToken(); - String name = tok.nextToken(); + final String containingStruct = tok.nextToken(); + final String name = tok.nextToken(); ignores.add(Pattern.compile(containingStruct + "\\." + name)); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"IgnoreField\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readManuallyImplement(StringTokenizer tok, String filename, int lineNo) { + protected void readManuallyImplement(final StringTokenizer tok, final String filename, final int lineNo) { try { - String name = tok.nextToken(); + final String name = tok.nextToken(); manuallyImplement.add(name); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"ManuallyImplement\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readManualStaticInitCall(StringTokenizer tok, String filename, int lineNo) { + protected void readManualStaticInitCall(final StringTokenizer tok, final String filename, final int lineNo) { try { - String name = tok.nextToken(); + final String name = tok.nextToken(); manualStaticInitCall.add(name); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"ManualStaticInitCall\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readForceStaticInitCode(StringTokenizer tok, String filename, int lineNo) { + protected void readForceStaticInitCode(final StringTokenizer tok, final String filename, final int lineNo) { try { - String name = tok.nextToken(); + final String name = tok.nextToken(); forceStaticInitCode.add(name); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"ForceStaticInitCode\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readCustomJavaCode(StringTokenizer tok, String filename, int lineNo) { + protected void readCustomJavaCode(final StringTokenizer tok, final String filename, final int lineNo) { try { - String tokenClassName = tok.nextToken(); + final String tokenClassName = tok.nextToken(); try { - String restOfLine = tok.nextToken("\n\r\f"); + final String restOfLine = tok.nextToken("\n\r\f"); addCustomJavaCode(tokenClassName, restOfLine); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { addCustomJavaCode(tokenClassName, ""); } - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"CustomJavaCode\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void addCustomJavaCode(String className, String code) { - List<String> codeList = customJavaCodeForClass(className); + protected void addCustomJavaCode(final String className, final String code) { + final List<String> codeList = customJavaCodeForClass(className); codeList.add(code); } - protected void readCustomCCode(StringTokenizer tok, String filename, int lineNo) { + protected void readCustomCCode(final StringTokenizer tok, final String filename, final int lineNo) { try { - String restOfLine = tok.nextToken("\n\r\f"); + final String restOfLine = tok.nextToken("\n\r\f"); customCCode.add(restOfLine); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { customCCode.add(""); } } - protected void readMethodJavadoc(StringTokenizer tok, String filename, int lineNo) { + protected void readMethodJavadoc(final StringTokenizer tok, final String filename, final int lineNo) { try { - String tokenClassName = tok.nextToken(); - String restOfLine = tok.nextToken("\n\r\f"); + final String tokenClassName = tok.nextToken(); + final String restOfLine = tok.nextToken("\n\r\f"); addMethodJavadoc(tokenClassName, restOfLine); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"MethodJavadoc\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void addMethodJavadoc(String methodName, String code) { - List<String> codeList = javadocForMethod(methodName); + protected void addMethodJavadoc(final String methodName, final String code) { + final List<String> codeList = javadocForMethod(methodName); codeList.add(code); } - protected void readClassJavadoc(StringTokenizer tok, String filename, int lineNo) { + protected void readClassJavadoc(final StringTokenizer tok, final String filename, final int lineNo) { try { - String tokenClassName = tok.nextToken(); - String restOfLine = tok.nextToken("\n\r\f"); + final String tokenClassName = tok.nextToken(); + final String restOfLine = tok.nextToken("\n\r\f"); addClassJavadoc(tokenClassName, restOfLine); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"ClassJavadoc\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void addClassJavadoc(String className, String code) { - List<String> codeList = javadocForClass(className); + protected void addClassJavadoc(final String className, final String code) { + final List<String> codeList = javadocForClass(className); codeList.add(code); } @@ -1463,12 +1463,12 @@ public class JavaConfiguration { * </pre> * */ - protected void readArgumentIsString(StringTokenizer tok, String filename, int lineNo) { + protected void readArgumentIsString(final StringTokenizer tok, final String filename, final int lineNo) { try { - String methodName = tok.nextToken(); - ArrayList<Integer> argIndices = new ArrayList<Integer>(2); + final String methodName = tok.nextToken(); + final ArrayList<Integer> argIndices = new ArrayList<Integer>(2); while (tok.hasMoreTokens()) { - Integer idx = Integer.valueOf(tok.nextToken()); + final Integer idx = Integer.valueOf(tok.nextToken()); argIndices.add(idx); } @@ -1478,51 +1478,51 @@ public class JavaConfiguration { throw new RuntimeException("ERROR: Error parsing \"ArgumentIsString\" command at line " + lineNo + " in file \"" + filename + "\": directive requires specification of at least 1 index"); } - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException( "Error parsing \"ArgumentIsString\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readStructPackage(StringTokenizer tok, String filename, int lineNo) { + protected void readStructPackage(final StringTokenizer tok, final String filename, final int lineNo) { try { - String struct = tok.nextToken(); - String pkg = tok.nextToken(); + final String struct = tok.nextToken(); + final String pkg = tok.nextToken(); structPackages.put(struct, pkg); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"StructPackage\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readReturnValueCapacity(StringTokenizer tok, String filename, int lineNo) { + protected void readReturnValueCapacity(final StringTokenizer tok, final String filename, final int lineNo) { try { - String functionName = tok.nextToken(); + final String functionName = tok.nextToken(); String restOfLine = tok.nextToken("\n\r\f"); restOfLine = restOfLine.trim(); returnValueCapacities.put(functionName, restOfLine); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"ReturnValueCapacity\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readReturnValueLength(StringTokenizer tok, String filename, int lineNo) { + protected void readReturnValueLength(final StringTokenizer tok, final String filename, final int lineNo) { try { - String functionName = tok.nextToken(); + final String functionName = tok.nextToken(); String restOfLine = tok.nextToken("\n\r\f"); restOfLine = restOfLine.trim(); returnValueLengths.put(functionName, restOfLine); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"ReturnValueLength\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readTemporaryCVariableDeclaration(StringTokenizer tok, String filename, int lineNo) { + protected void readTemporaryCVariableDeclaration(final StringTokenizer tok, final String filename, final int lineNo) { try { - String functionName = tok.nextToken(); + final String functionName = tok.nextToken(); String restOfLine = tok.nextToken("\n\r\f"); restOfLine = restOfLine.trim(); List<String> list = temporaryCVariableDeclarations.get(functionName); @@ -1531,15 +1531,15 @@ public class JavaConfiguration { temporaryCVariableDeclarations.put(functionName, list); } list.add(restOfLine); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"TemporaryCVariableDeclaration\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readTemporaryCVariableAssignment(StringTokenizer tok, String filename, int lineNo) { + protected void readTemporaryCVariableAssignment(final StringTokenizer tok, final String filename, final int lineNo) { try { - String functionName = tok.nextToken(); + final String functionName = tok.nextToken(); String restOfLine = tok.nextToken("\n\r\f"); restOfLine = restOfLine.trim(); List<String> list = temporaryCVariableAssignments.get(functionName); @@ -1548,117 +1548,117 @@ public class JavaConfiguration { temporaryCVariableAssignments.put(functionName, list); } list.add(restOfLine); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"TemporaryCVariableAssignment\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void doInclude(StringTokenizer tok, File file, String filename, int lineNo) throws IOException { + protected void doInclude(final StringTokenizer tok, final File file, final String filename, final int lineNo) throws IOException { try { - String includedFilename = tok.nextToken(); + final String includedFilename = tok.nextToken(); File includedFile = new File(includedFilename); if (!includedFile.isAbsolute()) { includedFile = new File(file.getParentFile(), includedFilename); } read(includedFile.getAbsolutePath()); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"Include\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void doIncludeAs(StringTokenizer tok, File file, String filename, int lineNo) throws IOException { + protected void doIncludeAs(final StringTokenizer tok, final File file, final String filename, final int lineNo) throws IOException { try { - StringBuilder linePrefix = new StringBuilder(128); + final StringBuilder linePrefix = new StringBuilder(128); while (tok.countTokens() > 1) { linePrefix.append(tok.nextToken()); linePrefix.append(" "); } // last token is filename - String includedFilename = tok.nextToken(); + final String includedFilename = tok.nextToken(); File includedFile = new File(includedFilename); if (!includedFile.isAbsolute()) { includedFile = new File(file.getParentFile(), includedFilename); } read(includedFile.getAbsolutePath(), linePrefix.toString()); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"IncludeAs\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readExtend(StringTokenizer tok, String filename, int lineNo) { + protected void readExtend(final StringTokenizer tok, final String filename, final int lineNo) { try { - String interfaceName = tok.nextToken(); - List<String> intfs = extendedInterfaces(interfaceName); + final String interfaceName = tok.nextToken(); + final List<String> intfs = extendedInterfaces(interfaceName); intfs.add(tok.nextToken()); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"Extends\" command at line " + lineNo + " in file \"" + filename + "\": missing expected parameter", e); } } - protected void readImplements(StringTokenizer tok, String filename, int lineNo) { + protected void readImplements(final StringTokenizer tok, final String filename, final int lineNo) { try { - String tokenClassName = tok.nextToken(); - List<String> intfs = implementedInterfaces(tokenClassName); + final String tokenClassName = tok.nextToken(); + final List<String> intfs = implementedInterfaces(tokenClassName); intfs.add(tok.nextToken()); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"Implements\" command at line " + lineNo + " in file \"" + filename + "\": missing expected parameter", e); } } - protected void readParentClass(StringTokenizer tok, String filename, int lineNo) { + protected void readParentClass(final StringTokenizer tok, final String filename, final int lineNo) { try { - String tokenClassName = tok.nextToken(); + final String tokenClassName = tok.nextToken(); parentClass.put(tokenClassName, tok.nextToken()); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"ParentClass\" command at line " + lineNo + " in file \"" + filename + "\": missing expected parameter", e); } } - protected void readRenameJavaType(StringTokenizer tok, String filename, int lineNo) { + protected void readRenameJavaType(final StringTokenizer tok, final String filename, final int lineNo) { try { - String fromName = tok.nextToken(); - String toName = tok.nextToken(); + final String fromName = tok.nextToken(); + final String toName = tok.nextToken(); javaTypeRenames.put(fromName, toName); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"RenameJavaType\" command at line " + lineNo + " in file \"" + filename + "\": missing expected parameter", e); } } - protected void readRenameJavaSymbol(StringTokenizer tok, String filename, int lineNo) { + protected void readRenameJavaSymbol(final StringTokenizer tok, final String filename, final int lineNo) { try { - String fromName = tok.nextToken(); - String toName = tok.nextToken(); + final String fromName = tok.nextToken(); + final String toName = tok.nextToken(); addJavaSymbolRename(fromName, toName); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"RenameJavaSymbol\" command at line " + lineNo + " in file \"" + filename + "\": missing expected parameter", e); } } - protected void readJavaPrologueOrEpilogue(StringTokenizer tok, String filename, int lineNo, boolean prologue) { + protected void readJavaPrologueOrEpilogue(final StringTokenizer tok, final String filename, final int lineNo, final boolean prologue) { try { String methodName = tok.nextToken(); String restOfLine = tok.nextToken("\n\r\f"); restOfLine = restOfLine.trim(); if (startsWithDescriptor(restOfLine)) { // Assume it starts with signature for disambiguation - int spaceIdx = restOfLine.indexOf(' '); + final int spaceIdx = restOfLine.indexOf(' '); if (spaceIdx > 0) { - String descriptor = restOfLine.substring(0, spaceIdx); + final String descriptor = restOfLine.substring(0, spaceIdx); restOfLine = restOfLine.substring(spaceIdx + 1, restOfLine.length()); methodName = methodName + descriptor; } } addJavaPrologueOrEpilogue(methodName, restOfLine, prologue); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"" + (prologue ? "JavaPrologue" : "JavaEpilogue") + "\" command at line " + lineNo + @@ -1666,8 +1666,8 @@ public class JavaConfiguration { } } - protected void addJavaPrologueOrEpilogue(String methodName, String code, boolean prologue) { - Map<String, List<String>> codes = (prologue ? javaPrologues : javaEpilogues); + protected void addJavaPrologueOrEpilogue(final String methodName, final String code, final boolean prologue) { + final Map<String, List<String>> codes = (prologue ? javaPrologues : javaEpilogues); List<String> data = codes.get(methodName); if (data == null) { data = new ArrayList<String>(); @@ -1676,10 +1676,10 @@ public class JavaConfiguration { data.add(code); } - protected void readRangeCheck(StringTokenizer tok, String filename, int lineNo, boolean inBytes) { + protected void readRangeCheck(final StringTokenizer tok, final String filename, final int lineNo, final boolean inBytes) { try { - String functionName = tok.nextToken(); - int argNum = Integer.parseInt(tok.nextToken()); + final String functionName = tok.nextToken(); + final int argNum = Integer.parseInt(tok.nextToken()); String restOfLine = tok.nextToken("\n\r\f"); restOfLine = restOfLine.trim(); // Construct a JavaPrologue for this @@ -1688,13 +1688,13 @@ public class JavaConfiguration { (inBytes ? "Bytes" : "") + "({" + argNum + "}, " + restOfLine + ");", true); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Error parsing \"RangeCheck" + (inBytes ? "Bytes" : "") + "\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected static TypeInfo parseTypeInfo(String cType, JavaType javaType) { + protected static TypeInfo parseTypeInfo(final String cType, final JavaType javaType) { String typeName = null; int pointerDepth = 0; int idx = 0; @@ -1714,7 +1714,7 @@ public class JavaConfiguration { return new TypeInfo(typeName, pointerDepth, javaType); } - protected void addTypeInfo(TypeInfo info) { + protected void addTypeInfo(final TypeInfo info) { TypeInfo tmp = typeInfoMap.get(info.name()); if (tmp == null) { typeInfoMap.put(info.name(), info); @@ -1726,10 +1726,10 @@ public class JavaConfiguration { tmp.setNext(info); } - private static int nextIndexAfterType(String s, int idx) { - int len = s.length(); + private static int nextIndexAfterType(final String s, int idx) { + final int len = s.length(); while (idx < len) { - char c = s.charAt(idx); + final char c = s.charAt(idx); if (Character.isJavaIdentifierStart(c) || Character.isJavaIdentifierPart(c) || @@ -1744,8 +1744,8 @@ public class JavaConfiguration { return -1; } - private static int nextIndexAfterDescriptor(String s, int idx) { - char c = s.charAt(idx); + private static int nextIndexAfterDescriptor(final String s, final int idx) { + final char c = s.charAt(idx); switch (c) { case 'B': case 'C': @@ -1763,12 +1763,12 @@ public class JavaConfiguration { return -1; } - protected static boolean startsWithDescriptor(String s) { + protected static boolean startsWithDescriptor(final String s) { // Try to see whether the String s starts with a valid Java // descriptor. int idx = 0; - int len = s.length(); + final int len = s.length(); while ((idx < len) && s.charAt(idx) == ' ') { ++idx; } @@ -1776,7 +1776,7 @@ public class JavaConfiguration { if (idx >= len) return false; if (s.charAt(idx++) != '(') return false; while (idx < len) { - int nextIdx = nextIndexAfterDescriptor(s, idx); + final int nextIdx = nextIndexAfterDescriptor(s, idx); if (nextIdx < 0) { return false; } @@ -1786,7 +1786,7 @@ public class JavaConfiguration { } idx = nextIdx; } - int nextIdx = nextIndexAfterDescriptor(s, idx + 1); + final int nextIdx = nextIndexAfterDescriptor(s, idx + 1); if (nextIdx < 0) { return false; } diff --git a/src/java/com/jogamp/gluegen/JavaEmitter.java b/src/java/com/jogamp/gluegen/JavaEmitter.java index abe9a62..0490e0c 100644 --- a/src/java/com/jogamp/gluegen/JavaEmitter.java +++ b/src/java/com/jogamp/gluegen/JavaEmitter.java @@ -91,7 +91,7 @@ public class JavaEmitter implements GlueEmitter { public final String getJavaName() { return javaName; } - MethodAccess(String javaName) { + MethodAccess(final String javaName) { this.javaName = javaName; } private final String javaName; @@ -106,7 +106,7 @@ public class JavaEmitter implements GlueEmitter { protected final static Logger LOG = Logger.getLogger(JavaEmitter.class.getPackage().getName()); @Override - public void readConfigurationFile(String filename) throws Exception { + public void readConfigurationFile(final String filename) throws Exception { cfg = createConfig(); cfg.read(filename); } @@ -116,7 +116,7 @@ public class JavaEmitter implements GlueEmitter { private List<ConstantDefinition> constants; @Override - public void filterSymbols(List<ConstantDefinition> constants, List<FunctionSymbol> functions) { + public void filterSymbols(final List<ConstantDefinition> constants, final List<FunctionSymbol> functions) { this.constants = constants; doWork(); } @@ -132,9 +132,9 @@ public class JavaEmitter implements GlueEmitter { } private void doWork() { - List<ConstantDefinition> newConstants = new ArrayList<ConstantDefinition>(); - JavaConfiguration cfg = getConfig(); - for (ConstantDefinition def : constants) { + final List<ConstantDefinition> newConstants = new ArrayList<ConstantDefinition>(); + final JavaConfiguration cfg = getConfig(); + for (final ConstantDefinition def : constants) { def.rename(cfg.getJavaSymbolRename(def.getName())); newConstants.add(def); } @@ -143,17 +143,17 @@ public class JavaEmitter implements GlueEmitter { } @Override - public void beginEmission(GlueEmitterControls controls) throws IOException { + public void beginEmission(final GlueEmitterControls controls) throws IOException { // Request emission of any structs requested - for (String structs : cfg.forcedStructs()) { + for (final String structs : cfg.forcedStructs()) { controls.forceStructEmission(structs); } if (!cfg.structsOnly()) { try { openWriters(); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Unable to open files for writing", e); } emitAllFileHeaders(); @@ -170,7 +170,7 @@ public class JavaEmitter implements GlueEmitter { try { closeWriters(); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Unable to close open files", e); } } @@ -183,7 +183,7 @@ public class JavaEmitter implements GlueEmitter { } } - protected static int getJavaRadix(String name, String value) { + protected static int getJavaRadix(final String name, final String value) { // FIXME: need to handle when type specifier is in last char (e.g., // "1.0d or 2759L", because parseXXX() methods don't allow the type // specifier character in the string. @@ -213,12 +213,12 @@ public class JavaEmitter implements GlueEmitter { //System.err.println("parsing " + value + " as long w/ radix " + radix); Long.parseLong(parseValue, radix); return radix; - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { try { // see if it's a double or float Double.parseDouble(value); return 10; - } catch (NumberFormatException e2) { + } catch (final NumberFormatException e2) { throw new RuntimeException( "Cannot emit define \""+name+"\": value \""+value+ "\" cannot be assigned to a int, long, float, or double", e2); @@ -226,22 +226,22 @@ public class JavaEmitter implements GlueEmitter { } } - protected static Object getJavaValue(String name, String value) { + protected static Object getJavaValue(final String name, final String value) { // "calculates" the result type of a simple expression // example: (2+3)-(2.0f-3.0) -> Double // example: (1 << 2) -> Integer - Scanner scanner = new Scanner(value).useDelimiter("[+-/*/></(/)]"); + final Scanner scanner = new Scanner(value).useDelimiter("[+-/*/></(/)]"); Object resultType = null; while (scanner.hasNext()) { - String t = scanner.next().trim(); + final String t = scanner.next().trim(); if(0<t.length()) { - Object type = getJavaValue2(name, t); + final Object type = getJavaValue2(name, t); //fast path if(type instanceof Double) @@ -272,12 +272,12 @@ public class JavaEmitter implements GlueEmitter { return resultType; } - private static Object getJavaValue2(String name, String value) { + private static Object getJavaValue2(final String name, final String value) { // FIXME: need to handle when type specifier is in last char (e.g., // "1.0d or 2759L", because parseXXX() methods don't allow the type // specifier character in the string. // - char lastChar = value.charAt(value.length()-1); + final char lastChar = value.charAt(value.length()-1); try { // see if it's a long or int @@ -302,24 +302,24 @@ public class JavaEmitter implements GlueEmitter { } //System.err.println("parsing " + value + " as long w/ radix " + radix); - long longVal = Long.parseLong(parseValue, radix); + final long longVal = Long.parseLong(parseValue, radix); // if constant is small enough, store it as an int instead of a long if (longVal > Integer.MIN_VALUE && longVal < Integer.MAX_VALUE) { return (int)longVal; } return longVal; - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { try { // see if it's a double or float - double dVal = Double.parseDouble(value); - double absVal = Math.abs(dVal); + final double dVal = Double.parseDouble(value); + final double absVal = Math.abs(dVal); // if constant is small enough, store it as a float instead of a double if (absVal < Float.MIN_VALUE || absVal > Float.MAX_VALUE) { return new Double(dVal); } return new Float((float) dVal); - } catch (NumberFormatException e2) { + } catch (final NumberFormatException e2) { throw new RuntimeException( "Cannot emit define \""+name+"\": value \""+value+ "\" cannot be assigned to a int, long, float, or double", e2); @@ -328,12 +328,12 @@ public class JavaEmitter implements GlueEmitter { } - protected static String getJavaType(String name, String value) { - Object oval = getJavaValue(name, value); + protected static String getJavaType(final String name, final String value) { + final Object oval = getJavaValue(name, value); return getJavaType(name, oval); } - protected static String getJavaType(String name, Object oval) { + protected static String getJavaType(final String name, final Object oval) { if(oval instanceof Integer) { return "int"; } else if(oval instanceof Long) { @@ -350,7 +350,7 @@ public class JavaEmitter implements GlueEmitter { } /** Mangle a class, package or function name for JNI usage, i.e. replace all '.' w/ '_' */ - protected static String jniMangle(String name) { + protected static String jniMangle(final String name) { return name.replaceAll("_", "_1").replace('.', '_'); } /** Returns the JNI method prefix consisting our of mangled package- and class-name */ @@ -359,7 +359,7 @@ public class JavaEmitter implements GlueEmitter { } @Override - public void emitDefine(ConstantDefinition def, String optionalComment) throws Exception { + public void emitDefine(final ConstantDefinition def, final String optionalComment) throws Exception { if (cfg.allStatic() || cfg.emitInterface()) { // TODO: Some defines (e.g., GL_DOUBLE_EXT in gl.h) are defined in terms @@ -371,11 +371,11 @@ public class JavaEmitter implements GlueEmitter { // currently only emits only numeric defines -- if it handled #define'd // objects it would make a bigger difference. - String name = def.getName(); + final String name = def.getName(); String value = def.getValue(); if (!cfg.shouldIgnoreInInterface(name)) { - String type = getJavaType(name, value); + final String type = getJavaType(name, value); if (optionalComment != null && optionalComment.length() != 0) { javaWriter().println(" /** " + optionalComment + " */"); } @@ -398,9 +398,9 @@ public class JavaEmitter implements GlueEmitter { } @Override - public void beginFunctions(TypeDictionary typedefDictionary, - TypeDictionary structDictionary, - Map<Type, Type> canonMap) throws Exception { + public void beginFunctions(final TypeDictionary typedefDictionary, + final TypeDictionary structDictionary, + final Map<Type, Type> canonMap) throws Exception { this.typedefDictionary = typedefDictionary; this.canonMap = canonMap; @@ -412,7 +412,7 @@ public class JavaEmitter implements GlueEmitter { } @Override - public Iterator<FunctionSymbol> emitFunctions(List<FunctionSymbol> originalCFunctions) throws Exception { + public Iterator<FunctionSymbol> emitFunctions(final List<FunctionSymbol> originalCFunctions) throws Exception { // Sometimes headers will have the same function prototype twice, once // with the argument names and once without. We'll remember the signatures @@ -421,8 +421,8 @@ public class JavaEmitter implements GlueEmitter { // Note: this code assumes that on the equals() method in FunctionSymbol // only considers function name and argument types (i.e., it does not // consider argument *names*) when comparing FunctionSymbols for equality - Set<FunctionSymbol> funcsToBindSet = new HashSet<FunctionSymbol>(100); - for (FunctionSymbol cFunc : originalCFunctions) { + final Set<FunctionSymbol> funcsToBindSet = new HashSet<FunctionSymbol>(100); + for (final FunctionSymbol cFunc : originalCFunctions) { if (!funcsToBindSet.contains(cFunc)) { funcsToBindSet.add(cFunc); } @@ -430,19 +430,19 @@ public class JavaEmitter implements GlueEmitter { // validateFunctionsToBind(funcsToBindSet); - ArrayList<FunctionSymbol> funcsToBind = new ArrayList<FunctionSymbol>(funcsToBindSet); + final ArrayList<FunctionSymbol> funcsToBind = new ArrayList<FunctionSymbol>(funcsToBindSet); // sort functions to make them easier to find in native code Collections.sort(funcsToBind, new Comparator<FunctionSymbol>() { @Override - public int compare(FunctionSymbol o1, FunctionSymbol o2) { + public int compare(final FunctionSymbol o1, final FunctionSymbol o2) { return o1.getName().compareTo(o2.getName()); } }); // Bind all the C funcs to Java methods - HashSet<MethodBinding> methodBindingSet = new HashSet<MethodBinding>(); - ArrayList<FunctionEmitter> methodBindingEmitters = new ArrayList<FunctionEmitter>(2*funcsToBind.size()); - for (FunctionSymbol cFunc : funcsToBind) { + final HashSet<MethodBinding> methodBindingSet = new HashSet<MethodBinding>(); + final ArrayList<FunctionEmitter> methodBindingEmitters = new ArrayList<FunctionEmitter>(2*funcsToBind.size()); + for (final FunctionSymbol cFunc : funcsToBind) { // Check to see whether this function should be ignored if (!cfg.shouldIgnoreInImpl(cFunc.getName())) { methodBindingEmitters.addAll(generateMethodBindingEmitters(methodBindingSet, cFunc)); @@ -451,13 +451,13 @@ public class JavaEmitter implements GlueEmitter { } // Emit all the methods - for (FunctionEmitter emitter : methodBindingEmitters) { + for (final FunctionEmitter emitter : methodBindingEmitters) { try { if (!emitter.isInterface() || !cfg.shouldIgnoreInInterface(emitter.getName())) { emitter.emit(); emitter.getDefaultOutput().println(); // put newline after method body } - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException( "Error while emitting binding for \"" + emitter.getName() + "\"", e); } @@ -506,7 +506,7 @@ public class JavaEmitter implements GlueEmitter { * native code because it doesn't need any processing of the * outgoing arguments). */ - protected void generatePublicEmitters(MethodBinding binding, List<FunctionEmitter> allEmitters, boolean signatureOnly) { + protected void generatePublicEmitters(final MethodBinding binding, final List<FunctionEmitter> allEmitters, final boolean signatureOnly) { if (cfg.manuallyImplement(binding.getName()) && !signatureOnly) { // We only generate signatures for manually-implemented methods; // user provides the implementation @@ -563,7 +563,7 @@ public class JavaEmitter implements GlueEmitter { default: break; // package-private adds no modifiers } if (cfg.allStatic()) { - emitter.addModifier(JavaMethodBindingEmitter.STATIC); + emitter.addModifier(FunctionEmitter.STATIC); } if (!isUnimplemented && !needsBody && !signatureOnly) { emitter.addModifier(JavaMethodBindingEmitter.NATIVE); @@ -583,8 +583,8 @@ public class JavaEmitter implements GlueEmitter { * many emitters which would lead to compilation errors from * creating duplicated methods / functions. */ - protected void generatePrivateEmitters(MethodBinding binding, - List<FunctionEmitter> allEmitters) { + protected void generatePrivateEmitters(final MethodBinding binding, + final List<FunctionEmitter> allEmitters) { if (cfg.manuallyImplement(binding.getName())) { // Don't produce emitters for the implementation class return; @@ -634,7 +634,7 @@ public class JavaEmitter implements GlueEmitter { cfg); emitter.addModifier(JavaMethodBindingEmitter.PRIVATE); if (cfg.allStatic()) { - emitter.addModifier(JavaMethodBindingEmitter.STATIC); + emitter.addModifier(FunctionEmitter.STATIC); } emitter.addModifier(JavaMethodBindingEmitter.NATIVE); emitter.setReturnedArrayLengthExpression(cfg.returnedArrayLength(binding.getName())); @@ -665,7 +665,7 @@ public class JavaEmitter implements GlueEmitter { } } - protected void prepCEmitter(String returnSizeLookupName, JavaType javaReturnType, CMethodBindingEmitter cEmitter) + protected void prepCEmitter(final String returnSizeLookupName, final JavaType javaReturnType, final CMethodBindingEmitter cEmitter) { // See whether we need an expression to help calculate the // length of any return type @@ -700,19 +700,19 @@ public class JavaEmitter implements GlueEmitter { * Generate all appropriate Java bindings for the specified C function * symbols. */ - protected List<? extends FunctionEmitter> generateMethodBindingEmitters(Set<MethodBinding> methodBindingSet, FunctionSymbol sym) throws Exception { + protected List<? extends FunctionEmitter> generateMethodBindingEmitters(final Set<MethodBinding> methodBindingSet, final FunctionSymbol sym) throws Exception { - ArrayList<FunctionEmitter> allEmitters = new ArrayList<FunctionEmitter>(); + final ArrayList<FunctionEmitter> allEmitters = new ArrayList<FunctionEmitter>(); try { // Get Java binding for the function - MethodBinding mb = bindFunction(sym, null, null, machDescJava); + final MethodBinding mb = bindFunction(sym, null, null, machDescJava); // JavaTypes representing C pointers in the initial // MethodBinding have not been lowered yet to concrete types - List<MethodBinding> bindings = expandMethodBinding(mb); + final List<MethodBinding> bindings = expandMethodBinding(mb); - for (MethodBinding binding : bindings) { + for (final MethodBinding binding : bindings) { if(!methodBindingSet.add(binding)) { // skip .. already exisiting binding .. @@ -780,7 +780,7 @@ public class JavaEmitter implements GlueEmitter { generatePrivateEmitters(binding, allEmitters); } } // end iteration over expanded bindings - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Error while generating bindings for \"" + sym + "\"", e); } @@ -811,16 +811,16 @@ public class JavaEmitter implements GlueEmitter { @Override public void beginStructLayout() throws Exception {} @Override - public void layoutStruct(CompoundType t) throws Exception { + public void layoutStruct(final CompoundType t) throws Exception { getLayout().layout(t); } @Override public void endStructLayout() throws Exception {} @Override - public void beginStructs(TypeDictionary typedefDictionary, - TypeDictionary structDictionary, - Map<Type, Type> canonMap) throws Exception { + public void beginStructs(final TypeDictionary typedefDictionary, + final TypeDictionary structDictionary, + final Map<Type, Type> canonMap) throws Exception { this.typedefDictionary = typedefDictionary; this.canonMap = canonMap; } @@ -922,7 +922,7 @@ public class JavaEmitter implements GlueEmitter { } else { jniWriter = null; } - } catch(Exception e) { + } catch(final Exception e) { throw new RuntimeException("Unable to open files for emission of struct class", e); } @@ -937,21 +937,21 @@ public class JavaEmitter implements GlueEmitter { javaWriter.println("import " + Buffers.class.getPackage().getName() + ".*;"); javaWriter.println("import " + MachineDescriptionRuntime.class.getName() + ";"); javaWriter.println(); - List<String> imports = cfg.imports(); - for (String str : imports) { + final List<String> imports = cfg.imports(); + for (final String str : imports) { javaWriter.print("import "); javaWriter.print(str); javaWriter.println(";"); } javaWriter.println(); - List<String> javadoc = cfg.javadocForClass(containingJTypeName); - for (String doc : javadoc) { + final List<String> javadoc = cfg.javadocForClass(containingJTypeName); + for (final String doc : javadoc) { javaWriter.println(doc); } javaWriter.print("public class " + containingJTypeName + " "); boolean firstIteration = true; - List<String> userSpecifiedInterfaces = cfg.implementedInterfaces(containingJTypeName); - for (String userInterface : userSpecifiedInterfaces) { + final List<String> userSpecifiedInterfaces = cfg.implementedInterfaces(containingJTypeName); + for (final String userInterface : userSpecifiedInterfaces) { if (firstIteration) { javaWriter.print("implements "); } @@ -1008,7 +1008,7 @@ public class JavaEmitter implements GlueEmitter { final JavaType externalJavaType; try { externalJavaType = typeToJavaType(fieldType, machDescJava); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Error occurred while creating accessor for field \"" + cfgFieldName1 + "\", "+fieldType.getDebugString(), e); } @@ -1057,7 +1057,7 @@ public class JavaEmitter implements GlueEmitter { javaWriter.println(" return accessor.getBuffer();"); javaWriter.println(" }"); - Set<MethodBinding> methodBindingSet = new HashSet<MethodBinding>(); + final Set<MethodBinding> methodBindingSet = new HashSet<MethodBinding>(); for (int i = 0; i < structCType.getNumFields(); i++) { final Field field = structCType.getField(i); @@ -1098,7 +1098,7 @@ public class JavaEmitter implements GlueEmitter { final JavaType javaType; try { javaType = typeToJavaType(fieldType, machDescJava); - } catch (Exception e) { + } catch (final Exception e) { System.err.println("Error occurred while creating accessor for field \"" + field.getName() + "\", "+fieldType.getDebugString()); throw(e); @@ -1176,13 +1176,13 @@ public class JavaEmitter implements GlueEmitter { @Override public void endStructs() throws Exception {} - public static int addStrings2Buffer(StringBuilder buf, String sep, String first, Collection<String> col) { + public static int addStrings2Buffer(StringBuilder buf, final String sep, final String first, final Collection<String> col) { int num = 0; if(null==buf) { buf = new StringBuilder(); } - Iterator<String> iter = col.iterator(); + final Iterator<String> iter = col.iterator(); if(null!=first) { buf.append(first); if( iter.hasNext() ) { @@ -1239,7 +1239,7 @@ public class JavaEmitter implements GlueEmitter { writer.print(")"); } - private void generateOffsetAndSizeArrays(PrintWriter writer, String prefix, String fieldName, Type fieldType, Field field, String postfix) { + private void generateOffsetAndSizeArrays(final PrintWriter writer, final String prefix, final String fieldName, final Type fieldType, final Field field, final String postfix) { if(null != field) { writer.print(prefix+"private static final int[] "+fieldName+"_offset = new int[] { "); for( int i=0; i < machDescTargetConfigs.length; i++ ) { @@ -1333,7 +1333,7 @@ public class JavaEmitter implements GlueEmitter { emitter.emit(); // Emit (private) C entry point for calling this function pointer - CMethodBindingEmitter cEmitter = + final CMethodBindingEmitter cEmitter = new CMethodBindingEmitter(binding, jniWriter, structClassPkgName, @@ -1398,7 +1398,7 @@ public class JavaEmitter implements GlueEmitter { emitter.emit(); // Emit (private) C entry point for calling this function pointer - CMethodBindingEmitter cEmitter = + final CMethodBindingEmitter cEmitter = new CMethodBindingEmitter(binding, jniWriter, structClassPkgName, @@ -1411,7 +1411,7 @@ public class JavaEmitter implements GlueEmitter { cEmitter.setIsCStructFunctionPointer(false); final String lenExprSet; if( null != nativeArrayLenExpr ) { - JavaType javaReturnType = binding.getJavaReturnType(); + final JavaType javaReturnType = binding.getJavaReturnType(); if (javaReturnType.isNIOBuffer() || javaReturnType.isCompoundTypeWrapper()) { final Type retType = funcSym.getReturnType(); @@ -1504,7 +1504,7 @@ public class JavaEmitter implements GlueEmitter { final JavaType javaType; try { javaType = typeToJavaType(fieldType, machDescJava); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Error occurred while creating array/pointer accessor for field \"" + returnSizeLookupName + "\", "+fieldType.getDebugString(), e); } @@ -1579,7 +1579,7 @@ public class JavaEmitter implements GlueEmitter { isConst = baseCElemType.isConst(); try { baseJElemType = typeToJavaType(baseCElemType, machDescJava); - } catch (Exception e ) { + } catch (final Exception e ) { throw new RuntimeException("Error occurred while creating array/pointer accessor for field \"" + returnSizeLookupName + "\", baseType "+baseCElemType.getDebugString()+", topType "+fieldType.getDebugString(), e); } @@ -1621,7 +1621,7 @@ public class JavaEmitter implements GlueEmitter { boolean _hasSingleElement=false; try { _hasSingleElement = 1 ==Integer.parseInt(_arrayLengthExpr); - } catch (Exception e ) {} + } catch (final Exception e ) {} hasSingleElement = _hasSingleElement; } if( GlueGen.debug() ) { @@ -1968,7 +1968,7 @@ public class JavaEmitter implements GlueEmitter { isPointerPointer = true; // t is<type>**, targetType is <type>*, we need to get <type> - Type bottomType = targetType.asPointer().getTargetType(); + final Type bottomType = targetType.asPointer().getTargetType(); if( GlueGen.debug() ) { LOG.log(INFO, "Opaque Type: {0}, targetType: {1}, bottomType: {2} is ptr-ptr", new Object[]{cType.getDebugString(), targetType, bottomType}); } @@ -2137,7 +2137,7 @@ public class JavaEmitter implements GlueEmitter { } } - private static boolean isIntegerType(Class<?> c) { + private static boolean isIntegerType(final Class<?> c) { return ((c == Byte.TYPE) || (c == Short.TYPE) || (c == Character.TYPE) || @@ -2158,7 +2158,7 @@ public class JavaEmitter implements GlueEmitter { * @return a {@link PrintWriter} instance to write the class source file or <code>null</code> to suppress output! * @throws IOException */ - protected PrintWriter openFile(String filename, String simpleClassName) throws IOException { + protected PrintWriter openFile(final String filename, final String simpleClassName) throws IOException { //System.out.println("Trying to open: " + filename); final File file = new File(filename); final String parentDir = file.getParent(); @@ -2168,14 +2168,14 @@ public class JavaEmitter implements GlueEmitter { return new PrintWriter(new BufferedWriter(new FileWriter(file))); } - private boolean isOpaque(Type type) { + private boolean isOpaque(final Type type) { return (cfg.typeInfo(type, typedefDictionary) != null); } - private String compatiblePrimitiveJavaTypeName(Type fieldType, - JavaType javaType, - MachineDescription curMachDesc) { - Class<?> c = javaType.getJavaClass(); + private String compatiblePrimitiveJavaTypeName(final Type fieldType, + final JavaType javaType, + final MachineDescription curMachDesc) { + final Class<?> c = javaType.getJavaClass(); if (!isIntegerType(c)) { // FIXME throw new RuntimeException("Can't yet handle opaque definitions of structs' fields to non-integer types (byte, short, int, long, etc.): type: "+fieldType+", javaType "+javaType+", javaClass "+c); @@ -2250,7 +2250,7 @@ public class JavaEmitter implements GlueEmitter { return cWriter; } - private void closeWriter(PrintWriter writer) throws IOException { + private void closeWriter(final PrintWriter writer) throws IOException { writer.flush(); writer.close(); } @@ -2298,14 +2298,14 @@ public class JavaEmitter implements GlueEmitter { * Emit all the strings specified in the "CustomJavaCode" parameters of * the configuration file. */ - protected void emitCustomJavaCode(PrintWriter writer, String className) throws Exception { - List<String> code = cfg.customJavaCodeForClass(className); + protected void emitCustomJavaCode(final PrintWriter writer, final String className) throws Exception { + final List<String> code = cfg.customJavaCodeForClass(className); if (code.isEmpty()) return; writer.println(); writer.println(" // --- Begin CustomJavaCode .cfg declarations"); - for (String line : code) { + for (final String line : code) { writer.println(line); } writer.println(" // ---- End CustomJavaCode .cfg declarations"); @@ -2317,7 +2317,7 @@ public class JavaEmitter implements GlueEmitter { */ protected void emitAllFileHeaders() throws IOException { try { - List<String> imports = new ArrayList<String>(cfg.imports()); + final List<String> imports = new ArrayList<String>(cfg.imports()); imports.add(cfg.gluegenRuntimePackage()+".*"); imports.add(DynamicLookupHelper.class.getPackage().getName()+".*"); imports.add(Buffers.class.getPackage().getName()+".*"); @@ -2336,11 +2336,11 @@ public class JavaEmitter implements GlueEmitter { userSpecifiedInterfaces.toArray(interfaces); final List<String> intfDocs = cfg.javadocForClass(cfg.className()); - CodeGenUtils.EmissionCallback docEmitter = + final CodeGenUtils.EmissionCallback docEmitter = new CodeGenUtils.EmissionCallback() { @Override - public void emit(PrintWriter w) { - for (Iterator<String> iter = intfDocs.iterator(); iter.hasNext(); ) { + public void emit(final PrintWriter w) { + for (final Iterator<String> iter = intfDocs.iterator(); iter.hasNext(); ) { w.println(iter.next()); } } @@ -2367,11 +2367,11 @@ public class JavaEmitter implements GlueEmitter { if (!cfg.allStatic() && cfg.emitImpl()) { final List<String> implDocs = cfg.javadocForClass(cfg.implClassName()); - CodeGenUtils.EmissionCallback docEmitter = + final CodeGenUtils.EmissionCallback docEmitter = new CodeGenUtils.EmissionCallback() { @Override - public void emit(PrintWriter w) { - for (Iterator<String> iter = implDocs.iterator(); iter.hasNext(); ) { + public void emit(final PrintWriter w) { + for (final Iterator<String> iter = implDocs.iterator(); iter.hasNext(); ) { w.println(iter.next()); } } @@ -2412,7 +2412,7 @@ public class JavaEmitter implements GlueEmitter { if (cfg.emitImpl()) { emitCHeader(cWriter(), getImplPackageName(), cfg.implClassName()); } - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException( "Error emitting all file headers: cfg.allStatic()=" + cfg.allStatic() + " cfg.emitImpl()=" + cfg.emitImpl() + " cfg.emitInterface()=" + cfg.emitInterface(), @@ -2421,7 +2421,7 @@ public class JavaEmitter implements GlueEmitter { } - protected void emitCHeader(PrintWriter cWriter, String packageName, String className) { + protected void emitCHeader(final PrintWriter cWriter, final String packageName, final String className) { cWriter.println("#include <jni.h>"); cWriter.println("#include <stdlib.h>"); cWriter.println("#include <string.h>"); @@ -2433,7 +2433,7 @@ public class JavaEmitter implements GlueEmitter { cWriter.println("static jobject JVMUtil_NewDirectByteBufferCopy(JNIEnv *env, void * source_address, jlong capacity); /* forward decl. */"); cWriter.println(); } - for (String code : cfg.customCCode()) { + for (final String code : cfg.customCCode()) { cWriter.println(code); } cWriter.println(); @@ -2502,7 +2502,7 @@ public class JavaEmitter implements GlueEmitter { " }\n"+ "\n"; - protected void emitCInitCode(PrintWriter cWriter, String packageName, String className) { + protected void emitCInitCode(final PrintWriter cWriter, final String packageName, final String className) { if ( requiresStaticInitialization(className) ) { cWriter.println(staticClassInitCodeCCode); cWriter.println("JNIEXPORT jboolean JNICALL "+JavaEmitter.getJNIMethodNamePrefix(packageName, className)+"_initializeImpl(JNIEnv *env, jclass _unused) {"); @@ -2516,7 +2516,7 @@ public class JavaEmitter implements GlueEmitter { } } - protected void emitJavaInitCode(PrintWriter jWriter, String className) { + protected void emitJavaInitCode(final PrintWriter jWriter, final String className) { if( null != jWriter && requiresStaticInitialization(className) ) { jWriter.println(); jWriter.println(" private static native boolean initializeImpl();"); @@ -2545,7 +2545,7 @@ public class JavaEmitter implements GlueEmitter { } } - private JavaType javaType(Class<?> c) { + private JavaType javaType(final Class<?> c) { return JavaType.createForClass(c); } @@ -2555,19 +2555,19 @@ public class JavaEmitter implements GlueEmitter { potentially representing C pointers rather than true Java types) and must be lowered to concrete Java types before creating emitters for them. */ - private MethodBinding bindFunction(FunctionSymbol sym, - JavaType containingType, - Type containingCType, - MachineDescription curMachDesc) { + private MethodBinding bindFunction(final FunctionSymbol sym, + final JavaType containingType, + final Type containingCType, + final MachineDescription curMachDesc) { - MethodBinding binding = new MethodBinding(sym, containingType, containingCType); + final MethodBinding binding = new MethodBinding(sym, containingType, containingCType); binding.renameMethodName(cfg.getJavaSymbolRename(sym.getName())); // System.out.println("bindFunction(0) "+sym.getReturnType()); if (cfg.returnsString(binding.getName())) { - PointerType prt = sym.getReturnType().asPointer(); + final PointerType prt = sym.getReturnType().asPointer(); if (prt == null || prt.getTargetType().asInt() == null || prt.getTargetType().getSize(curMachDesc) != 1) { @@ -2584,10 +2584,10 @@ public class JavaEmitter implements GlueEmitter { // List of the indices of the arguments in this function that should be // converted from byte[] or short[] to String - List<Integer> stringArgIndices = cfg.stringArguments(binding.getName()); + final List<Integer> stringArgIndices = cfg.stringArguments(binding.getName()); for (int i = 0; i < sym.getNumArguments(); i++) { - Type cArgType = sym.getArgumentType(i); + final Type cArgType = sym.getArgumentType(i); JavaType mappedType = typeToJavaType(cArgType, curMachDesc); // System.out.println("C arg type -> \"" + cArgType + "\"" ); // System.out.println(" Java -> \"" + mappedType + "\"" ); @@ -2628,16 +2628,16 @@ public class JavaEmitter implements GlueEmitter { return binding; } - private MethodBinding lowerMethodBindingPointerTypes(MethodBinding inputBinding, - boolean convertToArrays, - boolean[] canProduceArrayVariant) { + private MethodBinding lowerMethodBindingPointerTypes(final MethodBinding inputBinding, + final boolean convertToArrays, + final boolean[] canProduceArrayVariant) { MethodBinding result = inputBinding; boolean arrayPossible = false; // System.out.println("lowerMethodBindingPointerTypes(0): "+result); for (int i = 0; i < inputBinding.getNumArguments(); i++) { - JavaType t = inputBinding.getJavaArgumentType(i); + final JavaType t = inputBinding.getJavaArgumentType(i); if (t.isCPrimitivePointerType()) { if (t.isCVoidPointerType()) { // These are always bound to java.nio.Buffer @@ -2693,7 +2693,7 @@ public class JavaEmitter implements GlueEmitter { // System.out.println("lowerMethodBindingPointerTypes(1): "+result); // Always return primitive pointer types as NIO buffers - JavaType t = result.getJavaReturnType(); + final JavaType t = result.getJavaReturnType(); if (t.isCPrimitivePointerType()) { if (t.isCVoidPointerType()) { result = result.replaceJavaArgumentType(-1, JavaType.forNIOByteBufferClass()); @@ -2726,12 +2726,12 @@ public class JavaEmitter implements GlueEmitter { // Expands a MethodBinding containing C primitive pointer types into // multiple variants taking Java primitive arrays and NIO buffers, subject // to the per-function "NIO only" rule in the configuration file - protected List<MethodBinding> expandMethodBinding(MethodBinding binding) { + protected List<MethodBinding> expandMethodBinding(final MethodBinding binding) { - List<MethodBinding> result = new ArrayList<MethodBinding>(); + final List<MethodBinding> result = new ArrayList<MethodBinding>(); // Indicates whether it is possible to produce an array variant // Prevents e.g. char* -> String conversions from emitting two entry points - boolean[] canProduceArrayVariant = new boolean[1]; + final boolean[] canProduceArrayVariant = new boolean[1]; if (binding.signatureUsesCPrimitivePointers() || binding.signatureUsesCVoidPointers() || @@ -2751,8 +2751,8 @@ public class JavaEmitter implements GlueEmitter { return result; } - private Type canonicalize(Type t) { - Type res = canonMap.get(t); + private Type canonicalize(final Type t) { + final Type res = canonMap.get(t); if (res != null) { return res; } @@ -2763,7 +2763,7 @@ public class JavaEmitter implements GlueEmitter { /** * Converts first letter to upper case. */ - private final String capitalizeString(String string) { + private final String capitalizeString(final String string) { return Character.toUpperCase(string.charAt(0)) + string.substring(1); } } diff --git a/src/java/com/jogamp/gluegen/JavaMethodBindingEmitter.java b/src/java/com/jogamp/gluegen/JavaMethodBindingEmitter.java index ea7910a..6966315 100644 --- a/src/java/com/jogamp/gluegen/JavaMethodBindingEmitter.java +++ b/src/java/com/jogamp/gluegen/JavaMethodBindingEmitter.java @@ -100,21 +100,21 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { // Only present to provide more clear comments private final JavaConfiguration cfg; - public JavaMethodBindingEmitter(MethodBinding binding, - PrintWriter output, - String runtimeExceptionType, - String unsupportedExceptionType, - boolean emitBody, - boolean tagNativeBinding, - boolean eraseBufferAndArrayTypes, - boolean useNIOOnly, - boolean useNIODirectOnly, - boolean forImplementingMethodCall, - boolean forDirectBufferImplementation, - boolean forIndirectBufferAndArrayImplementation, - boolean isUnimplemented, - boolean isInterface, - JavaConfiguration configuration) { + public JavaMethodBindingEmitter(final MethodBinding binding, + final PrintWriter output, + final String runtimeExceptionType, + final String unsupportedExceptionType, + final boolean emitBody, + final boolean tagNativeBinding, + final boolean eraseBufferAndArrayTypes, + final boolean useNIOOnly, + final boolean useNIODirectOnly, + final boolean forImplementingMethodCall, + final boolean forDirectBufferImplementation, + final boolean forIndirectBufferAndArrayImplementation, + final boolean isUnimplemented, + final boolean isInterface, + final JavaConfiguration configuration) { super(output, isInterface); this.binding = binding; this.runtimeExceptionType = runtimeExceptionType; @@ -136,7 +136,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { cfg = configuration; } - public JavaMethodBindingEmitter(JavaMethodBindingEmitter arg) { + public JavaMethodBindingEmitter(final JavaMethodBindingEmitter arg) { super(arg); binding = arg.binding; runtimeExceptionType = arg.runtimeExceptionType; @@ -168,7 +168,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { return binding.getName(); } - protected String getArgumentName(int i) { + protected String getArgumentName(final int i) { return binding.getArgumentName(i); } @@ -190,11 +190,11 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { number of elements of the returned array. The parameters to the MessageFormat expression are the names of the incoming Java arguments. */ - public void setReturnedArrayLengthExpression(String expr) { + public void setReturnedArrayLengthExpression(final String expr) { returnedArrayLengthExpression = expr; returnedArrayLengthExpressionOnlyForComments = false; } - protected void setReturnedArrayLengthExpression(String expr, boolean onlyForComments) { + protected void setReturnedArrayLengthExpression(final String expr, final boolean onlyForComments) { returnedArrayLengthExpression = expr; returnedArrayLengthExpressionOnlyForComments = onlyForComments; } @@ -206,12 +206,12 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } /** Sets the manually-generated prologue code for this emitter. */ - public void setPrologue(List<String> prologue) { + public void setPrologue(final List<String> prologue) { this.prologue = prologue; } /** Sets the manually-generated epilogue code for this emitter. */ - public void setEpilogue(List<String> epilogue) { + public void setEpilogue(final List<String> epilogue) { this.epilogue = epilogue; } @@ -223,36 +223,36 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } /** Accessor for subclasses. */ - public void setEmitBody(boolean emitBody) { + public void setEmitBody(final boolean emitBody) { this.emitBody = emitBody; } /** Accessor for subclasses. */ - public void setEraseBufferAndArrayTypes(boolean erase) { + public void setEraseBufferAndArrayTypes(final boolean erase) { this.eraseBufferAndArrayTypes = erase; } /** Accessor for subclasses. */ - public void setForImplementingMethodCall(boolean impl) { + public void setForImplementingMethodCall(final boolean impl) { this.forImplementingMethodCall = impl; } /** Accessor for subclasses. */ - public void setForDirectBufferImplementation(boolean direct) { + public void setForDirectBufferImplementation(final boolean direct) { this.forDirectBufferImplementation = direct; } /** Accessor for subclasses. */ - public void setForIndirectBufferAndArrayImplementation(boolean indirect) { + public void setForIndirectBufferAndArrayImplementation(final boolean indirect) { this.forIndirectBufferAndArrayImplementation = indirect; } @Override - protected void emitReturnType(PrintWriter writer) { + protected void emitReturnType(final PrintWriter writer) { writer.print(getReturnTypeString(false)); } - protected String erasedTypeString(JavaType type, boolean skipBuffers) { + protected String erasedTypeString(final JavaType type, final boolean skipBuffers) { if (eraseBufferAndArrayTypes) { if (type.isNIOBuffer()) { if (!skipBuffers) { @@ -292,7 +292,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { if( null == name ) { throw new IllegalArgumentException("null type name: "+type.getDebugString()); } - int index = name.lastIndexOf('.')+1; // always >= 0 + final int index = name.lastIndexOf('.')+1; // always >= 0 name = name.substring(index); if (type.isArrayOfCompoundTypeWrappers()) { @@ -302,7 +302,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { return name; } - protected String getReturnTypeString(boolean skipArray) { + protected String getReturnTypeString(final boolean skipArray) { // The first arm of the "if" clause is used by the glue code // generation for arrays of compound type wrappers if (skipArray || @@ -321,7 +321,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } @Override - protected void emitName(PrintWriter writer) { + protected void emitName(final PrintWriter writer) { if (forImplementingMethodCall) { writer.print(getImplMethodName()); } else { @@ -330,7 +330,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } @Override - protected int emitArguments(PrintWriter writer) { + protected int emitArguments(final PrintWriter writer) { boolean needComma = false; int numEmitted = 0; @@ -343,7 +343,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } for (int i = 0; i < binding.getNumArguments(); i++) { - JavaType type = binding.getJavaArgumentType(i); + final JavaType type = binding.getJavaArgumentType(i); if (type.isVoid()) { // Make sure this is the only param to the method; if it isn't, // there's something wrong with our parsing of the headers. @@ -399,36 +399,36 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { return binding.getName() + ( useNIODirectOnly ? "0" : "1" ); } - protected String byteOffsetArgName(int i) { + protected String byteOffsetArgName(final int i) { return byteOffsetArgName(getArgumentName(i)); } - protected static String byteOffsetArgName(String s) { + protected static String byteOffsetArgName(final String s) { return s + "_byte_offset"; } - protected String isNIOArgName(int i) { + protected String isNIOArgName(final int i) { return isNIOArgName(binding.getArgumentName(i)); } - protected String isNIOArgName(String s) { + protected String isNIOArgName(final String s) { return s + "_is_direct"; } - protected String byteOffsetArrayArgName(int i) { + protected String byteOffsetArrayArgName(final int i) { return getArgumentName(i) + "_byte_offset_array"; } - protected String offsetArgName(int i) { + protected String offsetArgName(final int i) { return getArgumentName(i) + "_offset"; } @Override - protected void emitBody(PrintWriter writer) { + protected void emitBody(final PrintWriter writer) { if (!emitBody) { writer.println(';'); } else { - MethodBinding mBinding = getBinding(); + final MethodBinding mBinding = getBinding(); writer.println(" {"); writer.println(); if (isUnimplemented) { @@ -443,14 +443,14 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } } - protected void emitPrologueOrEpilogue(List<String> code, PrintWriter writer) { + protected void emitPrologueOrEpilogue(final List<String> code, final PrintWriter writer) { if (code != null) { - String[] argumentNames = argumentNameArray(); - for (String str : code) { + final String[] argumentNames = argumentNameArray(); + for (final String str : code) { try { - MessageFormat fmt = new MessageFormat(str); + final MessageFormat fmt = new MessageFormat(str); writer.println(" " + fmt.format(argumentNames)); - } catch (IllegalArgumentException e) { + } catch (final IllegalArgumentException e) { // (Poorly) handle case where prologue / epilogue contains blocks of code with braces writer.println(" " + str); } @@ -458,19 +458,19 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } } - protected void emitPreCallSetup(MethodBinding binding, PrintWriter writer) { + protected void emitPreCallSetup(final MethodBinding binding, final PrintWriter writer) { emitArrayLengthAndNIOBufferChecks(binding, writer); emitCompoundArrayCopies(binding, writer); } - protected void emitArrayLengthAndNIOBufferChecks(MethodBinding binding, PrintWriter writer) { + protected void emitArrayLengthAndNIOBufferChecks(final MethodBinding binding, final PrintWriter writer) { // Check lengths of any incoming arrays if necessary for (int i = 0; i < binding.getNumArguments(); i++) { final Type type = binding.getCArgumentType(i); final JavaType javaType = binding.getJavaArgumentType(i); if ( type.isArray() ) { // FIXME: Compound and Compound-Arrays // Simply add a range check upfront - ArrayType arrayType = type.asArray(); + final ArrayType arrayType = type.asArray(); if (javaType.isNIOBuffer()) { writer.println(" if ( Buffers.remainingElem("+getArgumentName(i)+") < " + arrayType.getLength() + ")"); } else { @@ -496,8 +496,8 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } } else if (javaType.isNIOBufferArray()) { // All buffers passed down in an array of NIO buffers must be direct - String argName = getArgumentName(i); - String arrayName = byteOffsetArrayArgName(i); + final String argName = getArgumentName(i); + final String arrayName = byteOffsetArrayArgName(i); writer.println(" final int[] " + arrayName + " = new int[" + argName + ".length];"); // Check direct buffer properties of all buffers within writer.println(" if (" + argName + " != null) {"); @@ -513,8 +513,8 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { writer.println(" }"); writer.println(" }"); } else if (javaType.isPrimitiveArray()) { - String argName = getArgumentName(i); - String offsetArg = offsetArgName(i); + final String argName = getArgumentName(i); + final String offsetArg = offsetArgName(i); writer.println(" if(" + argName + " != null && " + argName + ".length <= " + offsetArg + ")"); writer.print (" throw new " + getRuntimeExceptionType()); writer.println("(\"array offset argument \\\"" + offsetArg + "\\\" (\" + " + offsetArg + @@ -523,16 +523,16 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } } - protected void emitCompoundArrayCopies(MethodBinding binding, PrintWriter writer) { + protected void emitCompoundArrayCopies(final MethodBinding binding, final PrintWriter writer) { // If the method binding uses outgoing arrays of compound type // wrappers, we need to generate a temporary copy of this array // into a ByteBuffer[] for processing by the native code if (binding.signatureUsesArraysOfCompoundTypeWrappers()) { for (int i = 0; i < binding.getNumArguments(); i++) { - JavaType javaType = binding.getJavaArgumentType(i); + final JavaType javaType = binding.getJavaArgumentType(i); if (javaType.isArrayOfCompoundTypeWrappers()) { - String argName = getArgumentName(i); - String tempArrayName = argName + COMPOUND_ARRAY_SUFFIX; + final String argName = getArgumentName(i); + final String tempArrayName = argName + COMPOUND_ARRAY_SUFFIX; writer.println(" final ByteBuffer[] " + tempArrayName + " = new ByteBuffer[" + argName + ".length];"); writer.println(" for (int _ctr = 0; _ctr < + " + argName + ".length; _ctr++) {"); writer.println(" " + javaType.getName() + " _tmp = " + argName + "[_ctr];"); @@ -543,7 +543,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } } - protected void emitCall(MethodBinding binding, PrintWriter writer) { + protected void emitCall(final MethodBinding binding, final PrintWriter writer) { writer.print(getImplMethodName()); writer.print("("); emitCallArguments(binding, writer); @@ -551,9 +551,9 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } - protected void emitReturnVariableSetupAndCall(MethodBinding binding, PrintWriter writer) { + protected void emitReturnVariableSetupAndCall(final MethodBinding binding, final PrintWriter writer) { writer.print(" "); - JavaType returnType = binding.getJavaReturnType(); + final JavaType returnType = binding.getJavaReturnType(); boolean needsResultAssignment = false; if (!returnType.isVoid()) { @@ -592,7 +592,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } } - protected int emitCallArguments(MethodBinding binding, PrintWriter writer) { + protected int emitCallArguments(final MethodBinding binding, final PrintWriter writer) { boolean needComma = false; int numArgsEmitted = 0; @@ -604,7 +604,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { ++numArgsEmitted; } for (int i = 0; i < binding.getNumArguments(); i++) { - JavaType type = binding.getJavaArgumentType(i); + final JavaType type = binding.getJavaArgumentType(i); if (type.isJNIEnv() || binding.isArgumentThisPointer(i)) { // Don't need to expose these at the Java level continue; @@ -699,15 +699,15 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { return numArgsEmitted; } - protected void emitPostCallCleanup(MethodBinding binding, PrintWriter writer) { + protected void emitPostCallCleanup(final MethodBinding binding, final PrintWriter writer) { if (binding.signatureUsesArraysOfCompoundTypeWrappers()) { // For each such array, we need to take the ByteBuffer[] that // came back from the C method invocation and wrap the // ByteBuffers back into the wrapper types for (int i = 0; i < binding.getNumArguments(); i++) { - JavaType javaArgType = binding.getJavaArgumentType(i); + final JavaType javaArgType = binding.getJavaArgumentType(i); if ( javaArgType.isArrayOfCompoundTypeWrappers() && !isBaseTypeConst(javaArgType.getElementCType()) ) { - String argName = binding.getArgumentName(i); + final String argName = binding.getArgumentName(i); writer.println(" for (int _ctr = 0; _ctr < " + argName + ".length; _ctr++) {"); writer.println(" if ((" + argName + "[_ctr] == null && " + argName + COMPOUND_ARRAY_SUFFIX + "[_ctr] == null) ||"); writer.println(" (" + argName + "[_ctr] != null && " + argName + "[_ctr].getBuffer() == " + argName + COMPOUND_ARRAY_SUFFIX + "[_ctr])) {"); @@ -725,8 +725,8 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } } - protected void emitCallResultReturn(MethodBinding binding, PrintWriter writer) { - JavaType returnType = binding.getJavaReturnType(); + protected void emitCallResultReturn(final MethodBinding binding, final PrintWriter writer) { + final JavaType returnType = binding.getJavaReturnType(); if (returnType.isCompoundTypeWrapper()) { // Details are handled in JavaEmitter's struct handling! @@ -749,7 +749,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } else if (getBinding().getCReturnType().pointerDepth() == 1 && returnType.isNIOLongBuffer()) { writer.println(" return _res.asLongBuffer();"); } else { - String returnTypeName = returnType.getName().substring("java.nio.".length()); + final String returnTypeName = returnType.getName().substring("java.nio.".length()); writer.println(" return _res.as" + returnTypeName + "();"); } } else { @@ -770,7 +770,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } protected String[] argumentNameArray() { - String[] argumentNames = new String[binding.getNumArguments()]; + final String[] argumentNames = new String[binding.getNumArguments()]; for (int i = 0; i < binding.getNumArguments(); i++) { argumentNames[i] = getArgumentName(i); if (binding.getJavaArgumentType(i).isPrimitiveArray()) { @@ -793,7 +793,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { final StringBuilder sb = new StringBuilder(); final String methodName = binding.getName(); final List<String> methodDocs = cfg.javadocForMethod(methodName); - for (Iterator<String> iter = methodDocs.iterator(); iter.hasNext(); ) { + for (final Iterator<String> iter = methodDocs.iterator(); iter.hasNext(); ) { sb.append(JavaConfiguration.NEWLINE).append(getBaseIndentString()).append(iter.next()); } if( methodDocs.size() > 0 ) { @@ -813,7 +813,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { */ protected class DefaultCommentEmitter implements CommentEmitter { @Override - public void emit(FunctionEmitter emitter, PrintWriter writer) { + public void emit(final FunctionEmitter emitter, final PrintWriter writer) { emitBeginning(emitter, writer); emitBindingCSignature(((JavaMethodBindingEmitter)emitter).getBinding(), writer); final String arrayLengthExpr = getReturnedArrayLengthComment(); @@ -822,28 +822,28 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { } emitEnding(emitter, writer); } - protected void emitBeginning(FunctionEmitter emitter, PrintWriter writer) { + protected void emitBeginning(final FunctionEmitter emitter, final PrintWriter writer) { writer.print("Entry point to C language function: "); } - protected void emitBindingCSignature(MethodBinding binding, PrintWriter writer) { + protected void emitBindingCSignature(final MethodBinding binding, final PrintWriter writer) { writer.print("<code> "); writer.print(binding.getCSymbol().toString(tagNativeBinding)); writer.print(" </code> "); } - protected void emitEnding(FunctionEmitter emitter, PrintWriter writer) { + protected void emitEnding(final FunctionEmitter emitter, final PrintWriter writer) { // If argument type is a named enum, then emit a comment detailing the // acceptable values of that enum. // If we're emitting a direct buffer variant only, then declare // that the NIO buffer arguments must be direct. - MethodBinding binding = ((JavaMethodBindingEmitter)emitter).getBinding(); + final MethodBinding binding = ((JavaMethodBindingEmitter)emitter).getBinding(); for (int i = 0; i < binding.getNumArguments(); i++) { - Type type = binding.getCArgumentType(i); - JavaType javaType = binding.getJavaArgumentType(i); + final Type type = binding.getCArgumentType(i); + final JavaType javaType = binding.getJavaArgumentType(i); // don't emit param comments for anonymous enums, since we can't // distinguish between the values found within multiple anonymous // enums in the same C translation unit. if (type.isEnum() && !HeaderParser.ANONYMOUS_ENUM_NAME.equals(type.getName())) { - EnumType enumType = (EnumType)type; + final EnumType enumType = (EnumType)type; writer.println(); writer.print(emitter.getBaseIndentString()); writer.print(" "); @@ -874,7 +874,7 @@ public class JavaMethodBindingEmitter extends FunctionEmitter { protected class InterfaceCommentEmitter extends JavaMethodBindingEmitter.DefaultCommentEmitter { @Override - protected void emitBeginning(FunctionEmitter emitter, PrintWriter writer) { + protected void emitBeginning(final FunctionEmitter emitter, final PrintWriter writer) { writer.print("Interface to C language function: <br> "); } } diff --git a/src/java/com/jogamp/gluegen/JavaType.java b/src/java/com/jogamp/gluegen/JavaType.java index 9091588..87804bd 100644 --- a/src/java/com/jogamp/gluegen/JavaType.java +++ b/src/java/com/jogamp/gluegen/JavaType.java @@ -75,11 +75,11 @@ public class JavaType { private static JavaType nioByteBufferArrayType; @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if ((arg == null) || (!(arg instanceof JavaType))) { return false; } - JavaType t = (JavaType) arg; + final JavaType t = (JavaType) arg; return (this == t || (t.clazz == clazz && ((structName == null ? t.structName == null : structName.equals(t.structName)) || @@ -111,21 +111,21 @@ public class JavaType { can be used to represent arrays of primitive values or Strings; the emitters understand how to perform proper conversion from the corresponding C type. */ - public static JavaType createForClass(Class<?> clazz) { + public static JavaType createForClass(final Class<?> clazz) { return new JavaType(clazz); } /** Creates a JavaType corresponding to the specified C CompoundType name; for example, if "Foo" is supplied, then this JavaType represents a "Foo *" by way of a StructAccessor. */ - public static JavaType createForCStruct(String name) { + public static JavaType createForCStruct(final String name) { return new JavaType(name); } /** Creates a JavaType corresponding to an array of the given element type. This is used to represent arrays of "Foo **" which should be mapped to Foo[] in Java. */ - public static JavaType createForCArray(Type elementType) { + public static JavaType createForCArray(final Type elementType) { return new JavaType(elementType); } @@ -218,7 +218,7 @@ public class JavaType { public static JavaType forNIOByteBufferArrayClass() { if (nioByteBufferArrayType == null) { - ByteBuffer[] tmp = new ByteBuffer[0]; + final ByteBuffer[] tmp = new ByteBuffer[0]; nioByteBufferArrayType = createForClass(tmp.getClass()); } return nioByteBufferArrayType; @@ -307,7 +307,7 @@ public class JavaType { return "jobjectArray /*elements are String*/"; } - Class<?> elementType = clazz.getComponentType(); + final Class<?> elementType = clazz.getComponentType(); if (isNIOBufferArray()) { return "jobjectArray /*elements are " + elementType.getName() + "*/"; @@ -563,7 +563,7 @@ public class JavaType { * Constructs a representation for a type corresponding to the given Class * argument. */ - private JavaType(Class<?> clazz) { + private JavaType(final Class<?> clazz) { this.primitivePointerType = null; this.clazz = clazz; this.structName = null; @@ -571,7 +571,7 @@ public class JavaType { } /** Constructs a type representing a named C struct. */ - private JavaType(String structName) { + private JavaType(final String structName) { this.primitivePointerType = null; this.clazz = null; this.structName = structName; @@ -580,7 +580,7 @@ public class JavaType { /** Constructs a type representing a pointer to a C primitive (integer, floating-point, or void pointer) type. */ - private JavaType(C_PTR primitivePointerType) { + private JavaType(final C_PTR primitivePointerType) { this.primitivePointerType = primitivePointerType; this.clazz = null; this.structName = null; @@ -588,7 +588,7 @@ public class JavaType { } /** Constructs a type representing an array of C pointers. */ - private JavaType(Type elementType) { + private JavaType(final Type elementType) { this.primitivePointerType = null; this.clazz = null; this.structName = null; @@ -596,7 +596,7 @@ public class JavaType { } /** clone only */ - private JavaType(C_PTR primitivePointerType, Class<?> clazz, String name, Type elementType) { + private JavaType(final C_PTR primitivePointerType, final Class<?> clazz, final String name, final Type elementType) { this.primitivePointerType = primitivePointerType; this.clazz = clazz; this.structName = name; @@ -604,7 +604,7 @@ public class JavaType { } private String arrayName(Class<?> clazz) { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); int arrayCount = 0; while (clazz.isArray()) { ++arrayCount; @@ -618,7 +618,7 @@ public class JavaType { } private String arrayDescriptor(Class<?> clazz) { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); while (clazz.isArray()) { buf.append("["); clazz = clazz.getComponentType(); @@ -627,7 +627,7 @@ public class JavaType { return buf.toString(); } - private String descriptor(Class<?> clazz) { + private String descriptor(final Class<?> clazz) { if (clazz.isPrimitive()) { if (clazz == Boolean.TYPE) return "Z"; if (clazz == Byte.TYPE) return "B"; @@ -645,7 +645,7 @@ public class JavaType { return descriptor(clazz.getName()); } - private String descriptor(String referenceTypeName) { + private String descriptor(final String referenceTypeName) { return "L" + referenceTypeName.replace('.', '/') + ";"; } } diff --git a/src/java/com/jogamp/gluegen/Logging.java b/src/java/com/jogamp/gluegen/Logging.java index 4ed4dba..40eadcb 100644 --- a/src/java/com/jogamp/gluegen/Logging.java +++ b/src/java/com/jogamp/gluegen/Logging.java @@ -55,7 +55,7 @@ public class Logging { level = Level.WARNING; } - ConsoleHandler handler = new ConsoleHandler() { + final ConsoleHandler handler = new ConsoleHandler() { @Override public java.util.logging.Formatter getFormatter() { return new PlainLogFormatter(); @@ -64,7 +64,7 @@ public class Logging { handler.setFormatter(new PlainLogFormatter()); handler.setLevel(level); - Logger rootPackageLogger = Logger.getLogger(packageName); + final Logger rootPackageLogger = Logger.getLogger(packageName); rootPackageLogger.setUseParentHandlers(false); rootPackageLogger.setLevel(level); rootPackageLogger.addHandler(handler); @@ -77,8 +77,8 @@ public class Logging { private static class PlainLogFormatter extends Formatter { @Override - public String format(LogRecord record) { - StringBuilder sb = new StringBuilder(128); + public String format(final LogRecord record) { + final StringBuilder sb = new StringBuilder(128); sb.append("[").append(record.getLevel()).append(' ').append(record.getSourceClassName()).append("]: "); sb.append(formatMessage(record)).append("\n"); return sb.toString(); diff --git a/src/java/com/jogamp/gluegen/MethodBinding.java b/src/java/com/jogamp/gluegen/MethodBinding.java index 53f6c7d..93c55d5 100644 --- a/src/java/com/jogamp/gluegen/MethodBinding.java +++ b/src/java/com/jogamp/gluegen/MethodBinding.java @@ -78,7 +78,7 @@ public class MethodBinding { * argument, including the java return type and java argument * types. It's safe to modify this binding after construction. */ - public MethodBinding(MethodBinding bindingToCopy) { + public MethodBinding(final MethodBinding bindingToCopy) { this.sym = bindingToCopy.sym; this.renamedMethodName = bindingToCopy.renamedMethodName; @@ -102,26 +102,26 @@ public class MethodBinding { } /** Constructor for calling a C function. */ - public MethodBinding(FunctionSymbol sym) { + public MethodBinding(final FunctionSymbol sym) { this.sym = sym; this.aliasedNames = new HashSet<String>(); } /** Constructor for calling a function pointer contained in a struct. */ - public MethodBinding(FunctionSymbol sym, JavaType containingType, Type containingCType) { + public MethodBinding(final FunctionSymbol sym, final JavaType containingType, final Type containingCType) { this.sym = sym; this.containingType = containingType; this.containingCType = containingCType; this.aliasedNames = new HashSet<String>(); } - public void setJavaReturnType(JavaType type) { + public void setJavaReturnType(final JavaType type) { javaReturnType = type; computedSignatureProperties = false; } - public void addJavaArgumentType(JavaType type) { + public void addJavaArgumentType(final JavaType type) { if (javaArgumentTypes == null) { javaArgumentTypes = new ArrayList<JavaType>(); } @@ -137,7 +137,7 @@ public class MethodBinding { return sym.getNumArguments(); } - public JavaType getJavaArgumentType(int i) { + public JavaType getJavaArgumentType(final int i) { return javaArgumentTypes.get(i); } @@ -145,7 +145,7 @@ public class MethodBinding { return sym.getReturnType(); } - public Type getCArgumentType(int i) { + public Type getCArgumentType(final int i) { return sym.getArgumentType(i); } @@ -158,7 +158,7 @@ public class MethodBinding { position. Note that it is currently not guaranteed that there are no namespace clashes with these fabricated argument names. */ - public String getArgumentName(int i) { + public String getArgumentName(final int i) { final String ret = sym.getArgumentName(i); if ( null != ret ) { return ret; @@ -179,14 +179,14 @@ public class MethodBinding { } /** Supports renaming C function in Java binding. */ - public void renameMethodName(String name) { + public void renameMethodName(final String name) { if (null != name) { renamedMethodName = name; aliasedNames.add(sym.getName()); } } - public void addAliasedName(String name) { + public void addAliasedName(final String name) { aliasedNames.add(name); } @@ -197,9 +197,9 @@ public class MethodBinding { /** Creates a new MethodBinding replacing the specified Java argument type with a new argument type. If argumentNumber is less than 0 then replaces the return type. */ - public MethodBinding replaceJavaArgumentType(int argumentNumber, JavaType newArgType) { + public MethodBinding replaceJavaArgumentType(final int argumentNumber, final JavaType newArgType) { - MethodBinding binding = new MethodBinding(this); + final MethodBinding binding = new MethodBinding(this); binding.javaArgumentTypes = null; if (argumentNumber < 0) { binding.setJavaReturnType(newArgType); @@ -364,7 +364,7 @@ public class MethodBinding { signatureUsesNIO = true; } - Type cRetType = sym.getReturnType(); + final Type cRetType = sym.getReturnType(); if (cRetType.isArray()) { // Needs checking of array lengths signatureUsesCArrays = true; @@ -382,8 +382,8 @@ public class MethodBinding { } for (int i = 0; i < getNumArguments(); i++) { - JavaType javaArgType = getJavaArgumentType(i); - Type cArgType = getCArgumentType(i); + final JavaType javaArgType = getJavaArgumentType(i); + final Type cArgType = getCArgumentType(i); if (javaArgType.isCompoundTypeWrapper()) { // Needs unwrapping of accessors signatureUsesCompoundTypeWrappers = true; @@ -469,7 +469,7 @@ public class MethodBinding { public void findThisPointer() { clearThisPointer(); for (int i = 0; i < getNumArguments(); i++) { - JavaType arg = getJavaArgumentType(i); + final JavaType arg = getJavaArgumentType(i); if (arg.equals(containingType)) { thisPointerIndex = i; break; @@ -488,11 +488,11 @@ public class MethodBinding { /** Indicates whether the <i>i</i>th argument to this MethodBinding is actually a "this" pointer. */ - public boolean isArgumentThisPointer(int i) { + public boolean isArgumentThisPointer(final int i) { return (thisPointerIndex == i); } @Override - public boolean equals(Object obj) { + public boolean equals(final Object obj) { if (obj == this) { return true; } @@ -501,7 +501,7 @@ public class MethodBinding { return false; } - MethodBinding other = (MethodBinding)obj; + final MethodBinding other = (MethodBinding)obj; if ( !getName().equals(other.getName()) || !sym.getType().equals(other.sym.getType()) ) { return false; } if (!(javaReturnType.equals(other.getJavaReturnType()))) { return false; } @@ -515,8 +515,8 @@ public class MethodBinding { } for (int i = 0; i < javaArgumentTypes.size(); ++i) { - Object typeThis = javaArgumentTypes.get(i); - Object typeOther = other.getJavaArgumentType(i); + final Object typeThis = javaArgumentTypes.get(i); + final Object typeOther = other.getJavaArgumentType(i); if (!(typeThis.equals(typeOther))) { return false; } @@ -527,7 +527,7 @@ public class MethodBinding { @Override public int hashCode() { - StringBuilder buf = new StringBuilder(200); + final StringBuilder buf = new StringBuilder(200); buf.append(getName()); buf.append(sym.getType().getName(true)); buf.append(getJavaReturnType().getName()); @@ -536,7 +536,7 @@ public class MethodBinding { } for (int i = 0; i < getNumArguments(); i++) { - JavaType type = getJavaArgumentType(i); + final JavaType type = getJavaArgumentType(i); if (type.isVoid()) { // Make sure this is the only param to the method; if it isn't, // there's something wrong with our parsing of the headers. @@ -552,14 +552,14 @@ public class MethodBinding { /** Returns the signature of this binding. */ @Override public String toString() { - StringBuilder buf = new StringBuilder(200); + final StringBuilder buf = new StringBuilder(200); buf.append(getJavaReturnType().getName()); buf.append(' '); buf.append(getName()); buf.append('('); boolean needComma = false; for (int i = 0; i < getNumArguments(); i++) { - JavaType type = getJavaArgumentType(i); + final JavaType type = getJavaArgumentType(i); if (type.isVoid()) { // Make sure this is the only param to the method; if it isn't, // there's something wrong with our parsing of the headers. @@ -588,9 +588,9 @@ public class MethodBinding { internal format) of this MethodBinding as it will be emitted. This is used to disambiguate between overloadings when manually specifying prologue and epilogue code, for example. */ - public String getDescriptor(boolean forImplementingMethodCall, - boolean eraseBufferAndArrayTypes) { - StringBuilder buf = new StringBuilder(); + public String getDescriptor(final boolean forImplementingMethodCall, + final boolean eraseBufferAndArrayTypes) { + final StringBuilder buf = new StringBuilder(); buf.append('('); @@ -600,7 +600,7 @@ public class MethodBinding { } for (int i = 0; i < getNumArguments(); i++) { - JavaType type = getJavaArgumentType(i); + final JavaType type = getJavaArgumentType(i); if (type.isVoid()) { // Make sure this is the only param to the method; if it isn't, // there's something wrong with our parsing of the headers. @@ -643,7 +643,7 @@ public class MethodBinding { return buf.toString(); } - protected String erasedTypeDescriptor(JavaType type, boolean eraseBufferAndArrayTypes, boolean skipBuffers) { + protected String erasedTypeDescriptor(final JavaType type, final boolean eraseBufferAndArrayTypes, final boolean skipBuffers) { if (eraseBufferAndArrayTypes) { if (type.isNIOBuffer() || type.isPrimitiveArray()) { diff --git a/src/java/com/jogamp/gluegen/ReferencedStructs.java b/src/java/com/jogamp/gluegen/ReferencedStructs.java index 50c39b8..d06d47f 100644 --- a/src/java/com/jogamp/gluegen/ReferencedStructs.java +++ b/src/java/com/jogamp/gluegen/ReferencedStructs.java @@ -55,11 +55,11 @@ public class ReferencedStructs implements TypeVisitor { } @Override - public void visitType(Type t) { + public void visitType(final Type t) { if (t.isPointer()) { - PointerType p = t.asPointer(); + final PointerType p = t.asPointer(); if (p.hasTypedefedName()) { - CompoundType c = p.getTargetType().asCompound(); + final CompoundType c = p.getTargetType().asCompound(); if (c != null && c.getName() == null) { // This otherwise-unnamed CompoundType is referred to by a // PointerType that has a typedef name. Assume that it is diff --git a/src/java/com/jogamp/gluegen/TypeInfo.java b/src/java/com/jogamp/gluegen/TypeInfo.java index f5db353..d89ac79 100644 --- a/src/java/com/jogamp/gluegen/TypeInfo.java +++ b/src/java/com/jogamp/gluegen/TypeInfo.java @@ -43,12 +43,12 @@ package com.jogamp.gluegen; /** Utility class for handling Opaque directives for JavaEmitter. */ public class TypeInfo { - private String name; - private int pointerDepth; - private JavaType javaType; + private final String name; + private final int pointerDepth; + private final JavaType javaType; private TypeInfo next; - public TypeInfo(String name, int pointerDepth, JavaType javaType) { + public TypeInfo(final String name, final int pointerDepth, final JavaType javaType) { this.name = name; this.pointerDepth = pointerDepth; this.javaType = javaType; @@ -57,12 +57,12 @@ public class TypeInfo { public String name() { return name; } public int pointerDepth() { return pointerDepth; } public JavaType javaType() { return javaType; } - public void setNext(TypeInfo info) { this.next = info; } + public void setNext(final TypeInfo info) { this.next = info; } public TypeInfo next() { return next; } @Override public String toString() { - StringBuilder buf = new StringBuilder("TypeInfo: "); + final StringBuilder buf = new StringBuilder("TypeInfo: "); buf.append(name); buf.append(" pointerDepth "); buf.append(pointerDepth); diff --git a/src/java/com/jogamp/gluegen/ant/GlueGenTask.java b/src/java/com/jogamp/gluegen/ant/GlueGenTask.java index a3d134f..dd57365 100644 --- a/src/java/com/jogamp/gluegen/ant/GlueGenTask.java +++ b/src/java/com/jogamp/gluegen/ant/GlueGenTask.java @@ -92,7 +92,7 @@ public class GlueGenTask extends Task * <p>The {@link org.apache.tools.ant.types.CommandlineJava} that is used * to execute {@link com.jogamp.gluegen.GlueGen}.</p> */ - private CommandlineJava gluegenCommandline; + private final CommandlineJava gluegenCommandline; // ========================================================================= /** @@ -128,7 +128,7 @@ public class GlueGenTask extends Task /** * <p>The {@link org.apache.tools.ant.types.FileSet} of includes.</p> */ - private FileSet includeSet = new FileSet(); + private final FileSet includeSet = new FileSet(); /** * <p>Because a {@link org.apache.tools.ant.types.FileSet} will include @@ -143,7 +143,7 @@ public class GlueGenTask extends Task * fashions.</p> */ // FIXME: rename to listXXXX - private List<AbstractFileSet> setOfIncludeSets = new LinkedList<AbstractFileSet>(); + private final List<AbstractFileSet> setOfIncludeSets = new LinkedList<AbstractFileSet>(); /** * <p>Comma separated list of literal directories to include. This is to get around the @@ -175,7 +175,7 @@ public class GlueGenTask extends Task /** * <p>Set the debug flag (optional). This is called by ANT.</p> */ - public void setDebug(boolean debug) + public void setDebug(final boolean debug) { log( ("Setting debug flag: " + debug), Project.MSG_VERBOSE); this.debug=debug; @@ -184,7 +184,7 @@ public class GlueGenTask extends Task /** * <p>Set the dumpCPP flag (optional). This is called by ANT.</p> */ - public void setDumpCPP(boolean dumpCPP) + public void setDumpCPP(final boolean dumpCPP) { log( ("Setting dumpCPP flag: " + dumpCPP), Project.MSG_VERBOSE); this.dumpCPP=dumpCPP; @@ -195,7 +195,7 @@ public class GlueGenTask extends Task * * @param outputRootDir the optional output root dir */ - public void setOutputRootDir(String outputRootDir) + public void setOutputRootDir(final String outputRootDir) { log( ("Setting output root dir: " + outputRootDir), Project.MSG_VERBOSE); this.outputRootDir=outputRootDir; @@ -206,7 +206,7 @@ public class GlueGenTask extends Task * * @param emitter the name of the emitter class */ - public void setEmitter(String emitter) + public void setEmitter(final String emitter) { log( ("Setting emitter class name to: " + emitter), Project.MSG_VERBOSE); this.emitter = emitter; @@ -217,7 +217,7 @@ public class GlueGenTask extends Task * * @param configuration the name of the configuration file */ - public void setConfig(String configuration) + public void setConfig(final String configuration) { log( ("Setting configuration file name to: " + configuration), Project.MSG_VERBOSE); @@ -229,7 +229,7 @@ public class GlueGenTask extends Task * * @param sourceFile the name of the source file */ - public void setSrc(String sourceFile) + public void setSrc(final String sourceFile) { log( ("Setting source file name to: " + sourceFile), Project.MSG_VERBOSE); this.sourceFile = sourceFile; @@ -241,7 +241,7 @@ public class GlueGenTask extends Task * * @param commaSeparatedIncludes the comma separated directories to include */ - public void setLiteralInclude(String commaSeparatedIncludes) + public void setLiteralInclude(final String commaSeparatedIncludes) { this.literalIncludes = commaSeparatedIncludes.trim(); } @@ -276,7 +276,7 @@ public class GlueGenTask extends Task * * @param includes the string containing the include patterns */ - public void setIncludes(String includes) + public void setIncludes(final String includes) { usedIncludeSet = true; includeSet.setIncludes(includes); @@ -312,7 +312,7 @@ public class GlueGenTask extends Task * * @param includes the string containing the exclude patterns */ - public void setExcludes(String excludes) + public void setExcludes(final String excludes) { usedIncludeSet = true; includeSet.setExcludes(excludes); @@ -327,7 +327,7 @@ public class GlueGenTask extends Task * @throws BuildException if the specified <code>Reference</code> is not * either a <code>FileSet</code> or <code>DirSet</code> */ -public void setIncludeRefid(Reference reference) { +public void setIncludeRefid(final Reference reference) { // ensure that the referenced object is either a FileSet or DirSet final Object referencedObject = reference.getReferencedObject(getProject()); if (referencedObject instanceof FileSet) { @@ -348,7 +348,7 @@ public void setIncludeRefid(Reference reference) { * * @param dirset the <code>DirSet</code> to be added */ - public void addDirset(DirSet dirset) + public void addDirset(final DirSet dirset) { setOfIncludeSets.add(dirset); } @@ -426,7 +426,7 @@ public void setIncludeRefid(Reference reference) { * @return <code>true</code> if the string is valid. <code>false</code> * otherwise. */ - private boolean isValid(String string) + private boolean isValid(final String string) { // check for null if(string == null) @@ -486,12 +486,12 @@ public void setIncludeRefid(Reference reference) { // iterate over all include sets and add their directories to the // list of included directories. final List<String> includedDirectories = new LinkedList<String>(); - for (Iterator<AbstractFileSet> includes = setOfIncludeSets.iterator(); includes.hasNext();) + for (final Iterator<AbstractFileSet> includes = setOfIncludeSets.iterator(); includes.hasNext();) { // get the included set and based on its type add the directories // to includedDirectories - AbstractFileSet include = includes.next(); - DirectoryScanner directoryScanner = include.getDirectoryScanner(getProject()); + final AbstractFileSet include = includes.next(); + final DirectoryScanner directoryScanner = include.getDirectoryScanner(getProject()); final String[] directoryDirs = directoryScanner.getIncludedDirectories(); // add the directoryDirs to the includedDirectories @@ -515,9 +515,9 @@ public void setIncludeRefid(Reference reference) { } // add the included directories to the command - for(Iterator<String> includes=includedDirectories.iterator(); includes.hasNext(); ) + for(final Iterator<String> includes=includedDirectories.iterator(); includes.hasNext(); ) { - String directory = includes.next(); + final String directory = includes.next(); gluegenCommandline.createArgument().setValue("-I" + directory); } @@ -530,11 +530,11 @@ public void setIncludeRefid(Reference reference) { * * @throws BuildException */ - private int execute(String[] command) + private int execute(final String[] command) throws BuildException { // create the object that will perform the command execution - Execute execute = new Execute(new LogStreamHandler(this, Project.MSG_INFO, + final Execute execute = new Execute(new LogStreamHandler(this, Project.MSG_INFO, Project.MSG_WARN), null); @@ -547,7 +547,7 @@ public void setIncludeRefid(Reference reference) { try { return execute.execute(); - } catch(IOException ioe) + } catch(final IOException ioe) { throw new BuildException(ioe, location); } diff --git a/src/java/com/jogamp/gluegen/cgram/CSymbolTable.java b/src/java/com/jogamp/gluegen/cgram/CSymbolTable.java index ec2f979..6e00a72 100644 --- a/src/java/com/jogamp/gluegen/cgram/CSymbolTable.java +++ b/src/java/com/jogamp/gluegen/cgram/CSymbolTable.java @@ -8,10 +8,10 @@ import java.util.Enumeration; public class CSymbolTable { /** holds list of scopes */ - private Vector<String> scopeStack; + private final Vector<String> scopeStack; /** table where all defined names are mapped to TNode tree nodes */ - private Hashtable<String, TNode> symTable; + private final Hashtable<String, TNode> symTable; public CSymbolTable() { scopeStack = new Vector<String>(10); @@ -21,7 +21,7 @@ public class CSymbolTable { /** push a new scope onto the scope stack. */ - public void pushScope(String s) { + public void pushScope(final String s) { //System.out.println("push scope:" + s); scopeStack.addElement(s); } @@ -30,7 +30,7 @@ public class CSymbolTable { */ public void popScope() { //System.out.println("pop scope"); - int size = scopeStack.size(); + final int size = scopeStack.size(); if(size > 0) scopeStack.removeElementAt(size - 1); } @@ -38,9 +38,9 @@ public class CSymbolTable { /** return the current scope as a string */ public String currentScopeAsString() { - StringBuilder buf = new StringBuilder(100); + final StringBuilder buf = new StringBuilder(100); boolean first = true; - Enumeration<String> e = scopeStack.elements(); + final Enumeration<String> e = scopeStack.elements(); while(e.hasMoreElements()) { if(first) first = false; @@ -54,15 +54,15 @@ public class CSymbolTable { /** given a name for a type, append it with the current scope. */ - public String addCurrentScopeToName(String name) { - String currScope = currentScopeAsString(); + public String addCurrentScopeToName(final String name) { + final String currScope = currentScopeAsString(); return addScopeToName(currScope, name); } /** given a name for a type, append it with the given scope. MBZ */ - public String addScopeToName(String scope, String name) { + public String addScopeToName(final String scope, final String name) { if(scope == null || scope.length() > 0) return scope + "::" + name; else @@ -70,8 +70,8 @@ public class CSymbolTable { } /** remove one level of scope from name MBZ*/ - public String removeOneLevelScope(String scopeName) { - int index = scopeName.lastIndexOf("::"); + public String removeOneLevelScope(final String scopeName) { + final int index = scopeName.lastIndexOf("::"); if (index > 0) { return scopeName.substring(0,index); } @@ -83,13 +83,13 @@ public class CSymbolTable { /** add a node to the table with it's key as the current scope and the name */ - public TNode add(String name, TNode node) { + public TNode add(final String name, final TNode node) { return symTable.put(addCurrentScopeToName(name),node); } /** lookup a fully scoped name in the symbol table */ - public TNode lookupScopedName(String scopedName) { + public TNode lookupScopedName(final String scopedName) { return symTable.get(scopedName); } @@ -97,7 +97,7 @@ public class CSymbolTable { the current scope. MBZ -- if not found, pop scopes and look again */ - public TNode lookupNameInCurrentScope(String name) { + public TNode lookupNameInCurrentScope(final String name) { String scope = currentScopeAsString(); String scopedName; TNode tnode = null; @@ -116,11 +116,11 @@ public class CSymbolTable { /** convert this table to a string */ @Override public String toString() { - StringBuilder buff = new StringBuilder(300); + final StringBuilder buff = new StringBuilder(300); buff.append("CSymbolTable { \nCurrentScope: " + currentScopeAsString() + "\nDefinedSymbols:\n"); - Enumeration<String> ke = symTable.keys(); - Enumeration<TNode> ve = symTable.elements(); + final Enumeration<String> ke = symTable.keys(); + final Enumeration<TNode> ve = symTable.elements(); while(ke.hasMoreElements()) { buff.append(ke.nextElement().toString()); buff.append(" (").append(TNode.getNameForType(ve.nextElement().getType())).append(")\n"); diff --git a/src/java/com/jogamp/gluegen/cgram/CToken.java b/src/java/com/jogamp/gluegen/cgram/CToken.java index 78fc7f7..9e04c15 100644 --- a/src/java/com/jogamp/gluegen/cgram/CToken.java +++ b/src/java/com/jogamp/gluegen/cgram/CToken.java @@ -9,7 +9,7 @@ public class CToken extends antlr.CommonToken { return source; } - public void setSource(String src) + public void setSource(final String src) { source = src; } @@ -19,7 +19,7 @@ public class CToken extends antlr.CommonToken { return tokenNumber; } - public void setTokenNumber(int i) + public void setTokenNumber(final int i) { tokenNumber = i; } diff --git a/src/java/com/jogamp/gluegen/cgram/Define.java b/src/java/com/jogamp/gluegen/cgram/Define.java index 1b23346..797cf6f 100644 --- a/src/java/com/jogamp/gluegen/cgram/Define.java +++ b/src/java/com/jogamp/gluegen/cgram/Define.java @@ -43,10 +43,10 @@ package com.jogamp.gluegen.cgram; in string form.) */ public class Define { - private String name; - private String value; + private final String name; + private final String value; - public Define(String name, String value) { + public Define(final String name, final String value) { this.name = name; this.value = value; } diff --git a/src/java/com/jogamp/gluegen/cgram/LineObject.java b/src/java/com/jogamp/gluegen/cgram/LineObject.java index 31489fc..aee083f 100644 --- a/src/java/com/jogamp/gluegen/cgram/LineObject.java +++ b/src/java/com/jogamp/gluegen/cgram/LineObject.java @@ -14,7 +14,7 @@ class LineObject { super(); } - public LineObject( LineObject lobj ) + public LineObject( final LineObject lobj ) { parent = lobj.getParent(); source = lobj.getSource(); @@ -25,12 +25,12 @@ class LineObject { treatAsC = lobj.getTreatAsC(); } - public LineObject( String src) + public LineObject( final String src) { source = src; } - public void setSource(String src) + public void setSource(final String src) { source = src; } @@ -40,7 +40,7 @@ class LineObject { return source; } - public void setParent(LineObject par) + public void setParent(final LineObject par) { parent = par; } @@ -50,7 +50,7 @@ class LineObject { return parent; } - public void setLine(int l) + public void setLine(final int l) { line = l; } @@ -65,7 +65,7 @@ class LineObject { line++; } - public void setEnteringFile(boolean v) + public void setEnteringFile(final boolean v) { enteringFile = v; } @@ -75,7 +75,7 @@ class LineObject { return enteringFile; } - public void setReturningToFile(boolean v) + public void setReturningToFile(final boolean v) { returningToFile = v; } @@ -85,7 +85,7 @@ class LineObject { return returningToFile; } - public void setSystemHeader(boolean v) + public void setSystemHeader(final boolean v) { systemHeader = v; } @@ -95,7 +95,7 @@ class LineObject { return systemHeader; } - public void setTreatAsC(boolean v) + public void setTreatAsC(final boolean v) { treatAsC = v; } diff --git a/src/java/com/jogamp/gluegen/cgram/PreprocessorInfoChannel.java b/src/java/com/jogamp/gluegen/cgram/PreprocessorInfoChannel.java index 3bc8056..3ab565f 100644 --- a/src/java/com/jogamp/gluegen/cgram/PreprocessorInfoChannel.java +++ b/src/java/com/jogamp/gluegen/cgram/PreprocessorInfoChannel.java @@ -8,14 +8,14 @@ public class PreprocessorInfoChannel int firstValidTokenNumber = 0; int maxTokenNumber = 0; - public void addLineForTokenNumber( Object line, Integer toknum ) + public void addLineForTokenNumber( final Object line, final Integer toknum ) { if ( lineLists.containsKey( toknum ) ) { - Vector<Object> lines = lineLists.get( toknum ); + final Vector<Object> lines = lineLists.get( toknum ); lines.addElement(line); } else { - Vector<Object> lines = new Vector<Object>(); + final Vector<Object> lines = new Vector<Object>(); lines.addElement(line); lineLists.put(toknum, lines); if ( maxTokenNumber < toknum.intValue() ) { @@ -29,16 +29,16 @@ public class PreprocessorInfoChannel return maxTokenNumber; } - public Vector<Object> extractLinesPrecedingTokenNumber( Integer toknum ) + public Vector<Object> extractLinesPrecedingTokenNumber( final Integer toknum ) { - Vector<Object> lines = new Vector<Object>(); + final Vector<Object> lines = new Vector<Object>(); if (toknum == null) return lines; for (int i = firstValidTokenNumber; i < toknum.intValue(); i++){ - Integer inti = new Integer(i); + final Integer inti = new Integer(i); if ( lineLists.containsKey( inti ) ) { - Vector<Object> tokenLineVector = lineLists.get( inti ); + final Vector<Object> tokenLineVector = lineLists.get( inti ); if ( tokenLineVector != null) { - Enumeration<Object> tokenLines = tokenLineVector.elements(); + final Enumeration<Object> tokenLines = tokenLineVector.elements(); while ( tokenLines.hasMoreElements() ) { lines.addElement( tokenLines.nextElement() ); } @@ -53,13 +53,13 @@ public class PreprocessorInfoChannel @Override public String toString() { - StringBuilder sb = new StringBuilder("PreprocessorInfoChannel:\n"); + final StringBuilder sb = new StringBuilder("PreprocessorInfoChannel:\n"); for (int i = 0; i <= maxTokenNumber + 1; i++){ - Integer inti = new Integer(i); + final Integer inti = new Integer(i); if ( lineLists.containsKey( inti ) ) { - Vector<Object> tokenLineVector = lineLists.get( inti ); + final Vector<Object> tokenLineVector = lineLists.get( inti ); if ( tokenLineVector != null) { - Enumeration<Object> tokenLines = tokenLineVector.elements(); + final Enumeration<Object> tokenLines = tokenLineVector.elements(); while ( tokenLines.hasMoreElements() ) { sb.append(inti + ":" + tokenLines.nextElement() + '\n'); } diff --git a/src/java/com/jogamp/gluegen/cgram/TNode.java b/src/java/com/jogamp/gluegen/cgram/TNode.java index 2840d01..a564c54 100644 --- a/src/java/com/jogamp/gluegen/cgram/TNode.java +++ b/src/java/com/jogamp/gluegen/cgram/TNode.java @@ -46,14 +46,14 @@ public class TNode extends CommonAST { /** Set the token vocabulary to a tokentypes class generated by antlr. */ - public static void setTokenVocabulary(String s) { + public static void setTokenVocabulary(final String s) { tokenVocabulary = s; } @Override -public void initialize(Token token) { - CToken tok = (CToken) token; +public void initialize(final Token token) { + final CToken tok = (CToken) token; setText(tok.getText()); setType(tok.getType()); setLineNum(tok.getLine()); @@ -61,8 +61,8 @@ public void initialize(Token token) { setAttribute("tokenNumber", new Integer(tok.getTokenNumber())); } @Override -public void initialize(AST tr) { - TNode t = (TNode) tr; +public void initialize(final AST tr) { + final TNode t = (TNode) tr; setText(t.getText()); setType(t.getType()); setLineNum(t.getLineNum()); @@ -77,7 +77,7 @@ public void initialize(AST tr) { /** Set the token type for this node */ @Override - public void setType(int ttype_) { + public void setType(final int ttype_) { ttype = ttype_; } @@ -89,7 +89,7 @@ public void initialize(AST tr) { /** Set the marker value for this node. This property is a general-use boolean marker. */ - public void setMarker(boolean marker_) { + public void setMarker(final boolean marker_) { marker = marker_; } @@ -103,7 +103,7 @@ public void initialize(AST tr) { /** set an attribute in the attribute table. */ - public void setAttribute(String attrName, Object value) { + public void setAttribute(final String attrName, final Object value) { if(attributes == null) attributes = new Hashtable<String, Object>(7); attributes.put(attrName,value); @@ -112,7 +112,7 @@ public void initialize(AST tr) { /** lookup the attribute name in the attribute table. If the value does not exist, it returns null. */ - public Object getAttribute(String attrName) { + public Object getAttribute(final String attrName) { if(attributes == null) return null; else @@ -145,7 +145,7 @@ public void initialize(AST tr) { } /** Set the line number for this node */ - public void setLineNum(int lineNum_) { + public void setLineNum(final int lineNum_) { lineNum = lineNum_; } @@ -155,13 +155,13 @@ public void initialize(AST tr) { /** Set the token text for this node */ @Override - public void setText(String text_) { + public void setText(final String text_) { text = text_; } /** Returns the text for this node and all children */ public String getAllChildrenText() { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); buf.append(getText()); for (TNode node = (TNode) getFirstChild(); node != null; node = (TNode) node.getNextSibling()) { buf.append(node.getText()); @@ -171,7 +171,7 @@ public void initialize(AST tr) { /** return the last child of this node, or null if there is none */ public TNode getLastChild() { - TNode down = (TNode)getFirstChild(); + final TNode down = (TNode)getFirstChild(); if(down != null) return down.getLastSibling(); else @@ -181,7 +181,7 @@ public void initialize(AST tr) { /** return the last sibling of this node, which is this if the next sibling is null */ public TNode getLastSibling() { - TNode next = (TNode)getNextSibling(); + final TNode next = (TNode)getNextSibling(); if(next != null) return next.getLastSibling(); else @@ -191,7 +191,7 @@ public void initialize(AST tr) { /** return the first sibling of this node, which is this if the prev sibling is null */ public TNode getFirstSibling() { - TNode prev = left; + final TNode prev = left; if(prev != null) return prev.getFirstSibling(); else @@ -210,12 +210,12 @@ public void initialize(AST tr) { if node is null, nothing happens. If the node has siblings, then they are added in as well. */ - public void addSibling(AST node) { + public void addSibling(final AST node) { if(node == null) return; - TNode next = (TNode)right; + final TNode next = (TNode)right; right = (TNode)node; ((TNode)node).left = this; - TNode nodeLastSib = ((TNode)node).getLastSibling(); + final TNode nodeLastSib = ((TNode)node).getLastSibling(); nodeLastSib.right = next; if(next != null) next.left = nodeLastSib; @@ -237,9 +237,9 @@ public void initialize(AST tr) { /** remove this node from the tree, resetting sibling and parent pointers as necessary. This method maintains double-linking */ public void removeSelf() { - TNode parent = up; - TNode prev = left; - TNode next = (TNode)right; + final TNode parent = up; + final TNode prev = left; + final TNode next = (TNode)right; if(parent != null) { parent.down = next; @@ -263,7 +263,7 @@ public void initialize(AST tr) { } /** set the def node for this node */ - public void setDefNode(TNode n) { + public void setDefNode(final TNode n) { defNode = n; } @@ -273,7 +273,7 @@ public void initialize(AST tr) { Marker value is not copied! */ public TNode deepCopy() { - TNode copy = new TNode(); + final TNode copy = new TNode(); copy.ttype = ttype; copy.text = text; copy.lineNum = lineNum; @@ -292,7 +292,7 @@ public void initialize(AST tr) { New tree is doubleLinked, with no parent or left siblings. defNode is not copied */ public TNode deepCopyWithRightSiblings() { - TNode copy = new TNode(); + final TNode copy = new TNode(); copy.ttype = ttype; copy.text = text; copy.lineNum = lineNum; @@ -311,15 +311,15 @@ public void initialize(AST tr) { /** return a short string representation of the node */ @Override public String toString() { - StringBuilder str = new StringBuilder( getNameForType(getType()) + + final StringBuilder str = new StringBuilder( getNameForType(getType()) + "[" + getText() + ", " + "]"); if(this.getLineNum() != 0) str.append(" line:" + (this.getLineNum() ) ); - Enumeration<String> keys = (this.getAttributesTable().keys()); + final Enumeration<String> keys = (this.getAttributesTable().keys()); while (keys.hasMoreElements()) { - String key = keys.nextElement(); + final String key = keys.nextElement(); str.append(" " + key + ":" + (this.getAttribute(key))); } @@ -328,7 +328,7 @@ public void initialize(AST tr) { /** print given tree to System.out */ - public static void printTree(AST t) { + public static void printTree(final AST t) { if (t == null) return; printASTNode(t,0); System.out.print("\n"); @@ -336,7 +336,7 @@ public void initialize(AST tr) { /** protected method that does the work of printing */ - protected static void printASTNode(AST t, int indent) { + protected static void printASTNode(final AST t, final int indent) { AST child1, next; child1 = t.getFirstChild(); @@ -347,7 +347,7 @@ public void initialize(AST tr) { if(child1 != null) System.out.print("("); - String s = t.getText(); + final String s = t.getText(); if(s != null && s.length() > 0) { System.out.print(getNameForType(t.getType())); System.out.print(": \"" + s + "\""); @@ -357,12 +357,12 @@ public void initialize(AST tr) { if(((TNode)t).getLineNum() != 0) System.out.print(" line:" + ((TNode)t).getLineNum() ); - Enumeration<String> keys = ((TNode)t).getAttributesTable().keys(); + final Enumeration<String> keys = ((TNode)t).getAttributesTable().keys(); while (keys.hasMoreElements()) { - String key = keys.nextElement(); + final String key = keys.nextElement(); System.out.print(" " + key + ":" + ((TNode)t).getAttribute(key)); } - TNode def = ((TNode)t).getDefNode(); + final TNode def = ((TNode)t).getDefNode(); if(def != null) System.out.print("[" + getNameForType(def.getType()) + "]"); @@ -385,13 +385,13 @@ public void initialize(AST tr) { /** converts an int tree token type to a name. Does this by reflecting on nsdidl.IDLTreeTokenTypes, and is dependent on how ANTLR 2.00 outputs that class. */ - public static String getNameForType(int t) { + public static String getNameForType(final int t) { try{ - Class<?> c = Class.forName(tokenVocabulary); - Field[] fields = c.getDeclaredFields(); + final Class<?> c = Class.forName(tokenVocabulary); + final Field[] fields = c.getDeclaredFields(); if(t-2 < fields.length) return fields[t-2].getName(); - } catch (Exception e) { System.out.println(e); } + } catch (final Exception e) { System.out.println(e); } return "unfoundtype: " + t; } @@ -399,12 +399,12 @@ public void initialize(AST tr) { /** set up reverse links between this node and its first child and its first sibling, and link those as well */ public void doubleLink() { - TNode right = (TNode)getNextSibling(); + final TNode right = (TNode)getNextSibling(); if(right != null) { right.left = this; right.doubleLink(); } - TNode down = (TNode)getFirstChild(); + final TNode down = (TNode)getFirstChild(); if(down != null) { down.up = this; down.doubleLink(); @@ -413,7 +413,7 @@ public void initialize(AST tr) { /** find first parent of the given type, return null on failure */ - public TNode parentOfType(int type) { + public TNode parentOfType(final int type) { if(up == null) { if(left == null) return null; @@ -427,8 +427,8 @@ public void initialize(AST tr) { /** find the first child of the node of the given type, return null on failure */ - public TNode firstChildOfType(int type) { - TNode down = (TNode)getFirstChild(); + public TNode firstChildOfType(final int type) { + final TNode down = (TNode)getFirstChild(); if(down == null) return null; if(down.getType() == type) @@ -438,8 +438,8 @@ public void initialize(AST tr) { /** find the first sibling of the node of the given type, return null on failure */ - public TNode firstSiblingOfType(int type) { - TNode right = (TNode)getNextSibling(); + public TNode firstSiblingOfType(final int type) { + final TNode right = (TNode)getNextSibling(); if(right == null) return null; if(right.getType() == type) diff --git a/src/java/com/jogamp/gluegen/cgram/TNodeFactory.java b/src/java/com/jogamp/gluegen/cgram/TNodeFactory.java index ff2f1b0..f964438 100644 --- a/src/java/com/jogamp/gluegen/cgram/TNodeFactory.java +++ b/src/java/com/jogamp/gluegen/cgram/TNodeFactory.java @@ -15,8 +15,8 @@ public class TNodeFactory extends ASTFactory { /** Create a new AST node from type and text */ @Override - public AST create(int ttype, String text) { - AST ast = new TNode(); + public AST create(final int ttype, final String text) { + final AST ast = new TNode(); ast.setType(ttype); ast.setText(text); return ast; @@ -24,8 +24,8 @@ public class TNodeFactory extends ASTFactory { /** Create a new AST node from an existing AST node */ @Override - public AST create(AST ast) { - AST newast = new TNode(); + public AST create(final AST ast) { + final AST newast = new TNode(); newast.setType(ast.getType()); newast.setText(ast.getText()); return newast; diff --git a/src/java/com/jogamp/gluegen/cgram/types/ArrayType.java b/src/java/com/jogamp/gluegen/cgram/types/ArrayType.java index 401944b..d867b40 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/ArrayType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/ArrayType.java @@ -50,24 +50,24 @@ public class ArrayType extends MemoryLayoutType implements Cloneable { private final int length; private String computedName; - public ArrayType(Type elementType, SizeThunk sizeInBytes, int length, int cvAttributes) { + public ArrayType(final Type elementType, final SizeThunk sizeInBytes, final int length, final int cvAttributes) { super(elementType.getName() + " *", sizeInBytes, cvAttributes); this.elementType = elementType; this.length = length; } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == this) return true; if (arg == null || (!(arg instanceof ArrayType))) { return false; } - ArrayType t = (ArrayType) arg; + final ArrayType t = (ArrayType) arg; return (super.equals(arg) && elementType.equals(t.elementType) && (length == t.length)); } @Override - public String getName(boolean includeCVAttrs) { + public String getName(final boolean includeCVAttrs) { // Lazy computation of name due to lazy setting of compound type // names during parsing // Note: don't think cvAttributes can be set for array types (unlike pointer types) @@ -97,7 +97,7 @@ public class ArrayType extends MemoryLayoutType implements Cloneable { /** Recompute the size of this array if necessary. This needs to be done when the base element type is a compound type after layouting. */ void recomputeSize() { - ArrayType arrayElementType = getElementType().asArray(); + final ArrayType arrayElementType = getElementType().asArray(); if (arrayElementType != null) { arrayElementType.recomputeSize(); } @@ -109,8 +109,8 @@ public class ArrayType extends MemoryLayoutType implements Cloneable { return toString(null); } - public String toString(String variableName) { - StringBuilder buf = new StringBuilder(); + public String toString(final String variableName) { + final StringBuilder buf = new StringBuilder(); if(elementType.isConst()) { buf.append("const "); } @@ -126,13 +126,13 @@ public class ArrayType extends MemoryLayoutType implements Cloneable { } @Override - public void visit(TypeVisitor arg) { + public void visit(final TypeVisitor arg) { super.visit(arg); elementType.visit(arg); } @Override - Type newCVVariant(int cvAttributes) { + Type newCVVariant(final int cvAttributes) { return new ArrayType(elementType, getSize(), length, cvAttributes); } } diff --git a/src/java/com/jogamp/gluegen/cgram/types/BitType.java b/src/java/com/jogamp/gluegen/cgram/types/BitType.java index 4862749..2644551 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/BitType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/BitType.java @@ -43,11 +43,11 @@ package com.jogamp.gluegen.cgram.types; /** Represents a bitfield in a struct. */ public class BitType extends IntType implements Cloneable { - private IntType underlyingType; - private int sizeInBits; - private int offset; + private final IntType underlyingType; + private final int sizeInBits; + private final int offset; - public BitType(IntType underlyingType, int sizeInBits, int lsbOffset, int cvAttributes) { + public BitType(final IntType underlyingType, final int sizeInBits, final int lsbOffset, final int cvAttributes) { super(underlyingType.getName(), underlyingType.getSize(), underlyingType.isUnsigned(), cvAttributes); this.underlyingType = underlyingType; this.sizeInBits = sizeInBits; @@ -55,12 +55,12 @@ public class BitType extends IntType implements Cloneable { } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == this) return true; if (arg == null || (!(arg instanceof BitType))) { return false; } - BitType t = (BitType) arg; + final BitType t = (BitType) arg; return (super.equals(arg) && underlyingType.equals(t.underlyingType) && (sizeInBits == t.sizeInBits) && (offset == t.offset)); } @@ -80,13 +80,13 @@ public class BitType extends IntType implements Cloneable { } @Override - public void visit(TypeVisitor arg) { + public void visit(final TypeVisitor arg) { super.visit(arg); underlyingType.visit(arg); } @Override - Type newCVVariant(int cvAttributes) { + Type newCVVariant(final int cvAttributes) { return new BitType(underlyingType, sizeInBits, offset, cvAttributes); } } diff --git a/src/java/com/jogamp/gluegen/cgram/types/CompoundType.java b/src/java/com/jogamp/gluegen/cgram/types/CompoundType.java index 803cb50..9716f54 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/CompoundType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/CompoundType.java @@ -55,12 +55,12 @@ public abstract class CompoundType extends MemoryLayoutType implements Cloneable private boolean computedHashcode; private int hashcode; - CompoundType(String name, SizeThunk size, int cvAttributes, String structName) { + CompoundType(final String name, final SizeThunk size, final int cvAttributes, final String structName) { super(name, size, cvAttributes); this.structName = structName; } - public static CompoundType create(String name, SizeThunk size, CompoundTypeKind kind, int cvAttributes) { + public static CompoundType create(final String name, final SizeThunk size, final CompoundTypeKind kind, final int cvAttributes) { switch (kind) { case STRUCT: return new StructType(name, size, cvAttributes); @@ -73,7 +73,7 @@ public abstract class CompoundType extends MemoryLayoutType implements Cloneable @Override public Object clone() { - CompoundType n = (CompoundType) super.clone(); + final CompoundType n = (CompoundType) super.clone(); if(null!=this.fields) { n.fields = new ArrayList<Field>(this.fields); } @@ -99,12 +99,12 @@ public abstract class CompoundType extends MemoryLayoutType implements Cloneable } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == this) return true; if (arg == null || !(arg instanceof CompoundType)) { return false; } - CompoundType t = (CompoundType) arg; + final CompoundType t = (CompoundType) arg; return super.equals(arg) && ((structName == null ? t.structName == null : structName.equals(t.structName)) || (structName != null && structName.equals(t.structName))) && @@ -119,12 +119,12 @@ public abstract class CompoundType extends MemoryLayoutType implements Cloneable /** Sets the struct name of this CompoundType, i.e. the "foo" in the construct "struct foo { ... };". */ - public void setStructName(String structName) { + public void setStructName(final String structName) { this.structName = structName; } @Override - public void setSize(SizeThunk size) { + public void setSize(final SizeThunk size) { super.setSize(size); } @@ -132,7 +132,7 @@ public abstract class CompoundType extends MemoryLayoutType implements Cloneable public CompoundType asCompound() { return this; } ArrayList<Field> getFields() { return fields; } - void setFields(ArrayList<Field> fields) { this.fields = fields; } + void setFields(final ArrayList<Field> fields) { this.fields = fields; } /** Returns the number of fields in this type. */ public int getNumFields() { @@ -140,12 +140,12 @@ public abstract class CompoundType extends MemoryLayoutType implements Cloneable } /** Returns the <i>i</i>th field of this type. */ - public Field getField(int i) { + public Field getField(final int i) { return fields.get(i); } /** Adds a field to this type. */ - public void addField(Field f) { + public void addField(final Field f) { if (bodyParsed) { throw new RuntimeException("Body of this CompoundType has already been parsed; should not be adding more fields"); } @@ -168,7 +168,7 @@ public abstract class CompoundType extends MemoryLayoutType implements Cloneable @Override public String toString() { - String cvAttributesString = getCVAttributesString(); + final String cvAttributesString = getCVAttributesString(); if (getName() != null) { return cvAttributesString + getName(); } else if (getStructName() != null) { @@ -179,16 +179,16 @@ public abstract class CompoundType extends MemoryLayoutType implements Cloneable } @Override - public void visit(TypeVisitor arg) { + public void visit(final TypeVisitor arg) { if (visiting) { return; } try { visiting = true; super.visit(arg); - int n = getNumFields(); + final int n = getNumFields(); for (int i = 0; i < n; i++) { - Field f = getField(i); + final Field f = getField(i); f.getType().visit(arg); } } finally { @@ -206,10 +206,10 @@ public abstract class CompoundType extends MemoryLayoutType implements Cloneable try { visiting = true; - String kind = (isStruct() ? "struct {" : "union {"); - StringBuilder res = new StringBuilder(); + final String kind = (isStruct() ? "struct {" : "union {"); + final StringBuilder res = new StringBuilder(); res.append(kind); - int n = getNumFields(); + final int n = getNumFields(); for (int i = 0; i < n; i++) { res.append(" "); res.append(getField(i)); diff --git a/src/java/com/jogamp/gluegen/cgram/types/CompoundTypeKind.java b/src/java/com/jogamp/gluegen/cgram/types/CompoundTypeKind.java index 62d8d42..d218bb4 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/CompoundTypeKind.java +++ b/src/java/com/jogamp/gluegen/cgram/types/CompoundTypeKind.java @@ -35,7 +35,7 @@ public enum CompoundTypeKind { public final int id; - CompoundTypeKind(int id){ + CompoundTypeKind(final int id){ this.id = id; } } diff --git a/src/java/com/jogamp/gluegen/cgram/types/DoubleType.java b/src/java/com/jogamp/gluegen/cgram/types/DoubleType.java index 278b3d8..de42522 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/DoubleType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/DoubleType.java @@ -42,12 +42,12 @@ package com.jogamp.gluegen.cgram.types; /** Represents a double-word floating-point type (C type "double".) */ public class DoubleType extends PrimitiveType implements Cloneable { - public DoubleType(String name, SizeThunk size, int cvAttributes) { + public DoubleType(final String name, final SizeThunk size, final int cvAttributes) { super(name, size, cvAttributes); } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == this) { return true; } @@ -63,7 +63,7 @@ public class DoubleType extends PrimitiveType implements Cloneable { } @Override - Type newCVVariant(int cvAttributes) { + Type newCVVariant(final int cvAttributes) { return new DoubleType(getName(), getSize(), cvAttributes); } } diff --git a/src/java/com/jogamp/gluegen/cgram/types/EnumType.java b/src/java/com/jogamp/gluegen/cgram/types/EnumType.java index d02388b..0b1193b 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/EnumType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/EnumType.java @@ -54,7 +54,7 @@ public class EnumType extends IntType implements Cloneable { String name; long value; - Enum(String name, long value) { + Enum(final String name, final long value) { this.name = name; this.value = value; } @@ -70,24 +70,24 @@ public class EnumType extends IntType implements Cloneable { private ArrayList<Enum> enums; - public EnumType(String name) { + public EnumType(final String name) { super(name, SizeThunk.LONG, false, CVAttributes.CONST); this.underlyingType = new IntType(name, SizeThunk.LONG, false, CVAttributes.CONST); } - public EnumType(String name, SizeThunk enumSizeInBytes) { + public EnumType(final String name, final SizeThunk enumSizeInBytes) { super(name, enumSizeInBytes, false, CVAttributes.CONST); this.underlyingType = new IntType(name, enumSizeInBytes, false, CVAttributes.CONST); } - protected EnumType(String name, IntType underlyingType, int cvAttributes) { + protected EnumType(final String name, final IntType underlyingType, final int cvAttributes) { super(name, underlyingType.getSize(), underlyingType.isUnsigned(), cvAttributes); this.underlyingType = underlyingType; } @Override public Object clone() { - EnumType n = (EnumType) super.clone(); + final EnumType n = (EnumType) super.clone(); if(null!=this.underlyingType) { n.underlyingType = (IntType) this.underlyingType.clone(); } @@ -98,14 +98,14 @@ public class EnumType extends IntType implements Cloneable { } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == this) { return true; } if (arg == null || (!(arg instanceof EnumType))) { return false; } - EnumType t = (EnumType) arg; + final EnumType t = (EnumType) arg; return (super.equals(arg) && underlyingType.equals(t.underlyingType) && listsEqual(enums, t.enums)); @@ -116,7 +116,7 @@ public class EnumType extends IntType implements Cloneable { return this; } - public void addEnum(String name, long val) { + public void addEnum(final String name, final long val) { if (enums == null) { enums = new ArrayList<Enum>(); } @@ -129,19 +129,19 @@ public class EnumType extends IntType implements Cloneable { } /** Fetch <i>i</i>th (0..getNumEnumerates() - 1) name */ - public String getEnumName(int i) { + public String getEnumName(final int i) { return (enums.get(i)).getName(); } /** Fetch <i>i</i>th (0..getNumEnumerates() - 1) value */ - public long getEnumValue(int i) { + public long getEnumValue(final int i) { return (enums.get(i)).getValue(); } /** Fetch the value of the enumerate with the given name. */ - public long getEnumValue(String name) { + public long getEnumValue(final String name) { for (int i = 0; i < enums.size(); ++i) { - Enum n = (enums.get(i)); + final Enum n = (enums.get(i)); if (n.getName().equals(name)) { return n.getValue(); } @@ -152,7 +152,7 @@ public class EnumType extends IntType implements Cloneable { } /** Does this enum type contain an enumerate with the given name? */ - public boolean containsEnumerate(String name) { + public boolean containsEnumerate(final String name) { for (int i = 0; i < enums.size(); ++i) { if ((enums.get(i)).getName().equals(name)) { return true; @@ -164,9 +164,9 @@ public class EnumType extends IntType implements Cloneable { /** Remove the enumerate with the given name. Returns true if it was found * and removed; false if it was not found. */ - public boolean removeEnumerate(String name) { + public boolean removeEnumerate(final String name) { for (int i = 0; i < enums.size(); ++i) { - Enum e = enums.get(i); + final Enum e = enums.get(i); if (e.getName().equals(name)) { enums.remove(e); return true; @@ -176,14 +176,14 @@ public class EnumType extends IntType implements Cloneable { } @Override - public void visit(TypeVisitor arg) { + public void visit(final TypeVisitor arg) { super.visit(arg); underlyingType.visit(arg); } @Override - Type newCVVariant(int cvAttributes) { - EnumType t = new EnumType(getName(), underlyingType, cvAttributes); + Type newCVVariant(final int cvAttributes) { + final EnumType t = new EnumType(getName(), underlyingType, cvAttributes); t.enums = enums; return t; } diff --git a/src/java/com/jogamp/gluegen/cgram/types/Field.java b/src/java/com/jogamp/gluegen/cgram/types/Field.java index 1c4b4fa..afaeade 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/Field.java +++ b/src/java/com/jogamp/gluegen/cgram/types/Field.java @@ -44,11 +44,11 @@ import com.jogamp.common.os.MachineDescription; /** Represents a field in a struct or union. */ public class Field { - private String name; - private Type type; + private final String name; + private final Type type; private SizeThunk offset; - public Field(String name, Type type, SizeThunk offset) { + public Field(final String name, final Type type, final SizeThunk offset) { this.name = name; this.type = type; this.offset = offset; @@ -60,12 +60,12 @@ public class Field { } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == null || (!(arg instanceof Field))) { return false; } - Field f = (Field) arg; + final Field f = (Field) arg; // Note: don't know how to examine offset any more since it's // implemented in terms of code and they're not canonicalized return (((name != null && name.equals(f.name)) || @@ -84,10 +84,10 @@ public class Field { /** Offset, in bytes, of this field in the containing data structure given the specified MachineDescription. */ - public long getOffset(MachineDescription machDesc) { return offset.computeSize(machDesc); } + public long getOffset(final MachineDescription machDesc) { return offset.computeSize(machDesc); } /** Sets the offset of this field in the containing data structure. */ - public void setOffset(SizeThunk offset) { this.offset = offset; } + public void setOffset(final SizeThunk offset) { this.offset = offset; } @Override public String toString() { @@ -99,7 +99,7 @@ public class Field { } return "" + getType() + " " + getName() + ";"; } else { - FunctionType ft = getType().asPointer().getTargetType().asFunction(); + final FunctionType ft = getType().asPointer().getTargetType().asFunction(); // FIXME: pick up calling convention? return ft.toString(getName(), null, false, true) + ";"; } diff --git a/src/java/com/jogamp/gluegen/cgram/types/FloatType.java b/src/java/com/jogamp/gluegen/cgram/types/FloatType.java index ef1b4b9..d8b0b13 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/FloatType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/FloatType.java @@ -43,12 +43,12 @@ package com.jogamp.gluegen.cgram.types; /** Represents a single-word floating-point type (C type "float".) */ public class FloatType extends PrimitiveType implements Cloneable { - public FloatType(String name, SizeThunk size, int cvAttributes) { + public FloatType(final String name, final SizeThunk size, final int cvAttributes) { super(name, size, cvAttributes); } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == this) { return true; } @@ -62,7 +62,7 @@ public class FloatType extends PrimitiveType implements Cloneable { public FloatType asFloat() { return this; } @Override - Type newCVVariant(int cvAttributes) { + Type newCVVariant(final int cvAttributes) { return new FloatType(getName(), getSize(), cvAttributes); } } diff --git a/src/java/com/jogamp/gluegen/cgram/types/FunctionSymbol.java b/src/java/com/jogamp/gluegen/cgram/types/FunctionSymbol.java index c4802e7..d41f2fd 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/FunctionSymbol.java +++ b/src/java/com/jogamp/gluegen/cgram/types/FunctionSymbol.java @@ -53,10 +53,10 @@ package com.jogamp.gluegen.cgram.types; **/ public class FunctionSymbol { - private String name; - private FunctionType type; + private final String name; + private final FunctionType type; - public FunctionSymbol(String name, FunctionType type) { + public FunctionSymbol(final String name, final FunctionType type) { this.name = name; this.type = type; } @@ -82,18 +82,18 @@ public class FunctionSymbol { /** Returns the name of the <i>i</i>th argument. May return null if no argument names were available during parsing. */ - public String getArgumentName(int i) { + public String getArgumentName(final int i) { return type.getArgumentName(i); } /** Returns the type of the <i>i</i>th argument. */ - public Type getArgumentType(int i) { + public Type getArgumentType(final int i) { return type.getArgumentType(i); } /** Add an argument's name and type. Use null for unknown argument names. */ - public void addArgument(Type argumentType, String argumentName) { + public void addArgument(final Type argumentType, final String argumentName) { type.addArgument(argumentType, argumentName); } @@ -103,7 +103,7 @@ public class FunctionSymbol { } /** Helper routine for emitting native javadoc tags */ - public String toString(boolean emitNativeTag) { + public String toString(final boolean emitNativeTag) { return getType().toString(getName(), emitNativeTag); } @@ -116,7 +116,7 @@ public class FunctionSymbol { } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == this) { return true; } @@ -138,7 +138,7 @@ public class FunctionSymbol { * Compares the function type as well, since {@link #equals(Object)} * and {@link #hashCode()} won't. */ - public boolean isCompletelyEqual(Object arg) { + public boolean isCompletelyEqual(final Object arg) { if( !this.equals(arg) ) { return false; } diff --git a/src/java/com/jogamp/gluegen/cgram/types/FunctionType.java b/src/java/com/jogamp/gluegen/cgram/types/FunctionType.java index 7672744..4b39a34 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/FunctionType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/FunctionType.java @@ -49,14 +49,14 @@ public class FunctionType extends Type implements Cloneable { private ArrayList<Type> argumentTypes; private ArrayList<String> argumentNames; - public FunctionType(String name, SizeThunk size, Type returnType, int cvAttributes) { + public FunctionType(final String name, final SizeThunk size, final Type returnType, final int cvAttributes) { super(name, size, cvAttributes); this.returnType = returnType; } @Override public Object clone() { - FunctionType n = (FunctionType) super.clone(); + final FunctionType n = (FunctionType) super.clone(); if(null!=this.argumentTypes) { n.argumentTypes = new ArrayList<Type>(this.argumentTypes); } @@ -67,14 +67,14 @@ public class FunctionType extends Type implements Cloneable { } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == this) { return true; } if (arg == null || (!(arg instanceof FunctionType))) { return false; } - FunctionType t = (FunctionType) arg; + final FunctionType t = (FunctionType) arg; return (super.equals(arg) && returnType.equals(t.returnType) && listsEqual(argumentTypes, t.argumentTypes)); @@ -96,19 +96,19 @@ public class FunctionType extends Type implements Cloneable { /** Returns the name of the <i>i</i>th argument. May return null if no argument names were available during parsing. */ - public String getArgumentName(int i) { + public String getArgumentName(final int i) { return argumentNames.get(i); } /** Returns the type of the <i>i</i>th argument. */ - public Type getArgumentType(int i) { + public Type getArgumentType(final int i) { return argumentTypes.get(i); } /** * Add an argument's name and type. Use null for unknown argument names. */ - public void addArgument(Type argumentType, String argumentName) { + public void addArgument(final Type argumentType, final String argumentName) { if (argumentTypes == null) { argumentTypes = new ArrayList<Type>(); argumentNames = new ArrayList<String>(); @@ -117,7 +117,7 @@ public class FunctionType extends Type implements Cloneable { argumentNames.add(argumentName); } - public void setArgumentName(int i, String name) { + public void setArgumentName(final int i, final String name) { argumentNames.set(i, name); } @@ -159,18 +159,18 @@ public class FunctionType extends Type implements Cloneable { res.append(")"); } res.append("("); - int n = getNumArguments(); + final int n = getNumArguments(); for (int i = 0; i < n; i++) { - Type t = getArgumentType(i); + final Type t = getArgumentType(i); if (t.isFunctionPointer()) { - Type targetType = t.asPointer().getTargetType(); - FunctionType ft = targetType.asFunction(); + final Type targetType = t.asPointer().getTargetType(); + final FunctionType ft = targetType.asFunction(); res.append(ft.toString(getArgumentName(i), callingConvention, false, true)); } else if (t.isArray()) { res.append(t.asArray().toString(getArgumentName(i))); } else { res.append(t); - String argumentName = getArgumentName(i); + final String argumentName = getArgumentName(i); if (argumentName != null) { res.append(" "); res.append(argumentName); @@ -185,17 +185,17 @@ public class FunctionType extends Type implements Cloneable { } @Override - public void visit(TypeVisitor arg) { + public void visit(final TypeVisitor arg) { super.visit(arg); returnType.visit(arg); - int n = getNumArguments(); + final int n = getNumArguments(); for (int i = 0; i < n; i++) { getArgumentType(i).visit(arg); } } @Override - Type newCVVariant(int cvAttributes) { + Type newCVVariant(final int cvAttributes) { // Functions don't have const/volatile attributes return this; } diff --git a/src/java/com/jogamp/gluegen/cgram/types/IntType.java b/src/java/com/jogamp/gluegen/cgram/types/IntType.java index 6eeb997..3f8dddc 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/IntType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/IntType.java @@ -41,33 +41,33 @@ package com.jogamp.gluegen.cgram.types; public class IntType extends PrimitiveType implements Cloneable { - private boolean unsigned; + private final boolean unsigned; private boolean typedefedUnsigned; - public IntType(String name, SizeThunk size, boolean unsigned, int cvAttributes) { + public IntType(final String name, final SizeThunk size, final boolean unsigned, final int cvAttributes) { this(name, size, unsigned, cvAttributes, false); } - public IntType(String name, SizeThunk size, boolean unsigned, int cvAttributes, boolean typedefedUnsigned) { + public IntType(final String name, final SizeThunk size, final boolean unsigned, final int cvAttributes, final boolean typedefedUnsigned) { super(name, size, cvAttributes); this.unsigned = unsigned; this.typedefedUnsigned = typedefedUnsigned; } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == this) { return true; } if (arg == null || (!(arg instanceof IntType))) { return false; } - IntType t = (IntType) arg; + final IntType t = (IntType) arg; return (super.equals(arg) && (unsigned == t.unsigned)); } @Override - public void setName(String name) { + public void setName(final String name) { super.setName(name); typedefedUnsigned = unsigned; } @@ -93,7 +93,7 @@ public class IntType extends PrimitiveType implements Cloneable { } @Override - Type newCVVariant(int cvAttributes) { + Type newCVVariant(final int cvAttributes) { return new IntType(getName(), getSize(), isUnsigned(), cvAttributes, typedefedUnsigned); } } diff --git a/src/java/com/jogamp/gluegen/cgram/types/MemoryLayoutType.java b/src/java/com/jogamp/gluegen/cgram/types/MemoryLayoutType.java index df0d23e..25d2d1d 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/MemoryLayoutType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/MemoryLayoutType.java @@ -30,7 +30,7 @@ package com.jogamp.gluegen.cgram.types; public abstract class MemoryLayoutType extends Type { private boolean isLayouted; - protected MemoryLayoutType(String name, SizeThunk size, int cvAttributes) { + protected MemoryLayoutType(final String name, final SizeThunk size, final int cvAttributes) { super(name, size, cvAttributes); isLayouted = false; } diff --git a/src/java/com/jogamp/gluegen/cgram/types/PointerType.java b/src/java/com/jogamp/gluegen/cgram/types/PointerType.java index 5f19202..d1dfb17 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/PointerType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/PointerType.java @@ -45,13 +45,13 @@ public class PointerType extends Type implements Cloneable { private String computedName; private boolean hasTypedefedName; - public PointerType(SizeThunk size, Type targetType, int cvAttributes) { + public PointerType(final SizeThunk size, final Type targetType, final int cvAttributes) { // can pass null for the final name parameter because the PointerType's getName() // completely replaces superclass behavior this(size, targetType, cvAttributes, false, null); } - private PointerType(SizeThunk size, Type targetType, int cvAttributes, boolean hasTypedefedName, String typedefedName) { + private PointerType(final SizeThunk size, final Type targetType, final int cvAttributes, final boolean hasTypedefedName, final String typedefedName) { super(targetType.getName() + " *", size, cvAttributes); this.hasTypedefedName = false; this.targetType = targetType; @@ -66,14 +66,14 @@ public class PointerType extends Type implements Cloneable { } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == this) { return true; } if (arg == null || (!(arg instanceof PointerType))) { return false; } - PointerType t = (PointerType) arg; + final PointerType t = (PointerType) arg; // Note we ignore the name of this type (which might be a typedef // name) for comparison purposes because this is what allows // e.g. a newly-fabricated type "PIXELFORMATDESCRIPTOR *" to be @@ -84,13 +84,13 @@ public class PointerType extends Type implements Cloneable { } @Override - public void setName(String name) { + public void setName(final String name) { super.setName(name); hasTypedefedName = true; } @Override - public String getName(boolean includeCVAttrs) { + public String getName(final boolean includeCVAttrs) { if (hasTypedefedName) { return super.getName(includeCVAttrs); } else { @@ -150,7 +150,7 @@ public class PointerType extends Type implements Cloneable { /** For use only when printing function pointers. Calling convention string (i.e., "__stdcall") is optional and is generally only needed on Windows. */ - public String toString(String functionName, String callingConvention) { + public String toString(final String functionName, final String callingConvention) { if (!targetType.isFunction()) { throw new RuntimeException("<Internal error or misuse> This method is only for use when printing function pointers"); } @@ -158,13 +158,13 @@ public class PointerType extends Type implements Cloneable { } @Override - public void visit(TypeVisitor arg) { + public void visit(final TypeVisitor arg) { super.visit(arg); targetType.visit(arg); } @Override - Type newCVVariant(int cvAttributes) { + Type newCVVariant(final int cvAttributes) { return new PointerType(getSize(), targetType, cvAttributes, hasTypedefedName, (hasTypedefedName ? getName() : null)); } } diff --git a/src/java/com/jogamp/gluegen/cgram/types/PrimitiveType.java b/src/java/com/jogamp/gluegen/cgram/types/PrimitiveType.java index 9d108df..8a86337 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/PrimitiveType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/PrimitiveType.java @@ -41,7 +41,7 @@ package com.jogamp.gluegen.cgram.types; public abstract class PrimitiveType extends Type implements Cloneable { - protected PrimitiveType(String name, SizeThunk size, int cvAttributes) { + protected PrimitiveType(final String name, final SizeThunk size, final int cvAttributes) { super(name, size, cvAttributes); } diff --git a/src/java/com/jogamp/gluegen/cgram/types/SizeThunk.java b/src/java/com/jogamp/gluegen/cgram/types/SizeThunk.java index 021fa90..c13e5d5 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/SizeThunk.java +++ b/src/java/com/jogamp/gluegen/cgram/types/SizeThunk.java @@ -48,16 +48,16 @@ import com.jogamp.common.os.MachineDescription; 32-bit and 64-bit) from the same internal representation of the various types involved. */ public abstract class SizeThunk implements Cloneable { - private boolean fixedNativeSize; + private final boolean fixedNativeSize; // Private constructor because there are only a few of these - private SizeThunk(boolean fixedNativeSize) { this.fixedNativeSize = fixedNativeSize; } + private SizeThunk(final boolean fixedNativeSize) { this.fixedNativeSize = fixedNativeSize; } @Override public Object clone() { try { return super.clone(); - } catch (CloneNotSupportedException ex) { + } catch (final CloneNotSupportedException ex) { throw new InternalError(); } } @@ -69,99 +69,99 @@ public abstract class SizeThunk implements Cloneable { public static final SizeThunk INT8 = new SizeThunk(true) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { return machDesc.int8SizeInBytes(); } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { return machDesc.int8AlignmentInBytes(); } }; public static final SizeThunk INT16 = new SizeThunk(true) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { return machDesc.int16SizeInBytes(); } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { return machDesc.int16AlignmentInBytes(); } }; public static final SizeThunk INT32 = new SizeThunk(true) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { return machDesc.int32SizeInBytes(); } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { return machDesc.int32AlignmentInBytes(); } }; public static final SizeThunk INTxx = new SizeThunk(false) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { return machDesc.intSizeInBytes(); } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { return machDesc.intAlignmentInBytes(); } }; public static final SizeThunk LONG = new SizeThunk(false) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { return machDesc.longSizeInBytes(); } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { return machDesc.longAlignmentInBytes(); } }; public static final SizeThunk INT64 = new SizeThunk(true) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { return machDesc.int64SizeInBytes(); } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { return machDesc.int64AlignmentInBytes(); } }; public static final SizeThunk FLOAT = new SizeThunk(true) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { return machDesc.floatSizeInBytes(); } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { return machDesc.floatAlignmentInBytes(); } }; public static final SizeThunk DOUBLE = new SizeThunk(true) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { return machDesc.doubleSizeInBytes(); } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { return machDesc.doubleAlignmentInBytes(); } }; public static final SizeThunk POINTER = new SizeThunk(false) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { return machDesc.pointerSizeInBytes(); } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { return machDesc.pointerAlignmentInBytes(); } }; @@ -172,11 +172,11 @@ public abstract class SizeThunk implements Cloneable { final SizeThunk thunk2) { return new SizeThunk(false) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { return thunk1.computeSize(machDesc) + thunk2.computeSize(machDesc); } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { final long thunk1A = thunk1.computeAlignment(machDesc); final long thunk2A = thunk2.computeAlignment(machDesc); return ( thunk1A > thunk2A ) ? thunk1A : thunk2A ; @@ -188,11 +188,11 @@ public abstract class SizeThunk implements Cloneable { final SizeThunk thunk2) { return new SizeThunk(false) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { return thunk1.computeSize(machDesc) * thunk2.computeSize(machDesc); } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { final long thunk1A = thunk1.computeAlignment(machDesc); final long thunk2A = thunk2.computeAlignment(machDesc); return ( thunk1A > thunk2A ) ? thunk1A : thunk2A ; @@ -204,7 +204,7 @@ public abstract class SizeThunk implements Cloneable { final SizeThunk alignmentThunk) { return new SizeThunk(false) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { // x % 2n == x & (2n - 1) // remainder = net_size & ( alignment - 1 ) // padding = alignment - remainder ; @@ -219,7 +219,7 @@ public abstract class SizeThunk implements Cloneable { } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { final long thunk1A = offsetThunk.computeAlignment(machDesc); final long thunk2A = alignmentThunk.computeAlignment(machDesc); return ( thunk1A > thunk2A ) ? thunk1A : thunk2A ; @@ -231,11 +231,11 @@ public abstract class SizeThunk implements Cloneable { final SizeThunk thunk2) { return new SizeThunk(false) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { return Math.max(thunk1.computeSize(machDesc), thunk2.computeSize(machDesc)); } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { final long thunk1A = thunk1.computeAlignment(machDesc); final long thunk2A = thunk2.computeAlignment(machDesc); return ( thunk1A > thunk2A ) ? thunk1A : thunk2A ; @@ -246,11 +246,11 @@ public abstract class SizeThunk implements Cloneable { public static SizeThunk constant(final int constant) { return new SizeThunk(false) { @Override - public long computeSize(MachineDescription machDesc) { + public long computeSize(final MachineDescription machDesc) { return constant; } @Override - public long computeAlignment(MachineDescription machDesc) { + public long computeAlignment(final MachineDescription machDesc) { return 1; // no alignment for constants } }; diff --git a/src/java/com/jogamp/gluegen/cgram/types/StructLayout.java b/src/java/com/jogamp/gluegen/cgram/types/StructLayout.java index dfcb722..e3ed7c2 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/StructLayout.java +++ b/src/java/com/jogamp/gluegen/cgram/types/StructLayout.java @@ -53,11 +53,11 @@ import com.jogamp.gluegen.GlueGen; public class StructLayout { private final int baseOffset; - protected StructLayout(int baseOffset) { + protected StructLayout(final int baseOffset) { this.baseOffset = baseOffset; } - public void layout(CompoundType t) { + public void layout(final CompoundType t) { /** * - 1) align offset for the new data type, * - 2) add the aligned size of the new data type @@ -103,7 +103,7 @@ public class StructLayout { } else if (ft.isArray()) { final ArrayType arrayType = ft.asArray(); if(!arrayType.isLayouted()) { - CompoundType compoundElementType = arrayType.getBaseElementType().asCompound(); + final CompoundType compoundElementType = arrayType.getBaseElementType().asCompound(); if (compoundElementType != null) { if(!compoundElementType.isLayouted()) { StructLayout.layout(0, compoundElementType); @@ -144,11 +144,11 @@ public class StructLayout { t.setLayouted(); } - public static StructLayout create(int baseOffset) { + public static StructLayout create(final int baseOffset) { return new StructLayout(baseOffset); } - public static void layout(int baseOffset, CompoundType t) { + public static void layout(final int baseOffset, final CompoundType t) { create(baseOffset).layout(t); } } diff --git a/src/java/com/jogamp/gluegen/cgram/types/StructType.java b/src/java/com/jogamp/gluegen/cgram/types/StructType.java index da58a5f..27099e9 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/StructType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/StructType.java @@ -29,16 +29,16 @@ package com.jogamp.gluegen.cgram.types; public class StructType extends CompoundType { - public StructType(String name, SizeThunk size, int cvAttributes) { + public StructType(final String name, final SizeThunk size, final int cvAttributes) { this(name, size, cvAttributes, null); } - StructType(String name, SizeThunk size, int cvAttributes, String structName) { + StructType(final String name, final SizeThunk size, final int cvAttributes, final String structName) { super (name, size, cvAttributes, structName); } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == null || !(arg instanceof StructType)) { return false; } @@ -51,8 +51,8 @@ public class StructType extends CompoundType { public final boolean isUnion() { return false; } @Override - Type newCVVariant(int cvAttributes) { - StructType t = new StructType(getName(), getSize(), cvAttributes, getStructName()); + Type newCVVariant(final int cvAttributes) { + final StructType t = new StructType(getName(), getSize(), cvAttributes, getStructName()); t.setFields(getFields()); return t; } diff --git a/src/java/com/jogamp/gluegen/cgram/types/Type.java b/src/java/com/jogamp/gluegen/cgram/types/Type.java index 45d610d..32f48a6 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/Type.java +++ b/src/java/com/jogamp/gluegen/cgram/types/Type.java @@ -56,7 +56,7 @@ public abstract class Type implements Cloneable { private int typedefedCVAttributes; private boolean hasTypedefName; - protected Type(String name, SizeThunk size, int cvAttributes) { + protected Type(final String name, final SizeThunk size, final int cvAttributes) { setName(name); this.size = size; this.cvAttributes = cvAttributes; @@ -67,7 +67,7 @@ public abstract class Type implements Cloneable { public Object clone() { try { return super.clone(); - } catch (CloneNotSupportedException ex) { + } catch (final CloneNotSupportedException ex) { throw new InternalError(); } } @@ -80,7 +80,7 @@ public abstract class Type implements Cloneable { /** Returns the name of this type, optionally including const/volatile attributes. The returned string is suitable for use as a type specifier. */ - public String getName(boolean includeCVAttrs) { + public String getName(final boolean includeCVAttrs) { if (!includeCVAttrs) { return name; } @@ -113,7 +113,7 @@ public abstract class Type implements Cloneable { long _mdSize = -1; try { _mdSize = size.computeSize(MachineDescription.StaticConfig.X86_64_UNIX.md); - } catch (Exception e) {} + } catch (final Exception e) {} mdSize = _mdSize; } sb.append("[fixed ").append(size.hasFixedNativeSize()).append(", lnx64 ").append(mdSize).append("]"); @@ -166,7 +166,7 @@ public abstract class Type implements Cloneable { } /** Set the name of this type; used for handling typedefs. */ - public void setName(String name) { + public void setName(final String name) { if (name == null) { this.name = name; } else { @@ -181,15 +181,15 @@ public abstract class Type implements Cloneable { /** SizeThunk which computes size of this type in bytes. */ public SizeThunk getSize() { return size; } /** Size of this type in bytes according to the given MachineDescription. */ - public long getSize(MachineDescription machDesc) { - SizeThunk thunk = getSize(); + public long getSize(final MachineDescription machDesc) { + final SizeThunk thunk = getSize(); if (thunk == null) { throw new RuntimeException("No size set for type \"" + getName() + "\""); } return thunk.computeSize(machDesc); } /** Set the size of this type; only available for CompoundTypes. */ - void setSize(SizeThunk size) { this.size = size; } + void setSize(final SizeThunk size) { this.size = size; } /** Casts this to a BitType or returns null if not a BitType. */ public BitType asBit() { return null; } @@ -255,7 +255,7 @@ public abstract class Type implements Cloneable { } if (cvAttributes != 0) { - String nameWithAttribs = name + cvAttributes; + final String nameWithAttribs = name + cvAttributes; return nameWithAttribs.hashCode(); } return name.hashCode(); @@ -265,7 +265,7 @@ public abstract class Type implements Cloneable { * Equality test for Types. */ @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == this) { return true; } @@ -289,7 +289,7 @@ public abstract class Type implements Cloneable { /** Visit this type and all of the component types of this one; for example, the return type and argument types of a FunctionType. */ - public void visit(TypeVisitor visitor) { + public void visit(final TypeVisitor visitor) { visitor.visitType(this); } @@ -308,7 +308,7 @@ public abstract class Type implements Cloneable { /** Return a variant of this type matching the given const/volatile attributes. May return this object if the attributes match. */ - public final Type getCVVariant(int cvAttributes) { + public final Type getCVVariant(final int cvAttributes) { if (this.cvAttributes == cvAttributes) { return this; } @@ -329,7 +329,7 @@ public abstract class Type implements Cloneable { type represents (i.e., "void **" returns 2). Returns 0 if this type is not a pointer type. */ public int pointerDepth() { - PointerType pt = asPointer(); + final PointerType pt = asPointer(); if (pt == null) { return 0; } @@ -340,7 +340,7 @@ public abstract class Type implements Cloneable { type represents (i.e., "char[][]" returns 2). Returns 0 if this type is not an array type. */ public int arrayDimension() { - ArrayType arrayType = asArray(); + final ArrayType arrayType = asArray(); if (arrayType == null) { return 0; } @@ -359,7 +359,7 @@ public abstract class Type implements Cloneable { } /** Helper routine for list equality comparison */ - static <C> boolean listsEqual(List<C> a, List<C> b) { + static <C> boolean listsEqual(final List<C> a, final List<C> b) { return ((a == null && b == null) || (a != null && b != null && a.equals(b))); } } diff --git a/src/java/com/jogamp/gluegen/cgram/types/TypeDictionary.java b/src/java/com/jogamp/gluegen/cgram/types/TypeDictionary.java index 3994c12..f6409db 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/TypeDictionary.java +++ b/src/java/com/jogamp/gluegen/cgram/types/TypeDictionary.java @@ -46,10 +46,10 @@ import java.util.*; public class TypeDictionary { /** Mapping from type name to type.*/ - private HashMap<String, Type> map = new HashMap<String, Type>(); + private final HashMap<String, Type> map = new HashMap<String, Type>(); /** Reverse mapping; created lazily from the regular map */ - private HashMap<Set<Type>, String> reverseMap = new HashMap<Set<Type>, String>(); + private final HashMap<Set<Type>, String> reverseMap = new HashMap<Set<Type>, String>(); /** Has a type been added/removed since the last time the reverse map was * calculated? */ @@ -60,14 +60,14 @@ public class TypeDictionary { * @param name the name to which the type is defined * @param type the type that can be referred to by the specified name. */ - public Type put(String name, Type type) { + public Type put(final String name, final Type type) { reverseMapOutOfDate = true; return map.put(name, type); } /** Get the type corresponding to the given name. Returns null if no type * was found corresponding to the given name. */ - public Type get(String name) { + public Type get(final String name) { return map.get(name); } @@ -87,7 +87,7 @@ public class TypeDictionary { // } /** Remove the mapping from the specified name to its associated type.*/ - public Type remove(String name) { + public Type remove(final String name) { reverseMapOutOfDate = true; return map.remove(name); } @@ -103,11 +103,11 @@ public class TypeDictionary { return map.entrySet(); } - public boolean containsKey(String key) { + public boolean containsKey(final String key) { return map.containsKey(key); } - public boolean containsValue(Type value) { + public boolean containsValue(final Type value) { return map.containsValue(value); } diff --git a/src/java/com/jogamp/gluegen/cgram/types/UnionType.java b/src/java/com/jogamp/gluegen/cgram/types/UnionType.java index 36b4fdb..99d2fed 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/UnionType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/UnionType.java @@ -29,16 +29,16 @@ package com.jogamp.gluegen.cgram.types; public class UnionType extends CompoundType { - public UnionType(String name, SizeThunk size, int cvAttributes) { + public UnionType(final String name, final SizeThunk size, final int cvAttributes) { this(name, size, cvAttributes, null); } - UnionType(String name, SizeThunk size, int cvAttributes, String structName) { + UnionType(final String name, final SizeThunk size, final int cvAttributes, final String structName) { super (name, size, cvAttributes, structName); } @Override - public boolean equals(Object arg) { + public boolean equals(final Object arg) { if (arg == null || !(arg instanceof UnionType)) { return false; } @@ -51,8 +51,8 @@ public class UnionType extends CompoundType { public final boolean isUnion() { return true; } @Override - Type newCVVariant(int cvAttributes) { - UnionType t = new UnionType(getName(), getSize(), cvAttributes, getStructName()); + Type newCVVariant(final int cvAttributes) { + final UnionType t = new UnionType(getName(), getSize(), cvAttributes, getStructName()); t.setFields(getFields()); return t; } diff --git a/src/java/com/jogamp/gluegen/cgram/types/VoidType.java b/src/java/com/jogamp/gluegen/cgram/types/VoidType.java index afde0d2..2e1f069 100644 --- a/src/java/com/jogamp/gluegen/cgram/types/VoidType.java +++ b/src/java/com/jogamp/gluegen/cgram/types/VoidType.java @@ -41,11 +41,11 @@ package com.jogamp.gluegen.cgram.types; public class VoidType extends Type implements Cloneable { - public VoidType(int cvAttributes) { + public VoidType(final int cvAttributes) { this("void", cvAttributes); } - private VoidType(String name, int cvAttributes) { + private VoidType(final String name, final int cvAttributes) { super(name, null, cvAttributes); } @@ -55,7 +55,7 @@ public class VoidType extends Type implements Cloneable { } @Override - Type newCVVariant(int cvAttributes) { + Type newCVVariant(final int cvAttributes) { return new VoidType(getName(), cvAttributes); } } diff --git a/src/java/com/jogamp/gluegen/jgram/Test.java b/src/java/com/jogamp/gluegen/jgram/Test.java index 19d2110..2e41ef6 100644 --- a/src/java/com/jogamp/gluegen/jgram/Test.java +++ b/src/java/com/jogamp/gluegen/jgram/Test.java @@ -10,7 +10,7 @@ import java.util.Set; class Test { static boolean showTree = false; - public static void main(String[] args) { + public static void main(final String[] args) { // Use a try/catch block for parser exceptions try { // if we have at least one command-line argument @@ -30,7 +30,7 @@ class Test { System.err.println("Usage: java com.jogamp.gluegen.jgram.Test [-showtree] "+ "<directory or file name>"); } - catch(Exception e) { + catch(final Exception e) { System.err.println("exception: "+e); e.printStackTrace(System.err); // so we can get stack trace } @@ -39,11 +39,11 @@ class Test { // This method decides what action to take based on the type of // file we are looking at - public static void doFile(File f) + public static void doFile(final File f) throws Exception { // If this is a directory, walk each file/dir in that directory if (f.isDirectory()) { - String files[] = f.list(); + final String files[] = f.list(); for(int i=0; i < files.length; i++) doFile(new File(f, files[i])); } @@ -58,15 +58,15 @@ class Test { } // Here's where we do the real work... - public static void parseFile(String f, Reader r) + public static void parseFile(final String f, final Reader r) throws Exception { try { // Create a scanner that reads from the input stream passed to us - JavaLexer lexer = new JavaLexer(r); + final JavaLexer lexer = new JavaLexer(r); lexer.setFilename(f); // Create a parser that reads from the scanner - JavaParser parser = new JavaParser(lexer); + final JavaParser parser = new JavaParser(lexer); parser.setFilename(f); // start parsing at the compilationUnit rule @@ -74,21 +74,21 @@ class Test { Set<String> set = parser.getParsedEnumNames(); System.out.println("Enums"); - for(Iterator<String> iter = set.iterator(); iter.hasNext(); ) { - String s = iter.next(); + for(final Iterator<String> iter = set.iterator(); iter.hasNext(); ) { + final String s = iter.next(); System.out.println(s); } System.out.println("Functions"); set = parser.getParsedFunctionNames(); - for(Iterator<String> iter = set.iterator(); iter.hasNext(); ) { - String s = iter.next(); + for(final Iterator<String> iter = set.iterator(); iter.hasNext(); ) { + final String s = iter.next(); System.out.println(s); } // do something with the tree //doTreeAction(f, parser.getAST(), parser.getTokenNames()); } - catch (Exception e) { + catch (final Exception e) { System.err.println("parser exception: "+e); e.printStackTrace(); // so we can get stack trace } diff --git a/src/java/com/jogamp/gluegen/pcpp/ConcatenatingReader.java b/src/java/com/jogamp/gluegen/pcpp/ConcatenatingReader.java index c7e3635..7583d50 100644 --- a/src/java/com/jogamp/gluegen/pcpp/ConcatenatingReader.java +++ b/src/java/com/jogamp/gluegen/pcpp/ConcatenatingReader.java @@ -48,20 +48,20 @@ public class ConcatenatingReader extends FilterReader { // Any leftover characters go here private char[] curBuf; private int curPos; - private BufferedReader reader; + private final BufferedReader reader; private static String newline = System.getProperty("line.separator"); /** This class requires that the input reader be a BufferedReader so it can do line-oriented operations. */ - public ConcatenatingReader(BufferedReader in) { + public ConcatenatingReader(final BufferedReader in) { super(in); this.reader = in; } @Override public int read() throws IOException { - char[] tmp = new char[1]; - int num = read(tmp, 0, 1); + final char[] tmp = new char[1]; + final int num = read(tmp, 0, 1); if (num < 0) return -1; return tmp[0]; @@ -74,7 +74,7 @@ public class ConcatenatingReader extends FilterReader { } @Override - public void mark(int readAheadLimit) throws IOException { + public void mark(final int readAheadLimit) throws IOException { throw new IOException("mark/reset not supported"); } @@ -91,7 +91,7 @@ public class ConcatenatingReader extends FilterReader { } @Override - public int read(char[] cbuf, int off, int len) throws IOException { + public int read(final char[] cbuf, int off, int len) throws IOException { if (curBuf == null) { nextLine(); } @@ -121,9 +121,9 @@ public class ConcatenatingReader extends FilterReader { long numSkipped = 0; while (n > 0) { - int intN = (int) n; - char[] tmp = new char[intN]; - int numRead = read(tmp, 0, intN); + final int intN = (int) n; + final char[] tmp = new char[intN]; + final int numRead = read(tmp, 0, intN); n -= numRead; numSkipped += numRead; if (numRead < intN) @@ -133,7 +133,7 @@ public class ConcatenatingReader extends FilterReader { } private void nextLine() throws IOException { - String cur = reader.readLine(); + final String cur = reader.readLine(); if (cur == null) { curBuf = null; return; @@ -148,7 +148,7 @@ public class ConcatenatingReader extends FilterReader { --numChars; needNewline = false; } - char[] buf = new char[numChars + (needNewline ? newline.length() : 0)]; + final char[] buf = new char[numChars + (needNewline ? newline.length() : 0)]; cur.getChars(0, numChars, buf, 0); if (needNewline) { newline.getChars(0, newline.length(), buf, numChars); diff --git a/src/java/com/jogamp/gluegen/pcpp/PCPP.java b/src/java/com/jogamp/gluegen/pcpp/PCPP.java index 30d8dd8..aca7b14 100644 --- a/src/java/com/jogamp/gluegen/pcpp/PCPP.java +++ b/src/java/com/jogamp/gluegen/pcpp/PCPP.java @@ -73,26 +73,26 @@ public class PCPP { to constants. Macros and multi-line defines (which typically contain either macro definitions or expressions) are currently not handled. */ - private Map<String, String> defineMap = new HashMap<String, String>(128); - private Map<String, Macro> macroMap = new HashMap<String, Macro>(128); - private Set<String> nonConstantDefines = new HashSet<String>(128); + private final Map<String, String> defineMap = new HashMap<String, String>(128); + private final Map<String, Macro> macroMap = new HashMap<String, Macro>(128); + private final Set<String> nonConstantDefines = new HashSet<String>(128); /** List containing the #include paths as Strings */ - private List<String> includePaths; + private final List<String> includePaths; private ParseState state; - private boolean enableDebugPrint; - private boolean enableCopyOutput2Stderr; + private final boolean enableDebugPrint; + private final boolean enableCopyOutput2Stderr; - public PCPP(List<String> includePaths, boolean debug, boolean copyOutput2Stderr) { + public PCPP(final List<String> includePaths, final boolean debug, final boolean copyOutput2Stderr) { this.includePaths = includePaths; setOut(System.out); enableDebugPrint = debug; enableCopyOutput2Stderr = copyOutput2Stderr; } - public void run(Reader reader, String filename) throws IOException { + public void run(final Reader reader, final String filename) throws IOException { StreamTokenizer tok = null; BufferedReader bufReader = null; if (reader instanceof BufferedReader) { @@ -104,8 +104,8 @@ public class PCPP { tok = new StreamTokenizer(new ConcatenatingReader(bufReader)); initTokenizer(tok); - ParseState curState = new ParseState(tok, filename); - ParseState oldState = state; + final ParseState curState = new ParseState(tok, filename); + final ParseState oldState = state; state = curState; lineDirective(); parse(); @@ -115,7 +115,7 @@ public class PCPP { } } - private void initTokenizer(StreamTokenizer tok) { + private void initTokenizer(final StreamTokenizer tok) { tok.resetSyntax(); tok.wordChars('a', 'z'); tok.wordChars('A', 'Z'); @@ -131,11 +131,11 @@ public class PCPP { tok.slashStarComments(true); } - public String findFile(String filename) { - String sep = File.separator; - for (String inclPath : includePaths) { - String fullPath = inclPath + sep + filename; - File file = new File(fullPath); + public String findFile(final String filename) { + final String sep = File.separator; + for (final String inclPath : includePaths) { + final String fullPath = inclPath + sep + filename; + final File file = new File(fullPath); if (file.exists()) { return fullPath; } @@ -147,7 +147,7 @@ public class PCPP { return out; } - public void setOut(OutputStream out) { + public void setOut(final OutputStream out) { this.out = out; writer = new PrintWriter(out); } @@ -155,12 +155,12 @@ public class PCPP { // State static class ParseState { - private StreamTokenizer tok; - private String filename; + private final StreamTokenizer tok; + private final String filename; private boolean startOfLine; private boolean startOfFile; - ParseState(StreamTokenizer tok, String filename) { + ParseState(final StreamTokenizer tok, final String filename) { this.tok = tok; this.filename = filename; startOfLine = true; @@ -195,7 +195,7 @@ public class PCPP { return startOfLine; } - void setStartOfLine(boolean val) { + void setStartOfLine(final boolean val) { startOfLine = val; } @@ -203,7 +203,7 @@ public class PCPP { return startOfFile; } - void setStartOfFile(boolean val) { + void setStartOfFile(final boolean val) { startOfFile = val; } @@ -214,7 +214,7 @@ public class PCPP { private final List<String> values; private final List<String> params; - Macro(List<String> params, List<String> values) { + Macro(final List<String> params, final List<String> values) { this.values = values; this.params = params; } @@ -233,8 +233,8 @@ public class PCPP { return nextToken(false); } - private int nextToken(boolean returnEOLs) throws IOException { - int lineno = lineNumber(); + private int nextToken(final boolean returnEOLs) throws IOException { + final int lineno = lineNumber(); // Check to see whether the previous call to nextToken() left an // EOL on the stream if (state.curToken() == StreamTokenizer.TT_EOL) { @@ -266,8 +266,8 @@ public class PCPP { * Reads the next token and throws an IOException if it is not the specified * token character. */ - private void nextRequiredToken(int requiredToken) throws IOException { - int nextTok = nextToken(); + private void nextRequiredToken(final int requiredToken) throws IOException { + final int nextTok = nextToken(); if (nextTok != requiredToken) { String msg = "Expected token '" + requiredToken + "' but got "; switch (nextTok) { @@ -282,16 +282,16 @@ public class PCPP { private String curTokenAsString() { - int t = state.curToken(); + final int t = state.curToken(); if (t == StreamTokenizer.TT_WORD) { return state.curWord(); } if (t == StreamTokenizer.TT_EOL) { throw new RuntimeException("Should not be converting EOL characters to strings at file " + filename() + ", line " + lineNumber()); } - char c = (char) t; + final char c = (char) t; if (c == '"' || c == '\'') { - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); sb.append(c); sb.append(state.curWord()); sb.append(c); @@ -306,7 +306,7 @@ public class PCPP { } private String nextWord() throws IOException { - int val = nextToken(); + final int val = nextToken(); if (val != StreamTokenizer.TT_WORD) { throw new RuntimeException("Expected word at file " + filename() + ", line " + lineNumber()); @@ -345,18 +345,18 @@ public class PCPP { if (tok == StreamTokenizer.TT_WORD) { print(" "); } - String s = curTokenAsString(); + final String s = curTokenAsString(); String newS = defineMap.get(s); if (newS == null) { newS = s; } - Macro macro = macroMap.get(newS); + final Macro macro = macroMap.get(newS); if(macro != null) { newS = ""; - List<String> args = new ArrayList<String>(); + final List<String> args = new ArrayList<String>(); while (nextToken() != StreamTokenizer.TT_EOL) { - String token = curTokenAsString(); + final String token = curTokenAsString(); if(")".equals(token)) { break; }else if(!",".equals(token) && !"(".equals(token)) { @@ -368,7 +368,7 @@ public class PCPP { String value = macro.values.get(i); for (int j = 0; j < macro.params.size(); j++) { - String param = macro.params.get(j); + final String param = macro.params.get(j); if(param.equals(value)) { value = args.get(j); break; @@ -392,7 +392,7 @@ public class PCPP { } private void preprocessorDirective() throws IOException { - String w = nextWord(); + final String w = nextWord(); boolean shouldPrint = true; if (w.equals("warning")) { handleWarning(); @@ -426,11 +426,11 @@ public class PCPP { try { // try '# <line> "<filename>"' case line = Integer.parseInt(w); - String filename = nextWordOrString(); + final String filename = nextWordOrString(); print("# " + line + " " + filename); println(); shouldPrint = false; - } catch (NumberFormatException nfe) { + } catch (final NumberFormatException nfe) { // Unknown preprocessor directive (#pragma?) -- ignore } } @@ -446,18 +446,18 @@ public class PCPP { private void handleUndefine() throws IOException { // Next token is the name of the #undef - String name = nextWord(); + final String name = nextWord(); debugPrint(true, "UNDEF " + name); // there shouldn't be any extra symbols after the name, but just in case... - List<String> values = new ArrayList<String>(); + final List<String> values = new ArrayList<String>(); while (nextToken(true) != StreamTokenizer.TT_EOL) { values.add(curTokenAsString()); } if (enabled()) { - String oldDef = defineMap.remove(name); + final String oldDef = defineMap.remove(name); if (oldDef == null) { LOG.log(WARNING, "ignoring redundant \"#undef {0}\", at \"{1}\" line {2}: \"{3}\" was not previously defined", new Object[]{name, filename(), lineNumber(), name}); @@ -471,14 +471,14 @@ public class PCPP { } private void handleWarning() throws IOException { - String msg = nextWordOrString(); + final String msg = nextWordOrString(); if (enabled()) { LOG.log(WARNING, "#warning {0} at \"{1}\" line \"{2}\"", new Object[]{msg, filename(), lineNumber()}); } } private void handleError() throws IOException { - String msg = nextWordOrString(); + final String msg = nextWordOrString(); if (enabled()) { throw new RuntimeException("#error "+msg+" at \""+filename()+"\" line "+lineNumber()); } @@ -496,15 +496,15 @@ public class PCPP { // Next token is the name of the #define String name = nextWord(); - boolean macroDefinition = name.contains("("); + final boolean macroDefinition = name.contains("("); //System.err.println("IN HANDLE_DEFINE: '" + name + "' (line " + lineNumber() + " file " + filename() + ")"); // (Note that this is not actually proper handling for multi-line #defines) - List<String> values = new ArrayList<String>(); + final List<String> values = new ArrayList<String>(); if(macroDefinition) { - int index = name.indexOf('('); - String var = name.substring(index+1); + final int index = name.indexOf('('); + final String var = name.substring(index+1); name = name.substring(0, index); values.add("("); @@ -520,13 +520,13 @@ public class PCPP { addDefine(name, macroDefinition, values); } - public void addDefine(String name, String value) { - List<String> values = new ArrayList<String>(); + public void addDefine(final String name, final String value) { + final List<String> values = new ArrayList<String>(); values.add(value); addDefine(name, false, values); } - private void addDefine(String name, boolean nameIsMacro, List<String> values) { + private void addDefine(final String name, final boolean nameIsMacro, List<String> values) { // if we're not within an active block of code (like inside an "#ifdef // FOO" where FOO isn't defined), then don't actually alter the definition // map. @@ -535,11 +535,11 @@ public class PCPP { boolean emitDefine = true; // Handle #definitions to nothing or to a constant value - int sz = values.size(); + final int sz = values.size(); if (sz == 0) { // definition to nothing, like "#define FOO" - String value = ""; - String oldDef = defineMap.put(name, value); + final String value = ""; + final String oldDef = defineMap.put(name, value); if (oldDef != null && !oldDef.equals(value)) { LOG.log(WARNING, "\"{0}\" redefined from \"{1}\" to \"\"", new Object[]{name, oldDef}); } @@ -549,12 +549,12 @@ public class PCPP { //System.err.println("//---DEFINED: " + name + "to \"\""); } else if (sz == 1) { // See whether the value is a constant - String value = values.get(0); + final String value = values.get(0); if (isConstant(value)) { // Value is numeric constant like "#define FOO 5". // Put it in the #define map - String oldDef = defineMap.put(name, value); + final String oldDef = defineMap.put(name, value); if (oldDef != null && !oldDef.equals(value)) { LOG.log(WARNING, "\"{0}\" redefined from \"{1}\" to \"{2}\"", new Object[]{name, oldDef, value}); } @@ -563,7 +563,7 @@ public class PCPP { } else { // Value is a symbolic constant like "#define FOO BAR". // Try to look up the symbol's value - String newValue = resolveDefine(value, true); + final String newValue = resolveDefine(value, true); debugPrint(true, "DEFINE " + name + " -> "+value + " -> <" + newValue + "> SYMB"); if (newValue != null) { // Set the value to the value of the symbol. @@ -571,7 +571,7 @@ public class PCPP { // TO DO: Is this correct? Why not output the symbol unchanged? // I think that it's a good thing to see that some symbols are // defined in terms of others. -chris - boolean valueIsMacro = newValue.contains("("); + final boolean valueIsMacro = newValue.contains("("); if(valueIsMacro) { // parser can't dig this currently emitDefine = false; @@ -588,9 +588,9 @@ public class PCPP { } else if (nameIsMacro) { // list parameters - List<String> params = new ArrayList<String>(); + final List<String> params = new ArrayList<String>(); for (int i = 1; i < values.size(); i++) { - String v = values.get(i); + final String v = values.get(i); if(")".equals(v)) { // end of params if(i != values.size()-1) { values = values.subList(i+1, values.size()); @@ -603,8 +603,8 @@ public class PCPP { } } - Macro macro = new Macro(params, values); - Macro oldDef = macroMap.put(name, macro); + final Macro macro = new Macro(params, values); + final Macro oldDef = macroMap.put(name, macro); if (oldDef != null) { LOG.log(WARNING, "\"{0}\" redefined from \"{1}\" to \"{2}\"", new Object[]{name, oldDef, macro}); } @@ -617,7 +617,7 @@ public class PCPP { // expressions containing identifiers are currently ignored (casts too) boolean containsIdentifier = false; - for (String value : values) { + for (final String value : values) { if(isIdentifier(value)) { containsIdentifier = true; break; @@ -630,7 +630,7 @@ public class PCPP { // Non-constant define; try to do reasonable textual substitution anyway // (FIXME: should identify some of these, like (-1), as constants) emitDefine = false; - StringBuilder val = new StringBuilder(); + final StringBuilder val = new StringBuilder(); for (int i = 0; i < sz; i++) { if (i != 0) { val.append(" "); @@ -649,13 +649,13 @@ public class PCPP { }else{ // constant expression -> pass through - StringBuilder sb = new StringBuilder(); - for (String v : values) { + final StringBuilder sb = new StringBuilder(); + for (final String v : values) { sb.append(v); } - String value = sb.toString(); + final String value = sb.toString(); - String oldDef = defineMap.put(name, value); + final String oldDef = defineMap.put(name, value); if (oldDef != null && !oldDef.equals(value)) { LOG.log(WARNING, "\"{0}\" redefined from \"{1}\" to \"{2}\"", new Object[]{name, oldDef, value}); } @@ -670,7 +670,7 @@ public class PCPP { print("# define "); print(name); print(" "); - for (String v : values) { + for (final String v : values) { print(v); } println(); @@ -681,14 +681,14 @@ public class PCPP { //System.err.println("OUT HANDLE_DEFINE: " + name); } - private boolean isIdentifier(String value) { + private boolean isIdentifier(final String value) { boolean identifier = false; - char[] chars = value.toCharArray(); + final char[] chars = value.toCharArray(); for (int i = 0; i < chars.length; i++) { - char c = chars[i]; + final char c = chars[i]; if (i == 0) { if (Character.isJavaIdentifierStart(c)) { identifier = true; @@ -703,7 +703,7 @@ public class PCPP { return identifier; } - private boolean isConstant(String s) { + private boolean isConstant(final String s) { if (s.startsWith("0x") || s.startsWith("0X")) { return checkHex(s); } else { @@ -711,7 +711,7 @@ public class PCPP { } } - private boolean checkHex(String s) { + private boolean checkHex(final String s) { char c='\0'; int i; for (i = 2; i < s.length(); i++) { @@ -733,17 +733,17 @@ public class PCPP { return false; } - private boolean checkDecimal(String s) { + private boolean checkDecimal(final String s) { try { Float.valueOf(s); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { // not parsable as a number return false; } return true; } - private String resolveDefine(String word, boolean returnNullIfNotFound) { + private String resolveDefine(final String word, final boolean returnNullIfNotFound) { String lastWord = defineMap.get(word); if (lastWord == null) { if (returnNullIfNotFound) { @@ -777,16 +777,16 @@ public class PCPP { * @param isIfdef if true, we're processing #ifdef; if false, we're * processing #ifndef. */ - private void handleIfdef(boolean isIfdef) throws IOException { + private void handleIfdef(final boolean isIfdef) throws IOException { // Next token is the name of the #ifdef - String symbolName = nextWord(); + final String symbolName = nextWord(); - boolean enabledOutside = enabled(); - boolean symbolIsDefined = defineMap.get(symbolName) != null; + final boolean enabledOutside = enabled(); + final boolean symbolIsDefined = defineMap.get(symbolName) != null; debugPrint(false, (isIfdef ? "IFDEF " : "IFNDEF ") + symbolName + ", enabledOutside " + enabledOutside + ", isDefined " + symbolIsDefined + ", file \"" + filename() + " line " + lineNumber()); - boolean enabledNow = enabled() && symbolIsDefined == isIfdef ; + final boolean enabledNow = enabled() && symbolIsDefined == isIfdef ; pushEnableBit( enabledNow ) ; // StateCondition pushEnableBit( enabledNow ) ; // StateInside } @@ -794,9 +794,9 @@ public class PCPP { /** Handles #else directives */ private void handleElse() throws IOException { popEnableBit(); // Inside - boolean enabledCondition = enabled(); + final boolean enabledCondition = enabled(); popEnableBit(); // Condition - boolean enabledOutside = enabled(); + final boolean enabledOutside = enabled(); debugPrint(false, "ELSE, enabledOutside " + enabledOutside + ", file \"" + filename() + " line " + lineNumber()); pushEnableBit(enabledOutside && !enabledCondition); // Condition - don't care @@ -806,7 +806,7 @@ public class PCPP { private void handleEndif() { popEnableBit(); // Inside popEnableBit(); // Condition - boolean enabledOutside = enabled(); + final boolean enabledOutside = enabled(); // print the endif if we were enabled prior to popEnableBit() (sending // false to debugPrint means "print regardless of current enabled() state). @@ -817,7 +817,7 @@ public class PCPP { * @param isIf if true, we're processing #if; if false, we're * processing #elif. */ - private void handleIf(boolean isIf) throws IOException { + private void handleIf(final boolean isIf) throws IOException { boolean enabledCondition = false; boolean enabledOutside; @@ -828,7 +828,7 @@ public class PCPP { } enabledOutside = enabled(); - boolean defineEvaluatedToTrue = handleIfRecursive(true); + final boolean defineEvaluatedToTrue = handleIfRecursive(true); debugPrint(false, (isIf ? "IF" : "ELIF") + ", enabledOutside " + enabledOutside + ", eval " + defineEvaluatedToTrue + ", file \"" + filename() + " line " + lineNumber()); @@ -859,7 +859,7 @@ public class PCPP { * @return the value of the sub-expression or (if greedy==true) * series of sub-expressions. */ - private boolean handleIfRecursive(boolean greedy) throws IOException { + private boolean handleIfRecursive(final boolean greedy) throws IOException { //System.err.println("IN HANDLE_IF_RECURSIVE (" + ++tmp + ", greedy = " + greedy + ")"); System.err.flush(); // ifValue keeps track of the current value of the potentially nested @@ -883,7 +883,7 @@ public class PCPP { case '!': { //System.err.println("HANDLE_IF_RECURSIVE HANDLING !"); - boolean rhs = handleIfRecursive(false); + final boolean rhs = handleIfRecursive(false); ifValue = !rhs; //System.err.println("HANDLE_IF_RECURSIVE HANDLED OUT !, RHS = " + rhs); } @@ -892,7 +892,7 @@ public class PCPP { { nextRequiredToken('&'); //System.err.println("HANDLE_IF_RECURSIVE HANDLING &&, LHS = " + ifValue); - boolean rhs = handleIfRecursive(true); + final boolean rhs = handleIfRecursive(true); //System.err.println("HANDLE_IF_RECURSIVE HANDLED &&, RHS = " + rhs); ifValue = ifValue && rhs; } @@ -901,7 +901,7 @@ public class PCPP { { nextRequiredToken('|'); //System.err.println("HANDLE_IF_RECURSIVE HANDLING ||, LHS = " + ifValue); - boolean rhs = handleIfRecursive(true); + final boolean rhs = handleIfRecursive(true); //System.err.println("HANDLE_IF_RECURSIVE HANDLED ||, RHS = " + rhs); ifValue = ifValue || rhs; } @@ -909,38 +909,38 @@ public class PCPP { case '>': { // NOTE: we don't handle expressions like this properly - boolean rhs = handleIfRecursive(true); + final boolean rhs = handleIfRecursive(true); ifValue = false; } break; case '<': { // NOTE: we don't handle expressions like this properly - boolean rhs = handleIfRecursive(true); + final boolean rhs = handleIfRecursive(true); ifValue = false; } break; case '=': { // NOTE: we don't handle expressions like this properly - boolean rhs = handleIfRecursive(true); + final boolean rhs = handleIfRecursive(true); ifValue = false; } break; case StreamTokenizer.TT_WORD: { - String word = curTokenAsString(); + final String word = curTokenAsString(); if (word.equals("defined")) { // Handle things like #if defined(SOMESYMBOL) nextRequiredToken('('); - String symbol = nextWord(); - boolean isDefined = defineMap.get(symbol) != null; + final String symbol = nextWord(); + final boolean isDefined = defineMap.get(symbol) != null; //System.err.println("HANDLE_IF_RECURSIVE HANDLING defined(" + symbol + ") = " + isDefined); ifValue = ifValue && isDefined; nextRequiredToken(')'); } else { // Handle things like #if SOME_SYMBOL. - String symbolValue = defineMap.get(word); + final String symbolValue = defineMap.get(word); // See if the statement is "true"; i.e., a non-zero expression if (symbolValue != null) { @@ -956,11 +956,11 @@ public class PCPP { try { // see if it's in decimal form return Double.parseDouble(word) != 0; - } catch (NumberFormatException nfe1) { + } catch (final NumberFormatException nfe1) { try { // ok, it's not a valid decimal value, try hex/octal value return Long.parseLong(word) != 0; - } catch (NumberFormatException nfe2) { + } catch (final NumberFormatException nfe2) { // ok, it's not a valid hex/octal value, try boolean last return Boolean.valueOf(word).booleanValue(); } @@ -1003,7 +1003,7 @@ public class PCPP { } else if (t == '<') { // Components of path name are coming in as separate tokens; // concatenate them - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); while ((t = nextToken()) != '>' && (t != StreamTokenizer.TT_EOF)) { buf.append(curTokenAsString()); } @@ -1018,13 +1018,13 @@ public class PCPP { debugPrint(true, "INCLUDE [" + filename + "]"); if (enabled()) { // Look up file in known #include path - String fullname = findFile(filename); + final String fullname = findFile(filename); //System.err.println("ACTIVE BLOCK, LOADING " + filename); if (fullname == null) { throw new RuntimeException("Can't find #include file \"" + filename + "\" at file " + filename() + ", line " + lineNumber()); } // Process this file in-line - Reader reader = new BufferedReader(new FileReader(fullname)); + final Reader reader = new BufferedReader(new FileReader(fullname)); run(reader, fullname); } else { //System.err.println("INACTIVE BLOCK, SKIPPING " + filename); @@ -1037,11 +1037,11 @@ public class PCPP { private OutputStream out; private PrintWriter writer; - private List<Boolean> enabledBits = new ArrayList<Boolean>(); + private final List<Boolean> enabledBits = new ArrayList<Boolean>(); private static int debugPrintIndentLevel = 0; - private void debugPrint(boolean onlyPrintIfEnabled, String msg) { + private void debugPrint(final boolean onlyPrintIfEnabled, final String msg) { if (!enableDebugPrint) { return; } @@ -1055,7 +1055,7 @@ public class PCPP { } } - private void pushEnableBit(boolean enabled) { + private void pushEnableBit(final boolean enabled) { enabledBits.add(enabled); ++debugPrintIndentLevel; debugPrint(false, "PUSH_ENABLED, NOW: " + enabled()); @@ -1074,7 +1074,7 @@ public class PCPP { return (enabledBits.isEmpty() || enabledBits.get(enabledBits.size() - 1)); } - private void print(String s) { + private void print(final String s) { if (enabled()) { writer.print(s); if (enableCopyOutput2Stderr) { @@ -1085,7 +1085,7 @@ public class PCPP { } } - private void print(char c) { + private void print(final char c) { if (enabled()) { writer.print(c); if (enableCopyOutput2Stderr) { @@ -1135,7 +1135,7 @@ public class PCPP { System.exit(1); } - public static void main(String[] args) throws IOException { + public static void main(final String[] args) throws IOException { Reader reader = null; String filename = null; boolean debug = false; @@ -1144,12 +1144,12 @@ public class PCPP { usage(); } - List<String> includePaths = new ArrayList<String>(); + final List<String> includePaths = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { if (i < args.length - 1) { - String arg = args[i]; + final String arg = args[i]; if (arg.startsWith("-I")) { - String[] paths = arg.substring(2).split(System.getProperty("path.separator")); + final String[] paths = arg.substring(2).split(System.getProperty("path.separator")); for (int j = 0; j < paths.length; j++) { includePaths.add(paths[j]); } @@ -1159,7 +1159,7 @@ public class PCPP { usage(); } } else { - String arg = args[i]; + final String arg = args[i]; if (arg.equals("-")) { reader = new InputStreamReader(System.in); filename = "standard input"; diff --git a/src/java/com/jogamp/gluegen/procaddress/ProcAddressCMethodBindingEmitter.java b/src/java/com/jogamp/gluegen/procaddress/ProcAddressCMethodBindingEmitter.java index 49ff4fc..351e0cd 100644 --- a/src/java/com/jogamp/gluegen/procaddress/ProcAddressCMethodBindingEmitter.java +++ b/src/java/com/jogamp/gluegen/procaddress/ProcAddressCMethodBindingEmitter.java @@ -55,8 +55,8 @@ public class ProcAddressCMethodBindingEmitter extends CMethodBindingEmitter { private static final String procAddressJavaTypeName = JavaType.createForClass(Long.TYPE).jniTypeName(); private ProcAddressEmitter emitter; - public ProcAddressCMethodBindingEmitter(CMethodBindingEmitter methodToWrap, final boolean callThroughProcAddress, - boolean needsLocalTypedef, String localTypedefCallingConvention, ProcAddressEmitter emitter) { + public ProcAddressCMethodBindingEmitter(final CMethodBindingEmitter methodToWrap, final boolean callThroughProcAddress, + final boolean needsLocalTypedef, final String localTypedefCallingConvention, final ProcAddressEmitter emitter) { super( new MethodBinding(methodToWrap.getBinding()) { @@ -97,7 +97,7 @@ public class ProcAddressCMethodBindingEmitter extends CMethodBindingEmitter { } @Override - protected int emitArguments(PrintWriter writer) { + protected int emitArguments(final PrintWriter writer) { int numEmitted = super.emitArguments(writer); if (callThroughProcAddress) { if (numEmitted > 0) { @@ -112,11 +112,11 @@ public class ProcAddressCMethodBindingEmitter extends CMethodBindingEmitter { } @Override - protected void emitBodyVariableDeclarations(PrintWriter writer) { + protected void emitBodyVariableDeclarations(final PrintWriter writer) { if (callThroughProcAddress) { // create variable for the function pointer with the right type, and set // it to the value of the passed-in proc address - FunctionSymbol cSym = getBinding().getCSymbol(); + final FunctionSymbol cSym = getBinding().getCSymbol(); String funcPointerTypedefName = emitter.getFunctionPointerTypedefName(cSym); @@ -124,7 +124,7 @@ public class ProcAddressCMethodBindingEmitter extends CMethodBindingEmitter { // We (probably) didn't get a typedef for this function // pointer type in the header file; the user requested that we // forcibly generate one. Here we force the emission of one. - PointerType funcPtrType = new PointerType(null, cSym.getType(), 0); + final PointerType funcPtrType = new PointerType(null, cSym.getType(), 0); // Just for safety, emit this name slightly differently than // the mangling would otherwise produce funcPointerTypedefName = "_local_" + funcPointerTypedefName; @@ -145,18 +145,18 @@ public class ProcAddressCMethodBindingEmitter extends CMethodBindingEmitter { } @Override - protected void emitBodyVariablePreCallSetup(PrintWriter writer) { + protected void emitBodyVariablePreCallSetup(final PrintWriter writer) { super.emitBodyVariablePreCallSetup(writer); if (callThroughProcAddress) { // set the function pointer to the value of the passed-in procAddress - FunctionSymbol cSym = getBinding().getCSymbol(); + final FunctionSymbol cSym = getBinding().getCSymbol(); String funcPointerTypedefName = emitter.getFunctionPointerTypedefName(cSym); if (needsLocalTypedef) { funcPointerTypedefName = "_local_" + funcPointerTypedefName; } - String ptrVarName = "ptr_" + cSym.getName(); + final String ptrVarName = "ptr_" + cSym.getName(); writer.print(" "); writer.print(ptrVarName); @@ -169,7 +169,7 @@ public class ProcAddressCMethodBindingEmitter extends CMethodBindingEmitter { } @Override - protected void emitBodyCallCFunction(PrintWriter writer) { + protected void emitBodyCallCFunction(final PrintWriter writer) { if (!callThroughProcAddress) { super.emitBodyCallCFunction(writer); } else { @@ -178,12 +178,12 @@ public class ProcAddressCMethodBindingEmitter extends CMethodBindingEmitter { // WARNING: this code assumes that the return type has already been // typedef-resolved. - Type cReturnType = binding.getCReturnType(); + final Type cReturnType = binding.getCReturnType(); if (!cReturnType.isVoid()) { writer.print("_res = "); } - MethodBinding mBinding = getBinding(); + final MethodBinding mBinding = getBinding(); if (mBinding.hasContainingType()) { // FIXME: this can and should be handled and unified with the // associated code in the CMethodBindingEmitter @@ -201,8 +201,8 @@ public class ProcAddressCMethodBindingEmitter extends CMethodBindingEmitter { } @Override - protected String jniMangle(MethodBinding binding) { - StringBuilder buf = new StringBuilder(super.jniMangle(binding)); + protected String jniMangle(final MethodBinding binding) { + final StringBuilder buf = new StringBuilder(super.jniMangle(binding)); if (callThroughProcAddress) { jniMangle(Long.TYPE, buf, false); // to account for the additional _addr_ parameter } diff --git a/src/java/com/jogamp/gluegen/procaddress/ProcAddressConfiguration.java b/src/java/com/jogamp/gluegen/procaddress/ProcAddressConfiguration.java index 3341e45..7fc720c 100644 --- a/src/java/com/jogamp/gluegen/procaddress/ProcAddressConfiguration.java +++ b/src/java/com/jogamp/gluegen/procaddress/ProcAddressConfiguration.java @@ -61,10 +61,10 @@ public class ProcAddressConfiguration extends JavaConfiguration { // This is needed only on Windows. Ideally we would modify the // HeaderParser and PCPP to automatically pick up the calling // convention from the headers - private Map<String, String> localProcAddressCallingConventionMap = new HashMap<String, String>(); + private final Map<String, String> localProcAddressCallingConventionMap = new HashMap<String, String>(); @Override - protected void dispatch(String cmd, StringTokenizer tok, File file, String filename, int lineNo) throws IOException { + protected void dispatch(final String cmd, final StringTokenizer tok, final File file, final String filename, final int lineNo) throws IOException { if (cmd.equalsIgnoreCase("EmitProcAddressTable")) { emitProcAddressTable = readBoolean("EmitProcAddressTable", tok, filename, lineNo).booleanValue(); } else if (cmd.equalsIgnoreCase("ProcAddressTablePackage")) { @@ -72,10 +72,10 @@ public class ProcAddressConfiguration extends JavaConfiguration { } else if (cmd.equalsIgnoreCase("ProcAddressTableClassName")) { tableClassName = readString("ProcAddressTableClassName", tok, filename, lineNo); } else if (cmd.equalsIgnoreCase("SkipProcAddressGen")) { - String sym = readString("SkipProcAddressGen", tok, filename, lineNo); + final String sym = readString("SkipProcAddressGen", tok, filename, lineNo); skipProcAddressGen.add(sym); } else if (cmd.equalsIgnoreCase("ForceProcAddressGen")) { - String funcName = readString("ForceProcAddressGen", tok, filename, lineNo); + final String funcName = readString("ForceProcAddressGen", tok, filename, lineNo); if (funcName.equals("__ALL__")) { forceProcAddressGen4All = true; } else { @@ -92,24 +92,24 @@ public class ProcAddressConfiguration extends JavaConfiguration { } } - protected String readGetProcAddressTableExpr(StringTokenizer tok, String filename, int lineNo) { + protected String readGetProcAddressTableExpr(final StringTokenizer tok, final String filename, final int lineNo) { try { - String restOfLine = tok.nextToken("\n\r\f"); + final String restOfLine = tok.nextToken("\n\r\f"); return restOfLine.trim(); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"GetProcAddressTableExpr\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void setProcAddressNameExpr(String expr) { + protected void setProcAddressNameExpr(final String expr) { // Parse this into something allowing us to map from a function // name to the typedef'ed function pointer name - List<String> tokens = new ArrayList<String>(); - StringTokenizer tok1 = new StringTokenizer(expr); + final List<String> tokens = new ArrayList<String>(); + final StringTokenizer tok1 = new StringTokenizer(expr); while (tok1.hasMoreTokens()) { - String sstr = tok1.nextToken(); - StringTokenizer tok2 = new StringTokenizer(sstr, "$()", true); + final String sstr = tok1.nextToken(); + final StringTokenizer tok2 = new StringTokenizer(sstr, "$()", true); while (tok2.hasMoreTokens()) { tokens.add(tok2.nextToken()); } @@ -122,40 +122,40 @@ public class ProcAddressConfiguration extends JavaConfiguration { } } - protected void readProcAddressNameExpr(StringTokenizer tok, String filename, int lineNo) { + protected void readProcAddressNameExpr(final StringTokenizer tok, final String filename, final int lineNo) { try { String restOfLine = tok.nextToken("\n\r\f"); restOfLine = restOfLine.trim(); setProcAddressNameExpr(restOfLine); - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"ProcAddressNameExpr\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - protected void readLocalProcAddressCallingConvention(StringTokenizer tok, String filename, int lineNo) throws IOException { + protected void readLocalProcAddressCallingConvention(final StringTokenizer tok, final String filename, final int lineNo) throws IOException { try { - String functionName = tok.nextToken(); - String callingConvention = tok.nextToken(); + final String functionName = tok.nextToken(); + final String callingConvention = tok.nextToken(); if (functionName.equals("__ALL__")) { localProcAddressCallingConvention4All = callingConvention; } else { localProcAddressCallingConventionMap.put(functionName, callingConvention); } - } catch (NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new RuntimeException("Error parsing \"LocalProcAddressCallingConvention\" command at line " + lineNo + " in file \"" + filename + "\"", e); } } - private static ConvNode makeConverter(Iterator<String> iter) { - List<ConvNode> result = new ArrayList<ConvNode>(); + private static ConvNode makeConverter(final Iterator<String> iter) { + final List<ConvNode> result = new ArrayList<ConvNode>(); while (iter.hasNext()) { - String str = iter.next(); + final String str = iter.next(); if (str.equals("$")) { - String command = iter.next(); - String openParen = iter.next(); + final String command = iter.next(); + final String openParen = iter.next(); if (!openParen.equals("(")) { throw new NoSuchElementException("Expected \"(\""); } @@ -191,15 +191,15 @@ public class ProcAddressConfiguration extends JavaConfiguration { static class FormatNode extends ConvNode { - private MessageFormat msgFmt; + private final MessageFormat msgFmt; - FormatNode(String fmt) { + FormatNode(final String fmt) { msgFmt = new MessageFormat(fmt); } @Override - String convert(String funcName) { - StringBuffer buf = new StringBuffer(); + String convert(final String funcName) { + final StringBuffer buf = new StringBuffer(); msgFmt.format(new Object[]{funcName}, buf, null); return buf.toString(); } @@ -207,30 +207,30 @@ public class ProcAddressConfiguration extends JavaConfiguration { static class ConstStringNode extends ConvNode { - private String str; + private final String str; - ConstStringNode(String str) { + ConstStringNode(final String str) { this.str = str; } @Override - String convert(String funcName) { + String convert(final String funcName) { return str; } } static class ConcatNode extends ConvNode { - private List<ConvNode> children; + private final List<ConvNode> children; - ConcatNode(List<ConvNode> children) { + ConcatNode(final List<ConvNode> children) { this.children = children; } @Override - String convert(String funcName) { - StringBuilder res = new StringBuilder(); - for (ConvNode node : children) { + String convert(final String funcName) { + final StringBuilder res = new StringBuilder(); + for (final ConvNode node : children) { res.append(node.convert(funcName)); } return res.toString(); @@ -239,16 +239,16 @@ public class ProcAddressConfiguration extends JavaConfiguration { static class CaseNode extends ConvNode { - private boolean upperCase; - private ConvNode child; + private final boolean upperCase; + private final ConvNode child; - CaseNode(boolean upperCase, ConvNode child) { + CaseNode(final boolean upperCase, final ConvNode child) { this.upperCase = upperCase; this.child = child; } @Override - public String convert(String funcName) { + public String convert(final String funcName) { if (upperCase) { return child.convert(funcName).toUpperCase(); } else { @@ -269,7 +269,7 @@ public class ProcAddressConfiguration extends JavaConfiguration { return tableClassName; } - public boolean skipProcAddressGen(String name) { + public boolean skipProcAddressGen(final String name) { return skipProcAddressGen.contains(name); } @@ -288,27 +288,27 @@ public class ProcAddressConfiguration extends JavaConfiguration { return getProcAddressTableExpr; } - public String convertToFunctionPointerName(String funcName) { + public String convertToFunctionPointerName(final String funcName) { if (procAddressNameConverter == null) { throw new RuntimeException("ProcAddressNameExpr was not defined in .cfg file"); } return procAddressNameConverter.convert(funcName); } - public boolean forceProcAddressGen(String funcName) { + public boolean forceProcAddressGen(final String funcName) { return forceProcAddressGen4All || forceProcAddressGenSet.contains(funcName); } - public void addForceProcAddressGen(String funcName) { + public void addForceProcAddressGen(final String funcName) { forceProcAddressGen.add(funcName); forceProcAddressGenSet.add(funcName); } - public void addLocalProcAddressCallingConvention(String funcName, String callingConvention) { + public void addLocalProcAddressCallingConvention(final String funcName, final String callingConvention) { localProcAddressCallingConventionMap.put(funcName, callingConvention); } - public String getLocalProcAddressCallingConvention(String funcName) { + public String getLocalProcAddressCallingConvention(final String funcName) { if (isLocalProcAddressCallingConvention4All()) { return getLocalProcAddressCallingConvention4All(); } diff --git a/src/java/com/jogamp/gluegen/procaddress/ProcAddressEmitter.java b/src/java/com/jogamp/gluegen/procaddress/ProcAddressEmitter.java index 6acaacd..a0adbd0 100644 --- a/src/java/com/jogamp/gluegen/procaddress/ProcAddressEmitter.java +++ b/src/java/com/jogamp/gluegen/procaddress/ProcAddressEmitter.java @@ -78,7 +78,7 @@ public class ProcAddressEmitter extends JavaEmitter { protected String tableClassName; @Override - public void beginFunctions(TypeDictionary typedefDictionary, TypeDictionary structDictionary, Map<Type, Type> canonMap) throws Exception { + public void beginFunctions(final TypeDictionary typedefDictionary, final TypeDictionary structDictionary, final Map<Type, Type> canonMap) throws Exception { this.typedefDictionary = typedefDictionary; if (getProcAddressConfig().emitProcAddressTable()) { @@ -96,7 +96,7 @@ public class ProcAddressEmitter extends JavaEmitter { } @Override - public void beginStructs(TypeDictionary typedefDictionary, TypeDictionary structDictionary, Map<Type, Type> canonMap) throws Exception { + public void beginStructs(final TypeDictionary typedefDictionary, final TypeDictionary structDictionary, final Map<Type, Type> canonMap) throws Exception { super.beginStructs(typedefDictionary, structDictionary, canonMap); } @@ -114,11 +114,11 @@ public class ProcAddressEmitter extends JavaEmitter { } @Override - protected List<? extends FunctionEmitter> generateMethodBindingEmitters(Set<MethodBinding> methodBindingSet, FunctionSymbol sym) throws Exception { + protected List<? extends FunctionEmitter> generateMethodBindingEmitters(final Set<MethodBinding> methodBindingSet, final FunctionSymbol sym) throws Exception { return generateMethodBindingEmittersImpl(methodBindingSet, sym); } - protected boolean needsModifiedEmitters(FunctionSymbol sym) { + protected boolean needsModifiedEmitters(final FunctionSymbol sym) { if (!needsProcAddressWrapper(sym) || getConfig().isUnimplemented(getAliasedSymName(sym))) { return false; } @@ -126,8 +126,8 @@ public class ProcAddressEmitter extends JavaEmitter { return true; } - private List<? extends FunctionEmitter> generateMethodBindingEmittersImpl(Set<MethodBinding> methodBindingSet, FunctionSymbol sym) throws Exception { - List<? extends FunctionEmitter> defaultEmitters = super.generateMethodBindingEmitters(methodBindingSet, sym); + private List<? extends FunctionEmitter> generateMethodBindingEmittersImpl(final Set<MethodBinding> methodBindingSet, final FunctionSymbol sym) throws Exception { + final List<? extends FunctionEmitter> defaultEmitters = super.generateMethodBindingEmitters(methodBindingSet, sym); // if the superclass didn't generate any bindings for the symbol, let's // honor that (for example, the superclass might have caught an Ignore @@ -142,7 +142,7 @@ public class ProcAddressEmitter extends JavaEmitter { return defaultEmitters; } - ArrayList<FunctionEmitter> modifiedEmitters = new ArrayList<FunctionEmitter>(defaultEmitters.size()); + final ArrayList<FunctionEmitter> modifiedEmitters = new ArrayList<FunctionEmitter>(defaultEmitters.size()); if (needsProcAddressWrapper(sym)) { if (getProcAddressConfig().emitProcAddressTable()) { @@ -150,7 +150,7 @@ public class ProcAddressEmitter extends JavaEmitter { emitProcAddressTableEntryForString(getAliasedSymName(sym)); } } - for (FunctionEmitter emitter : defaultEmitters) { + for (final FunctionEmitter emitter : defaultEmitters) { if (emitter instanceof JavaMethodBindingEmitter) { generateModifiedEmitters((JavaMethodBindingEmitter)emitter, modifiedEmitters); } else if (emitter instanceof CMethodBindingEmitter) { @@ -171,7 +171,7 @@ public class ProcAddressEmitter extends JavaEmitter { * "PFNGLFUNCNAMEPROC". This returns a valid string regardless of * whether or not the typedef is actually defined. */ - protected String getFunctionPointerTypedefName(FunctionSymbol sym) { + protected String getFunctionPointerTypedefName(final FunctionSymbol sym) { return getProcAddressConfig().convertToFunctionPointerName(sym.getName()); } @@ -180,7 +180,7 @@ public class ProcAddressEmitter extends JavaEmitter { // /** If 'native', enforce 'private native' modifiers. */ - protected void fixSecurityModifiers(JavaMethodBindingEmitter javaEmitter) { + protected void fixSecurityModifiers(final JavaMethodBindingEmitter javaEmitter) { if( javaEmitter.hasModifier(JavaMethodBindingEmitter.NATIVE) && !javaEmitter.hasModifier(JavaMethodBindingEmitter.PRIVATE) ) { @@ -192,9 +192,9 @@ public class ProcAddressEmitter extends JavaEmitter { } } - protected void generateModifiedEmitters(JavaMethodBindingEmitter baseJavaEmitter, List<FunctionEmitter> emitters) { + protected void generateModifiedEmitters(final JavaMethodBindingEmitter baseJavaEmitter, final List<FunctionEmitter> emitters) { // See whether we need a proc address entry for this one - boolean callThroughProcAddress = needsProcAddressWrapper(baseJavaEmitter.getBinding().getCSymbol()); + final boolean callThroughProcAddress = needsProcAddressWrapper(baseJavaEmitter.getBinding().getCSymbol()); // If this emitter doesn't have a body (i.e., is a direct native // call with no intervening argument processing), we need to force @@ -238,13 +238,13 @@ public class ProcAddressEmitter extends JavaEmitter { } } - protected void generateModifiedEmitters(CMethodBindingEmitter baseCEmitter, List<FunctionEmitter> emitters) { + protected void generateModifiedEmitters(final CMethodBindingEmitter baseCEmitter, final List<FunctionEmitter> emitters) { - FunctionSymbol cSymbol = baseCEmitter.getBinding().getCSymbol(); + final FunctionSymbol cSymbol = baseCEmitter.getBinding().getCSymbol(); // See whether we need a proc address entry for this one - boolean callThroughProcAddress = needsProcAddressWrapper(cSymbol); - boolean forceProcAddress = getProcAddressConfig().forceProcAddressGen(cSymbol.getName()); + final boolean callThroughProcAddress = needsProcAddressWrapper(cSymbol); + final boolean forceProcAddress = getProcAddressConfig().forceProcAddressGen(cSymbol.getName()); String forcedCallingConvention = null; if (forceProcAddress) { @@ -257,17 +257,17 @@ public class ProcAddressEmitter extends JavaEmitter { // The C-side JNI binding for this particular function will have an // extra final argument, which is the address (the OpenGL procedure // address) of the function it needs to call - ProcAddressCMethodBindingEmitter res = new ProcAddressCMethodBindingEmitter( + final ProcAddressCMethodBindingEmitter res = new ProcAddressCMethodBindingEmitter( baseCEmitter, callThroughProcAddress, forceProcAddress, forcedCallingConvention, this); - MessageFormat exp = baseCEmitter.getReturnValueCapacityExpression(); + final MessageFormat exp = baseCEmitter.getReturnValueCapacityExpression(); if (exp != null) { res.setReturnValueCapacityExpression(exp); } emitters.add(res); } - private String getAliasedSymName(FunctionSymbol sym) { + private String getAliasedSymName(final FunctionSymbol sym) { String symName = getConfig().getJavaSymbolRename(sym.getName()); if (null == symName) { symName = sym.getName(); @@ -275,14 +275,14 @@ public class ProcAddressEmitter extends JavaEmitter { return symName; } - protected boolean needsProcAddressWrapper(FunctionSymbol sym) { - String symName = getAliasedSymName(sym); + protected boolean needsProcAddressWrapper(final FunctionSymbol sym) { + final String symName = getAliasedSymName(sym); - ProcAddressConfiguration config = getProcAddressConfig(); + final ProcAddressConfiguration config = getProcAddressConfig(); // We should only generate code to call through a function pointer // if the symbol has an associated function pointer typedef. - String funcPointerTypedefName = getFunctionPointerTypedefName(sym); + final String funcPointerTypedefName = getFunctionPointerTypedefName(sym); boolean shouldWrap = typedefDictionary.containsKey(funcPointerTypedefName); //System.err.println(funcPointerTypedefName + " defined: " + shouldWrap); @@ -319,7 +319,7 @@ public class ProcAddressEmitter extends JavaEmitter { tableWriter.println("package " + implPackageName + ";"); tableWriter.println(); - for (String imporT : getConfig().imports()) { + for (final String imporT : getConfig().imports()) { tableWriter.println("import " + imporT + ";"); } tableWriter.println("import " + ProcAddressTable.class.getName() + ";"); @@ -333,7 +333,7 @@ public class ProcAddressEmitter extends JavaEmitter { tableWriter.println(tableClassAccess.getJavaName() + " final class " + tableClassName + " extends "+ ProcAddressTable.class.getSimpleName() + " {"); tableWriter.println(); - for (String string : getProcAddressConfig().getForceProcAddressGen()) { + for (final String string : getProcAddressConfig().getForceProcAddressGen()) { emitProcAddressTableEntryForString(string); } @@ -351,7 +351,7 @@ public class ProcAddressEmitter extends JavaEmitter { tableWriter.close(); } - protected void emitProcAddressTableEntryForString(String str) { + protected void emitProcAddressTableEntryForString(final String str) { // Deal gracefully with forced proc address generation in the face // of having the function pointer typedef in the header file too if (emittedTableEntries.contains(str)) { diff --git a/src/java/com/jogamp/gluegen/procaddress/ProcAddressJavaMethodBindingEmitter.java b/src/java/com/jogamp/gluegen/procaddress/ProcAddressJavaMethodBindingEmitter.java index f28c50d..a70c18d 100644 --- a/src/java/com/jogamp/gluegen/procaddress/ProcAddressJavaMethodBindingEmitter.java +++ b/src/java/com/jogamp/gluegen/procaddress/ProcAddressJavaMethodBindingEmitter.java @@ -53,8 +53,8 @@ public class ProcAddressJavaMethodBindingEmitter extends JavaMethodBindingEmitte protected String getProcAddressTableExpr; protected ProcAddressEmitter emitter; - public ProcAddressJavaMethodBindingEmitter(JavaMethodBindingEmitter methodToWrap, boolean callThroughProcAddress, - String getProcAddressTableExpr, boolean changeNameAndArguments, ProcAddressEmitter emitter) { + public ProcAddressJavaMethodBindingEmitter(final JavaMethodBindingEmitter methodToWrap, final boolean callThroughProcAddress, + final String getProcAddressTableExpr, final boolean changeNameAndArguments, final ProcAddressEmitter emitter) { super(methodToWrap); @@ -74,14 +74,14 @@ public class ProcAddressJavaMethodBindingEmitter extends JavaMethodBindingEmitte } } - public ProcAddressJavaMethodBindingEmitter(ProcAddressJavaMethodBindingEmitter methodToWrap) { + public ProcAddressJavaMethodBindingEmitter(final ProcAddressJavaMethodBindingEmitter methodToWrap) { this(methodToWrap, methodToWrap.callThroughProcAddress, methodToWrap.getProcAddressTableExpr, methodToWrap.changeNameAndArguments, methodToWrap.emitter); } @Override public String getName() { - String res = super.getName(); + final String res = super.getName(); if (changeNameAndArguments) { return ProcAddressEmitter.WRAP_PREFIX + res; } @@ -89,7 +89,7 @@ public class ProcAddressJavaMethodBindingEmitter extends JavaMethodBindingEmitte } @Override - protected int emitArguments(PrintWriter writer) { + protected int emitArguments(final PrintWriter writer) { int numEmitted = super.emitArguments(writer); if (callThroughProcAddress) { if (changeNameAndArguments) { @@ -107,7 +107,7 @@ public class ProcAddressJavaMethodBindingEmitter extends JavaMethodBindingEmitte @Override protected String getImplMethodName() { - String name = super.getImplMethodName(); + final String name = super.getImplMethodName(); if (callThroughProcAddress) { return ProcAddressEmitter.WRAP_PREFIX + name; } @@ -115,11 +115,11 @@ public class ProcAddressJavaMethodBindingEmitter extends JavaMethodBindingEmitte } @Override - protected void emitPreCallSetup(MethodBinding binding, PrintWriter writer) { + protected void emitPreCallSetup(final MethodBinding binding, final PrintWriter writer) { super.emitPreCallSetup(binding, writer); if (callThroughProcAddress) { - String procAddressVariable = ProcAddressEmitter.PROCADDRESS_VAR_PREFIX + binding.getName(); + final String procAddressVariable = ProcAddressEmitter.PROCADDRESS_VAR_PREFIX + binding.getName(); writer.println(" final long __addr_ = " + getProcAddressTableExpr + "." + procAddressVariable + ";"); writer.println(" if (__addr_ == 0) {"); writer.format(" throw new %s(String.format(\"Method \\\"%%s\\\" not available\", \"%s\"));%n", @@ -129,7 +129,7 @@ public class ProcAddressJavaMethodBindingEmitter extends JavaMethodBindingEmitte } @Override - protected int emitCallArguments(MethodBinding binding, PrintWriter writer) { + protected int emitCallArguments(final MethodBinding binding, final PrintWriter writer) { int numEmitted = super.emitCallArguments(binding, writer); if (callThroughProcAddress) { if (numEmitted > 0) { @@ -146,7 +146,7 @@ public class ProcAddressJavaMethodBindingEmitter extends JavaMethodBindingEmitte public class WrappedMethodCommentEmitter extends JavaMethodBindingEmitter.DefaultCommentEmitter { @Override - protected void emitBeginning(FunctionEmitter methodEmitter, PrintWriter writer) { + protected void emitBeginning(final FunctionEmitter methodEmitter, final PrintWriter writer) { writer.print("Entry point (through function pointer) to C language function: <br> "); } } diff --git a/src/java/com/jogamp/gluegen/runtime/ProcAddressTable.java b/src/java/com/jogamp/gluegen/runtime/ProcAddressTable.java index 727d0b4..a0988cd 100644 --- a/src/java/com/jogamp/gluegen/runtime/ProcAddressTable.java +++ b/src/java/com/jogamp/gluegen/runtime/ProcAddressTable.java @@ -105,7 +105,7 @@ public abstract class ProcAddressTable { this(new One2OneResolver()); } - public ProcAddressTable(FunctionAddressResolver resolver) { + public ProcAddressTable(final FunctionAddressResolver resolver) { this.resolver = resolver; } @@ -118,7 +118,7 @@ public abstract class ProcAddressTable { * </p> * @throws SecurityException if user is not granted access for all libraries. */ - public void reset(DynamicLookupHelper lookup) throws SecurityException, RuntimeException { + public void reset(final DynamicLookupHelper lookup) throws SecurityException, RuntimeException { SecurityUtil.checkAllLinkPermission(); if(null==lookup) { @@ -179,7 +179,7 @@ public abstract class ProcAddressTable { if (DEBUG) { getDebugOutStream().println(" " + addressField.getName() + " -> 0x" + Long.toHexString(newProcAddress)); } - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Can not get proc address for method \"" + funcName + "\": Couldn't set value of field \"" + addressField, e); } @@ -192,7 +192,7 @@ public abstract class ProcAddressTable { private final Field fieldForFunction(final String name) throws IllegalArgumentException { try { return getClass().getDeclaredField(PROCADDRESS_VAR_PREFIX + name); - } catch (NoSuchFieldException ex) { + } catch (final NoSuchFieldException ex) { throw new IllegalArgumentException(getClass().getName() +" has no entry for the function '"+name+"'.", ex); } } @@ -213,14 +213,14 @@ public abstract class ProcAddressTable { final Field addressField = ProcAddressTable.this.getClass().getDeclaredField(PROCADDRESS_VAR_PREFIX + name); addressField.setAccessible(true); // we need to read the protected value! return addressField; - } catch (NoSuchFieldException ex) { + } catch (final NoSuchFieldException ex) { throw new IllegalArgumentException(getClass().getName() +" has no entry for the function '"+name+"'.", ex); } } } ); } - private final boolean isAddressField(String fieldName) { + private final boolean isAddressField(final String fieldName) { return fieldName.startsWith(PROCADDRESS_VAR_PREFIX); } @@ -231,7 +231,7 @@ public abstract class ProcAddressTable { try { out = new PrintStream(new BufferedOutputStream(new FileOutputStream(DEBUG_PREFIX + File.separatorChar + "procaddresstable-" + (++debugNum) + ".txt"))); - } catch (IOException e) { + } catch (final IOException e) { e.printStackTrace(); out = System.err; } @@ -256,9 +256,9 @@ public abstract class ProcAddressTable { map.put(fieldToFunctionName(addressFieldName), (Long)fields[i].get(this)); } } - } catch (IllegalArgumentException ex) { + } catch (final IllegalArgumentException ex) { throw new RuntimeException(ex); - } catch (IllegalAccessException ex) { + } catch (final IllegalAccessException ex) { throw new RuntimeException(ex); } @@ -268,10 +268,10 @@ public abstract class ProcAddressTable { /** * Returns true only if non null function pointer to this function exists. */ - public final boolean isFunctionAvailable(String functionName) { + public final boolean isFunctionAvailable(final String functionName) { try{ return isFunctionAvailableImpl(functionName); - } catch (IllegalArgumentException ex) { + } catch (final IllegalArgumentException ex) { return false; } } @@ -286,11 +286,11 @@ public abstract class ProcAddressTable { * * @throws IllegalArgumentException if this function is not in this table. */ - protected boolean isFunctionAvailableImpl(String functionName) throws IllegalArgumentException { + protected boolean isFunctionAvailableImpl(final String functionName) throws IllegalArgumentException { final Field addressField = fieldForFunctionInSec(functionName); try { return 0 != addressField.getLong(this); - } catch (IllegalAccessException ex) { + } catch (final IllegalAccessException ex) { throw new RuntimeException(ex); } } @@ -310,12 +310,12 @@ public abstract class ProcAddressTable { * @throws IllegalArgumentException if this function is not in this table. * @throws SecurityException if user is not granted access for all libraries. */ - public long getAddressFor(String functionName) throws SecurityException, IllegalArgumentException { + public long getAddressFor(final String functionName) throws SecurityException, IllegalArgumentException { SecurityUtil.checkAllLinkPermission(); final Field addressField = fieldForFunctionInSec(functionName); try { return addressField.getLong(this); - } catch (IllegalAccessException ex) { + } catch (final IllegalAccessException ex) { throw new RuntimeException(ex); } } @@ -324,11 +324,11 @@ public abstract class ProcAddressTable { * Returns all functions pointing to null. */ public final Set<String> getNullPointerFunctions() { - Map<String, Long> table = toMap(); - Set<String> nullPointers = new LinkedHashSet<String>(); - for (Iterator<Map.Entry<String, Long>> it = table.entrySet().iterator(); it.hasNext();) { - Map.Entry<String, Long> entry = it.next(); - long address = entry.getValue().longValue(); + final Map<String, Long> table = toMap(); + final Set<String> nullPointers = new LinkedHashSet<String>(); + for (final Iterator<Map.Entry<String, Long>> it = table.entrySet().iterator(); it.hasNext();) { + final Map.Entry<String, Long> entry = it.next(); + final long address = entry.getValue().longValue(); if(address == 0) { nullPointers.add(entry.getKey()); } @@ -343,7 +343,7 @@ public abstract class ProcAddressTable { private static class One2OneResolver implements FunctionAddressResolver { @Override - public long resolve(String name, DynamicLookupHelper lookup) { + public long resolve(final String name, final DynamicLookupHelper lookup) { return lookup.dynamicLookupFunction(name); } } diff --git a/src/java/com/jogamp/gluegen/structgen/CStructAnnotationProcessor.java b/src/java/com/jogamp/gluegen/structgen/CStructAnnotationProcessor.java index 0e5ef85..c4dedb7 100644 --- a/src/java/com/jogamp/gluegen/structgen/CStructAnnotationProcessor.java +++ b/src/java/com/jogamp/gluegen/structgen/CStructAnnotationProcessor.java @@ -92,7 +92,7 @@ public class CStructAnnotationProcessor extends AbstractProcessor { static { Debug.initSingleton(); - DEBUG = Debug.isPropertyDefined("jogamp.gluegen.structgen.debug", true); + DEBUG = PropertyAccess.isPropertyDefined("jogamp.gluegen.structgen.debug", true); } private static final String STRUCTGENOUTPUT_OPTION = "structgen.output"; @@ -107,7 +107,7 @@ public class CStructAnnotationProcessor extends AbstractProcessor { @Override - public void init(ProcessingEnvironment processingEnv) { + public void init(final ProcessingEnvironment processingEnv) { super.init(processingEnv); filer = processingEnv.getFiler(); @@ -118,7 +118,7 @@ public class CStructAnnotationProcessor extends AbstractProcessor { outputPath = outputPath == null ? STRUCTGENOUTPUT : outputPath; } - private File locateSource(String packageName, String relativeName) { + private File locateSource(final String packageName, final String relativeName) { try { if( DEBUG ) { System.err.println("CStruct.locateSource.0: p "+packageName+", r "+relativeName); @@ -131,28 +131,28 @@ public class CStructAnnotationProcessor extends AbstractProcessor { if( f.exists() ) { return f; } - } catch (IOException e) { if(DEBUG) { System.err.println("Caught "+e.getClass().getSimpleName()+": "+e.getMessage()); /* e.printStackTrace(); */ } } + } catch (final IOException e) { if(DEBUG) { System.err.println("Caught "+e.getClass().getSimpleName()+": "+e.getMessage()); /* e.printStackTrace(); */ } } return null; } @Override - public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) { + public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment env) { final String user_dir = System.getProperty("user.dir"); final Set<? extends Element> cStructsElements = env.getElementsAnnotatedWith(CStructs.class); - for (Element structsElement : cStructsElements) { + for (final Element structsElement : cStructsElements) { final String packageName = eltUtils.getPackageOf(structsElement).toString(); final CStructs cstructs = structsElement.getAnnotation(CStructs.class); if( null != cstructs ) { final CStruct[] cstructArray = cstructs.value(); - for(CStruct cstruct : cstructArray) { + for(final CStruct cstruct : cstructArray) { processCStruct(cstruct, structsElement, packageName, user_dir); } } } final Set<? extends Element> cStructElements = env.getElementsAnnotatedWith(CStruct.class); - for (Element structElement : cStructElements) { + for (final Element structElement : cStructElements) { final String packageName = eltUtils.getPackageOf(structElement).toString(); final CStruct cstruct = structElement.getAnnotation(CStruct.class); if( null != cstruct ) { @@ -205,12 +205,12 @@ public class CStructAnnotationProcessor extends AbstractProcessor { System.err.println("CStruct: "+headerFile+", abs: "+headerFile.isAbsolute()+", headerParent "+headerParent+", rootOut "+rootOut); generateStructBinding(element, struct, isPackageOrType, rootOut, packageName, headerFile, headerParent); - } catch (IOException ex) { + } catch (final IOException ex) { throw new RuntimeException("IOException while processing!", ex); } } - private void generateStructBinding(Element element, CStruct struct, boolean isPackageOrType, String rootOut, String pakage, File header, String headerParent) throws IOException { + private void generateStructBinding(final Element element, final CStruct struct, final boolean isPackageOrType, final String rootOut, final String pakage, final File header, final String headerParent) throws IOException { final String declaredType = element.asType().toString(); final boolean useStructName = !struct.name().equals(DEFAULT); final String structName = useStructName ? struct.name() : declaredType; @@ -260,7 +260,7 @@ public class CStructAnnotationProcessor extends AbstractProcessor { final String filename = header.getPath(); try { reader = new BufferedReader(new FileReader(filename)); - } catch (FileNotFoundException ex) { + } catch (final FileNotFoundException ex) { throw new RuntimeException("input file not found", ex); } new GlueGen().run(reader, filename, AnnotationProcessorJavaStructEmitter.class, @@ -273,7 +273,7 @@ public class CStructAnnotationProcessor extends AbstractProcessor { public static class AnnotationProcessorJavaStructEmitter extends JavaEmitter { @Override - protected PrintWriter openFile(String filename, String simpleClassName) throws IOException { + protected PrintWriter openFile(final String filename, final String simpleClassName) throws IOException { if( generatedStructs.contains(simpleClassName) ) { System.err.println("skipping -> " + simpleClassName); |