- Added final keyword wherever possible
- Improved some font code
v5stable
Ondřej Hruška 11 years ago
parent da67300522
commit e2b6752efb
  1. 26
      src/mightypork/rogue/App.java
  2. 2
      src/mightypork/rogue/AppAdapter.java
  3. 3
      src/mightypork/rogue/Config.java
  4. 8
      src/mightypork/rogue/MainLoop.java
  5. 11
      src/mightypork/rogue/Res.java
  6. 5
      src/mightypork/rogue/bus/events/ActionRequest.java
  7. 2
      src/mightypork/rogue/bus/events/KeyboardEvent.java
  8. 5
      src/mightypork/rogue/bus/events/MainLoopTaskRequest.java
  9. 4
      src/mightypork/rogue/bus/events/MouseButtonEvent.java
  10. 7
      src/mightypork/rogue/bus/events/MouseMotionEvent.java
  11. 11
      src/mightypork/rogue/bus/events/ResourceLoadRequest.java
  12. 2
      src/mightypork/rogue/bus/events/ScreenChangeEvent.java
  13. 10
      src/mightypork/rogue/bus/events/ScreenRequestEvent.java
  14. 11
      src/mightypork/rogue/fonts/DeferredFont.java
  15. 2
      src/mightypork/rogue/fonts/FontBank.java
  16. 12
      src/mightypork/rogue/fonts/GLFont.java
  17. 4
      src/mightypork/rogue/fonts/SlickFont.java
  18. 2
      src/mightypork/rogue/gui/LayeredScreen.java
  19. 6
      src/mightypork/rogue/gui/Screen.java
  20. 2
      src/mightypork/rogue/gui/ScreenLayer.java
  21. 2
      src/mightypork/rogue/gui/ScreenRegistry.java
  22. 16
      src/mightypork/rogue/gui/constraints/ElementHolder.java
  23. 7
      src/mightypork/rogue/gui/constraints/RenderableWithContext.java
  24. 12
      src/mightypork/rogue/gui/screens/test_bouncyboxes/BouncyBox.java
  25. 8
      src/mightypork/rogue/gui/screens/test_bouncyboxes/LayerBouncyBoxes.java
  26. 2
      src/mightypork/rogue/gui/screens/test_bouncyboxes/ScreenTestBouncy.java
  27. 18
      src/mightypork/rogue/gui/screens/test_cat_sound/LayerFlyingCat.java
  28. 6
      src/mightypork/rogue/gui/screens/test_font/ScreenTestFont.java
  29. 22
      src/mightypork/rogue/input/InputSystem.java
  30. 4
      src/mightypork/rogue/input/KeyBinder.java
  31. 18
      src/mightypork/rogue/input/KeyBinding.java
  32. 8
      src/mightypork/rogue/input/KeyBindingPool.java
  33. 21
      src/mightypork/rogue/input/KeyStroke.java
  34. 30
      src/mightypork/rogue/loading/AsyncResourceLoader.java
  35. 127
      src/mightypork/rogue/loading/BaseDeferredResource.java
  36. 23
      src/mightypork/rogue/loading/Deferred.java
  37. 118
      src/mightypork/rogue/loading/DeferredResource.java
  38. 12
      src/mightypork/rogue/loading/MustLoadInMainThread.java
  39. 18
      src/mightypork/rogue/render/DisplaySystem.java
  40. 52
      src/mightypork/rogue/render/Render.java
  41. 4
      src/mightypork/rogue/render/Renderable.java
  42. 6
      src/mightypork/rogue/sound/DeferredAudio.java
  43. 2
      src/mightypork/rogue/sound/JointVolume.java
  44. 4
      src/mightypork/rogue/sound/SoundBank.java
  45. 12
      src/mightypork/rogue/sound/SoundSystem.java
  46. 2
      src/mightypork/rogue/sound/players/LoopPlayer.java
  47. 20
      src/mightypork/rogue/tasks/TaskTakeScreenshot.java
  48. 7
      src/mightypork/rogue/textures/DeferredTexture.java
  49. 8
      src/mightypork/rogue/textures/FilteredTexture.java
  50. 20
      src/mightypork/rogue/textures/TextureBank.java
  51. 6
      src/mightypork/rogue/textures/TxQuad.java
  52. 2
      src/mightypork/rogue/util/Utils.java
  53. 8
      src/mightypork/utils/control/bus/BufferedHashSet.java
  54. 36
      src/mightypork/utils/control/bus/EventBus.java
  55. 15
      src/mightypork/utils/control/bus/EventChannel.java
  56. 14
      src/mightypork/utils/control/bus/SingularEvent.java
  57. 4
      src/mightypork/utils/control/timing/TimerDelta.java
  58. 12
      src/mightypork/utils/control/timing/TimerFps.java
  59. 34
      src/mightypork/utils/files/FileTreeDiff.java
  60. 56
      src/mightypork/utils/files/FileUtils.java
  61. 8
      src/mightypork/utils/files/OsUtils.java
  62. 98
      src/mightypork/utils/files/PropertyManager.java
  63. 20
      src/mightypork/utils/files/SimpleConfig.java
  64. 10
      src/mightypork/utils/files/ZipBuilder.java
  65. 34
      src/mightypork/utils/files/ZipUtils.java
  66. 10
      src/mightypork/utils/files/ion/AbstractIonList.java
  67. 12
      src/mightypork/utils/files/ion/AbstractIonMap.java
  68. 18
      src/mightypork/utils/files/ion/BinaryUtils.java
  69. 30
      src/mightypork/utils/files/ion/Ion.java
  70. 4
      src/mightypork/utils/files/ion/IonList.java
  71. 12
      src/mightypork/utils/logging/Log.java
  72. 40
      src/mightypork/utils/logging/LogInstance.java
  73. 44
      src/mightypork/utils/math/Calc.java
  74. 2
      src/mightypork/utils/math/Polar.java
  75. 6
      src/mightypork/utils/math/Range.java
  76. 4
      src/mightypork/utils/math/animation/AnimDouble.java
  77. 4
      src/mightypork/utils/math/animation/AnimDoubleDeg.java
  78. 4
      src/mightypork/utils/math/animation/AnimDoubleRad.java
  79. 12
      src/mightypork/utils/math/animation/Easing.java
  80. 2
      src/mightypork/utils/math/color/HSV.java
  81. 14
      src/mightypork/utils/math/color/RGB.java
  82. 22
      src/mightypork/utils/math/constraints/ConstraintFactory.java
  83. 4
      src/mightypork/utils/math/coord/Coord.java
  84. 20
      src/mightypork/utils/objects/Convertor.java
  85. 76
      src/mightypork/utils/objects/MapSort.java
  86. 2
      src/mightypork/utils/objects/Mutable.java
  87. 79
      src/mightypork/utils/objects/ObjectUtils.java
  88. 2
      src/mightypork/utils/objects/Pair.java
  89. 4
      src/mightypork/utils/objects/VarargsParser.java
  90. 8
      src/mightypork/utils/string/StringUtils.java
  91. 2
      src/mightypork/utils/string/validation/CharValidatorRegex.java
  92. 2
      src/mightypork/utils/string/validation/CharValidatorWhitelist.java
  93. 4
      src/mightypork/utils/string/validation/FileSuffixFilter.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<Runnable> loopTasks = new ArrayList<Runnable>();
