From e2b6752efbef74bb97788e3c52cf981e0163c13d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Hru=C5=A1ka?= Date: Sun, 6 Apr 2014 20:53:52 +0200 Subject: [PATCH] Clean up - Added final keyword wherever possible - Improved some font code --- src/mightypork/rogue/App.java | 26 ++-- src/mightypork/rogue/AppAdapter.java | 2 +- src/mightypork/rogue/Config.java | 3 +- src/mightypork/rogue/MainLoop.java | 8 +- src/mightypork/rogue/Res.java | 11 +- .../rogue/bus/events/ActionRequest.java | 5 +- .../rogue/bus/events/KeyboardEvent.java | 2 +- .../rogue/bus/events/MainLoopTaskRequest.java | 5 +- .../rogue/bus/events/MouseButtonEvent.java | 4 +- .../rogue/bus/events/MouseMotionEvent.java | 7 +- .../rogue/bus/events/ResourceLoadRequest.java | 11 +- .../rogue/bus/events/ScreenChangeEvent.java | 2 +- .../rogue/bus/events/ScreenRequestEvent.java | 10 +- src/mightypork/rogue/fonts/DeferredFont.java | 11 +- src/mightypork/rogue/fonts/FontBank.java | 2 +- src/mightypork/rogue/fonts/GLFont.java | 12 +- src/mightypork/rogue/fonts/SlickFont.java | 4 +- src/mightypork/rogue/gui/LayeredScreen.java | 2 +- src/mightypork/rogue/gui/Screen.java | 6 +- src/mightypork/rogue/gui/ScreenLayer.java | 2 +- src/mightypork/rogue/gui/ScreenRegistry.java | 2 +- .../rogue/gui/constraints/ElementHolder.java | 16 +-- .../constraints/RenderableWithContext.java | 7 +- .../screens/test_bouncyboxes/BouncyBox.java | 12 +- .../test_bouncyboxes/LayerBouncyBoxes.java | 8 +- .../test_bouncyboxes/ScreenTestBouncy.java | 2 +- .../test_cat_sound/LayerFlyingCat.java | 18 +-- .../gui/screens/test_font/ScreenTestFont.java | 6 +- src/mightypork/rogue/input/InputSystem.java | 22 +-- src/mightypork/rogue/input/KeyBinder.java | 4 +- src/mightypork/rogue/input/KeyBinding.java | 18 +++ .../rogue/input/KeyBindingPool.java | 8 +- src/mightypork/rogue/input/KeyStroke.java | 21 ++- ...edLoader.java => AsyncResourceLoader.java} | 30 ++--- .../rogue/loading/BaseDeferredResource.java | 127 ++++++++++++++++++ src/mightypork/rogue/loading/Deferred.java | 23 ---- .../rogue/loading/DeferredResource.java | 118 +--------------- .../rogue/loading/MustLoadInMainThread.java | 12 +- .../rogue/render/DisplaySystem.java | 18 +-- src/mightypork/rogue/render/Render.java | 52 ++++--- .../constraints => render}/Renderable.java | 4 +- src/mightypork/rogue/sound/DeferredAudio.java | 6 +- src/mightypork/rogue/sound/JointVolume.java | 2 +- src/mightypork/rogue/sound/SoundBank.java | 4 +- src/mightypork/rogue/sound/SoundSystem.java | 12 +- .../rogue/sound/players/LoopPlayer.java | 2 +- .../rogue/tasks/TaskTakeScreenshot.java | 20 +-- .../DeferredTexture.java | 7 +- .../FilteredTexture.java | 8 +- .../{texture => textures}/TextureBank.java | 20 +-- .../rogue/{texture => textures}/TxQuad.java | 6 +- src/mightypork/rogue/util/Utils.java | 2 +- .../utils/control/bus/BufferedHashSet.java | 8 +- .../utils/control/bus/EventBus.java | 36 +++-- .../utils/control/bus/EventChannel.java | 15 ++- .../utils/control/bus/SingularEvent.java | 14 +- .../utils/control/timing/TimerDelta.java | 4 +- .../utils/control/timing/TimerFps.java | 12 +- src/mightypork/utils/files/FileTreeDiff.java | 34 ++--- src/mightypork/utils/files/FileUtils.java | 56 ++++---- src/mightypork/utils/files/OsUtils.java | 8 +- .../utils/files/PropertyManager.java | 98 +++++++------- src/mightypork/utils/files/SimpleConfig.java | 20 +-- src/mightypork/utils/files/ZipBuilder.java | 10 +- src/mightypork/utils/files/ZipUtils.java | 34 ++--- .../utils/files/ion/AbstractIonList.java | 10 +- .../utils/files/ion/AbstractIonMap.java | 12 +- .../utils/files/ion/BinaryUtils.java | 18 +-- src/mightypork/utils/files/ion/Ion.java | 30 ++--- src/mightypork/utils/files/ion/IonList.java | 4 +- src/mightypork/utils/logging/Log.java | 12 +- src/mightypork/utils/logging/LogInstance.java | 40 +++--- src/mightypork/utils/math/Calc.java | 44 +++--- src/mightypork/utils/math/Polar.java | 2 +- src/mightypork/utils/math/Range.java | 6 +- .../utils/math/animation/AnimDouble.java | 4 +- .../utils/math/animation/AnimDoubleDeg.java | 4 +- .../utils/math/animation/AnimDoubleRad.java | 4 +- .../utils/math/animation/Easing.java | 12 +- src/mightypork/utils/math/color/HSV.java | 2 +- src/mightypork/utils/math/color/RGB.java | 14 +- .../math/constraints/ConstraintFactory.java | 22 +-- src/mightypork/utils/math/coord/Coord.java | 4 +- src/mightypork/utils/objects/Convertor.java | 20 +-- src/mightypork/utils/objects/MapSort.java | 76 +++++++++++ src/mightypork/utils/objects/Mutable.java | 2 +- src/mightypork/utils/objects/ObjectUtils.java | 79 ++--------- src/mightypork/utils/objects/Pair.java | 2 +- .../utils/objects/VarargsParser.java | 4 +- src/mightypork/utils/string/StringUtils.java | 8 +- .../string/validation/CharValidatorRegex.java | 2 +- .../validation/CharValidatorWhitelist.java | 2 +- .../string/validation/FileSuffixFilter.java | 4 +- 93 files changed, 803 insertions(+), 741 deletions(-) rename src/mightypork/rogue/loading/{DeferredLoader.java => AsyncResourceLoader.java} (62%) create mode 100644 src/mightypork/rogue/loading/BaseDeferredResource.java delete mode 100644 src/mightypork/rogue/loading/Deferred.java rename src/mightypork/rogue/{gui/constraints => render}/Renderable.java (65%) rename src/mightypork/rogue/{texture => textures}/DeferredTexture.java (94%) rename src/mightypork/rogue/{texture => textures}/FilteredTexture.java (80%) rename src/mightypork/rogue/{texture => textures}/TextureBank.java (85%) rename src/mightypork/rogue/{texture => textures}/TxQuad.java (93%) create mode 100644 src/mightypork/utils/objects/MapSort.java diff --git a/src/mightypork/rogue/App.java b/src/mightypork/rogue/App.java index 54026c8..d05f6e0 100644 --- a/src/mightypork/rogue/App.java +++ b/src/mightypork/rogue/App.java @@ -16,7 +16,6 @@ import mightypork.rogue.gui.screens.test_cat_sound.ScreenTestCat; import mightypork.rogue.gui.screens.test_font.ScreenTestFont; import mightypork.rogue.input.InputSystem; import mightypork.rogue.input.KeyStroke; -import mightypork.rogue.loading.DeferredLoader; import mightypork.rogue.render.DisplaySystem; import mightypork.rogue.sound.SoundSystem; import mightypork.utils.control.bus.EventBus; @@ -62,7 +61,7 @@ public class App implements AppAccess { try { inst.start(); - } catch (Throwable t) { + } catch (final Throwable t) { onCrash(t); } @@ -124,7 +123,7 @@ public class App implements AppAccess { /* * Setup logging */ - LogInstance log = Log.create("runtime", Paths.LOGS, 10); + final LogInstance log = Log.create("runtime", Paths.LOGS, 10); log.enable(Config.LOGGING_ENABLED); log.enableSysout(Config.LOG_TO_STDOUT); @@ -153,14 +152,6 @@ public class App implements AppAccess { soundSystem = new SoundSystem(this); soundSystem.setMasterVolume(1); - /* - * Load resources - */ - Log.f1("Registering resources..."); - bus().subscribe(new DeferredLoader(this)); - - Res.load(this); - /* * Input */ @@ -168,6 +159,13 @@ public class App implements AppAccess { inputSystem = new InputSystem(this); setupGlobalKeystrokes(); + /* + * Load resources + */ + Log.f1("Loading resources..."); + + Res.load(this); + /* * Screen registry */ @@ -179,7 +177,7 @@ public class App implements AppAccess { * Prepare main loop */ Log.f1("Preparing main loop..."); - ArrayList loopTasks = new ArrayList(); + final ArrayList loopTasks = new ArrayList(); loopTasks.add(new Runnable() { @@ -304,7 +302,7 @@ public class App implements AppAccess { fileLock.release(); randomAccessFile.close(); lockFile.delete(); - } catch (Exception e) { + } catch (final Exception e) { System.err.println("Unable to remove lock file."); e.printStackTrace(); } @@ -313,7 +311,7 @@ public class App implements AppAccess { return true; } - } catch (Exception e) { + } catch (final Exception e) { System.err.println("Unable to create and/or lock file."); e.printStackTrace(); } diff --git a/src/mightypork/rogue/AppAdapter.java b/src/mightypork/rogue/AppAdapter.java index f2593bb..a575970 100644 --- a/src/mightypork/rogue/AppAdapter.java +++ b/src/mightypork/rogue/AppAdapter.java @@ -14,7 +14,7 @@ import mightypork.utils.control.bus.EventBus; */ public class AppAdapter implements AppAccess { - private AppAccess app; + private final AppAccess app; public AppAdapter(AppAccess app) { diff --git a/src/mightypork/rogue/Config.java b/src/mightypork/rogue/Config.java index 73dcf6b..9b37e70 100644 --- a/src/mightypork/rogue/Config.java +++ b/src/mightypork/rogue/Config.java @@ -33,7 +33,7 @@ public class Config { { Log.f2("Initializing configuration manager."); - String comment = Const.APP_NAME + " config file"; + final String comment = Const.APP_NAME + " config file"; mgr = new PropertyManager(Paths.CONFIG, comment); @@ -76,7 +76,6 @@ public class Config { public static boolean LOG_TO_STDOUT = true; public static boolean SINGLE_INSTANCE = true; - public static boolean LOG_FONTS = false; public static boolean LOG_BUS = false; } diff --git a/src/mightypork/rogue/MainLoop.java b/src/mightypork/rogue/MainLoop.java index 49b8758..cf92ece 100644 --- a/src/mightypork/rogue/MainLoop.java +++ b/src/mightypork/rogue/MainLoop.java @@ -18,8 +18,8 @@ import mightypork.utils.control.timing.TimerDelta; public class MainLoop extends Subsystem implements ActionRequest.Listener, MainLoopTaskRequest.Listener { - private Queue taskQueue = new ConcurrentLinkedQueue(); - private List regularTasks; + private final Queue taskQueue = new ConcurrentLinkedQueue(); + private final List regularTasks; public MainLoop(App app, ArrayList loopTasks) { @@ -42,7 +42,7 @@ public class MainLoop extends Subsystem implements ActionRequest.Listener, MainL bus().send(new UpdateEvent(timer.getDelta())); - for (Runnable r : regularTasks) { + for (final Runnable r : regularTasks) { r.run(); } @@ -113,7 +113,7 @@ public class MainLoop extends Subsystem implements ActionRequest.Listener, MainL @Override - public void queueTask(Runnable request) + public synchronized void queueTask(Runnable request) { taskQueue.add(request); } diff --git a/src/mightypork/rogue/Res.java b/src/mightypork/rogue/Res.java index 58e29f7..636e8d8 100644 --- a/src/mightypork/rogue/Res.java +++ b/src/mightypork/rogue/Res.java @@ -5,13 +5,14 @@ import mightypork.rogue.fonts.DeferredFont; import mightypork.rogue.fonts.DeferredFont.FontStyle; import mightypork.rogue.fonts.FontBank; import mightypork.rogue.fonts.GLFont; +import mightypork.rogue.loading.AsyncResourceLoader; import mightypork.rogue.sound.SoundBank; import mightypork.rogue.sound.players.EffectPlayer; import mightypork.rogue.sound.players.LoopPlayer; -import mightypork.rogue.texture.FilteredTexture.Filter; -import mightypork.rogue.texture.FilteredTexture.Wrap; -import mightypork.rogue.texture.TextureBank; -import mightypork.rogue.texture.TxQuad; +import mightypork.rogue.textures.TextureBank; +import mightypork.rogue.textures.TxQuad; +import mightypork.rogue.textures.FilteredTexture.Filter; +import mightypork.rogue.textures.FilteredTexture.Wrap; import org.newdawn.slick.opengl.Texture; @@ -40,6 +41,8 @@ public class Res { if (initialized) return; initialized = true; + AsyncResourceLoader.launch(app); + textures = new TextureBank(app); sounds = new SoundBank(app); fonts = new FontBank(app); diff --git a/src/mightypork/rogue/bus/events/ActionRequest.java b/src/mightypork/rogue/bus/events/ActionRequest.java index 330e08e..1a25cf1 100644 --- a/src/mightypork/rogue/bus/events/ActionRequest.java +++ b/src/mightypork/rogue/bus/events/ActionRequest.java @@ -10,7 +10,8 @@ import mightypork.utils.control.bus.SingularEvent; * * @author MightyPork */ -public class ActionRequest implements Event, SingularEvent { +@SingularEvent +public class ActionRequest implements Event { private final RequestType type; @@ -33,7 +34,7 @@ public class ActionRequest implements Event, SingularEve * * @param request */ - public void requestAction(RequestType request); + void requestAction(RequestType request); } public static enum RequestType diff --git a/src/mightypork/rogue/bus/events/KeyboardEvent.java b/src/mightypork/rogue/bus/events/KeyboardEvent.java index f1d00ce..7abb6c2 100644 --- a/src/mightypork/rogue/bus/events/KeyboardEvent.java +++ b/src/mightypork/rogue/bus/events/KeyboardEvent.java @@ -74,7 +74,7 @@ public class KeyboardEvent implements Event { * * @param event event */ - public void receive(KeyboardEvent event); + void receive(KeyboardEvent event); } diff --git a/src/mightypork/rogue/bus/events/MainLoopTaskRequest.java b/src/mightypork/rogue/bus/events/MainLoopTaskRequest.java index badfe30..dea4701 100644 --- a/src/mightypork/rogue/bus/events/MainLoopTaskRequest.java +++ b/src/mightypork/rogue/bus/events/MainLoopTaskRequest.java @@ -10,7 +10,8 @@ import mightypork.utils.control.bus.SingularEvent; * * @author MightyPork */ -public class MainLoopTaskRequest implements Event, SingularEvent { +@SingularEvent +public class MainLoopTaskRequest implements Event { private final Runnable task; @@ -33,6 +34,6 @@ public class MainLoopTaskRequest implements Event, * * @param request */ - public void queueTask(Runnable request); + void queueTask(Runnable request); } } diff --git a/src/mightypork/rogue/bus/events/MouseButtonEvent.java b/src/mightypork/rogue/bus/events/MouseButtonEvent.java index 62c6a06..06aad0c 100644 --- a/src/mightypork/rogue/bus/events/MouseButtonEvent.java +++ b/src/mightypork/rogue/bus/events/MouseButtonEvent.java @@ -6,7 +6,7 @@ import mightypork.utils.math.coord.Coord; /** - * Mouse button / wheel event + * Mouse button / wheel event triggered * * @author MightyPork */ @@ -114,6 +114,6 @@ public class MouseButtonEvent implements Event { * * @param event event */ - public void receive(MouseButtonEvent event); + void receive(MouseButtonEvent event); } } diff --git a/src/mightypork/rogue/bus/events/MouseMotionEvent.java b/src/mightypork/rogue/bus/events/MouseMotionEvent.java index 81248f7..d88faa6 100644 --- a/src/mightypork/rogue/bus/events/MouseMotionEvent.java +++ b/src/mightypork/rogue/bus/events/MouseMotionEvent.java @@ -5,6 +5,11 @@ import mightypork.utils.control.bus.Event; import mightypork.utils.math.coord.Coord; +/** + * Mouse moved + * + * @author MightyPork + */ public class MouseMotionEvent implements Event { private final Coord move; @@ -48,7 +53,7 @@ public class MouseMotionEvent implements Event { * * @param event event */ - public void receive(MouseMotionEvent event); + void receive(MouseMotionEvent event); } } diff --git a/src/mightypork/rogue/bus/events/ResourceLoadRequest.java b/src/mightypork/rogue/bus/events/ResourceLoadRequest.java index 85ec024..e445b0f 100644 --- a/src/mightypork/rogue/bus/events/ResourceLoadRequest.java +++ b/src/mightypork/rogue/bus/events/ResourceLoadRequest.java @@ -1,7 +1,7 @@ package mightypork.rogue.bus.events; -import mightypork.rogue.loading.Deferred; +import mightypork.rogue.loading.DeferredResource; import mightypork.utils.control.bus.Event; import mightypork.utils.control.bus.SingularEvent; @@ -11,12 +11,13 @@ import mightypork.utils.control.bus.SingularEvent; * * @author MightyPork */ -public class ResourceLoadRequest implements Event, SingularEvent { +@SingularEvent +public class ResourceLoadRequest implements Event { - private final Deferred resource; + private final DeferredResource resource; - public ResourceLoadRequest(Deferred resource) { + public ResourceLoadRequest(DeferredResource resource) { this.resource = resource; } @@ -34,6 +35,6 @@ public class ResourceLoadRequest implements Event, * * @param resource */ - public void loadResource(Deferred resource); + void loadResource(DeferredResource resource); } } diff --git a/src/mightypork/rogue/bus/events/ScreenChangeEvent.java b/src/mightypork/rogue/bus/events/ScreenChangeEvent.java index b18600d..53961a2 100644 --- a/src/mightypork/rogue/bus/events/ScreenChangeEvent.java +++ b/src/mightypork/rogue/bus/events/ScreenChangeEvent.java @@ -45,6 +45,6 @@ public class ScreenChangeEvent implements Event { public interface Listener { - public void receive(ScreenChangeEvent event); + void receive(ScreenChangeEvent event); } } diff --git a/src/mightypork/rogue/bus/events/ScreenRequestEvent.java b/src/mightypork/rogue/bus/events/ScreenRequestEvent.java index 2183dc8..d2b033d 100644 --- a/src/mightypork/rogue/bus/events/ScreenRequestEvent.java +++ b/src/mightypork/rogue/bus/events/ScreenRequestEvent.java @@ -5,7 +5,13 @@ import mightypork.utils.control.bus.Event; import mightypork.utils.control.bus.SingularEvent; -public class ScreenRequestEvent implements Event, SingularEvent { +/** + * Request to change screen + * + * @author MightyPork + */ +@SingularEvent +public class ScreenRequestEvent implements Event { private final String scrName; @@ -23,7 +29,7 @@ public class ScreenRequestEvent implements Event, S public interface Listener { - public void showScreen(String key); + void showScreen(String key); } } diff --git a/src/mightypork/rogue/fonts/DeferredFont.java b/src/mightypork/rogue/fonts/DeferredFont.java index 2295300..a4c8f2e 100644 --- a/src/mightypork/rogue/fonts/DeferredFont.java +++ b/src/mightypork/rogue/fonts/DeferredFont.java @@ -6,7 +6,7 @@ import java.awt.FontFormatException; import java.io.IOException; import java.io.InputStream; -import mightypork.rogue.loading.DeferredResource; +import mightypork.rogue.loading.BaseDeferredResource; import mightypork.rogue.loading.MustLoadInMainThread; import mightypork.utils.files.FileUtils; import mightypork.utils.math.color.RGB; @@ -18,7 +18,8 @@ import mightypork.utils.math.coord.Coord; * * @author MightyPork */ -public class DeferredFont extends DeferredResource implements MustLoadInMainThread, GLFont { +@MustLoadInMainThread +public class DeferredFont extends BaseDeferredResource implements GLFont { public static enum FontStyle { @@ -44,7 +45,7 @@ public class DeferredFont extends DeferredResource implements MustLoadInMainThre * * @param resourcePath resource to load * @param extraChars extra chars (0-255 loaded by default) - * @param size size (pt) + * @param size size (px) */ public DeferredFont(String resourcePath, String extraChars, double size) { this(resourcePath, extraChars, size, FontStyle.PLAIN, true); @@ -85,7 +86,7 @@ public class DeferredFont extends DeferredResource implements MustLoadInMainThre @Override protected final void loadResource(String path) throws FontFormatException, IOException { - Font awtFont = getAwtFont(path, (float) size, style.numeric); + final Font awtFont = getAwtFont(path, (float) size, style.numeric); font = new SlickFont(awtFont, antiAlias, extraChars); } @@ -119,7 +120,7 @@ public class DeferredFont extends DeferredResource implements MustLoadInMainThre } finally { try { if (in != null) in.close(); - } catch (IOException e) { + } catch (final IOException e) { //pass } } diff --git a/src/mightypork/rogue/fonts/FontBank.java b/src/mightypork/rogue/fonts/FontBank.java index 0cbcf2e..96e0df1 100644 --- a/src/mightypork/rogue/fonts/FontBank.java +++ b/src/mightypork/rogue/fonts/FontBank.java @@ -62,7 +62,7 @@ public class FontBank extends AppAdapter { */ public GLFont getFont(String key) { - GLFont f = fonts.get(key); + final GLFont f = fonts.get(key); if (f == null) { Log.w("There's no font called " + key + "!"); diff --git a/src/mightypork/rogue/fonts/GLFont.java b/src/mightypork/rogue/fonts/GLFont.java index 7a50042..89ed227 100644 --- a/src/mightypork/rogue/fonts/GLFont.java +++ b/src/mightypork/rogue/fonts/GLFont.java @@ -13,7 +13,7 @@ public interface GLFont { * @param text string to draw * @param color draw color */ - abstract void draw(String text, RGB color); + void draw(String text, RGB color); /** @@ -24,7 +24,7 @@ public interface GLFont { * @param startIndex first drawn character index * @param endIndex last drawn character index */ - abstract void draw(String text, RGB color, int startIndex, int endIndex); + void draw(String text, RGB color, int startIndex, int endIndex); /** @@ -32,7 +32,7 @@ public interface GLFont { * * @param str string to draw */ - abstract void draw(String str); + void draw(String str); /** @@ -41,19 +41,19 @@ public interface GLFont { * @param text string to check * @return coord (width, height) */ - abstract Coord getNeededSpace(String text); + Coord getNeededSpace(String text); /** * @return font height */ - abstract int getHeight(); + int getHeight(); /** * @param text texted text * @return space needed */ - abstract int getWidth(String text); + int getWidth(String text); } diff --git a/src/mightypork/rogue/fonts/SlickFont.java b/src/mightypork/rogue/fonts/SlickFont.java index b95fdc6..97de8a6 100644 --- a/src/mightypork/rogue/fonts/SlickFont.java +++ b/src/mightypork/rogue/fonts/SlickFont.java @@ -39,8 +39,8 @@ public class SlickFont implements GLFont { { if (chars == null) return null; - StringBuilder sb = new StringBuilder(); - for (char c : chars.toCharArray()) { + final StringBuilder sb = new StringBuilder(); + for (final char c : chars.toCharArray()) { if (c <= 255) continue; // already included in default set sb.append(c); } diff --git a/src/mightypork/rogue/gui/LayeredScreen.java b/src/mightypork/rogue/gui/LayeredScreen.java index e38e97f..7d558c0 100644 --- a/src/mightypork/rogue/gui/LayeredScreen.java +++ b/src/mightypork/rogue/gui/LayeredScreen.java @@ -20,7 +20,7 @@ public abstract class LayeredScreen extends Screen { @Override protected final void renderScreen() { - for (ScreenLayer layer : layers) { + for (final ScreenLayer layer : layers) { layer.render(); } } diff --git a/src/mightypork/rogue/gui/Screen.java b/src/mightypork/rogue/gui/Screen.java index 3b09faa..936e0e3 100644 --- a/src/mightypork/rogue/gui/Screen.java +++ b/src/mightypork/rogue/gui/Screen.java @@ -8,6 +8,7 @@ import mightypork.rogue.bus.events.ScreenChangeEvent; import mightypork.rogue.input.KeyBinder; import mightypork.rogue.input.KeyBindingPool; import mightypork.rogue.input.KeyStroke; +import mightypork.rogue.render.Renderable; import mightypork.utils.control.interf.Destroyable; import mightypork.utils.math.constraints.ConstraintContext; import mightypork.utils.math.coord.Coord; @@ -19,7 +20,7 @@ import mightypork.utils.math.coord.Rect; * * @author MightyPork */ -public abstract class Screen extends ChildClient implements Destroyable, KeyBinder, ConstraintContext, ScreenChangeEvent.Listener { +public abstract class Screen extends ChildClient implements Renderable, Destroyable, KeyBinder, ConstraintContext, ScreenChangeEvent.Listener { private final KeyBindingPool keybindings = new KeyBindingPool(); @@ -148,6 +149,7 @@ public abstract class Screen extends ChildClient implements Destroyable, KeyBind } + @Override public final void render() { if (!isActive()) return; @@ -165,7 +167,7 @@ public abstract class Screen extends ChildClient implements Destroyable, KeyBind // fix projection for changed size glMatrixMode(GL_PROJECTION); glLoadIdentity(); - Coord s = disp().getSize(); + final Coord s = disp().getSize(); glViewport(0, 0, s.xi(), s.yi()); glOrtho(0, s.x, s.y, 0, -1000, 1000); diff --git a/src/mightypork/rogue/gui/ScreenLayer.java b/src/mightypork/rogue/gui/ScreenLayer.java index 1f64684..fb7afe3 100644 --- a/src/mightypork/rogue/gui/ScreenLayer.java +++ b/src/mightypork/rogue/gui/ScreenLayer.java @@ -2,10 +2,10 @@ package mightypork.rogue.gui; import mightypork.rogue.bus.ChildClient; -import mightypork.rogue.gui.constraints.Renderable; import mightypork.rogue.input.KeyBinder; import mightypork.rogue.input.KeyBindingPool; import mightypork.rogue.input.KeyStroke; +import mightypork.rogue.render.Renderable; import mightypork.utils.math.constraints.ConstraintContext; import mightypork.utils.math.coord.Rect; diff --git a/src/mightypork/rogue/gui/ScreenRegistry.java b/src/mightypork/rogue/gui/ScreenRegistry.java index ff492d6..f30a85f 100644 --- a/src/mightypork/rogue/gui/ScreenRegistry.java +++ b/src/mightypork/rogue/gui/ScreenRegistry.java @@ -32,7 +32,7 @@ public class ScreenRegistry extends Subsystem implements ScreenRequestEvent.List { Log.f3("Request to show screen \"" + key + "\""); - Screen toshow = screens.get(key); + final Screen toshow = screens.get(key); if (toshow == null) throw new RuntimeException("Screen " + key + " not defined."); if (active != null) active.setActive(false); diff --git a/src/mightypork/rogue/gui/constraints/ElementHolder.java b/src/mightypork/rogue/gui/constraints/ElementHolder.java index 4c27050..05c9313 100644 --- a/src/mightypork/rogue/gui/constraints/ElementHolder.java +++ b/src/mightypork/rogue/gui/constraints/ElementHolder.java @@ -5,6 +5,7 @@ import java.util.LinkedList; import mightypork.rogue.AppAccess; import mightypork.rogue.bus.ChildClient; +import mightypork.rogue.render.Renderable; import mightypork.utils.control.bus.EventBus; import mightypork.utils.math.constraints.ConstraintContext; import mightypork.utils.math.constraints.RectConstraint; @@ -44,7 +45,7 @@ public class ElementHolder extends ChildClient implements ConstraintContext, Ren @Override public void render() { - for (Renderable element : elements) { + for (final Renderable element : elements) { element.render(); } } @@ -57,19 +58,6 @@ public class ElementHolder extends ChildClient implements ConstraintContext, Ren } -// /** -// * Add element to the holder. -// * -// * @param elem -// */ -// public void add(RenderableWithContext elem) -// { -// if (elem == null) return; -// elem.setContext(this); -// elements.add(elem); -// addChildClient(elem); -// } - /** * Add element to the holder. * diff --git a/src/mightypork/rogue/gui/constraints/RenderableWithContext.java b/src/mightypork/rogue/gui/constraints/RenderableWithContext.java index acc31f8..4ea971f 100644 --- a/src/mightypork/rogue/gui/constraints/RenderableWithContext.java +++ b/src/mightypork/rogue/gui/constraints/RenderableWithContext.java @@ -1,6 +1,7 @@ package mightypork.rogue.gui.constraints; +import mightypork.rogue.render.Renderable; import mightypork.utils.math.constraints.ConstraintContext; import mightypork.utils.math.constraints.SettableContext; @@ -13,9 +14,5 @@ import mightypork.utils.math.constraints.SettableContext; public interface RenderableWithContext extends Renderable, SettableContext { @Override - public void render(); - - - @Override - public void setContext(ConstraintContext context); + void setContext(ConstraintContext context); } diff --git a/src/mightypork/rogue/gui/screens/test_bouncyboxes/BouncyBox.java b/src/mightypork/rogue/gui/screens/test_bouncyboxes/BouncyBox.java index df1509b..e50b941 100644 --- a/src/mightypork/rogue/gui/screens/test_bouncyboxes/BouncyBox.java +++ b/src/mightypork/rogue/gui/screens/test_bouncyboxes/BouncyBox.java @@ -19,23 +19,23 @@ import mightypork.utils.math.coord.Rect; public class BouncyBox implements RenderableWithContext, Updateable, ConstraintContext { - private Random rand = new Random(); + private final Random rand = new Random(); private ConstraintContext context; - private RectConstraint box; + private final RectConstraint box; - private AnimDouble pos = new AnimDouble(0, Easing.BOUNCE_OUT); + private final AnimDouble pos = new AnimDouble(0, Easing.BOUNCE_OUT); public BouncyBox() { // create box - NumConstraint side = c_height(this); + final NumConstraint side = c_height(this); RectConstraint abox = c_box_sized(this, side, side); // move - NumConstraint move_length = c_sub(c_width(this), side); - NumConstraint offset = c_mul(move_length, c_n(pos)); + final NumConstraint move_length = c_sub(c_width(this), side); + final NumConstraint offset = c_mul(move_length, c_n(pos)); abox = c_move(abox, offset, c_n(0)); // add padding diff --git a/src/mightypork/rogue/gui/screens/test_bouncyboxes/LayerBouncyBoxes.java b/src/mightypork/rogue/gui/screens/test_bouncyboxes/LayerBouncyBoxes.java index dfed278..86f4b99 100644 --- a/src/mightypork/rogue/gui/screens/test_bouncyboxes/LayerBouncyBoxes.java +++ b/src/mightypork/rogue/gui/screens/test_bouncyboxes/LayerBouncyBoxes.java @@ -22,12 +22,12 @@ public class LayerBouncyBoxes extends ScreenLayer { super(screen); // shrink screen rect by 8% on all sides - RectConstraint holder_rect = c_shrink(this, c_percent(c_height(this), c_n(8))); + final RectConstraint holder_rect = c_shrink(this, c_percent(c_height(this), c_n(8))); addChildClient(layout = new RowHolder(screen, holder_rect, 16)); for (int i = 0; i < 16; i++) { - BouncyBox bbr = new BouncyBox(); + final BouncyBox bbr = new BouncyBox(); layout.addRow(bbr); boxes.add(bbr); } @@ -44,7 +44,7 @@ public class LayerBouncyBoxes extends ScreenLayer { public void goLeft() { - for (BouncyBox bbr : boxes) { + for (final BouncyBox bbr : boxes) { bbr.goLeft(); } } @@ -52,7 +52,7 @@ public class LayerBouncyBoxes extends ScreenLayer { public void goRight() { - for (BouncyBox bbr : boxes) { + for (final BouncyBox bbr : boxes) { bbr.goRight(); } } diff --git a/src/mightypork/rogue/gui/screens/test_bouncyboxes/ScreenTestBouncy.java b/src/mightypork/rogue/gui/screens/test_bouncyboxes/ScreenTestBouncy.java index 1f16042..4eab32b 100644 --- a/src/mightypork/rogue/gui/screens/test_bouncyboxes/ScreenTestBouncy.java +++ b/src/mightypork/rogue/gui/screens/test_bouncyboxes/ScreenTestBouncy.java @@ -11,7 +11,7 @@ import org.lwjgl.input.Keyboard; public class ScreenTestBouncy extends LayeredScreen { - private LayerBouncyBoxes layer; + private final LayerBouncyBoxes layer; public ScreenTestBouncy(AppAccess app) { diff --git a/src/mightypork/rogue/gui/screens/test_cat_sound/LayerFlyingCat.java b/src/mightypork/rogue/gui/screens/test_cat_sound/LayerFlyingCat.java index 0708279..a30e677 100644 --- a/src/mightypork/rogue/gui/screens/test_cat_sound/LayerFlyingCat.java +++ b/src/mightypork/rogue/gui/screens/test_cat_sound/LayerFlyingCat.java @@ -23,15 +23,15 @@ import org.newdawn.slick.opengl.Texture; public class LayerFlyingCat extends ScreenLayer implements Updateable, MouseButtonEvent.Listener { - private RectConstraint kittenbox; + private final RectConstraint kittenbox; - private AnimDouble s = new AnimDouble(400, Easing.SINE_BOTH); - private AnimDouble x = new AnimDouble(200, Easing.ELASTIC_OUT); - private AnimDouble y = new AnimDouble(200, Easing.ELASTIC_OUT); + private final AnimDouble s = new AnimDouble(400, Easing.SINE_BOTH); + private final AnimDouble x = new AnimDouble(200, Easing.ELASTIC_OUT); + private final AnimDouble y = new AnimDouble(200, Easing.ELASTIC_OUT); - private Random rand = new Random(); + private final Random rand = new Random(); - private Texture cat_tx = Res.getTexture("test.kitten"); + private final Texture cat_tx = Res.getTexture("test.kitten"); public LayerFlyingCat(Screen screen) { @@ -65,11 +65,11 @@ public class LayerFlyingCat extends ScreenLayer implements Updateable, MouseButt { if (!event.isDown()) return; - Coord pos = event.getPos(); + final Coord pos = event.getPos(); - double newSize = 200 + rand.nextInt(600); + final double newSize = 200 + rand.nextInt(600); - double t = 2; + final double t = 2; s.fadeTo(newSize, t / 2D); x.fadeTo(pos.x - newSize / 2D, t); diff --git a/src/mightypork/rogue/gui/screens/test_font/ScreenTestFont.java b/src/mightypork/rogue/gui/screens/test_font/ScreenTestFont.java index 5208e69..2a8c192 100644 --- a/src/mightypork/rogue/gui/screens/test_font/ScreenTestFont.java +++ b/src/mightypork/rogue/gui/screens/test_font/ScreenTestFont.java @@ -40,10 +40,10 @@ public class ScreenTestFont extends Screen { @Override protected void renderScreen() { - GLFont font = Res.getFont("PolygonPixel_16"); + final GLFont font = Res.getFont("PolygonPixel_16"); - String s = "It works!"; - double scale = getRect().height() / 50D; + final String s = "It works!"; + final double scale = getRect().height() / 50D; Render.pushState(); Render.translate(getRect().getCenter().sub(font.getNeededSpace(s).mul(scale).half())); Render.scale(new Coord(scale)); diff --git a/src/mightypork/rogue/input/InputSystem.java b/src/mightypork/rogue/input/InputSystem.java index 94536cb..a1b4620 100644 --- a/src/mightypork/rogue/input/InputSystem.java +++ b/src/mightypork/rogue/input/InputSystem.java @@ -53,7 +53,7 @@ public class InputSystem extends Subsystem implements Updateable, KeyBinder { Mouse.create(); Keyboard.create(); Keyboard.enableRepeatEvents(false); - } catch (LWJGLException e) { + } catch (final LWJGLException e) { throw new RuntimeException("Failed to initialize input devices.", e); } } @@ -83,8 +83,8 @@ public class InputSystem extends Subsystem implements Updateable, KeyBinder { Display.processMessages(); - Coord moveSum = Coord.zero(); - Coord lastPos = Coord.zero(); + final Coord moveSum = Coord.zero(); + final Coord lastPos = Coord.zero(); boolean wasMouse = false; while (Mouse.next()) { @@ -106,11 +106,11 @@ public class InputSystem extends Subsystem implements Updateable, KeyBinder { private void onMouseEvent(Coord moveSum, Coord lastPos) { - int button = Mouse.getEventButton(); - boolean down = Mouse.getEventButtonState(); - Coord pos = new Coord(Mouse.getEventX(), Mouse.getEventY()); - Coord move = new Coord(Mouse.getEventDX(), Mouse.getEventDY()); - int wheeld = Mouse.getEventDWheel(); + final int button = Mouse.getEventButton(); + final boolean down = Mouse.getEventButtonState(); + final Coord pos = new Coord(Mouse.getEventX(), Mouse.getEventY()); + final Coord move = new Coord(Mouse.getEventDX(), Mouse.getEventDY()); + final int wheeld = Mouse.getEventDWheel(); if (yAxisDown) { flipScrY(pos); @@ -128,9 +128,9 @@ public class InputSystem extends Subsystem implements Updateable, KeyBinder { private void onKeyEvent() { - int key = Keyboard.getEventKey(); - boolean down = Keyboard.getEventKeyState(); - char c = Keyboard.getEventCharacter(); + final int key = Keyboard.getEventKey(); + final boolean down = Keyboard.getEventKeyState(); + final char c = Keyboard.getEventCharacter(); bus().queue(new KeyboardEvent(key, c, down)); } diff --git a/src/mightypork/rogue/input/KeyBinder.java b/src/mightypork/rogue/input/KeyBinder.java index 6cfd10a..b881d32 100644 --- a/src/mightypork/rogue/input/KeyBinder.java +++ b/src/mightypork/rogue/input/KeyBinder.java @@ -9,7 +9,7 @@ public interface KeyBinder { * @param stroke trigger keystroke * @param task handler */ - abstract void bindKeyStroke(KeyStroke stroke, Runnable task); + void bindKeyStroke(KeyStroke stroke, Runnable task); /** @@ -17,6 +17,6 @@ public interface KeyBinder { * * @param stroke stroke */ - abstract void unbindKeyStroke(KeyStroke stroke); + void unbindKeyStroke(KeyStroke stroke); } diff --git a/src/mightypork/rogue/input/KeyBinding.java b/src/mightypork/rogue/input/KeyBinding.java index 4c56159..15ba81a 100644 --- a/src/mightypork/rogue/input/KeyBinding.java +++ b/src/mightypork/rogue/input/KeyBinding.java @@ -4,6 +4,11 @@ package mightypork.rogue.input; import mightypork.rogue.bus.events.KeyboardEvent; +/** + * Key binding, trigger activated by a keystroke event + * + * @author MightyPork + */ public class KeyBinding implements KeyboardEvent.Listener { private final KeyStroke keystroke; @@ -11,6 +16,10 @@ public class KeyBinding implements KeyboardEvent.Listener { private boolean wasActive = false; + /** + * @param stroke trigger keystroke + * @param handler action + */ public KeyBinding(KeyStroke stroke, Runnable handler) { this.keystroke = stroke; this.handler = handler; @@ -19,12 +28,21 @@ public class KeyBinding implements KeyboardEvent.Listener { } + /** + * Check for equality of keystroke + * + * @param stroke other keystroke + * @return true if keystrokes are equal (cannot co-exist) + */ public boolean matches(KeyStroke stroke) { return this.keystroke.equals(stroke); } + /** + * @param handler event handler + */ public void setHandler(Runnable handler) { this.handler = handler; diff --git a/src/mightypork/rogue/input/KeyBindingPool.java b/src/mightypork/rogue/input/KeyBindingPool.java index 2d7252a..9acfb13 100644 --- a/src/mightypork/rogue/input/KeyBindingPool.java +++ b/src/mightypork/rogue/input/KeyBindingPool.java @@ -28,7 +28,7 @@ public class KeyBindingPool implements KeyBinder, KeyboardEvent.Listener { @Override public void bindKeyStroke(KeyStroke stroke, Runnable task) { - for (KeyBinding kb : bindings) { + for (final KeyBinding kb : bindings) { if (kb.matches(stroke)) { Log.w("Duplicate KeyBinding (" + stroke + "), using newest handler."); kb.setHandler(task); @@ -48,10 +48,10 @@ public class KeyBindingPool implements KeyBinder, KeyboardEvent.Listener { @Override public void unbindKeyStroke(KeyStroke stroke) { - Iterator iter = bindings.iterator(); + final Iterator iter = bindings.iterator(); while (iter.hasNext()) { - KeyBinding kb = iter.next(); + final KeyBinding kb = iter.next(); if (kb.matches(stroke)) { iter.remove(); return; @@ -63,7 +63,7 @@ public class KeyBindingPool implements KeyBinder, KeyboardEvent.Listener { @Override public void receive(KeyboardEvent event) { - for (KeyBinding kb : bindings) { + for (final KeyBinding kb : bindings) { kb.receive(event); } } diff --git a/src/mightypork/rogue/input/KeyStroke.java b/src/mightypork/rogue/input/KeyStroke.java index aee83f1..1c2b751 100644 --- a/src/mightypork/rogue/input/KeyStroke.java +++ b/src/mightypork/rogue/input/KeyStroke.java @@ -8,6 +8,11 @@ import java.util.Set; import org.lwjgl.input.Keyboard; +/** + * Key stroke trigger + * + * @author MightyPork + */ public class KeyStroke { private final Set keys = new LinkedHashSet(); @@ -22,7 +27,7 @@ public class KeyStroke { */ public KeyStroke(boolean fallingEdge, int... keys) { this.fallingEdge = fallingEdge; - for (int k : keys) { + for (final int k : keys) { this.keys.add(k); } } @@ -35,16 +40,19 @@ public class KeyStroke { */ public KeyStroke(int... keys) { fallingEdge = false; - for (int k : keys) { + for (final int k : keys) { this.keys.add(k); } } + /** + * @return true if the keystroke is currently satisfied (keys pressed) + */ public boolean isActive() { boolean st = true; - for (int k : keys) { + for (final int k : keys) { st &= Keyboard.isKeyDown(k); } @@ -68,7 +76,7 @@ public class KeyStroke { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof KeyStroke)) return false; - KeyStroke other = (KeyStroke) obj; + final KeyStroke other = (KeyStroke) obj; if (keys == null) { if (other.keys != null) return false; @@ -88,7 +96,7 @@ public class KeyStroke { String s = "("; int cnt = 0; - Iterator i = keys.iterator(); + final Iterator i = keys.iterator(); for (; i.hasNext(); cnt++) { if (cnt > 0) s += "+"; s += Keyboard.getKeyName(i.next()); @@ -102,6 +110,9 @@ public class KeyStroke { } + /** + * @return the key set + */ public Set getKeys() { return keys; diff --git a/src/mightypork/rogue/loading/DeferredLoader.java b/src/mightypork/rogue/loading/AsyncResourceLoader.java similarity index 62% rename from src/mightypork/rogue/loading/DeferredLoader.java rename to src/mightypork/rogue/loading/AsyncResourceLoader.java index c957575..fe9d959 100644 --- a/src/mightypork/rogue/loading/DeferredLoader.java +++ b/src/mightypork/rogue/loading/AsyncResourceLoader.java @@ -17,28 +17,29 @@ import mightypork.utils.logging.Log; * * @author MightyPork */ -public class DeferredLoader extends Thread implements ResourceLoadRequest.Listener, Destroyable { +public class AsyncResourceLoader extends Thread implements ResourceLoadRequest.Listener, Destroyable { public static void launch(AppAccess app) { - (new DeferredLoader(app)).start(); + (new AsyncResourceLoader(app)).start(); } - private ExecutorService exs = Executors.newCachedThreadPool(); + private final ExecutorService exs = Executors.newCachedThreadPool(); - private LinkedBlockingQueue toLoad = new LinkedBlockingQueue(); + private final LinkedBlockingQueue toLoad = new LinkedBlockingQueue(); private boolean stopped; - private AppAccess app; + private final AppAccess app; - public DeferredLoader(AppAccess app) { + public AsyncResourceLoader(AppAccess app) { super("Deferred loader"); this.app = app; + app.bus().subscribe(this); } @Override - public void loadResource(Deferred resource) + public void loadResource(DeferredResource resource) { toLoad.add(resource); } @@ -47,10 +48,12 @@ public class DeferredLoader extends Thread implements ResourceLoadRequest.Listen @Override public void run() { + Log.f3("Asynchronous resource loader started."); + while (!stopped) { try { - final Deferred def = toLoad.take(); + final DeferredResource def = toLoad.take(); if (def == null) continue; if (!def.isLoaded()) { @@ -58,11 +61,8 @@ public class DeferredLoader extends Thread implements ResourceLoadRequest.Listen // skip nulls if (def instanceof NullResource) continue; - // texture needs to be loaded in main thread, unfortunately. - // -> delegate to MainLoop - if (def instanceof MustLoadInMainThread) { - Log.f3(" Loading \"" + Log.str(def) + "\" in main thread (texture based)."); - + // textures & fonts needs to be loaded in main thread + if (def.getClass().isAnnotationPresent(MustLoadInMainThread.class)) { app.bus().queue(new MainLoopTaskRequest(new Runnable() { @Override @@ -75,8 +75,6 @@ public class DeferredLoader extends Thread implements ResourceLoadRequest.Listen continue; } - Log.f3(" Loading \"" + Log.str(def) + "\" asynchronously."); - exs.submit(new Runnable() { @Override @@ -87,7 +85,7 @@ public class DeferredLoader extends Thread implements ResourceLoadRequest.Listen }); } - } catch (InterruptedException ignored) { + } catch (final InterruptedException ignored) { // } diff --git a/src/mightypork/rogue/loading/BaseDeferredResource.java b/src/mightypork/rogue/loading/BaseDeferredResource.java new file mode 100644 index 0000000..00be040 --- /dev/null +++ b/src/mightypork/rogue/loading/BaseDeferredResource.java @@ -0,0 +1,127 @@ +package mightypork.rogue.loading; + + +import mightypork.utils.control.interf.Destroyable; +import mightypork.utils.logging.Log; + + +/** + * Deferred resource abstraction.
+ * Resources implementing {@link NullResource} will be treated as fake and not + * attempted to load. + * + * @author MightyPork + */ +public abstract class BaseDeferredResource implements DeferredResource, Destroyable { + + private final String resource; + private boolean loadFailed = false; + private boolean loadAttempted = false; + + + public BaseDeferredResource(String resource) { + this.resource = resource; + } + + + @Override + public synchronized final void load() + { + + if (loadAttempted) return; + + loadAttempted = true; + loadFailed = false; + + if (isNull()) return; + try { + if (resource == null) throw new NullPointerException("Resource string cannot be null for non-null resource."); + + Log.f3(" Loading: " + this); + loadResource(resource); + Log.f3(" Loaded: " + this + " loaded."); + } catch (final Exception e) { + loadFailed = true; + Log.e("Failed to load resource \"" + resource + "\"", e); + } + } + + + @Override + public synchronized final boolean isLoaded() + { + if (isNull()) return false; + + return loadAttempted && !loadFailed; + } + + + /** + * Check if the resource is loaded; if not, try to do so. + * + * @return true if it's loaded now. + */ + public synchronized final boolean ensureLoaded() + { + if (isNull()) return false; + + if (isLoaded()) { + return true; + } else { + load(); + } + + return isLoaded(); + } + + + /** + * Load the resource. Called from load() - once only. + * + * @param resource the path / name of a resource + * @throws Exception when some problem prevented the resource from being + * loaded. + */ + protected abstract void loadResource(String resource) throws Exception; + + + @Override + public abstract void destroy(); + + + @Override + public String toString() + { + return Log.str(getClass()) + "(\"" + resource + "\")"; + } + + + @Override + public int hashCode() + { + final int prime = 31; + int result = 1; + result = prime * result + ((resource == null) ? 0 : resource.hashCode()); + return result; + } + + + @Override + public boolean equals(Object obj) + { + if (this == obj) return true; + if (obj == null) return false; + if (!(obj instanceof BaseDeferredResource)) return false; + final BaseDeferredResource other = (BaseDeferredResource) obj; + if (resource == null) { + if (other.resource != null) return false; + } else if (!resource.equals(other.resource)) return false; + return true; + } + + + private boolean isNull() + { + return this instanceof NullResource; + } +} diff --git a/src/mightypork/rogue/loading/Deferred.java b/src/mightypork/rogue/loading/Deferred.java deleted file mode 100644 index 68f1603..0000000 --- a/src/mightypork/rogue/loading/Deferred.java +++ /dev/null @@ -1,23 +0,0 @@ -package mightypork.rogue.loading; - - -/** - * Deferred resource - * - * @author MightyPork - */ -public interface Deferred { - - /** - * Load the actual resource, if not loaded yet. - */ - public void load(); - - - /** - * Check if resource was successfully loaded. - * - * @return true if already loaded - */ - public boolean isLoaded(); -} diff --git a/src/mightypork/rogue/loading/DeferredResource.java b/src/mightypork/rogue/loading/DeferredResource.java index 3ef132c..c274368 100644 --- a/src/mightypork/rogue/loading/DeferredResource.java +++ b/src/mightypork/rogue/loading/DeferredResource.java @@ -1,127 +1,23 @@ package mightypork.rogue.loading; -import mightypork.utils.control.interf.Destroyable; -import mightypork.utils.logging.Log; - - /** - * Deferred resource abstraction.
- * Resources implementing {@link NullResource} will be treated as fake and not - * attempted to load. + * Deferred resource * * @author MightyPork */ -public abstract class DeferredResource implements Deferred, Destroyable { - - private String resource; - private boolean loadFailed = false; - private boolean loadAttempted = false; - - - public DeferredResource(String resource) { - this.resource = resource; - } - - - @Override - public synchronized final void load() - { - - if (loadAttempted) return; - - loadAttempted = true; - loadFailed = false; - - if (isNull()) return; - try { - if (resource == null) throw new NullPointerException("Resource string cannot be null for non-null resource."); - - Log.f3("Loading resource " + this); - loadResource(resource); - Log.f3("Resource " + this + " loaded."); - } catch (Exception e) { - loadFailed = true; - Log.e("Failed to load resource \"" + resource + "\"", e); - } - } - - - @Override - public synchronized final boolean isLoaded() - { - if (isNull()) return false; - - return loadAttempted && !loadFailed; - } - +public interface DeferredResource { /** - * Check if the resource is loaded; if not, try to do so. - * - * @return true if it's loaded now. + * Load the actual resource, if not loaded yet. */ - public synchronized final boolean ensureLoaded() - { - if (isNull()) return false; - - if (isLoaded()) { - return true; - } else { - load(); - } - - return isLoaded(); - } + void load(); /** - * Load the resource. Called from load() - once only. + * Check if resource was successfully loaded. * - * @param resource the path / name of a resource - * @throws Exception when some problem prevented the resource from being - * loaded. + * @return true if already loaded */ - protected abstract void loadResource(String resource) throws Exception; - - - @Override - public abstract void destroy(); - - - @Override - public String toString() - { - return Log.str(getClass()) + "(\"" + resource + "\")"; - } - - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ((resource == null) ? 0 : resource.hashCode()); - return result; - } - - - @Override - public boolean equals(Object obj) - { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof DeferredResource)) return false; - DeferredResource other = (DeferredResource) obj; - if (resource == null) { - if (other.resource != null) return false; - } else if (!resource.equals(other.resource)) return false; - return true; - } - - - private boolean isNull() - { - return this instanceof NullResource; - } + boolean isLoaded(); } diff --git a/src/mightypork/rogue/loading/MustLoadInMainThread.java b/src/mightypork/rogue/loading/MustLoadInMainThread.java index 59436a8..c4e9199 100644 --- a/src/mightypork/rogue/loading/MustLoadInMainThread.java +++ b/src/mightypork/rogue/loading/MustLoadInMainThread.java @@ -1,12 +1,18 @@ package mightypork.rogue.loading; +import java.lang.annotation.*; + + /** * Resource that is texture-based and therefore needs to be loaded in the main * thread (ie. main loop). * * @author MightyPork */ -public interface MustLoadInMainThread { - -} + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Inherited +@Documented +public @interface MustLoadInMainThread {} diff --git a/src/mightypork/rogue/render/DisplaySystem.java b/src/mightypork/rogue/render/DisplaySystem.java index faf8dfe..54e2c93 100644 --- a/src/mightypork/rogue/render/DisplaySystem.java +++ b/src/mightypork/rogue/render/DisplaySystem.java @@ -59,7 +59,7 @@ public class DisplaySystem extends Subsystem implements ConstraintContext { Render.init(); - } catch (LWJGLException e) { + } catch (final LWJGLException e) { throw new RuntimeException("Could not initialize screen", e); } } @@ -88,12 +88,12 @@ public class DisplaySystem extends Subsystem implements ConstraintContext { bus().queue(new ScreenChangeEvent(true, Display.isFullscreen(), getSize())); - } catch (Throwable t) { + } catch (final Throwable t) { Log.e("Failed to toggle fullscreen mode.", t); try { Display.setDisplayMode(windowDisplayMode); Display.update(); - } catch (Throwable t1) { + } catch (final Throwable t1) { throw new RuntimeException("Failed to revert failed fullscreen toggle.", t1); } } @@ -103,14 +103,14 @@ public class DisplaySystem extends Subsystem implements ConstraintContext { public Screenshot takeScreenshot() { glReadBuffer(GL_FRONT); - int width = Display.getDisplayMode().getWidth(); - int height = Display.getDisplayMode().getHeight(); - int bpp = 4; // Assuming a 32-bit display with a byte each for red, - // green, blue, and alpha. - ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * bpp); + final int width = Display.getDisplayMode().getWidth(); + final int height = Display.getDisplayMode().getHeight(); + final int bpp = 4; // Assuming a 32-bit display with a byte each for red, + // green, blue, and alpha. + final ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * bpp); glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); - Screenshot sc = new Screenshot(width, height, bpp, buffer); + final Screenshot sc = new Screenshot(width, height, bpp, buffer); return sc; } diff --git a/src/mightypork/rogue/render/Render.java b/src/mightypork/rogue/render/Render.java index 1e1085f..d1afb5a 100644 --- a/src/mightypork/rogue/render/Render.java +++ b/src/mightypork/rogue/render/Render.java @@ -5,7 +5,7 @@ import static org.lwjgl.opengl.GL11.*; import java.io.IOException; -import mightypork.rogue.texture.TxQuad; +import mightypork.rogue.textures.TxQuad; import mightypork.utils.files.FileUtils; import mightypork.utils.logging.Log; import mightypork.utils.math.color.RGB; @@ -170,7 +170,7 @@ public class Render { */ public static void rotate(double angle, Coord axis) { - Coord vec = axis.norm(1); + final Coord vec = axis.norm(1); glRotated(angle, vec.x, vec.y, vec.z); } @@ -204,11 +204,9 @@ public class Render { try { - String ext = FileUtils.getExtension(resourcePath).toUpperCase(); + final String ext = FileUtils.getExtension(resourcePath).toUpperCase(); - Log.f3("Loading texture " + ext + " at " + resourcePath); - - Texture texture = TextureLoader.getTexture(ext, ResourceLoader.getResourceAsStream(resourcePath)); + final Texture texture = TextureLoader.getTexture(ext, ResourceLoader.getResourceAsStream(resourcePath)); if (texture == null) { Log.w("Texture " + resourcePath + " could not be loaded."); @@ -216,7 +214,7 @@ public class Render { return texture; - } catch (IOException e) { + } catch (final IOException e) { Log.e("Loading of texture " + resourcePath + " failed.", e); throw new RuntimeException("Could not load texture " + resourcePath + ".", e); } @@ -280,10 +278,10 @@ public class Render { */ public static void quad(Rect quad) { - double left = quad.xMin(); - double bottom = quad.yMin(); - double right = quad.xMax(); - double top = quad.yMax(); + final double left = quad.xMin(); + final double bottom = quad.yMin(); + final double right = quad.xMax(); + final double top = quad.yMax(); // draw with color unbindTexture(); @@ -320,15 +318,15 @@ public class Render { */ public static void quadUV_nobound(Rect quad, Rect uvs) { - double left = quad.xMin(); - double bottom = quad.yMin(); - double right = quad.xMax(); - double top = quad.yMax(); + final double left = quad.xMin(); + final double bottom = quad.yMin(); + final double right = quad.xMax(); + final double top = quad.yMax(); - double tleft = uvs.xMin(); - double tbottom = uvs.yMin(); - double tright = uvs.xMax(); - double ttop = uvs.yMax(); + final double tleft = uvs.xMin(); + final double tbottom = uvs.yMin(); + final double tright = uvs.xMax(); + final double ttop = uvs.yMax(); // quad with texture glTexCoord2d(tleft, ttop); @@ -344,10 +342,10 @@ public class Render { public static void quadGradH(Rect quad, RGB colorLeft, RGB colorRight) { - double left = quad.xMin(); - double bottom = quad.yMin(); - double right = quad.yMax(); - double top = quad.yMax(); + final double left = quad.xMin(); + final double bottom = quad.yMin(); + final double right = quad.yMax(); + final double top = quad.yMax(); // draw with color unbindTexture(); @@ -368,10 +366,10 @@ public class Render { public static void quadGradV(Rect quad, RGB colorTop, RGB colorBottom) { - double left = quad.xMin(); - double bottom = quad.yMin(); - double right = quad.yMax(); - double top = quad.yMax(); + final double left = quad.xMin(); + final double bottom = quad.yMin(); + final double right = quad.yMax(); + final double top = quad.yMax(); // draw with color unbindTexture(); diff --git a/src/mightypork/rogue/gui/constraints/Renderable.java b/src/mightypork/rogue/render/Renderable.java similarity index 65% rename from src/mightypork/rogue/gui/constraints/Renderable.java rename to src/mightypork/rogue/render/Renderable.java index 44849bb..6c73885 100644 --- a/src/mightypork/rogue/gui/constraints/Renderable.java +++ b/src/mightypork/rogue/render/Renderable.java @@ -1,4 +1,4 @@ -package mightypork.rogue.gui.constraints; +package mightypork.rogue.render; /** @@ -11,6 +11,6 @@ public interface Renderable { /** * Render on screen */ - public void render(); + void render(); } diff --git a/src/mightypork/rogue/sound/DeferredAudio.java b/src/mightypork/rogue/sound/DeferredAudio.java index b47aa99..395c17d 100644 --- a/src/mightypork/rogue/sound/DeferredAudio.java +++ b/src/mightypork/rogue/sound/DeferredAudio.java @@ -3,7 +3,7 @@ package mightypork.rogue.sound; import java.io.IOException; -import mightypork.rogue.loading.DeferredResource; +import mightypork.rogue.loading.BaseDeferredResource; import mightypork.utils.files.FileUtils; import mightypork.utils.math.coord.Coord; @@ -16,7 +16,7 @@ import org.newdawn.slick.openal.SoundStore; * * @author MightyPork */ -public class DeferredAudio extends DeferredResource { +public class DeferredAudio extends BaseDeferredResource { private enum PlayMode { @@ -86,7 +86,7 @@ public class DeferredAudio extends DeferredResource { @Override protected void loadResource(String resource) throws IOException { - String ext = FileUtils.getExtension(resource); + final String ext = FileUtils.getExtension(resource); if (ext.equalsIgnoreCase("ogg")) { backingAudio = SoundStore.get().getOgg(resource); diff --git a/src/mightypork/rogue/sound/JointVolume.java b/src/mightypork/rogue/sound/JointVolume.java index 7e278fd..7cc0c99 100644 --- a/src/mightypork/rogue/sound/JointVolume.java +++ b/src/mightypork/rogue/sound/JointVolume.java @@ -33,7 +33,7 @@ public class JointVolume extends Mutable { public Double get() { double d = super.get(); - for (Mutable v : volumes) + for (final Mutable v : volumes) d *= v.get(); return Calc.clampd(d, 0, 1); diff --git a/src/mightypork/rogue/sound/SoundBank.java b/src/mightypork/rogue/sound/SoundBank.java index 49cc8b6..7fabd77 100644 --- a/src/mightypork/rogue/sound/SoundBank.java +++ b/src/mightypork/rogue/sound/SoundBank.java @@ -65,7 +65,7 @@ public class SoundBank extends AppAdapter { */ public LoopPlayer getLoop(String key) { - LoopPlayer p = loops.get(key); + final LoopPlayer p = loops.get(key); if (p == null) { Log.w("Requesting unknown sound loop \"" + key + "\"."); return NULL_LOOP; @@ -82,7 +82,7 @@ public class SoundBank extends AppAdapter { */ public EffectPlayer getEffect(String key) { - EffectPlayer p = effects.get(key); + final EffectPlayer p = effects.get(key); if (p == null) { Log.w("Requesting unknown sound effect \"" + key + "\"."); return NULL_EFFECT; diff --git a/src/mightypork/rogue/sound/SoundSystem.java b/src/mightypork/rogue/sound/SoundSystem.java index 54c3aab..bfd435d 100644 --- a/src/mightypork/rogue/sound/SoundSystem.java +++ b/src/mightypork/rogue/sound/SoundSystem.java @@ -88,7 +88,7 @@ public class SoundSystem extends Subsystem implements Updateable { @Override public final void deinit() { - for (DeferredAudio r : resources) { + for (final DeferredAudio r : resources) { r.destroy(); } @@ -100,7 +100,7 @@ public class SoundSystem extends Subsystem implements Updateable { @Override public void update(double delta) { - for (Updateable lp : loopPlayers) { + for (final Updateable lp : loopPlayers) { lp.update(delta); } } @@ -132,7 +132,7 @@ public class SoundSystem extends Subsystem implements Updateable { */ public LoopPlayer createLoop(String resource, double pitch, double gain, double fadeIn, double fadeOut) { - LoopPlayer p = new LoopPlayer(getResource(resource), pitch, gain, loopsVolume); + final LoopPlayer p = new LoopPlayer(getResource(resource), pitch, gain, loopsVolume); p.setFadeTimes(fadeIn, fadeOut); loopPlayers.add(p); return p; @@ -148,7 +148,7 @@ public class SoundSystem extends Subsystem implements Updateable { */ private DeferredAudio getResource(String res) { - DeferredAudio a = new DeferredAudio(res); + final DeferredAudio a = new DeferredAudio(res); bus().queue(new ResourceLoadRequest(a)); if (resources.contains(a)) throw new IllegalArgumentException("Sound resource " + res + " is already registered."); @@ -162,7 +162,7 @@ public class SoundSystem extends Subsystem implements Updateable { */ public void fadeOutAllLoops() { - for (LoopPlayer p : loopPlayers) { + for (final LoopPlayer p : loopPlayers) { p.fadeOut(); } } @@ -173,7 +173,7 @@ public class SoundSystem extends Subsystem implements Updateable { */ public void pauseAllLoops() { - for (LoopPlayer p : loopPlayers) { + for (final LoopPlayer p : loopPlayers) { p.pause(); } } diff --git a/src/mightypork/rogue/sound/players/LoopPlayer.java b/src/mightypork/rogue/sound/players/LoopPlayer.java index 20428d1..562699a 100644 --- a/src/mightypork/rogue/sound/players/LoopPlayer.java +++ b/src/mightypork/rogue/sound/players/LoopPlayer.java @@ -92,7 +92,7 @@ public class LoopPlayer extends BaseAudioPlayer implements Updateable, Pauseable fadeAnim.update(delta); - double gain = getGain(fadeAnim.now()); + final double gain = getGain(fadeAnim.now()); if (!paused && gain != lastUpdateGain) { AL10.alSourcef(sourceID, AL10.AL_GAIN, (float) gain); lastUpdateGain = gain; diff --git a/src/mightypork/rogue/tasks/TaskTakeScreenshot.java b/src/mightypork/rogue/tasks/TaskTakeScreenshot.java index f8bd777..1d116e8 100644 --- a/src/mightypork/rogue/tasks/TaskTakeScreenshot.java +++ b/src/mightypork/rogue/tasks/TaskTakeScreenshot.java @@ -18,7 +18,7 @@ import mightypork.utils.logging.Log; public class TaskTakeScreenshot implements Runnable { - private Screenshot scr; + private final Screenshot scr; public TaskTakeScreenshot(DisplaySystem disp) { @@ -30,20 +30,20 @@ public class TaskTakeScreenshot implements Runnable { public void run() { - BufferedImage image = new BufferedImage(scr.width, scr.height, BufferedImage.TYPE_INT_RGB); + final BufferedImage image = new BufferedImage(scr.width, scr.height, BufferedImage.TYPE_INT_RGB); // convert to a buffered image for (int x = 0; x < scr.width; x++) { for (int y = 0; y < scr.height; y++) { - int i = (x + (scr.width * y)) * scr.bpp; - int r = scr.bytes.get(i) & 0xFF; - int g = scr.bytes.get(i + 1) & 0xFF; - int b = scr.bytes.get(i + 2) & 0xFF; + final int i = (x + (scr.width * y)) * scr.bpp; + final int r = scr.bytes.get(i) & 0xFF; + final int g = scr.bytes.get(i + 1) & 0xFF; + final int b = scr.bytes.get(i + 2) & 0xFF; image.setRGB(x, scr.height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b); } } - String fname = getUniqueScreenshotName(); + final String fname = getUniqueScreenshotName(); // generate unique filename File file; @@ -56,12 +56,12 @@ public class TaskTakeScreenshot implements Runnable { Log.f3("Saving screenshot to file: " + file); - String format = "PNG"; + final String format = "PNG"; // save to disk try { ImageIO.write(image, format, file); - } catch (IOException e) { + } catch (final IOException e) { Log.e("Failed to save screenshot.", e); } } @@ -69,7 +69,7 @@ public class TaskTakeScreenshot implements Runnable { private static String getUniqueScreenshotName() { - DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); + final DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); return df.format(new Date()); } diff --git a/src/mightypork/rogue/texture/DeferredTexture.java b/src/mightypork/rogue/textures/DeferredTexture.java similarity index 94% rename from src/mightypork/rogue/texture/DeferredTexture.java rename to src/mightypork/rogue/textures/DeferredTexture.java index 84c0586..8dc2745 100644 --- a/src/mightypork/rogue/texture/DeferredTexture.java +++ b/src/mightypork/rogue/textures/DeferredTexture.java @@ -1,7 +1,7 @@ -package mightypork.rogue.texture; +package mightypork.rogue.textures; -import mightypork.rogue.loading.DeferredResource; +import mightypork.rogue.loading.BaseDeferredResource; import mightypork.rogue.loading.MustLoadInMainThread; import mightypork.rogue.render.Render; import mightypork.utils.math.coord.Rect; @@ -15,7 +15,8 @@ import org.newdawn.slick.opengl.Texture; * * @author MightyPork */ -public class DeferredTexture extends DeferredResource implements FilteredTexture, MustLoadInMainThread { +@MustLoadInMainThread +public class DeferredTexture extends BaseDeferredResource implements FilteredTexture { private Texture backingTexture; private Filter filter_min = Filter.LINEAR; diff --git a/src/mightypork/rogue/texture/FilteredTexture.java b/src/mightypork/rogue/textures/FilteredTexture.java similarity index 80% rename from src/mightypork/rogue/texture/FilteredTexture.java rename to src/mightypork/rogue/textures/FilteredTexture.java index bf01294..e45c20d 100644 --- a/src/mightypork/rogue/texture/FilteredTexture.java +++ b/src/mightypork/rogue/textures/FilteredTexture.java @@ -1,4 +1,4 @@ -package mightypork.rogue.texture; +package mightypork.rogue.textures; import org.lwjgl.opengl.GL11; @@ -38,7 +38,7 @@ public interface FilteredTexture extends Texture { * @param filterMin downscale filter * @param filterMag upscale filter */ - public void setFilter(Filter filterMin, Filter filterMag); + void setFilter(Filter filterMin, Filter filterMag); /** @@ -46,11 +46,11 @@ public interface FilteredTexture extends Texture { * * @param filter filter */ - public void setFilter(Filter filter); + void setFilter(Filter filter); /** * @param wrapping wrap mode */ - public void setWrap(Wrap wrapping); + void setWrap(Wrap wrapping); } diff --git a/src/mightypork/rogue/texture/TextureBank.java b/src/mightypork/rogue/textures/TextureBank.java similarity index 85% rename from src/mightypork/rogue/texture/TextureBank.java rename to src/mightypork/rogue/textures/TextureBank.java index 4cf7dbb..5d2b309 100644 --- a/src/mightypork/rogue/texture/TextureBank.java +++ b/src/mightypork/rogue/textures/TextureBank.java @@ -1,4 +1,4 @@ -package mightypork.rogue.texture; +package mightypork.rogue.textures; import java.util.HashMap; @@ -6,8 +6,8 @@ import java.util.HashMap; import mightypork.rogue.AppAccess; import mightypork.rogue.AppAdapter; import mightypork.rogue.bus.events.ResourceLoadRequest; -import mightypork.rogue.texture.FilteredTexture.Filter; -import mightypork.rogue.texture.FilteredTexture.Wrap; +import mightypork.rogue.textures.FilteredTexture.Filter; +import mightypork.rogue.textures.FilteredTexture.Wrap; import mightypork.utils.math.coord.Rect; import org.newdawn.slick.opengl.Texture; @@ -54,7 +54,7 @@ public class TextureBank extends AppAdapter { */ public void loadTexture(String key, String resourcePath, Filter filter_min, Filter filter_mag, Wrap wrap) { - DeferredTexture tx = new DeferredTexture(resourcePath); + final DeferredTexture tx = new DeferredTexture(resourcePath); tx.setFilter(filter_min, filter_mag); tx.setWrap(wrap); @@ -74,10 +74,10 @@ public class TextureBank extends AppAdapter { */ public void makeQuad(String quadKey, String textureKey, Rect quad) { - DeferredTexture tx = textures.get(textureKey); + final DeferredTexture tx = textures.get(textureKey); if (tx == null) throw new RuntimeException("Texture with key " + textureKey + " not defined!"); - TxQuad txquad = tx.getQuad(quad); + final TxQuad txquad = tx.getQuad(quad); quads.put(quadKey, txquad); } @@ -91,10 +91,10 @@ public class TextureBank extends AppAdapter { */ public void makeQuad(String quadKey, Rect quad) { - DeferredTexture tx = lastTx; + final DeferredTexture tx = lastTx; if (tx == null) throw new RuntimeException("There's no texture loaded yet, can't define quads!"); - TxQuad txquad = tx.getQuad(quad); + final TxQuad txquad = tx.getQuad(quad); quads.put(quadKey, txquad); } @@ -108,7 +108,7 @@ public class TextureBank extends AppAdapter { */ public TxQuad getTxQuad(String key) { - TxQuad q = quads.get(key); + final TxQuad q = quads.get(key); if (q == null) throw new RuntimeException("There's no quad called " + key + "!"); @@ -124,7 +124,7 @@ public class TextureBank extends AppAdapter { */ public Texture getTexture(String key) { - Texture t = textures.get(key); + final Texture t = textures.get(key); if (t == null) throw new RuntimeException("There's no texture called " + key + "!"); diff --git a/src/mightypork/rogue/texture/TxQuad.java b/src/mightypork/rogue/textures/TxQuad.java similarity index 93% rename from src/mightypork/rogue/texture/TxQuad.java rename to src/mightypork/rogue/textures/TxQuad.java index 5463c88..4e66a60 100644 --- a/src/mightypork/rogue/texture/TxQuad.java +++ b/src/mightypork/rogue/textures/TxQuad.java @@ -1,4 +1,4 @@ -package mightypork.rogue.texture; +package mightypork.rogue.textures; import mightypork.utils.math.coord.Rect; @@ -31,8 +31,8 @@ public class TxQuad { */ public static TxQuad fromSizePx(Texture tx, double xPx, double yPx, double widthPx, double heightPx) { - double w = tx.getImageWidth(); - double h = tx.getImageHeight(); + final double w = tx.getImageWidth(); + final double h = tx.getImageHeight(); return fromSize(tx, xPx / w, yPx / h, widthPx / w, heightPx / h); } diff --git a/src/mightypork/rogue/util/Utils.java b/src/mightypork/rogue/util/Utils.java index dc172f5..3be0db4 100644 --- a/src/mightypork/rogue/util/Utils.java +++ b/src/mightypork/rogue/util/Utils.java @@ -10,7 +10,7 @@ public class Utils { public static Thread runAsThread(Runnable r) { - Thread t = new Thread(r); + final Thread t = new Thread(r); t.start(); return t; } diff --git a/src/mightypork/utils/control/bus/BufferedHashSet.java b/src/mightypork/utils/control/bus/BufferedHashSet.java index 826467c..29ce5bb 100644 --- a/src/mightypork/utils/control/bus/BufferedHashSet.java +++ b/src/mightypork/utils/control/bus/BufferedHashSet.java @@ -16,8 +16,8 @@ import java.util.List; */ public class BufferedHashSet extends HashSet { - private List toAdd = new LinkedList(); - private List toRemove = new LinkedList(); + private final List toAdd = new LinkedList(); + private final List toRemove = new LinkedList(); private boolean buffering = false; @@ -72,11 +72,11 @@ public class BufferedHashSet extends HashSet { */ private void flush() { - for (E e : toAdd) { + for (final E e : toAdd) { super.add(e); } - for (Object e : toRemove) { + for (final Object e : toRemove) { super.remove(e); } diff --git a/src/mightypork/utils/control/bus/EventBus.java b/src/mightypork/utils/control/bus/EventBus.java index a646210..97f169a 100644 --- a/src/mightypork/utils/control/bus/EventBus.java +++ b/src/mightypork/utils/control/bus/EventBus.java @@ -17,16 +17,16 @@ import mightypork.utils.logging.Log; final public class EventBus implements Destroyable { /** Message channels */ - private BufferedHashSet> channels = new BufferedHashSet>(); + private final BufferedHashSet> channels = new BufferedHashSet>(); /** Registered clients */ - private BufferedHashSet clients = new BufferedHashSet(); + private final BufferedHashSet clients = new BufferedHashSet(); /** Messages queued for delivery */ - private DelayQueue sendQueue = new DelayQueue(); + private final DelayQueue sendQueue = new DelayQueue(); /** Queue polling thread */ - private QueuePollingThread busThread; + private final QueuePollingThread busThread; /** Log all */ private boolean logging = false; @@ -55,7 +55,7 @@ final public class EventBus implements Destroyable { logging = level; - for (EventChannel ch : channels) { + for (final EventChannel ch : channels) { ch.enableLogging(logging); } } @@ -73,7 +73,7 @@ final public class EventBus implements Destroyable { assertLive(); // if the channel already exists, return this instance instead. - for (EventChannel ch : channels) { + for (final EventChannel ch : channels) { if (ch.equals(channel)) { Log.w(" Channel of type " + Log.str(channel) + " already registered."); return ch; @@ -99,7 +99,7 @@ final public class EventBus implements Destroyable { { assertLive(); - EventChannel channel = EventChannel.create(messageClass, clientClass); + final EventChannel channel = EventChannel.create(messageClass, clientClass); return addChannel(channel); } @@ -140,7 +140,7 @@ final public class EventBus implements Destroyable { { assertLive(); - DelayedMessage dm = new DelayedMessage(delay, message); + final DelayedMessage dm = new DelayedMessage(delay, message); if (logging) Log.f3(" + [ Queuing: " + Log.str(message) + " ]"); @@ -168,9 +168,17 @@ final public class EventBus implements Destroyable { boolean sent = false; boolean channelAccepted = false; - for (EventChannel b : channels) { - if (b.canBroadcast(message)) channelAccepted = true; - sent |= b.broadcast(message, clients); + final boolean singular = message.getClass().isAnnotationPresent(SingularEvent.class); + + for (final EventChannel b : channels) { + if (b.canBroadcast(message)) { + channelAccepted = true; + sent |= b.broadcast(message, clients); + } + + if (sent && singular) { + break; + } } // more severe @@ -224,7 +232,7 @@ final public class EventBus implements Destroyable { if (client == null) return false; - for (EventChannel ch : channels) { + for (final EventChannel ch : channels) { if (ch.isClientValid(client)) { return true; } @@ -235,7 +243,7 @@ final public class EventBus implements Destroyable { private class DelayedMessage implements Delayed { - private long due; + private final long due; private Event theMessage = null; @@ -287,7 +295,7 @@ final public class EventBus implements Destroyable { try { dm = sendQueue.take(); - } catch (InterruptedException ignored) { + } catch (final InterruptedException ignored) { // } diff --git a/src/mightypork/utils/control/bus/EventChannel.java b/src/mightypork/utils/control/bus/EventChannel.java index 517d92c..84932dc 100644 --- a/src/mightypork/utils/control/bus/EventChannel.java +++ b/src/mightypork/utils/control/bus/EventChannel.java @@ -18,8 +18,8 @@ import mightypork.utils.logging.Log; */ final public class EventChannel, CLIENT> { - private Class clientClass; - private Class messageClass; + private final Class clientClass; + private final Class messageClass; private boolean logging = false; @@ -61,7 +61,7 @@ final public class EventChannel, CLIENT> { { if (!canBroadcast(message)) return false; - EVENT evt = messageClass.cast(message); + final EVENT evt = messageClass.cast(message); return doBroadcast(evt, clients, new HashSet()); } @@ -78,8 +78,9 @@ final public class EventChannel, CLIENT> { private boolean doBroadcast(final EVENT message, final Collection clients, final Collection processed) { boolean sent = false; + final boolean singular = message.getClass().isAnnotationPresent(SingularEvent.class); - for (Object client : clients) { + for (final Object client : clients) { // exclude obvious non-clients if (!isClientValid(client)) { @@ -104,13 +105,13 @@ final public class EventChannel, CLIENT> { sent |= sendTo(client, message); // singular event ain't no whore, handled once only. - if (sent && message instanceof SingularEvent) return true; + if (sent && singular) return true; // pass on to delegated clients if (client instanceof DelegatingClient) { if (((DelegatingClient) client).doesDelegate()) { - Collection children = ((DelegatingClient) client).getChildClients(); + final Collection children = ((DelegatingClient) client).getChildClients(); if (children != null && children.size() > 0) { sent |= doBroadcast(message, children, processed); @@ -212,7 +213,7 @@ final public class EventChannel, CLIENT> { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof EventChannel)) return false; - EventChannel other = (EventChannel) obj; + final EventChannel other = (EventChannel) obj; if (clientClass == null) { if (other.clientClass != null) return false; } else if (!clientClass.equals(other.clientClass)) return false; diff --git a/src/mightypork/utils/control/bus/SingularEvent.java b/src/mightypork/utils/control/bus/SingularEvent.java index 4226763..332c7ba 100644 --- a/src/mightypork/utils/control/bus/SingularEvent.java +++ b/src/mightypork/utils/control/bus/SingularEvent.java @@ -1,11 +1,17 @@ package mightypork.utils.control.bus; +import java.lang.annotation.*; + + /** - * Event handled by only single client. + * Event that is handled by only single client, and then discarded (ie. only one + * client receives it when it's broadcasted). * * @author MightyPork */ -public interface SingularEvent { - -} +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Inherited +@Documented +public @interface SingularEvent {} diff --git a/src/mightypork/utils/control/timing/TimerDelta.java b/src/mightypork/utils/control/timing/TimerDelta.java index 9642e8b..f882e9e 100644 --- a/src/mightypork/utils/control/timing/TimerDelta.java +++ b/src/mightypork/utils/control/timing/TimerDelta.java @@ -39,8 +39,8 @@ public class TimerDelta { */ public double getDelta() { - long time = getTime(); - double delta = (time - lastFrame) / (double) SECOND; + final long time = getTime(); + final double delta = (time - lastFrame) / (double) SECOND; lastFrame = time; return delta; } diff --git a/src/mightypork/utils/control/timing/TimerFps.java b/src/mightypork/utils/control/timing/TimerFps.java index 83438e3..24da007 100644 --- a/src/mightypork/utils/control/timing/TimerFps.java +++ b/src/mightypork/utils/control/timing/TimerFps.java @@ -14,7 +14,7 @@ public class TimerFps { private long lastSkipped = 0; private static final long SECOND = 1000000000; // a million nanoseconds - private long FRAME; // a time of one frame in nanoseconds + private final long FRAME; // a time of one frame in nanoseconds /** @@ -35,9 +35,9 @@ public class TimerFps { */ public void sync() { - long time = getTime(); + final long time = getTime(); if (time >= nextFrame) { - long skippedNow = (long) Math.floor((time - nextFrame) / (double) FRAME) + 1; + final long skippedNow = (long) Math.floor((time - nextFrame) / (double) FRAME) + 1; skipped += skippedNow; lastFrame = nextFrame + (1 - skippedNow) * FRAME; nextFrame += skippedNow * FRAME; @@ -67,7 +67,7 @@ public class TimerFps { return 1; } - long time = getTime(); + final long time = getTime(); if (time <= nextFrame) { return (double) (time - lastFrame) / (double) FRAME; @@ -84,7 +84,7 @@ public class TimerFps { */ public int getSkipped() { - long change = skipped - lastSkipped; + final long change = skipped - lastSkipped; lastSkipped = skipped; return (int) change; } @@ -95,7 +95,7 @@ public class TimerFps { */ public void startNewFrame() { - long time = getTime(); + final long time = getTime(); lastFrame = time; nextFrame = time + FRAME; lastSkipped = skipped; diff --git a/src/mightypork/utils/files/FileTreeDiff.java b/src/mightypork/utils/files/FileTreeDiff.java index 9529e6c..eaef035 100644 --- a/src/mightypork/utils/files/FileTreeDiff.java +++ b/src/mightypork/utils/files/FileTreeDiff.java @@ -18,13 +18,13 @@ import mightypork.utils.logging.Log; public class FileTreeDiff { private static final byte[] BUFFER = new byte[2048]; - private Checksum ck1 = new Adler32(); - private Checksum ck2 = new Adler32(); + private final Checksum ck1 = new Adler32(); + private final Checksum ck2 = new Adler32(); private boolean logging = true; - private List> compared = new ArrayList>(); - private Comparator fileFirstSorter = new Comparator() { + private final List> compared = new ArrayList>(); + private final Comparator fileFirstSorter = new Comparator() { @Override public int compare(File o1, File o2) @@ -57,7 +57,7 @@ public class FileTreeDiff { return true; - } catch (NotEqualException e) { + } catch (final NotEqualException e) { if (logging) Log.f3("Difference found:\n" + e.getMessage()); return false; @@ -70,7 +70,7 @@ public class FileTreeDiff { FileInputStream in1 = null, in2 = null; CheckedInputStream cin1 = null, cin2 = null; - for (Tuple pair : compared) { + for (final Tuple pair : compared) { try { ck1.reset(); ck2.reset(); @@ -82,8 +82,8 @@ public class FileTreeDiff { cin2 = new CheckedInputStream(in2, ck2); while (true) { - int read1 = cin1.read(BUFFER); - int read2 = cin2.read(BUFFER); + final int read1 = cin1.read(BUFFER); + final int read2 = cin2.read(BUFFER); if (read1 != read2 || ck1.getValue() != ck2.getValue()) { throw new NotEqualException("Bytes differ:\n" + pair.a + "\n" + pair.b); @@ -92,31 +92,31 @@ public class FileTreeDiff { if (read1 == -1) break; } - } catch (IOException e) { + } catch (final IOException e) { // ignore } finally { try { if (cin1 != null) cin1.close(); - } catch (Exception e) { + } catch (final Exception e) { // ignore } try { if (cin2 != null) cin2.close(); - } catch (Exception e) { + } catch (final Exception e) { // ignore } try { if (in1 != null) in1.close(); - } catch (Exception e) { + } catch (final Exception e) { // ignore } try { if (in2 != null) in2.close(); - } catch (Exception e) { + } catch (final Exception e) { // ignore } @@ -134,8 +134,8 @@ public class FileTreeDiff { } if (f1.isDirectory()) { - File[] children1 = f1.listFiles(); - File[] children2 = f2.listFiles(); + final File[] children1 = f1.listFiles(); + final File[] children2 = f2.listFiles(); Arrays.sort(children1, fileFirstSorter); Arrays.sort(children2, fileFirstSorter); @@ -143,8 +143,8 @@ public class FileTreeDiff { if (children1.length != children2.length) throw new NotEqualException("Child counts differ:\n" + f1 + "\n" + f2); for (int i = 0; i < children1.length; i++) { - File ch1 = children1[i]; - File ch2 = children2[i]; + final File ch1 = children1[i]; + final File ch2 = children2[i]; if (!ch1.getName().equals(ch2.getName())) throw new NotEqualException("Filenames differ:\n" + ch1 + "\n" + ch2); diff --git a/src/mightypork/utils/files/FileUtils.java b/src/mightypork/utils/files/FileUtils.java index e5f2325..2423745 100644 --- a/src/mightypork/utils/files/FileUtils.java +++ b/src/mightypork/utils/files/FileUtils.java @@ -43,7 +43,7 @@ public class FileUtils { target.mkdir(); } - String[] children = source.list(); + final String[] children = source.list(); for (int i = 0; i < children.length; i++) { copyDirectory(new File(source, children[i]), new File(target, children[i]), filter, filesCopied); } @@ -70,7 +70,7 @@ public class FileUtils { public static void listDirectoryRecursive(File source, StringFilter filter, List files) throws IOException { if (source.isDirectory()) { - String[] children = source.list(); + final String[] children = source.list(); for (int i = 0; i < children.length; i++) { listDirectoryRecursive(new File(source, children[i]), filter, files); } @@ -105,12 +105,12 @@ public class FileUtils { } finally { try { if (in != null) in.close(); - } catch (IOException e) { + } catch (final IOException e) { e.printStackTrace(); } try { if (out != null) out.close(); - } catch (IOException e) { + } catch (final IOException e) { e.printStackTrace(); } } @@ -134,7 +134,7 @@ public class FileUtils { throw new NullPointerException("Output stream is null"); } - byte[] buf = new byte[2048]; + final byte[] buf = new byte[2048]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); @@ -157,7 +157,7 @@ public class FileUtils { if (!recursive || !path.isDirectory()) return path.delete(); - String[] list = path.list(); + final String[] list = path.list(); for (int i = 0; i < list.length; i++) { if (!delete(new File(path, list[i]), true)) return false; } @@ -175,7 +175,7 @@ public class FileUtils { */ public static String fileToString(File file) throws IOException { - FileInputStream fin = new FileInputStream(file); + final FileInputStream fin = new FileInputStream(file); return streamToString(fin); } @@ -204,17 +204,17 @@ public class FileUtils { { try { dir.mkdir(); - } catch (RuntimeException e) { + } catch (final RuntimeException e) { Log.e("Error creating folder " + dir, e); } - List list = new ArrayList(); + final List list = new ArrayList(); try { - for (File f : dir.listFiles(filter)) { + for (final File f : dir.listFiles(filter)) { list.add(f); } - } catch (Exception e) { + } catch (final Exception e) { Log.e("Error listing folder " + dir, e); } @@ -258,13 +258,13 @@ public class FileUtils { try { ext = StringUtils.fromLastDot(filename); - } catch (StringIndexOutOfBoundsException e) { + } catch (final StringIndexOutOfBoundsException e) { ext = ""; } try { name = StringUtils.toLastDot(filename); - } catch (StringIndexOutOfBoundsException e) { + } catch (final StringIndexOutOfBoundsException e) { name = ""; Log.w("Error extracting extension from file " + filename); } @@ -300,7 +300,7 @@ public class FileUtils { } BufferedReader br = null; - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); String line; try { @@ -315,12 +315,12 @@ public class FileUtils { sb.append("--- end of preview ---\n"); } - } catch (IOException e) { + } catch (final IOException e) { Log.e(e); } finally { try { if (br != null) br.close(); - } catch (IOException e) { + } catch (final IOException e) { // ignore } } @@ -335,7 +335,7 @@ public class FileUtils { try { return new ByteArrayInputStream(text.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { + } catch (final UnsupportedEncodingException e) { Log.e(e); return null; } @@ -344,13 +344,13 @@ public class FileUtils { public static InputStream getResource(String path) { - InputStream in = FileUtils.class.getResourceAsStream(path); + final InputStream in = FileUtils.class.getResourceAsStream(path); if (in != null) return in; try { return new FileInputStream(new File(".", path)); - } catch (FileNotFoundException e) { + } catch (final FileNotFoundException e) { // error Log.w("Could not open resource stream: " + path); return null; @@ -390,12 +390,12 @@ public class FileUtils { public static void deleteEmptyDirs(File base) { - for (File f : listDirectory(base)) { + for (final File f : listDirectory(base)) { if (!f.isDirectory()) continue; deleteEmptyDirs(f); - List children = listDirectory(f); + final List children = listDirectory(f); if (children.size() == 0) { f.delete(); continue; @@ -413,9 +413,9 @@ public class FileUtils { */ public static String escapeFileString(String filestring) { - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); - for (char c : filestring.toCharArray()) { + for (final char c : filestring.toCharArray()) { switch (c) { case '%': sb.append("%%"); @@ -458,7 +458,7 @@ public class FileUtils { */ public static String escapeFilename(String filename) { - String[] parts = getFilenameParts(filename); + final String[] parts = getFilenameParts(filename); return escapeFileString(parts[0]) + "." + parts[1]; } @@ -472,7 +472,7 @@ public class FileUtils { */ public static String unescapeFilename(String filename) { - String[] parts = getFilenameParts(filename); + final String[] parts = getFilenameParts(filename); return unescapeFileString(parts[0]) + "." + parts[1]; } @@ -510,13 +510,13 @@ public class FileUtils { } finally { try { if (in != null) in.close(); - } catch (IOException e) { + } catch (final IOException e) { // ignore } try { if (out != null) out.close(); - } catch (IOException e) { + } catch (final IOException e) { // ignore } } @@ -532,7 +532,7 @@ public class FileUtils { */ public static String resourceToString(String resname) { - InputStream in = FileUtils.getResource(resname); + final InputStream in = FileUtils.getResource(resname); return streamToString(in); } } diff --git a/src/mightypork/utils/files/OsUtils.java b/src/mightypork/utils/files/OsUtils.java index a3c12f2..d51580e 100644 --- a/src/mightypork/utils/files/OsUtils.java +++ b/src/mightypork/utils/files/OsUtils.java @@ -53,7 +53,7 @@ public class OsUtils { */ public static File getWorkDir(String dirname, String subfolderName, boolean create) { - File f = new File(getWorkDir(dirname), subfolderName); + final File f = new File(getWorkDir(dirname), subfolderName); if (!f.exists() && create) { if (!f.mkdirs()) { @@ -82,7 +82,7 @@ public class OsUtils { { if (cachedOs != null) return cachedOs; - String s = System.getProperty("os.name").toLowerCase(); + final String s = System.getProperty("os.name").toLowerCase(); if (s.contains("win")) { cachedOs = EnumOS.windows; @@ -106,7 +106,7 @@ public class OsUtils { private static File getWorkDir(String dirname, boolean create) { - String userhome = System.getProperty("user.home", "."); + final String userhome = System.getProperty("user.home", "."); File file; switch (getOs()) { @@ -116,7 +116,7 @@ public class OsUtils { break; case windows: - String appdata = System.getenv("APPDATA"); + final String appdata = System.getenv("APPDATA"); if (appdata != null) { file = new File(appdata, "." + dirname + '/'); diff --git a/src/mightypork/utils/files/PropertyManager.java b/src/mightypork/utils/files/PropertyManager.java index aed3e44..c79dab9 100644 --- a/src/mightypork/utils/files/PropertyManager.java +++ b/src/mightypork/utils/files/PropertyManager.java @@ -45,16 +45,16 @@ public class PropertyManager { private static void writeComments(BufferedWriter bw, String comm) throws IOException { - String comments = comm.replace("\n\n", "\n \n"); + final String comments = comm.replace("\n\n", "\n \n"); - int len = comments.length(); + final int len = comments.length(); int current = 0; int last = 0; - char[] uu = new char[6]; + final char[] uu = new char[6]; uu[0] = '\\'; uu[1] = 'u'; while (current < len) { - char c = comments.charAt(current); + final char c = comments.charAt(current); if (c > '\u00ff' || c == '\n' || c == '\r') { if (last != current) { bw.write("# " + comments.substring(last, current)); @@ -96,7 +96,7 @@ public class PropertyManager { private boolean firstEntry = true; /** Comments for individual keys */ - private Hashtable keyComments = new Hashtable(); + private final Hashtable keyComments = new Hashtable(); private String lastSectionBeginning = ""; @@ -105,8 +105,8 @@ public class PropertyManager { @Override public synchronized Enumeration keys() { - Enumeration keysEnum = super.keys(); - Vector keyList = new Vector(); + final Enumeration keysEnum = super.keys(); + final Vector keyList = new Vector(); while (keysEnum.hasMoreElements()) { keyList.add(keysEnum.nextElement()); } @@ -117,15 +117,15 @@ public class PropertyManager { private static String saveConvert(String theString, boolean escapeSpace, boolean escapeUnicode) { - int len = theString.length(); + final int len = theString.length(); int bufLen = len * 2; if (bufLen < 0) { bufLen = Integer.MAX_VALUE; } - StringBuffer outBuffer = new StringBuffer(bufLen); + final StringBuffer outBuffer = new StringBuffer(bufLen); for (int x = 0; x < len; x++) { - char aChar = theString.charAt(x); + final char aChar = theString.charAt(x); // Handle common case first, selecting largest block that // avoids the specials below @@ -209,16 +209,16 @@ public class PropertyManager { @Override public void store(OutputStream out, String comments) throws IOException { - BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); + final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); - boolean escUnicode = false; + final boolean escUnicode = false; if (comments != null) { writeComments(bw, comments); } synchronized (this) { - for (Enumeration e = keys(); e.hasMoreElements();) { + for (final Enumeration e = keys(); e.hasMoreElements();) { boolean wasNewLine = false; String key = (String) e.nextElement(); @@ -242,12 +242,12 @@ public class PropertyManager { cm = cm.replace("\r\n", "\n"); cm = cm.replace("\n\n", "\n \n"); - String[] cmlines = cm.split("\n"); + final String[] cmlines = cm.split("\n"); if (!wasNewLine && !firstEntry && cfgEmptyLineBeforeComment) { bw.newLine(); } - for (String cmline : cmlines) { + for (final String cmline : cmlines) { bw.write("# " + cmline); bw.newLine(); } @@ -273,11 +273,11 @@ public class PropertyManager { private static String escapifyStr(String str) { - StringBuilder result = new StringBuilder(); + final StringBuilder result = new StringBuilder(); - int len = str.length(); + final int len = str.length(); for (int x = 0; x < len; x++) { - char ch = str.charAt(x); + final char ch = str.charAt(x); if (ch <= 0x007e) { result.append(ch); continue; @@ -296,7 +296,7 @@ public class PropertyManager { private static char hexDigit(char ch, int offset) { - int val = (ch >> offset) & 0xF; + final int val = (ch >> offset) & 0xF; if (val <= 9) { return (char) ('0' + val); } @@ -313,25 +313,25 @@ public class PropertyManager { public static SortedProperties loadProperties(SortedProperties props, InputStream is, String encoding) throws IOException { - StringBuilder sb = new StringBuilder(); - InputStreamReader isr = new InputStreamReader(is, encoding); + final StringBuilder sb = new StringBuilder(); + final InputStreamReader isr = new InputStreamReader(is, encoding); while (true) { - int temp = isr.read(); + final int temp = isr.read(); if (temp < 0) { break; } - char c = (char) temp; + final char c = (char) temp; sb.append(c); } - String read = sb.toString(); + final String read = sb.toString(); - String inputString = escapifyStr(read); - byte[] bs = inputString.getBytes("ISO-8859-1"); - ByteArrayInputStream bais = new ByteArrayInputStream(bs); + final String inputString = escapifyStr(read); + final byte[] bs = inputString.getBytes("ISO-8859-1"); + final ByteArrayInputStream bais = new ByteArrayInputStream(bs); - SortedProperties ps = props; + final SortedProperties ps = props; ps.load(bais); return ps; } @@ -491,7 +491,7 @@ public class PropertyManager { try { num = Integer.parseInt(string.trim()); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { num = defnum; } @@ -506,7 +506,7 @@ public class PropertyManager { try { num = Double.parseDouble(string.trim()); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { num = defnum; } @@ -529,7 +529,7 @@ public class PropertyManager { return false; } - String string2 = string.toLowerCase(); + final String string2 = string.toLowerCase(); bool = string2.equals("yes") || string2.equals("true") || string2.equals("on") || string2.equals("enabled") || string2.equals("enable"); } @@ -598,12 +598,12 @@ public class PropertyManager { /** Force save, even if nothing changed (used to save changed comments) */ private boolean cfgForceSave; - private File file; + private final File file; private String fileComment = ""; - private TreeMap entries; - private TreeMap keyRename; - private TreeMap setValues; + private final TreeMap entries; + private final TreeMap keyRename; + private final TreeMap setValues; private SortedProperties pr = new SortedProperties(); @@ -634,13 +634,13 @@ public class PropertyManager { fis = new FileInputStream(file); pr = PropertiesLoader.loadProperties(pr, fis); - } catch (IOException e) { + } catch (final IOException e) { needsSave = true; pr = new SortedProperties(); } finally { try { if (fis != null) fis.close(); - } catch (IOException e) { + } catch (final IOException e) { e.printStackTrace(); } } @@ -648,10 +648,10 @@ public class PropertyManager { pr.cfgSeparateSectionsByEmptyLine = cfgSeparateSections; pr.cfgEmptyLineBeforeComment = cfgNewlineBeforeComments; - ArrayList keyList = new ArrayList(); + final ArrayList keyList = new ArrayList(); // rename keys - for (Entry entry : keyRename.entrySet()) { + for (final Entry entry : keyRename.entrySet()) { if (pr.getProperty(entry.getKey()) == null) { continue; } @@ -661,16 +661,16 @@ public class PropertyManager { } // set the override values into the freshly loaded properties file - for (Entry entry : setValues.entrySet()) { + for (final Entry entry : setValues.entrySet()) { pr.setProperty(entry.getKey(), entry.getValue()); needsSave = true; } // validate entries one by one, replace with default when needed - for (Property entry : entries.values()) { + for (final Property entry : entries.values()) { keyList.add(entry.name); - String propOrig = pr.getProperty(entry.name); + final String propOrig = pr.getProperty(entry.name); if (!entry.parse(propOrig)) needsSave = true; if (!cfgNoValidate) { entry.validate(); @@ -688,7 +688,7 @@ public class PropertyManager { } // removed unused props - for (String propname : pr.keySet().toArray(new String[pr.size()])) { + for (final String propname : pr.keySet().toArray(new String[pr.size()])) { if (!keyList.contains(propname)) { pr.remove(propname); needsSave = true; @@ -700,7 +700,7 @@ public class PropertyManager { if (needsSave || cfgForceSave) { try { pr.store(new FileOutputStream(file), fileComment); - } catch (IOException ioe) { + } catch (final IOException ioe) { ioe.printStackTrace(); } } @@ -756,7 +756,7 @@ public class PropertyManager { { try { return entries.get(n); - } catch (Throwable t) { + } catch (final Throwable t) { return null; } } @@ -772,7 +772,7 @@ public class PropertyManager { { try { return entries.get(n).getBoolean(); - } catch (Throwable t) { + } catch (final Throwable t) { return false; } } @@ -788,7 +788,7 @@ public class PropertyManager { { try { return get(n).getInteger(); - } catch (Throwable t) { + } catch (final Throwable t) { return -1; } } @@ -804,7 +804,7 @@ public class PropertyManager { { try { return get(n).getDouble(); - } catch (Throwable t) { + } catch (final Throwable t) { return -1D; } } @@ -820,7 +820,7 @@ public class PropertyManager { { try { return get(n).getString(); - } catch (Throwable t) { + } catch (final Throwable t) { return null; } } diff --git a/src/mightypork/utils/files/SimpleConfig.java b/src/mightypork/utils/files/SimpleConfig.java index eaa074a..66784e4 100644 --- a/src/mightypork/utils/files/SimpleConfig.java +++ b/src/mightypork/utils/files/SimpleConfig.java @@ -32,7 +32,7 @@ public class SimpleConfig { */ public static List listFromFile(File file) throws IOException { - String fileText = FileUtils.fileToString(file); + final String fileText = FileUtils.fileToString(file); return listFromString(fileText); } @@ -47,7 +47,7 @@ public class SimpleConfig { */ public static Map mapFromFile(File file) throws IOException { - String fileText = FileUtils.fileToString(file); + final String fileText = FileUtils.fileToString(file); return mapFromString(fileText); } @@ -61,9 +61,9 @@ public class SimpleConfig { */ public static List listFromString(String text) { - List list = new ArrayList(); + final List list = new ArrayList(); - String[] groupsLines = text.split("\n"); + final String[] groupsLines = text.split("\n"); for (String s : groupsLines) { // ignore invalid lines @@ -91,11 +91,11 @@ public class SimpleConfig { */ public static Map mapFromString(String text) { - LinkedHashMap pairs = new LinkedHashMap(); + final LinkedHashMap pairs = new LinkedHashMap(); - String[] groupsLines = text.split("\n"); + final String[] groupsLines = text.split("\n"); - for (String s : groupsLines) { + for (final String s : groupsLines) { // ignore invalid lines if (s.length() == 0) continue; if (s.startsWith("#") || s.startsWith("//")) continue; @@ -147,9 +147,9 @@ public class SimpleConfig { */ public static void mapToFile(File target, Map data, boolean allowNulls) throws IOException { - List lines = new ArrayList(); + final List lines = new ArrayList(); - for (Entry e : data.entrySet()) { + for (final Entry e : data.entrySet()) { String key = e.getKey(); String value = e.getValue(); @@ -166,7 +166,7 @@ public class SimpleConfig { String text = ""; // # File written by SimpleConfig - for (String s : lines) { + for (final String s : lines) { if (text.length() > 0) text += "\n"; text += s; diff --git a/src/mightypork/utils/files/ZipBuilder.java b/src/mightypork/utils/files/ZipBuilder.java index 4ef83f4..e684e96 100644 --- a/src/mightypork/utils/files/ZipBuilder.java +++ b/src/mightypork/utils/files/ZipBuilder.java @@ -16,8 +16,8 @@ import mightypork.utils.logging.Log; */ public class ZipBuilder { - private ZipOutputStream out; - private HashSet included = new HashSet(); + private final ZipOutputStream out; + private final HashSet included = new HashSet(); /** @@ -28,7 +28,7 @@ public class ZipBuilder { public ZipBuilder(File target) throws FileNotFoundException { target.getParentFile().mkdirs(); - FileOutputStream dest = new FileOutputStream(target); + final FileOutputStream dest = new FileOutputStream(target); out = new ZipOutputStream(new BufferedOutputStream(dest)); } @@ -70,7 +70,7 @@ public class ZipBuilder { out.putNextEntry(new ZipEntry(path)); - InputStream in = FileUtils.stringToStream(text); + final InputStream in = FileUtils.stringToStream(text); FileUtils.copyStream(in, out); } @@ -90,7 +90,7 @@ public class ZipBuilder { out.putNextEntry(new ZipEntry(path)); - InputStream in = FileUtils.getResource(resPath); + final InputStream in = FileUtils.getResource(resPath); FileUtils.copyStream(in, out); } diff --git a/src/mightypork/utils/files/ZipUtils.java b/src/mightypork/utils/files/ZipUtils.java index 7669981..b9f81f6 100644 --- a/src/mightypork/utils/files/ZipUtils.java +++ b/src/mightypork/utils/files/ZipUtils.java @@ -45,7 +45,7 @@ public class ZipUtils { } finally { try { if (zip != null) zip.close(); - } catch (IOException e) { + } catch (final IOException e) { // ignore } } @@ -63,20 +63,20 @@ public class ZipUtils { */ public static List extractZip(ZipFile zip, File outputDir, StringFilter filter) throws IOException { - ArrayList files = new ArrayList(); + final ArrayList files = new ArrayList(); outputDir.mkdirs(); - Enumeration zipFileEntries = zip.entries(); + final Enumeration zipFileEntries = zip.entries(); // process each entry while (zipFileEntries.hasMoreElements()) { - ZipEntry entry = zipFileEntries.nextElement(); + final ZipEntry entry = zipFileEntries.nextElement(); // parse filename and path - String entryPath = entry.getName(); - File destFile = new File(outputDir, entryPath); - File destinationParent = destFile.getParentFile(); + final String entryPath = entry.getName(); + final File destFile = new File(outputDir, entryPath); + final File destinationParent = destFile.getParentFile(); if (entry.isDirectory() || (filter != null && !filter.accept(entryPath))) continue; @@ -109,7 +109,7 @@ public class ZipUtils { } finally { try { if (zip != null) zip.close(); - } catch (IOException e) { + } catch (final IOException e) { // ignore } } @@ -125,13 +125,13 @@ public class ZipUtils { */ public static List listZip(ZipFile zip) throws IOException { - ArrayList files = new ArrayList(); + final ArrayList files = new ArrayList(); - Enumeration zipFileEntries = zip.entries(); + final Enumeration zipFileEntries = zip.entries(); // process each entry while (zipFileEntries.hasMoreElements()) { - ZipEntry entry = zipFileEntries.nextElement(); + final ZipEntry entry = zipFileEntries.nextElement(); if (!entry.isDirectory()) { files.add(entry.getName()); @@ -167,13 +167,13 @@ public class ZipUtils { } finally { try { if (is != null) is.close(); - } catch (IOException e) { + } catch (final IOException e) { // ignore } try { if (dest != null) dest.close(); - } catch (IOException e) { + } catch (final IOException e) { // ignore } @@ -194,12 +194,12 @@ public class ZipUtils { BufferedInputStream is = null; try { is = new BufferedInputStream(zip.getInputStream(entry)); - String s = FileUtils.streamToString(is); + final String s = FileUtils.streamToString(is); return s; } finally { try { if (is != null) is.close(); - } catch (IOException e) { + } catch (final IOException e) { // ignore } } @@ -213,12 +213,12 @@ public class ZipUtils { try { zf = new ZipFile(selectedFile); return zf.getEntry(string) != null; - } catch (Exception e) { + } catch (final Exception e) { return false; } finally { try { if (zf != null) zf.close(); - } catch (IOException e) { + } catch (final IOException e) { // ignore } } diff --git a/src/mightypork/utils/files/ion/AbstractIonList.java b/src/mightypork/utils/files/ion/AbstractIonList.java index a1f7ebe..15633b2 100644 --- a/src/mightypork/utils/files/ion/AbstractIonList.java +++ b/src/mightypork/utils/files/ion/AbstractIonList.java @@ -20,10 +20,10 @@ public abstract class AbstractIonList extends ArrayList implements Ionizab { try { while (true) { - byte b = BinaryUtils.readByte(in); + final byte b = BinaryUtils.readByte(in); if (b == IonMarks.ENTRY) { - T value = (T) Ion.readObject(in); + final T value = (T) Ion.readObject(in); add(value); } else if (b == IonMarks.END) { break; @@ -32,7 +32,7 @@ public abstract class AbstractIonList extends ArrayList implements Ionizab } } ionReadCustomData(in); - } catch (IOException e) { + } catch (final IOException e) { throw new IonException("Error reading ion list", e); } } @@ -42,14 +42,14 @@ public abstract class AbstractIonList extends ArrayList implements Ionizab public void ionWrite(OutputStream out) throws IonException { try { - for (T entry : this) { + for (final T entry : this) { if (entry instanceof IonizableOptional && !((IonizableOptional) entry).ionShouldSave()) continue; BinaryUtils.writeByte(out, IonMarks.ENTRY); Ion.writeObject(out, entry); } BinaryUtils.writeByte(out, IonMarks.END); ionWriteCustomData(out); - } catch (IOException e) { + } catch (final IOException e) { throw new IonException("Error reading ion map", e); } } diff --git a/src/mightypork/utils/files/ion/AbstractIonMap.java b/src/mightypork/utils/files/ion/AbstractIonMap.java index 7cdea7e..d6963d3 100644 --- a/src/mightypork/utils/files/ion/AbstractIonMap.java +++ b/src/mightypork/utils/files/ion/AbstractIonMap.java @@ -34,11 +34,11 @@ public abstract class AbstractIonMap extends LinkedHashMap impleme { try { while (true) { - byte b = BinaryUtils.readByte(in); + final byte b = BinaryUtils.readByte(in); if (b == IonMarks.ENTRY) { - String key = BinaryUtils.readString(in); + final String key = BinaryUtils.readString(in); - V value = (V) Ion.readObject(in); + final V value = (V) Ion.readObject(in); put(key, value); } else if (b == IonMarks.END) { @@ -48,7 +48,7 @@ public abstract class AbstractIonMap extends LinkedHashMap impleme } } ionReadCustomData(in); - } catch (IOException e) { + } catch (final IOException e) { throw new IonException("Error reading ion map", e); } } @@ -58,14 +58,14 @@ public abstract class AbstractIonMap extends LinkedHashMap impleme public void ionWrite(OutputStream out) throws IonException { try { - for (java.util.Map.Entry entry : entrySet()) { + for (final java.util.Map.Entry entry : entrySet()) { BinaryUtils.writeByte(out, IonMarks.ENTRY); BinaryUtils.writeString(out, entry.getKey()); Ion.writeObject(out, entry.getValue()); } BinaryUtils.writeByte(out, IonMarks.END); ionWriteCustomData(out); - } catch (IOException e) { + } catch (final IOException e) { throw new IonException("Error reading ion map", e); } } diff --git a/src/mightypork/utils/files/ion/BinaryUtils.java b/src/mightypork/utils/files/ion/BinaryUtils.java index 380b646..042e371 100644 --- a/src/mightypork/utils/files/ion/BinaryUtils.java +++ b/src/mightypork/utils/files/ion/BinaryUtils.java @@ -93,10 +93,10 @@ public class BinaryUtils { public static byte[] getBytesString(String str) { - char[] chars = str.toCharArray(); + final char[] chars = str.toCharArray(); - ByteBuffer bstr = ByteBuffer.allocate((Character.SIZE / 8) * chars.length + (Character.SIZE / 8)); - for (char c : chars) { + final ByteBuffer bstr = ByteBuffer.allocate((Character.SIZE / 8) * chars.length + (Character.SIZE / 8)); + for (final char c : chars) { bstr.putChar(c); } @@ -177,7 +177,7 @@ public class BinaryUtils { public static char readChar(InputStream in) throws IOException { in.read(ac, 0, ac.length); - ByteBuffer buf = ByteBuffer.wrap(ac); + final ByteBuffer buf = ByteBuffer.wrap(ac); return buf.getChar(); } @@ -185,7 +185,7 @@ public class BinaryUtils { public static short readShort(InputStream in) throws IOException { in.read(as, 0, as.length); - ByteBuffer buf = ByteBuffer.wrap(as); + final ByteBuffer buf = ByteBuffer.wrap(as); return buf.getShort(); } @@ -193,7 +193,7 @@ public class BinaryUtils { public static long readLong(InputStream in) throws IOException { in.read(al, 0, al.length); - ByteBuffer buf = ByteBuffer.wrap(al); + final ByteBuffer buf = ByteBuffer.wrap(al); return buf.getLong(); } @@ -201,7 +201,7 @@ public class BinaryUtils { public static int readInt(InputStream in) throws IOException { in.read(ai, 0, ai.length); - ByteBuffer buf = ByteBuffer.wrap(ai); + final ByteBuffer buf = ByteBuffer.wrap(ai); return buf.getInt(); } @@ -209,7 +209,7 @@ public class BinaryUtils { public static float readFloat(InputStream in) throws IOException { in.read(af, 0, af.length); - ByteBuffer buf = ByteBuffer.wrap(af); + final ByteBuffer buf = ByteBuffer.wrap(af); return buf.getFloat(); } @@ -217,7 +217,7 @@ public class BinaryUtils { public static double readDouble(InputStream in) throws IOException { in.read(ad, 0, ad.length); - ByteBuffer buf = ByteBuffer.wrap(ad); + final ByteBuffer buf = ByteBuffer.wrap(ad); return buf.getDouble(); } diff --git a/src/mightypork/utils/files/ion/Ion.java b/src/mightypork/utils/files/ion/Ion.java index a758af2..4e990a7 100644 --- a/src/mightypork/utils/files/ion/Ion.java +++ b/src/mightypork/utils/files/ion/Ion.java @@ -23,7 +23,7 @@ public class Ion { try { registerIonizable(IonMarks.MAP, IonMap.class); registerIonizable(IonMarks.LIST, IonList.class); - } catch (IonException e) { + } catch (final IonException e) { e.printStackTrace(); } } @@ -70,16 +70,16 @@ public class Ion { InputStream in = null; try { in = new FileInputStream(file); - Object obj = fromStream(in); + final Object obj = fromStream(in); return obj; - } catch (IOException e) { + } catch (final IOException e) { throw new IonException("Error loading ION file.", e); } finally { if (in != null) { try { in.close(); - } catch (IOException e) { + } catch (final IOException e) { e.printStackTrace(); } } @@ -124,8 +124,8 @@ public class Ion { { OutputStream out = null; try { - String f = path.toString(); - File dir = new File(f.substring(0, f.lastIndexOf(File.separator))); + final String f = path.toString(); + final File dir = new File(f.substring(0, f.lastIndexOf(File.separator))); dir.mkdirs(); @@ -135,13 +135,13 @@ public class Ion { out.flush(); out.close(); - } catch (Exception e) { + } catch (final Exception e) { throw new IonException("Error writing to ION file.", e); } finally { if (out != null) { try { out.close(); - } catch (IOException e) { + } catch (final IOException e) { e.printStackTrace(); } } @@ -173,16 +173,16 @@ public class Ion { public static Object readObject(InputStream in) throws IonException { try { - int bi = in.read(); + final int bi = in.read(); if (bi == -1) throw new IonException("Unexpected end of stream."); - byte b = (byte) bi; + final byte b = (byte) bi; if (customIonizables.containsKey(b)) { Ionizable ion; try { ion = ((Ionizable) customIonizables.get(b).newInstance()); - } catch (InstantiationException e) { + } catch (final InstantiationException e) { throw new IonException("Cound not instantiate " + customIonizables.get(b).getSimpleName(), e); - } catch (IllegalAccessException e) { + } catch (final IllegalAccessException e) { throw new IonException("Cound not instantiate " + customIonizables.get(b).getSimpleName(), e); } ion.ionRead(in); @@ -207,12 +207,12 @@ public class Ion { case IonMarks.DOUBLE: return BinaryUtils.readDouble(in); case IonMarks.STRING: - String s = BinaryUtils.readString(in); + final String s = BinaryUtils.readString(in); return s; default: throw new IonException("Invalid Ion mark " + Integer.toHexString(bi)); } - } catch (IOException e) { + } catch (final IOException e) { throw new IonException("Error loading ION file: ", e); } } @@ -290,7 +290,7 @@ public class Ion { throw new IonException(Calc.cname(obj) + " can't be stored in Ion storage."); - } catch (IOException e) { + } catch (final IOException e) { throw new IonException("Could not store " + obj, e); } } diff --git a/src/mightypork/utils/files/ion/IonList.java b/src/mightypork/utils/files/ion/IonList.java index bcc1d7e..266062b 100644 --- a/src/mightypork/utils/files/ion/IonList.java +++ b/src/mightypork/utils/files/ion/IonList.java @@ -131,12 +131,12 @@ public class IonList extends AbstractIonList { public Object getCheckType(int index, Class type) throws IonException { try { - Object o = super.get(index); + final Object o = super.get(index); if (o == null || !o.getClass().isAssignableFrom(type)) { throw new IonException("Incorrect object type"); } return o; - } catch (IndexOutOfBoundsException e) { + } catch (final IndexOutOfBoundsException e) { throw new IonException("Out of bounds"); } } diff --git a/src/mightypork/utils/logging/Log.java b/src/mightypork/utils/logging/Log.java index 9da5c90..0d470c7 100644 --- a/src/mightypork/utils/logging/Log.java +++ b/src/mightypork/utils/logging/Log.java @@ -133,7 +133,7 @@ public class Log { public static synchronized LogInstance create(String logName, File logsDir, int oldLogsCount) { if (logs.containsKey(logName)) return logs.get(logName); - LogInstance log = new LogInstance(logName, logsDir, oldLogsCount); + final LogInstance log = new LogInstance(logName, logsDir, oldLogsCount); if (main == null) main = log; logs.put(logName, log); @@ -153,7 +153,7 @@ public class Log { public static synchronized LogInstance create(String logName, File logsDir) { if (logs.containsKey(logName)) return logs.get(logName); - LogInstance log = new LogInstance(logName, logsDir, -1); + final LogInstance log = new LogInstance(logName, logsDir, -1); if (main == null) main = log; logs.put(logName, log); @@ -184,7 +184,7 @@ public class Log { try { hasToString = (o.getClass().getMethod("toString").getDeclaringClass() != Object.class); - } catch (Exception e) { + } catch (final Exception e) { // oh well.. } @@ -192,9 +192,9 @@ public class Log { return o.toString(); } else { - Class cls = o.getClass(); + final Class cls = o.getClass(); - Class enclosing = cls.getEnclosingClass(); + final Class enclosing = cls.getEnclosingClass(); return (enclosing == null ? "" : enclosing.getSimpleName() + ".") + cls.getSimpleName(); } @@ -203,7 +203,7 @@ public class Log { public static String str(Class cls) { - Class enclosing = cls.getEnclosingClass(); + final Class enclosing = cls.getEnclosingClass(); return (enclosing == null ? "" : enclosing.getSimpleName() + ".") + cls.getSimpleName(); } diff --git a/src/mightypork/utils/logging/LogInstance.java b/src/mightypork/utils/logging/LogInstance.java index c637e84..7551520 100644 --- a/src/mightypork/utils/logging/LogInstance.java +++ b/src/mightypork/utils/logging/LogInstance.java @@ -29,16 +29,16 @@ import mightypork.utils.files.FileUtils; public class LogInstance { /** log file */ - private File file; + private final File file; /** Log name */ - private String name; + private final String name; /** Number of old logs to keep */ - private int logs_to_keep; + private final int logs_to_keep; /** Logs dir */ - private File dir; + private final File dir; /** Logger instance. */ private Logger logger; @@ -49,7 +49,7 @@ public class LogInstance { private boolean sysout = true; private int monitorId = 0; - private HashMap monitors = new HashMap(); + private final HashMap monitors = new HashMap(); private LogToSysoutMonitor sysoutMonitor; @@ -77,7 +77,7 @@ public class LogInstance { try { handler = new FileHandler(file.getPath()); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Failed to init log", e); } @@ -101,13 +101,13 @@ public class LogInstance { { if (logs_to_keep == 0) return; // overwrite - for (File f : FileUtils.listDirectory(file.getParentFile())) { + for (final File f : FileUtils.listDirectory(file.getParentFile())) { if (!f.isFile()) continue; if (f.equals(file)) { - Date d = new Date(f.lastModified()); + final Date d = new Date(f.lastModified()); - String fbase = name + '_' + (new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")).format(d); - String suff = getSuffix(); + final String fbase = name + '_' + (new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")).format(d); + final String suff = getSuffix(); String cntStr = ""; File f2; @@ -119,7 +119,7 @@ public class LogInstance { if (logs_to_keep == -1) return; // keep all - List oldLogs = FileUtils.listDirectory(dir, new FileFilter() { + final List oldLogs = FileUtils.listDirectory(dir, new FileFilter() { @Override public boolean accept(File f) @@ -156,7 +156,7 @@ public class LogInstance { */ public synchronized int addMonitor(LogMonitor mon) { - int id = monitorId; + final int id = monitorId; monitorId++; monitors.put(id, mon); return id; @@ -294,8 +294,8 @@ public class LogInstance { */ private static String getStackTrace(Throwable t) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw, true); + final StringWriter sw = new StringWriter(); + final PrintWriter pw = new PrintWriter(sw, true); t.printStackTrace(pw); pw.flush(); sw.flush(); @@ -317,7 +317,7 @@ public class LogInstance { @Override public String format(LogRecord record) { - StringBuffer buf = new StringBuffer(180); + final StringBuffer buf = new StringBuffer(180); if (record.getMessage().equals("\n")) { return nl; @@ -328,7 +328,7 @@ public class LogInstance { record.setMessage(record.getMessage().substring(1)); } - Level level = record.getLevel(); + final Level level = record.getLevel(); String trail = "[ ? ]"; if (level == Level.FINE) { trail = "[ # ] "; @@ -356,7 +356,7 @@ public class LogInstance { buf.append(nl); - Throwable throwable = record.getThrown(); + final Throwable throwable = record.getThrown(); if (throwable != null) { buf.append("at "); buf.append(record.getSourceClassName()); @@ -364,16 +364,16 @@ public class LogInstance { buf.append(record.getSourceMethodName()); buf.append(nl); - StringWriter sink = new StringWriter(); + final StringWriter sink = new StringWriter(); throwable.printStackTrace(new PrintWriter(sink, true)); buf.append(sink.toString()); buf.append(nl); } - String str = buf.toString(); + final String str = buf.toString(); - for (LogMonitor mon : monitors.values()) { + for (final LogMonitor mon : monitors.values()) { mon.log(level, str); } diff --git a/src/mightypork/utils/math/Calc.java b/src/mightypork/utils/math/Calc.java index 92393c3..9d73dd3 100644 --- a/src/mightypork/utils/math/Calc.java +++ b/src/mightypork/utils/math/Calc.java @@ -34,17 +34,17 @@ public class Calc { public static double linePointDist(Coord lineDirVec, Coord linePoint, Coord point) { // line point L[lx,ly] - double lx = linePoint.x; - double ly = linePoint.y; + final double lx = linePoint.x; + final double ly = linePoint.y; // line equation ax+by+c=0 - double a = -lineDirVec.y; - double b = lineDirVec.x; - double c = -a * lx - b * ly; + final double a = -lineDirVec.y; + final double b = lineDirVec.x; + final double c = -a * lx - b * ly; // checked point P[x,y] - double x = point.x; - double y = point.y; + final double x = point.x; + final double y = point.y; // distance return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b); @@ -285,10 +285,10 @@ public class Calc { */ public static int roundX(double deg, double x) { - double half = x / 2d; + final double half = x / 2d; deg += half; deg = norm(deg); - int times = (int) Math.floor(deg / x); + final int times = (int) Math.floor(deg / x); double a = times * x; if (a == 360) a = 0; return (int) Math.round(a); @@ -511,8 +511,8 @@ public class Calc { private static double clamp_double(Number number, Number min, Number max) { double n = number.doubleValue(); - double mind = min.doubleValue(); - double maxd = max.doubleValue(); + final double mind = min.doubleValue(); + final double maxd = max.doubleValue(); if (n > maxd) n = maxd; if (n < mind) n = mind; if (Double.isNaN(n)) return mind; @@ -530,7 +530,7 @@ public class Calc { private static double clamp_double(Number number, Number min) { double n = number.doubleValue(); - double mind = min.doubleValue(); + final double mind = min.doubleValue(); if (n < mind) n = mind; return n; } @@ -790,7 +790,7 @@ public class Calc { public static double max(double... numbers) { double highest = numbers[0]; - for (double num : numbers) { + for (final double num : numbers) { if (num > highest) highest = num; } return highest; @@ -806,7 +806,7 @@ public class Calc { public static float max(float... numbers) { float highest = numbers[0]; - for (float num : numbers) { + for (final float num : numbers) { if (num > highest) highest = num; } return highest; @@ -822,7 +822,7 @@ public class Calc { public static int max(int... numbers) { int highest = numbers[0]; - for (int num : numbers) { + for (final int num : numbers) { if (num > highest) highest = num; } return highest; @@ -838,7 +838,7 @@ public class Calc { public static double min(double... numbers) { double lowest = numbers[0]; - for (double num : numbers) { + for (final double num : numbers) { if (num < lowest) lowest = num; } return lowest; @@ -854,7 +854,7 @@ public class Calc { public static float min(float... numbers) { float lowest = numbers[0]; - for (float num : numbers) { + for (final float num : numbers) { if (num < lowest) lowest = num; } return lowest; @@ -870,7 +870,7 @@ public class Calc { public static int min(int... numbers) { int lowest = numbers[0]; - for (int num : numbers) { + for (final int num : numbers) { if (num < lowest) lowest = num; } return lowest; @@ -888,14 +888,14 @@ public class Calc { if (list == null) { return null; } - String[] parts = list.split(","); + final String[] parts = list.split(","); - ArrayList intList = new ArrayList(); + final ArrayList intList = new ArrayList(); - for (String part : parts) { + for (final String part : parts) { try { intList.add(Integer.parseInt(part)); - } catch (NumberFormatException e) {} + } catch (final NumberFormatException e) {} } return intList; diff --git a/src/mightypork/utils/math/Polar.java b/src/mightypork/utils/math/Polar.java index 4768a21..0e2d405 100644 --- a/src/mightypork/utils/math/Polar.java +++ b/src/mightypork/utils/math/Polar.java @@ -161,7 +161,7 @@ public class Polar { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Polar)) return false; - Polar other = (Polar) obj; + final Polar other = (Polar) obj; if (Double.doubleToLongBits(angle) != Double.doubleToLongBits(other.angle)) return false; if (Double.doubleToLongBits(radius) != Double.doubleToLongBits(other.radius)) return false; return true; diff --git a/src/mightypork/utils/math/Range.java b/src/mightypork/utils/math/Range.java index 4d76d57..80f1558 100644 --- a/src/mightypork/utils/math/Range.java +++ b/src/mightypork/utils/math/Range.java @@ -32,7 +32,7 @@ public class Range { */ public Range(double min, double max) { if (min > max) { - double t = min; + final double t = min; min = max; max = t; } @@ -170,7 +170,7 @@ public class Range { max = other.max; if (min > max) { - double t = min; + final double t = min; min = max; max = t; } @@ -186,7 +186,7 @@ public class Range { public void setTo(double min, double max) { if (min > max) { - double t = min; + final double t = min; min = max; max = t; } diff --git a/src/mightypork/utils/math/animation/AnimDouble.java b/src/mightypork/utils/math/animation/AnimDouble.java index ab79191..73f0f26 100644 --- a/src/mightypork/utils/math/animation/AnimDouble.java +++ b/src/mightypork/utils/math/animation/AnimDouble.java @@ -191,12 +191,12 @@ public class AnimDouble implements Updateable, Pauseable { */ public void animate(double from, double to, double time) { - double current = now(); + final double current = now(); this.from = from; this.to = to; - double progress = getProgressFromValue(current); + final double progress = getProgressFromValue(current); this.from = (progress > 0 ? current : from); diff --git a/src/mightypork/utils/math/animation/AnimDoubleDeg.java b/src/mightypork/utils/math/animation/AnimDoubleDeg.java index 74e55f9..a98bdd7 100644 --- a/src/mightypork/utils/math/animation/AnimDoubleDeg.java +++ b/src/mightypork/utils/math/animation/AnimDoubleDeg.java @@ -38,9 +38,9 @@ public class AnimDoubleDeg extends AnimDouble { @Override protected double getProgressFromValue(double value) { - double whole = Deg.diff(from, to); + final double whole = Deg.diff(from, to); if (Deg.diff(value, from) < whole && Deg.diff(value, to) < whole) { - double partial = Deg.diff(from, value); + final double partial = Deg.diff(from, value); return partial / whole; } diff --git a/src/mightypork/utils/math/animation/AnimDoubleRad.java b/src/mightypork/utils/math/animation/AnimDoubleRad.java index f1a2717..e358013 100644 --- a/src/mightypork/utils/math/animation/AnimDoubleRad.java +++ b/src/mightypork/utils/math/animation/AnimDoubleRad.java @@ -38,9 +38,9 @@ public class AnimDoubleRad extends AnimDouble { @Override protected double getProgressFromValue(double value) { - double whole = Rad.diff(from, to); + final double whole = Rad.diff(from, to); if (Rad.diff(value, from) < whole && Rad.diff(value, to) < whole) { - double partial = Rad.diff(from, value); + final double partial = Rad.diff(from, value); return partial / whole; } diff --git a/src/mightypork/utils/math/animation/Easing.java b/src/mightypork/utils/math/animation/Easing.java index 5f1e4a9..69c4352 100644 --- a/src/mightypork/utils/math/animation/Easing.java +++ b/src/mightypork/utils/math/animation/Easing.java @@ -60,7 +60,7 @@ public abstract class Easing { */ private static class Reverse extends Easing { - private Easing ea; + private final Easing ea; /** @@ -85,8 +85,8 @@ public abstract class Easing { */ private static class Composite extends Easing { - private Easing in; - private Easing out; + private final Easing in; + private final Easing out; /** @@ -277,7 +277,7 @@ public abstract class Easing { @Override public double get(double t) { - float s = 1.70158f; + final float s = 1.70158f; return t * t * ((s + 1) * t - s); } }; @@ -297,8 +297,8 @@ public abstract class Easing { if (t == 0) return 0; if (t == 1) return 1; - double p = .3f; - double s = p / 4; + final double p = .3f; + final double s = p / 4; return -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p)); } }; diff --git a/src/mightypork/utils/math/color/HSV.java b/src/mightypork/utils/math/color/HSV.java index 45297ad..36cf90a 100644 --- a/src/mightypork/utils/math/color/HSV.java +++ b/src/mightypork/utils/math/color/HSV.java @@ -125,7 +125,7 @@ public class HSV { { norm(); - int rgb = Color.HSBtoRGB((float) h, (float) s, (float) v); + final int rgb = Color.HSBtoRGB((float) h, (float) s, (float) v); return RGB.fromHex(rgb); } diff --git a/src/mightypork/utils/math/color/RGB.java b/src/mightypork/utils/math/color/RGB.java index 1eb96a5..f4ebedf 100644 --- a/src/mightypork/utils/math/color/RGB.java +++ b/src/mightypork/utils/math/color/RGB.java @@ -311,9 +311,9 @@ public class RGB { */ public int getHex() { - int ri = (int) Math.round(r * 255); - int gi = (int) Math.round(g * 255); - int bi = (int) Math.round(b * 255); + final int ri = (int) Math.round(r * 255); + final int gi = (int) Math.round(g * 255); + final int bi = (int) Math.round(b * 255); return (ri << 16) | (gi << 8) | bi; } @@ -325,7 +325,7 @@ public class RGB { */ public HSV toHSV() { - float[] hsv = { 0, 0, 0 }; + final float[] hsv = { 0, 0, 0 }; Color.RGBtoHSB((int) (r * 255), (int) (g * 255), (int) (b * 255), hsv); return new HSV(hsv[0], hsv[1], hsv[2]); } @@ -339,9 +339,9 @@ public class RGB { */ public static RGB fromHex(int hex) { - int bi = hex & 0xff; - int gi = (hex >> 8) & 0xff; - int ri = (hex >> 16) & 0xff; + final int bi = hex & 0xff; + final int gi = (hex >> 8) & 0xff; + final int ri = (hex >> 16) & 0xff; return new RGB(ri / 255D, gi / 255D, bi / 255D); } diff --git a/src/mightypork/utils/math/constraints/ConstraintFactory.java b/src/mightypork/utils/math/constraints/ConstraintFactory.java index b8aa636..8f5701e 100644 --- a/src/mightypork/utils/math/constraints/ConstraintFactory.java +++ b/src/mightypork/utils/math/constraints/ConstraintFactory.java @@ -242,8 +242,8 @@ public class ConstraintFactory { @Override public Rect getRect() { - double height = getContext().getRect().size().y; - double perRow = height / rows; + final double height = getContext().getRect().size().y; + final double perRow = height / rows; return Rect.fromSize(getOrigin().add(0, perRow * index), getSize().setY(perRow)); } @@ -258,8 +258,8 @@ public class ConstraintFactory { @Override public Rect getRect() { - double width = getContext().getRect().size().x; - double perCol = width / columns; + final double width = getContext().getRect().size().x; + final double perCol = width / columns; return Rect.fromSize(getOrigin().add(perCol * index, 0), getSize().setX(perCol)); } @@ -337,10 +337,10 @@ public class ConstraintFactory { @Override public Rect getRect() { - double height = getSize().y; - double width = getSize().y; - double perRow = height / rows; - double perCol = width / cols; + final double height = getSize().y; + final double width = getSize().y; + final double perRow = height / rows; + final double perCol = width / cols; return Rect.fromSize(getOrigin().add(perCol * left, perRow * (rows - top - 1)), perCol, perRow); } @@ -355,7 +355,7 @@ public class ConstraintFactory { @Override public Rect getRect() { - Coord origin = getOrigin(); + final Coord origin = getOrigin(); //@formatter:off return Rect.fromSize( @@ -377,7 +377,7 @@ public class ConstraintFactory { @Override public Rect getRect() { - Coord origin = getOrigin(); + final Coord origin = getOrigin(); //@formatter:off return Rect.fromSize( @@ -399,7 +399,7 @@ public class ConstraintFactory { @Override public Rect getRect() { - Coord origin = getOrigin(); + final Coord origin = getOrigin(); //@formatter:off return new Rect( diff --git a/src/mightypork/utils/math/coord/Coord.java b/src/mightypork/utils/math/coord/Coord.java index 33ffd17..b2b984c 100644 --- a/src/mightypork/utils/math/coord/Coord.java +++ b/src/mightypork/utils/math/coord/Coord.java @@ -863,7 +863,7 @@ public class Coord { { if (isZero()) return this; - double k = size / size(); + final double k = size / size(); return mul_ip(k); } @@ -919,7 +919,7 @@ public class Coord { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Coord)) return false; - Coord other = (Coord) obj; + final Coord other = (Coord) obj; if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x)) return false; if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y)) return false; if (Double.doubleToLongBits(z) != Double.doubleToLongBits(other.z)) return false; diff --git a/src/mightypork/utils/objects/Convertor.java b/src/mightypork/utils/objects/Convertor.java index b778b50..9b194e9 100644 --- a/src/mightypork/utils/objects/Convertor.java +++ b/src/mightypork/utils/objects/Convertor.java @@ -29,7 +29,7 @@ public class Convertor { if (o instanceof Number) return ((Number) o).intValue(); if (o instanceof Range) return ((Range) o).randInt(); if (o instanceof Boolean) return ((Boolean) o) ? 1 : 0; - } catch (NumberFormatException e) {} + } catch (final NumberFormatException e) {} Log.w("Cannot convert " + o + " to Integer."); return def; } @@ -50,7 +50,7 @@ public class Convertor { if (o instanceof Number) return ((Number) o).doubleValue(); if (o instanceof Range) return ((Range) o).randDouble(); if (o instanceof Boolean) return ((Boolean) o) ? 1 : 0; - } catch (NumberFormatException e) {} + } catch (final NumberFormatException e) {} Log.w("Cannot convert " + o + " to Double."); return def; } @@ -68,7 +68,7 @@ public class Convertor { try { if (o == null) return def; if (o instanceof Number) return ((Number) o).floatValue(); - } catch (NumberFormatException e) {} + } catch (final NumberFormatException e) {} Log.w("Cannot convert " + o + " to Float."); return def; } @@ -86,13 +86,13 @@ public class Convertor { if (o == null) return def; if (o instanceof String) { - String s = ((String) o).trim().toLowerCase(); + final String s = ((String) o).trim().toLowerCase(); if (s.equals("0")) return false; if (s.equals("1")) return true; try { - double n = Double.parseDouble(s); + final double n = Double.parseDouble(s); return n != 0; - } catch (NumberFormatException e) {} + } catch (final NumberFormatException e) {} if (s.equals("true")) return true; if (s.equals("yes")) return true; @@ -149,11 +149,11 @@ public class Convertor { s = s.replace(',', ';'); // remove brackets if any s = s.replaceAll("[\\(\\[\\{\\)\\]\\}]", ""); - String[] parts = s.split("[;]"); + final String[] parts = s.split("[;]"); return new Coord(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[1].trim())); } if (o instanceof Coord) return new Coord((Coord) o); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { // ignore } Log.w("Cannot convert " + o + " to Coord."); @@ -184,13 +184,13 @@ public class Convertor { s = s.replaceAll("([0-9])\\s?[\\-]", "$1:"); // remove brackets if any s = s.replaceAll("[\\(\\[\\{\\)\\]\\}]", ""); - String[] parts = s.split("[:]"); + final String[] parts = s.split("[:]"); if (parts.length == 2) return new Range(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[1].trim())); return new Range(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[0].trim())); } if (o instanceof Range) return (Range) o; - } catch (NumberFormatException e) {} + } catch (final NumberFormatException e) {} Log.w("Cannot convert " + o + " to Range."); return def; } diff --git a/src/mightypork/utils/objects/MapSort.java b/src/mightypork/utils/objects/MapSort.java new file mode 100644 index 0000000..768ad54 --- /dev/null +++ b/src/mightypork/utils/objects/MapSort.java @@ -0,0 +1,76 @@ +package mightypork.utils.objects; + + +import java.util.*; +import java.util.Map.Entry; + + +/** + * Map sorting utils + * + * @author MightyPork + */ +public class MapSort { + + /** + * Sort a map by keys, maintaining key-value pairs. + * + * @param map map to be sorted + * @param comparator a comparator, or null for natural ordering + * @return linked hash map with sorted entries + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static Map sortByKeys(Map map, final Comparator comparator) + { + final List keys = new LinkedList(map.keySet()); + + if (comparator == null) { + Collections.sort(keys); + } else { + Collections.sort(keys, comparator); + } + + // LinkedHashMap will keep the keys in the order they are inserted + // which is currently sorted on natural ordering + final Map sortedMap = new LinkedHashMap(); + for (final K key : keys) { + sortedMap.put(key, map.get(key)); + } + + return sortedMap; + } + + + /** + * Sort a map by values, maintaining key-value pairs. + * + * @param map map to be sorted + * @param comparator a comparator, or null for natural ordering + * @return linked hash map with sorted entries + */ + @SuppressWarnings("rawtypes") + public static Map sortByValues(Map map, final Comparator comparator) + { + final List> entries = new LinkedList>(map.entrySet()); + + Collections.sort(entries, new Comparator>() { + + @Override + public int compare(Entry o1, Entry o2) + { + if (comparator == null) return o1.getValue().compareTo(o2.getValue()); + return comparator.compare(o1.getValue(), o2.getValue()); + } + }); + + // LinkedHashMap will keep the keys in the order they are inserted + // which is currently sorted on natural ordering + final Map sortedMap = new LinkedHashMap(); + + for (final Map.Entry entry : entries) { + sortedMap.put(entry.getKey(), entry.getValue()); + } + + return sortedMap; + } +} diff --git a/src/mightypork/utils/objects/Mutable.java b/src/mightypork/utils/objects/Mutable.java index 171c022..961bb7e 100644 --- a/src/mightypork/utils/objects/Mutable.java +++ b/src/mightypork/utils/objects/Mutable.java @@ -62,7 +62,7 @@ public class Mutable { if (obj == null) return false; if (!(obj instanceof Mutable)) return false; - Mutable other = (Mutable) obj; + final Mutable other = (Mutable) obj; if (o == null) { if (other.o != null) return false; } else if (!o.equals(other.o)) { diff --git a/src/mightypork/utils/objects/ObjectUtils.java b/src/mightypork/utils/objects/ObjectUtils.java index 3518bb7..c79588b 100644 --- a/src/mightypork/utils/objects/ObjectUtils.java +++ b/src/mightypork/utils/objects/ObjectUtils.java @@ -1,8 +1,8 @@ package mightypork.utils.objects; -import java.util.*; -import java.util.Map.Entry; +import java.util.ArrayList; +import java.util.List; /** @@ -14,83 +14,20 @@ public class ObjectUtils { public static Object fallback(Object... options) { - for (Object o : options) { + for (final Object o : options) { if (o != null) return o; } return null; // error } - /** - * Sort a map by keys, maintaining key-value pairs. - * - * @param map map to be sorted - * @param comparator a comparator, or null for natural ordering - * @return linked hash map with sorted entries - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static Map sortByKeys(Map map, final Comparator comparator) - { - List keys = new LinkedList(map.keySet()); - - if (comparator == null) { - Collections.sort(keys); - } else { - Collections.sort(keys, comparator); - } - - // LinkedHashMap will keep the keys in the order they are inserted - // which is currently sorted on natural ordering - Map sortedMap = new LinkedHashMap(); - for (K key : keys) { - sortedMap.put(key, map.get(key)); - } - - return sortedMap; - } - - - /** - * Sort a map by values, maintaining key-value pairs. - * - * @param map map to be sorted - * @param comparator a comparator, or null for natural ordering - * @return linked hash map with sorted entries - */ - @SuppressWarnings("rawtypes") - public static Map sortByValues(Map map, final Comparator comparator) - { - List> entries = new LinkedList>(map.entrySet()); - - Collections.sort(entries, new Comparator>() { - - @Override - public int compare(Entry o1, Entry o2) - { - if (comparator == null) return o1.getValue().compareTo(o2.getValue()); - return comparator.compare(o1.getValue(), o2.getValue()); - } - }); - - // LinkedHashMap will keep the keys in the order they are inserted - // which is currently sorted on natural ordering - Map sortedMap = new LinkedHashMap(); - - for (Map.Entry entry : entries) { - sortedMap.put(entry.getKey(), entry.getValue()); - } - - return sortedMap; - } - - public static String arrayToString(Object[] arr) { - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); sb.append('['); - boolean first = true; - for (Object o : arr) { + final boolean first = true; + for (final Object o : arr) { if (!first) sb.append(','); sb.append(o.toString()); } @@ -102,8 +39,8 @@ public class ObjectUtils { public static List arrayToList(T[] objs) { - ArrayList list = new ArrayList(); - for (T o : objs) { + final ArrayList list = new ArrayList(); + for (final T o : objs) { list.add(o); } return list; diff --git a/src/mightypork/utils/objects/Pair.java b/src/mightypork/utils/objects/Pair.java index 6a62c67..27c8246 100644 --- a/src/mightypork/utils/objects/Pair.java +++ b/src/mightypork/utils/objects/Pair.java @@ -66,7 +66,7 @@ public class Pair { return false; } - Pair t = (Pair) obj; + final Pair t = (Pair) obj; return Calc.areObjectsEqual(first, t.first) && Calc.areObjectsEqual(second, t.second); diff --git a/src/mightypork/utils/objects/VarargsParser.java b/src/mightypork/utils/objects/VarargsParser.java index fc1aca8..f20722f 100644 --- a/src/mightypork/utils/objects/VarargsParser.java +++ b/src/mightypork/utils/objects/VarargsParser.java @@ -32,14 +32,14 @@ public class VarargsParser { @SuppressWarnings("unchecked") public Map parse(Object... args) throws ClassCastException, IllegalArgumentException { - LinkedHashMap attrs = new LinkedHashMap(); + final LinkedHashMap attrs = new LinkedHashMap(); if (args.length % 2 != 0) { throw new IllegalArgumentException("Odd number of elements in varargs map!"); } K key = null; - for (Object o : args) { + for (final Object o : args) { if (key == null) { if (o == null) throw new RuntimeException("Key cannot be NULL in varargs map."); key = (K) o; diff --git a/src/mightypork/utils/string/StringUtils.java b/src/mightypork/utils/string/StringUtils.java index 0a3cd8e..42b2b92 100644 --- a/src/mightypork/utils/string/StringUtils.java +++ b/src/mightypork/utils/string/StringUtils.java @@ -19,12 +19,12 @@ public class StringUtils { public static boolean isInArray(String needle, boolean case_sensitive, String... haystack) { if (case_sensitive) { - for (String s : haystack) { + for (final String s : haystack) { if (needle.equals(s)) return true; } return false; } else { - for (String s : haystack) { + for (final String s : haystack) { if (needle.equalsIgnoreCase(s)) return true; } return false; @@ -124,9 +124,9 @@ public class StringUtils { */ public static String formatInt(long number) { - String num = number + ""; + final String num = number + ""; String out = ""; - String dot = "."; + final String dot = "."; int cnt = 1; for (int i = num.length() - 1; i >= 0; i--) { out = num.charAt(i) + out; diff --git a/src/mightypork/utils/string/validation/CharValidatorRegex.java b/src/mightypork/utils/string/validation/CharValidatorRegex.java index d79ed8c..4b2d548 100644 --- a/src/mightypork/utils/string/validation/CharValidatorRegex.java +++ b/src/mightypork/utils/string/validation/CharValidatorRegex.java @@ -3,7 +3,7 @@ package mightypork.utils.string.validation; public class CharValidatorRegex implements CharValidator { - private String formula; + private final String formula; public CharValidatorRegex(String regex) { diff --git a/src/mightypork/utils/string/validation/CharValidatorWhitelist.java b/src/mightypork/utils/string/validation/CharValidatorWhitelist.java index 58c9804..834d2ad 100644 --- a/src/mightypork/utils/string/validation/CharValidatorWhitelist.java +++ b/src/mightypork/utils/string/validation/CharValidatorWhitelist.java @@ -3,7 +3,7 @@ package mightypork.utils.string.validation; public class CharValidatorWhitelist implements CharValidator { - private String whitelist; + private final String whitelist; public CharValidatorWhitelist(String allowed) { diff --git a/src/mightypork/utils/string/validation/FileSuffixFilter.java b/src/mightypork/utils/string/validation/FileSuffixFilter.java index 278fabc..e246682 100644 --- a/src/mightypork/utils/string/validation/FileSuffixFilter.java +++ b/src/mightypork/utils/string/validation/FileSuffixFilter.java @@ -31,9 +31,9 @@ public class FileSuffixFilter implements FileFilter { { if (!pathname.isFile()) return false; - String fname = pathname.getName().toLowerCase().trim(); + final String fname = pathname.getName().toLowerCase().trim(); - for (String suffix : suffixes) { + for (final String suffix : suffixes) { if (fname.endsWith(suffix.toLowerCase().trim())) { return true; }