final ArrayList<Runnable> loopTasks = new ArrayList<Runnable>();
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();
}

@ -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) {

@ -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;
}

@ -18,8 +18,8 @@ import mightypork.utils.control.timing.TimerDelta;
public class MainLoop extends Subsystem implements ActionRequest.Listener, MainLoopTaskRequest.Listener {
private Queue<Runnable> taskQueue = new ConcurrentLinkedQueue<Runnable>();
private List<Runnable> regularTasks;
private final Queue<Runnable> taskQueue = new ConcurrentLinkedQueue<Runnable>();
private final List<Runnable> regularTasks;
public MainLoop(App app, ArrayList<Runnable> 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);
}

@ -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);

@ -10,7 +10,8 @@ import mightypork.utils.control.bus.SingularEvent;
*
* @author MightyPork
*/
public class ActionRequest implements Event<ActionRequest.Listener>, SingularEvent {
@SingularEvent
public class ActionRequest implements Event<ActionRequest.Listener> {
private final RequestType type;
@ -33,7 +34,7 @@ public class ActionRequest implements Event<ActionRequest.Listener>, SingularEve
*
* @param request
*/
public void requestAction(RequestType request);
void requestAction(RequestType request);
}
public static enum RequestType

@ -74,7 +74,7 @@ public class KeyboardEvent implements Event<KeyboardEvent.Listener> {
*
* @param event event
*/
public void receive(KeyboardEvent event);
void receive(KeyboardEvent event);
}

@ -10,7 +10,8 @@ import mightypork.utils.control.bus.SingularEvent;
*
* @author MightyPork
*/
public class MainLoopTaskRequest implements Event<MainLoopTaskRequest.Listener>, SingularEvent {
@SingularEvent
public class MainLoopTaskRequest implements Event<MainLoopTaskRequest.Listener> {
private final Runnable task;
@ -33,6 +34,6 @@ public class MainLoopTaskRequest implements Event<MainLoopTaskRequest.Listener>,
*
* @param request
*/
public void queueTask(Runnable request);
void queueTask(Runnable request);
}
}

@ -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<MouseButtonEvent.Listener> {
*
* @param event event
*/
public void receive(MouseButtonEvent event);
void receive(MouseButtonEvent event);
}
}

@ -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<MouseMotionEvent.Listener> {
private final Coord move;
@ -48,7 +53,7 @@ public class MouseMotionEvent implements Event<MouseMotionEvent.Listener> {
*
* @param event event
*/
public void receive(MouseMotionEvent event);
void receive(MouseMotionEvent event);
}
}

@ -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<ResourceLoadRequest.Listener>, SingularEvent {
@SingularEvent
public class ResourceLoadRequest implements Event<ResourceLoadRequest.Listener> {
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<ResourceLoadRequest.Listener>,
*
* @param resource
*/
public void loadResource(Deferred resource);
void loadResource(DeferredResource resource);
}
}

@ -45,6 +45,6 @@ public class ScreenChangeEvent implements Event<ScreenChangeEvent.Listener> {
public interface Listener {
public void receive(ScreenChangeEvent event);
void receive(ScreenChangeEvent event);
}
}

@ -5,7 +5,13 @@ import mightypork.utils.control.bus.Event;
import mightypork.utils.control.bus.SingularEvent;
public class ScreenRequestEvent implements Event<ScreenRequestEvent.Listener>, SingularEvent {
/**
* Request to change screen
*
* @author MightyPork
*/
@SingularEvent
public class ScreenRequestEvent implements Event<ScreenRequestEvent.Listener> {
private final String scrName;
@ -23,7 +29,7 @@ public class ScreenRequestEvent implements Event<ScreenRequestEvent.Listener>, S
public interface Listener {
public void showScreen(String key);
void showScreen(String key);
}
}

@ -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
}
}

@ -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 + "!");

@ -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);
}

@ -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);
}

@ -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();
}
}

@ -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);

@ -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;

@ -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);

@ -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.
*

@ -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);
}

@ -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

@ -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();
}
}

@ -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) {

@ -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);

@ -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));

@ -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));
}

@ -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);
}

@ -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;

@ -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<KeyBinding> iter = bindings.iterator();
final Iterator<KeyBinding> 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);
}
}

@ -8,6 +8,11 @@ import java.util.Set;
import org.lwjgl.input.Keyboard;
/**
* Key stroke trigger
*
* @author MightyPork
*/
public class KeyStroke {
private final Set<Integer> keys = new LinkedHashSet<Integer>();
@ -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<Integer> i = keys.iterator();
final Iterator<Integer> 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<Integer> getKeys()
{
return keys;

@ -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<Deferred> toLoad = new LinkedBlockingQueue<Deferred>();
private final LinkedBlockingQueue<DeferredResource> toLoad = new LinkedBlockingQueue<DeferredResource>();
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("<DEFERRED> 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("<DEFERRED> 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) {
//
}

@ -0,0 +1,127 @@
package mightypork.rogue.loading;
import mightypork.utils.control.interf.Destroyable;
import mightypork.utils.logging.Log;
/**
* Deferred resource abstraction.<br>
* 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("<res> Loading: " + this);
loadResource(resource);
Log.f3("<res> 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;
}
}

@ -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();
}

@ -1,127 +1,23 @@
package mightypork.rogue.loading;
import mightypork.utils.control.interf.Destroyable;
import mightypork.utils.logging.Log;
/**
* Deferred resource abstraction.<br>
* 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();
}

@ -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 {}

@ -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;
}

@ -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();

@ -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();
}

@ -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);

@ -33,7 +33,7 @@ public class JointVolume extends Mutable<Double> {
public Double get()
{
double d = super.get();
for (Mutable<Double> v : volumes)
for (final Mutable<Double> v : volumes)
d *= v.get();
return Calc.clampd(d, 0, 1);

@ -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;

@ -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();
}
}

@ -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;

@ -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());
}

@ -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;

@ -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);
}

@ -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 + "!");

@ -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);
}

@ -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;
}

@ -16,8 +16,8 @@ import java.util.List;
*/
public class BufferedHashSet<E> extends HashSet<E> {
private List<E> toAdd = new LinkedList<E>();
private List<Object> toRemove = new LinkedList<Object>();
private final List<E> toAdd = new LinkedList<E>();
private final List<Object> toRemove = new LinkedList<Object>();
private boolean buffering = false;
@ -72,11 +72,11 @@ public class BufferedHashSet<E> extends HashSet<E> {
*/
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);
}

@ -17,16 +17,16 @@ import mightypork.utils.logging.Log;
final public class EventBus implements Destroyable {
/** Message channels */
private BufferedHashSet<EventChannel<?, ?>> channels = new BufferedHashSet<EventChannel<?, ?>>();
private final BufferedHashSet<EventChannel<?, ?>> channels = new BufferedHashSet<EventChannel<?, ?>>();
/** Registered clients */
private BufferedHashSet<Object> clients = new BufferedHashSet<Object>();
private final BufferedHashSet<Object> clients = new BufferedHashSet<Object>();
/** Messages queued for delivery */
private DelayQueue<DelayedMessage> sendQueue = new DelayQueue<DelayedMessage>();
private final DelayQueue<DelayedMessage> sendQueue = new DelayQueue<DelayedMessage>();
/** 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("<bus> Channel of type " + Log.str(channel) + " already registered.");
return ch;
@ -99,7 +99,7 @@ final public class EventBus implements Destroyable {
{
assertLive();
EventChannel<F_EVENT, F_CLIENT> channel = EventChannel.create(messageClass, clientClass);
final EventChannel<F_EVENT, F_CLIENT> 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("<bus> + [ 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) {
//
}

@ -18,8 +18,8 @@ import mightypork.utils.logging.Log;
*/
final public class EventChannel<EVENT extends Event<CLIENT>, CLIENT> {
private Class<CLIENT> clientClass;
private Class<EVENT> messageClass;
private final Class<CLIENT> clientClass;
private final Class<EVENT> messageClass;
private boolean logging = false;
@ -61,7 +61,7 @@ final public class EventChannel<EVENT extends Event<CLIENT>, CLIENT> {
{
if (!canBroadcast(message)) return false;
EVENT evt = messageClass.cast(message);
final EVENT evt = messageClass.cast(message);
return doBroadcast(evt, clients, new HashSet<Object>());
}
@ -78,8 +78,9 @@ final public class EventChannel<EVENT extends Event<CLIENT>, CLIENT> {
private boolean doBroadcast(final EVENT message, final Collection<Object> clients, final Collection<Object> 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<EVENT extends Event<CLIENT>, 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<Object> children = ((DelegatingClient) client).getChildClients();
final Collection<Object> children = ((DelegatingClient) client).getChildClients();
if (children != null && children.size() > 0) {
sent |= doBroadcast(message, children, processed);
@ -212,7 +213,7 @@ final public class EventChannel<EVENT extends Event<CLIENT>, 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;

@ -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 {}

@ -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;
}

@ -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;

@ -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<Tuple<File>> compared = new ArrayList<Tuple<File>>();
private Comparator<File> fileFirstSorter = new Comparator<File>() {
private final List<Tuple<File>> compared = new ArrayList<Tuple<File>>();
private final Comparator<File> fileFirstSorter = new Comparator<File>() {
@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<File> pair : compared) {
for (final Tuple<File> 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);

@ -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<File> 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<File> list = new ArrayList<File>();
final List<File> list = new ArrayList<File>();
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<File> children = listDirectory(f);
final List<File> 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);
}
}

@ -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 + '/');

@ -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<String, String> keyComments = new Hashtable<String, String>();
private final Hashtable<String, String> keyComments = new Hashtable<String, String>();
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<String, Property> entries;
private TreeMap<String, String> keyRename;
private TreeMap<String, String> setValues;
private final TreeMap<String, Property> entries;
private final TreeMap<String, String> keyRename;
private final TreeMap<String, String> 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<String> keyList = new ArrayList<String>();
final ArrayList<String> keyList = new ArrayList<String>();
// rename keys
for (Entry<String, String> entry : keyRename.entrySet()) {
for (final Entry<String, String> 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<String, String> entry : setValues.entrySet()) {
for (final Entry<String, String> 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;
}
}

@ -32,7 +32,7 @@ public class SimpleConfig {
*/
public static List<String> 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<String, String> 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<String> listFromString(String text)
{
List<String> list = new ArrayList<String>();
final List<String> list = new ArrayList<String>();
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<String, String> mapFromString(String text)
{
LinkedHashMap<String, String> pairs = new LinkedHashMap<String, String>();
final LinkedHashMap<String, String> pairs = new LinkedHashMap<String, String>();
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<String, String> data, boolean allowNulls) throws IOException
{
List<String> lines = new ArrayList<String>();
final List<String> lines = new ArrayList<String>();
for (Entry<String, String> e : data.entrySet()) {
for (final Entry<String, String> 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;

@ -16,8 +16,8 @@ import mightypork.utils.logging.Log;
*/
public class ZipBuilder {
private ZipOutputStream out;
private HashSet<String> included = new HashSet<String>();
private final ZipOutputStream out;
private final HashSet<String> included = new HashSet<String>();
/**
@ -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);
}

@ -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<String> extractZip(ZipFile zip, File outputDir, StringFilter filter) throws IOException
{
ArrayList<String> files = new ArrayList<String>();
final ArrayList<String> files = new ArrayList<String>();
outputDir.mkdirs();
Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
final Enumeration<? extends ZipEntry> 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<String> listZip(ZipFile zip) throws IOException
{
ArrayList<String> files = new ArrayList<String>();
final ArrayList<String> files = new ArrayList<String>();
Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
final Enumeration<? extends ZipEntry> 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
}
}

@ -20,10 +20,10 @@ public abstract class AbstractIonList<T> extends ArrayList<T> 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<T> extends ArrayList<T> 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<T> extends ArrayList<T> 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);
}
}

@ -34,11 +34,11 @@ public abstract class AbstractIonMap<V> extends LinkedHashMap<String, V> 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<V> extends LinkedHashMap<String, V> 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<V> extends LinkedHashMap<String, V> impleme
public void ionWrite(OutputStream out) throws IonException
{
try {
for (java.util.Map.Entry<String, V> entry : entrySet()) {
for (final java.util.Map.Entry<String, V> 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);
}
}

@ -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();
}

@ -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);
}
}

@ -131,12 +131,12 @@ public class IonList extends AbstractIonList<Object> {
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");
}
}

@ -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();
}

@ -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<Integer, LogMonitor> monitors = new HashMap<Integer, LogMonitor>();
private final HashMap<Integer, LogMonitor> monitors = new HashMap<Integer, LogMonitor>();
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<File> oldLogs = FileUtils.listDirectory(dir, new FileFilter() {
final List<File> 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);
}

@ -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<Integer> intList = new ArrayList<Integer>();
final ArrayList<Integer> intList = new ArrayList<Integer>();
for (String part : parts) {
for (final String part : parts) {
try {
intList.add(Integer.parseInt(part));
} catch (NumberFormatException e) {}
} catch (final NumberFormatException e) {}
}
return intList;

@ -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;

@ -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;
}

@ -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);

@ -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;
}

@ -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;
}

@ -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));
}
};

@ -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);
}

@ -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);
}

@ -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(

@ -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;

@ -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;
}

@ -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 <K extends Comparable, V extends Comparable> Map<K, V> sortByKeys(Map<K, V> map, final Comparator<K> comparator)
{
final List<K> keys = new LinkedList<K>(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<K, V> sortedMap = new LinkedHashMap<K, V>();
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 <K extends Comparable, V extends Comparable> Map<K, V> sortByValues(Map<K, V> map, final Comparator<V> comparator)
{
final List<Map.Entry<K, V>> entries = new LinkedList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Entry<K, V> o1, Entry<K, V> 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<K, V> sortedMap = new LinkedHashMap<K, V>();
for (final Map.Entry<K, V> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}

@ -62,7 +62,7 @@ public class Mutable<T> {
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)) {

@ -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 <K extends Comparable, V extends Comparable> Map<K, V> sortByKeys(Map<K, V> map, final Comparator<K> comparator)
{
List<K> keys = new LinkedList<K>(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<K, V> sortedMap = new LinkedHashMap<K, V>();
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 <K extends Comparable, V extends Comparable> Map<K, V> sortByValues(Map<K, V> map, final Comparator<V> comparator)
{
List<Map.Entry<K, V>> entries = new LinkedList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Entry<K, V> o1, Entry<K, V> 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<K, V> sortedMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> 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 <T extends Object> List<T> arrayToList(T[] objs)
{
ArrayList<T> list = new ArrayList<T>();
for (T o : objs) {
final ArrayList<T> list = new ArrayList<T>();
for (final T o : objs) {
list.add(o);
}
return list;

@ -66,7 +66,7 @@ public class Pair<T1, T2> {
return false;
}
Pair<?, ?> t = (Pair<?, ?>) obj;
final Pair<?, ?> t = (Pair<?, ?>) obj;
return Calc.areObjectsEqual(first, t.first) && Calc.areObjectsEqual(second, t.second);

@ -32,14 +32,14 @@ public class VarargsParser<K, V> {
@SuppressWarnings("unchecked")
public Map<K, V> parse(Object... args) throws ClassCastException, IllegalArgumentException
{
LinkedHashMap<K, V> attrs = new LinkedHashMap<K, V>();
final LinkedHashMap<K, V> attrs = new LinkedHashMap<K, V>();
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;

@ -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;

@ -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) {

@ -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) {

@ -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;
}

Loading…
Cancel
Save