- Reduce CheckStyle, FindBugs, and PMD output for recently changed files.

This commit is contained in:
Braids
2011-08-19 03:48:50 +00:00
parent fdb1199223
commit 664a535a47
5 changed files with 572 additions and 495 deletions

View File

@@ -37,31 +37,39 @@ import forge.view.FView;
* @author Forge * @author Forge
* @version $Id$ * @version $Id$
*/ */
public class CardReader implements Runnable, NewConstants { public class CardReader
implements Runnable, // NOPMD by Braids on 8/18/11 10:55 PM
NewConstants
{
private static final String CARD_FILE_DOT_EXTENSION = ".txt"; // NOPMD by Braids on 8/18/11 11:04 PM
/** Default charset when loading from files. */ /** Default charset when loading from files. */
public static final String DEFAULT_CHARSET_NAME = "US-ASCII"; public static final String DEFAULT_CHARSET_NAME = "US-ASCII"; // NOPMD by Braids on 8/18/11 10:54 PM
/** Regex that matches a single hyphen (-) or space. */ /** Regex that matches a single hyphen (-) or space. */
public static final Pattern HYPHEN_OR_SPACE = Pattern.compile("[ -]"); public static final Pattern HYPHEN_OR_SPACE = Pattern.compile("[ -]");
/** Regex for punctuation that we omit from card file names. */ /** Regex for punctuation that we omit from card file names. */
public static final Pattern PUNCTUATION_TO_ZAP = Pattern.compile("[,'\"]"); public static final Pattern PUNCTUATION_TO_ZAP = Pattern.compile("[,'\"]"); // NOPMD by Braids on 8/18/11 10:54 PM
/** Regex that matches two or more underscores (_). */ /** Regex that matches two or more underscores (_). */
public static final Pattern MULTIPLE_UNDERSCORES = Pattern.compile("__+"); public static final Pattern MULTIPLE_UNDERSCORES = Pattern.compile("__+"); // NOPMD by Braids on 8/18/11 10:54 PM
/** Special value for estimatedFilesRemaining. */ /** Special value for estimatedFilesRemaining. */
protected static final int UNKNOWN_NUMBER_OF_FILES_REMAINING = -1; protected static final int UNKNOWN_NUMBER_OF_FILES_REMAINING = -1; // NOPMD by Braids on 8/18/11 10:54 PM
private Map<String, Card> mapToFill; private transient Map<String, Card> mapToFill;
private File cardsfolder; private transient File cardsfolder;
private ZipFile zip; private transient ZipFile zip;
private Charset charset; private transient Charset charset;
private Enumeration<? extends ZipEntry> zipEnum; private transient Enumeration<? extends ZipEntry> zipEnum;
private long estimatedFilesRemaining = UNKNOWN_NUMBER_OF_FILES_REMAINING;
private Iterable<File> findNonDirsIterable; private transient long estimatedFilesRemaining = // NOPMD by Braids on 8/18/11 10:56 PM
UNKNOWN_NUMBER_OF_FILES_REMAINING;
private transient Iterable<File> findNonDirsIterable; // NOPMD by Braids on 8/18/11 10:56 PM
@@ -90,17 +98,19 @@ public class CardReader implements Runnable, NewConstants {
*/ */
public CardReader(final File theCardsFolder, final Map<String, Card> theMapToFill, final boolean useZip) { public CardReader(final File theCardsFolder, final Map<String, Card> theMapToFill, final boolean useZip) {
if (theMapToFill == null) { if (theMapToFill == null) {
throw new NullPointerException("theMapToFill must not be null."); throw new NullPointerException("theMapToFill must not be null."); // NOPMD by Braids on 8/18/11 10:53 PM
} }
this.mapToFill = theMapToFill; this.mapToFill = theMapToFill;
if (!theCardsFolder.exists()) { if (!theCardsFolder.exists()) {
throw new RuntimeException("CardReader : constructor error -- file not found -- filename is " throw new RuntimeException(// NOPMD by Braids on 8/18/11 10:53 PM
"CardReader : constructor error -- file not found -- filename is "
+ theCardsFolder.getAbsolutePath()); + theCardsFolder.getAbsolutePath());
} }
if (!theCardsFolder.isDirectory()) { if (!theCardsFolder.isDirectory()) {
throw new RuntimeException("CardReader : constructor error -- not a directory -- " throw new RuntimeException(// NOPMD by Braids on 8/18/11 10:53 PM
"CardReader : constructor error -- not a directory -- "
+ theCardsFolder.getAbsolutePath()); + theCardsFolder.getAbsolutePath());
} }
@@ -114,7 +124,7 @@ public class CardReader implements Runnable, NewConstants {
try { try {
this.zip = new ZipFile(zipFile); this.zip = new ZipFile(zipFile);
} catch (Exception exn) { } catch (Exception exn) {
System.err.println("Error reading zip file \"" System.err.println("Error reading zip file \"" // NOPMD by Braids on 8/18/11 10:53 PM
+ zipFile.getAbsolutePath() + "\": " + exn + ". " + zipFile.getAbsolutePath() + "\": " + exn + ". "
+ "Defaulting to txt files in \"" + "Defaulting to txt files in \""
+ theCardsFolder.getAbsolutePath() + theCardsFolder.getAbsolutePath()
@@ -186,28 +196,7 @@ public class CardReader implements Runnable, NewConstants {
} }
if (zip != null) { if (zip == null) {
monitor.setTotalUnitsThisPhase(estimatedFilesRemaining);
ZipEntry entry;
// zipEnum was initialized in the constructor.
while (zipEnum.hasMoreElements()) {
entry = (ZipEntry) zipEnum.nextElement();
if (entry.isDirectory() || !entry.getName().endsWith(".txt")) {
monitor.incrementUnitsCompletedThisPhase(1L);
continue;
}
result = loadCard(entry);
monitor.incrementUnitsCompletedThisPhase(1L);
if (cardName != null && cardName.equals(result.getName())) {
break;
}
}
} else {
if (estimatedFilesRemaining == UNKNOWN_NUMBER_OF_FILES_REMAINING) { if (estimatedFilesRemaining == UNKNOWN_NUMBER_OF_FILES_REMAINING) {
final Generator<File> findNonDirsGen = new FindNonDirectoriesSkipDotDirectoriesGenerator(cardsfolder); final Generator<File> findNonDirsGen = new FindNonDirectoriesSkipDotDirectoriesGenerator(cardsfolder);
estimatedFilesRemaining = GeneratorFunctions.estimateSize(findNonDirsGen); estimatedFilesRemaining = GeneratorFunctions.estimateSize(findNonDirsGen);
@@ -217,7 +206,7 @@ public class CardReader implements Runnable, NewConstants {
monitor.setTotalUnitsThisPhase(estimatedFilesRemaining); monitor.setTotalUnitsThisPhase(estimatedFilesRemaining);
for (File cardTxtFile : findNonDirsIterable) { for (File cardTxtFile : findNonDirsIterable) {
if (!cardTxtFile.getName().endsWith(".txt")) { if (!cardTxtFile.getName().endsWith(CARD_FILE_DOT_EXTENSION)) {
monitor.incrementUnitsCompletedThisPhase(1L); monitor.incrementUnitsCompletedThisPhase(1L);
continue; continue;
} }
@@ -231,6 +220,27 @@ public class CardReader implements Runnable, NewConstants {
} //endfor } //endfor
} else {
monitor.setTotalUnitsThisPhase(estimatedFilesRemaining);
ZipEntry entry;
// zipEnum was initialized in the constructor.
while (zipEnum.hasMoreElements()) {
entry = (ZipEntry) zipEnum.nextElement();
if (entry.isDirectory() || !entry.getName().endsWith(CARD_FILE_DOT_EXTENSION)) {
monitor.incrementUnitsCompletedThisPhase(1L);
continue;
}
result = loadCard(entry);
monitor.incrementUnitsCompletedThisPhase(1L);
if (cardName != null && cardName.equals(result.getName())) {
break;
}
}
} //endif } //endif
if (monitor != null) { if (monitor != null) {
@@ -270,7 +280,7 @@ public class CardReader implements Runnable, NewConstants {
return line; return line;
} catch (Exception ex) { } catch (Exception ex) {
ErrorViewer.showError(ex); ErrorViewer.showError(ex);
throw new RuntimeException("CardReader : readLine(Card) error", ex); throw new RuntimeException("CardReader : readLine(Card) error", ex); // NOPMD by Braids on 8/18/11 10:53 PM
} }
} //readLine(BufferedReader) } //readLine(BufferedReader)
@@ -290,76 +300,88 @@ public class CardReader implements Runnable, NewConstants {
inputStreamReader = new InputStreamReader(inputStream, charset); inputStreamReader = new InputStreamReader(inputStream, charset);
reader = new BufferedReader(inputStreamReader); reader = new BufferedReader(inputStreamReader);
String s = readLine(reader); String line = readLine(reader);
while (!"End".equals(s)) { while (!"End".equals(line)) {
if (s.startsWith("#")) { if (line.charAt(0) == '#') { // NOPMD by Braids on 8/18/11 10:59 PM
//no need to do anything, this indicates a comment line //no need to do anything, this indicates a comment line
} else if (s.startsWith("Name:")) { } else if (line.startsWith("Name:")) {
String t = s.substring(5); final String value = line.substring(5);
//System.out.println(s); //System.out.println(s);
if (!mapToFill.containsKey(t)) { if (mapToFill.containsKey(value)) {
card.setName(t);
} else {
break; // this card has already been loaded. break; // this card has already been loaded.
} else {
card.setName(value);
} }
} else if (s.startsWith("ManaCost:")) { } else if (line.startsWith("ManaCost:")) {
String t = s.substring(9); final String value = line.substring(9);
//System.out.println(s); //System.out.println(s);
if (!"no cost".equals(t)) { if (!"no cost".equals(value)) {
card.setManaCost(t); card.setManaCost(value);
} }
} else if (s.startsWith("Types:")) { } else if (line.startsWith("Types:")) {
addTypes(card, s.substring(6)); addTypes(card, line.substring("Types:".length()));
} else if (s.startsWith("Text:")) { } else if (line.startsWith("Text:")) {
String t = s.substring(5); String value = line.substring("Text:".length());
// if (!t.equals("no text")); // if (!t.equals("no text"));
if ("no text".equals(t)) { if ("no text".equals(value)) {
t = ""; value = "";
} }
card.setText(t); card.setText(value);
} else if (s.startsWith("PT:")) { } else if (line.startsWith("PT:")) {
String t = s.substring(3); final String value = line.substring("PT:".length());
String[] pt = t.split("/"); final String[] powTough = value.split("/");
int att = pt[0].contains("*") ? 0 : Integer.parseInt(pt[0]); int att;
int def = pt[1].contains("*") ? 0 : Integer.parseInt(pt[1]); if (powTough[0].contains("*")) {
card.setBaseAttackString(pt[0]); att = 0;
card.setBaseDefenseString(pt[1]); } else {
att = Integer.parseInt(powTough[0]);
}
int def;
if (powTough[1].contains("*")) {
def = 0;
} else {
def = Integer.parseInt(powTough[1]);
}
card.setBaseAttackString(powTough[0]);
card.setBaseDefenseString(powTough[1]);
card.setBaseAttack(att); card.setBaseAttack(att);
card.setBaseDefense(def); card.setBaseDefense(def);
} else if (s.startsWith("Loyalty:")) { } else if (line.startsWith("Loyalty:")) {
String[] splitStr = s.split(":"); final String[] splitStr = line.split(":");
int loyal = Integer.parseInt(splitStr[1]); final int loyal = Integer.parseInt(splitStr[1]);
card.setBaseLoyalty(loyal); card.setBaseLoyalty(loyal);
} else if (s.startsWith("K:")) { } else if (line.startsWith("K:")) {
String t = s.substring(2); final String value = line.substring(2);
card.addIntrinsicKeyword(t); card.addIntrinsicKeyword(value);
} else if (s.startsWith("SVar:")) { } else if (line.startsWith("SVar:")) {
String[] t = s.split(":", 3); final String[] value = line.split(":", 3);
card.setSVar(t[1], t[2]); card.setSVar(value[1], value[2]);
} else if (s.startsWith("A:")) { } else if (line.startsWith("A:")) {
String t = s.substring(2); final String value = line.substring(2);
card.addIntrinsicAbility(t); card.addIntrinsicAbility(value);
} else if (s.startsWith("T:")) { } else if (line.startsWith("T:")) {
String t = s.substring(2); final String value = line.substring(2);
card.addTrigger(TriggerHandler.parseTrigger(t, card, true)); card.addTrigger(TriggerHandler.parseTrigger(value, card, true));
} else if (s.startsWith("S:")) { } else if (line.startsWith("S:")) {
String t = s.substring(2); final String value = line.substring(2);
card.addStaticAbilityString(t); card.addStaticAbilityString(value);
} else if (s.startsWith("SetInfo:")) { } else if (line.startsWith("SetInfo:")) {
String t = s.substring(8); final String value = line.substring("SetInfo:".length());
card.addSet(new SetInfo(t)); card.addSet(new SetInfo(value)); // NOPMD by Braids on 8/18/11 11:08 PM
} }
s = readLine(reader); line = readLine(reader);
} // while !End } // while !End
} finally { } finally {
try { try {
reader.close(); reader.close();
} catch (IOException ignored) { } catch (IOException ignored) { // NOPMD by Braids on 8/18/11 11:08 PM
} }
try { try {
inputStreamReader.close(); inputStreamReader.close();
} catch (IOException ignored) { } catch (IOException ignored) { // NOPMD by Braids on 8/18/11 11:08 PM
} }
} }
@@ -392,12 +414,13 @@ public class CardReader implements Runnable, NewConstants {
return loadCard(fileInputStream); return loadCard(fileInputStream);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
ErrorViewer.showError(ex, "File \"%s\" exception", pathToTxtFile.getAbsolutePath()); ErrorViewer.showError(ex, "File \"%s\" exception", pathToTxtFile.getAbsolutePath());
throw new RuntimeException("CardReader : run error -- file exception -- filename is " throw new RuntimeException(// NOPMD by Braids on 8/18/11 10:53 PM
"CardReader : run error -- file exception -- filename is "
+ pathToTxtFile.getPath(), ex); + pathToTxtFile.getPath(), ex);
} finally { } finally {
try { try {
fileInputStream.close(); fileInputStream.close();
} catch (IOException ignored) { } catch (IOException ignored) { // NOPMD by Braids on 8/18/11 11:08 PM
} }
} }
} }
@@ -416,13 +439,13 @@ public class CardReader implements Runnable, NewConstants {
return loadCard(zipInputStream); return loadCard(zipInputStream);
} catch (IOException exn) { } catch (IOException exn) {
throw new RuntimeException(exn); throw new RuntimeException(exn); // NOPMD by Braids on 8/18/11 10:53 PM
} finally { } finally {
try { try {
if (zipInputStream != null) { if (zipInputStream != null) {
zipInputStream.close(); zipInputStream.close();
} }
} catch (IOException ignored) { } catch (IOException ignored) { // NOPMD by Braids on 8/18/11 11:08 PM
} }
} }
} }
@@ -455,14 +478,14 @@ public class CardReader implements Runnable, NewConstants {
baseFileName = PUNCTUATION_TO_ZAP.matcher(baseFileName).replaceAll(""); baseFileName = PUNCTUATION_TO_ZAP.matcher(baseFileName).replaceAll("");
// Place the file within a single-letter subdirectory. // Place the file within a single-letter subdirectory.
StringBuffer buf = new StringBuffer(1 + 1 + baseFileName.length() + ".txt".length()); final StringBuffer buf = new StringBuffer(1 + 1 + baseFileName.length() + CARD_FILE_DOT_EXTENSION.length());
buf.append(Character.toLowerCase(baseFileName.charAt(0))); buf.append(Character.toLowerCase(baseFileName.charAt(0)));
// Zip file is always created with unix-style path names. // Zip file is always created with unix-style path names.
buf.append('/'); buf.append('/');
buf.append(baseFileName.toLowerCase(Locale.ENGLISH)); buf.append(baseFileName.toLowerCase(Locale.ENGLISH));
buf.append(".txt"); buf.append(CARD_FILE_DOT_EXTENSION);
return buf.toString(); return buf.toString();
} }
@@ -474,20 +497,18 @@ public class CardReader implements Runnable, NewConstants {
* *
* @return a new Card instance having that name, or null if not found * @return a new Card instance having that name, or null if not found
*/ */
public final Card findCard(final String canonicalASCIIName) { public final Card findCard(final String canonicalASCIIName) { // NOPMD by Braids on 8/18/11 11:08 PM
UtilFunctions.checkNotNull("canonicalASCIIName", canonicalASCIIName); UtilFunctions.checkNotNull("canonicalASCIIName", canonicalASCIIName);
String cardFilePath = toMostLikelyPath(canonicalASCIIName); final String cardFilePath = toMostLikelyPath(canonicalASCIIName);
Card result = null; Card result = null;
if (zip != null) { if (zip != null) {
ZipEntry entry = zip.getEntry(cardFilePath); final ZipEntry entry = zip.getEntry(cardFilePath);
if (entry != null) { if (entry != null) {
result = loadCard(entry); result = loadCard(entry);
} else {
//System.err.println(":Could not find \"" + cardFilePath + "\" in zip file.");
} }
} }

View File

@@ -1,15 +1,13 @@
package forge.gui; package forge.gui;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JDialog; import javax.swing.JDialog;
import javax.swing.JProgressBar; import javax.swing.JProgressBar;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import javax.swing.SwingWorker; import javax.swing.SwingWorker;
import forge.Gui_ProgressBarWindow;
import net.slightlymagic.braids.util.UtilFunctions; import net.slightlymagic.braids.util.UtilFunctions;
import net.slightlymagic.braids.util.progress_monitor.BaseProgressMonitor; import net.slightlymagic.braids.util.progress_monitor.BaseProgressMonitor;
import forge.Gui_ProgressBarWindow;
/** /**
* GUI Progress Monitor that displays the ETA (Estimated Time of Arrival or * GUI Progress Monitor that displays the ETA (Estimated Time of Arrival or
@@ -20,88 +18,98 @@ import net.slightlymagic.braids.util.progress_monitor.BaseProgressMonitor;
*/ */
public class MultiPhaseProgressMonitorWithETA extends BaseProgressMonitor { public class MultiPhaseProgressMonitorWithETA extends BaseProgressMonitor {
private Gui_ProgressBarWindow dialog; private transient Gui_ProgressBarWindow dialog;
private String title; private transient String title;
/** /**
* Convenience for * Convenience for
* MultiPhaseProgressMonitorWithETA(title, numPhases, totalUnitsFirstPhase, * MultiPhaseProgressMonitorWithETA(title, numPhases, totalUnitsFirstPhase,
* minUIUpdateIntervalSec, null); * minUIUpdateIntervalSec, null).
* *
* @see #MultiPhaseProgressMonitorWithETA(String,int,long,float,float[]) * @see #MultiPhaseProgressMonitorWithETA(String,int,long,float,float[])
*/ *
public MultiPhaseProgressMonitorWithETA(String title, int numPhases, * @param neoTitle the title to give the dialog box(es)
long totalUnitsFirstPhase, float minUIUpdateIntervalSec) *
{ * @param numPhases the total number of phases to expect
this(title, numPhases, totalUnitsFirstPhase, minUIUpdateIntervalSec, null); *
} * @param totalUnitsFirstPhase the total number of units that will be
/** * processed in the first phase
* Create a GUI progress monitor and open its first dialog. *
* * @param minUIUpdateIntervalSec the approximate interval at which to
* Like all swing components, this constructor must be invoked from the * update the dialog box in seconds
* swing Event Dispatching Thread. The rest of the methods of this class */
* are exempt from this requirement. public MultiPhaseProgressMonitorWithETA(final String neoTitle, final int numPhases,
* final long totalUnitsFirstPhase, final float minUIUpdateIntervalSec) // NOPMD by Braids on 8/18/11 11:16 PM
* @param title the title to give the dialog box(es) {
* this(neoTitle, numPhases, totalUnitsFirstPhase, minUIUpdateIntervalSec, null);
* @param numPhases the total number of phases to expect }
* /**
* @param totalUnitsFirstPhase the total number of units that will be * Create a GUI progress monitor and open its first dialog.
* processed in the first phase *
* * Like all swing components, this constructor must be invoked from the
* @param minUIUpdateIntervalSec the approximate interval at which to * swing Event Dispatching Thread. The rest of the methods of this class
* update the dialog box in seconds * are exempt from this requirement.
* *
* @param phaseWeights see BaseProgressMonitor * @param neoTitle the title to give the dialog box(es)
* *
* @see BaseProgressMonitor#BaseProgressMonitor(int,long,float,float[]) * @param numPhases the total number of phases to expect
*/ *
public MultiPhaseProgressMonitorWithETA(String title, int numPhases, * @param totalUnitsFirstPhase the total number of units that will be
long totalUnitsFirstPhase, float minUIUpdateIntervalSec, * processed in the first phase
float[] phaseWeights) *
{ * @param minUIUpdateIntervalSec the approximate interval at which to
super(numPhases, totalUnitsFirstPhase, minUIUpdateIntervalSec, * update the dialog box in seconds
phaseWeights); *
* @param phaseWeights see BaseProgressMonitor
*
* @see BaseProgressMonitor#BaseProgressMonitor(int,long,float,float[])
*/
public MultiPhaseProgressMonitorWithETA(final String neoTitle, final int numPhases,
final long totalUnitsFirstPhase, final float minUIUpdateIntervalSec, // NOPMD by Braids on 8/18/11 11:16 PM
final float[] phaseWeights)
{
super(numPhases, totalUnitsFirstPhase, minUIUpdateIntervalSec,
phaseWeights);
if (!SwingUtilities.isEventDispatchThread()) { if (!SwingUtilities.isEventDispatchThread()) {
throw new IllegalStateException("must be called from within an event dispatch thread"); throw new IllegalStateException("must be called from within an event dispatch thread");
} }
this.title = title; this.title = neoTitle;
if (totalUnitsFirstPhase > 0 && dialog == null) { if (totalUnitsFirstPhase > 0 && dialog == null) {
throw new IllegalStateException("dialog is null"); throw new IllegalStateException("dialog is null");
} }
} }
/** /**
* For developer testing. * For developer testing.
* *
* @param args ignored * @param args ignored
*/ */
public static void main(final String[] args) { public static void main(final String[] args) {
System.out.println("Initializing..."); System.out.println("Initializing..."); // NOPMD by Braids on 8/18/11 11:13 PM
SwingUtilities.invokeLater(new Runnable() { SwingUtilities.invokeLater(new Runnable() { // NOPMD by Braids on 8/18/11 11:16 PM
public void run() { public void run() {
final int totalUnitsFirstPhase = 5000; final int totalUnitsFirstPhase = 5000; // NOPMD by Braids on 8/18/11 11:16 PM
final MultiPhaseProgressMonitorWithETA monitor = final MultiPhaseProgressMonitorWithETA monitor =
new MultiPhaseProgressMonitorWithETA("Testing 2 phases", 2, totalUnitsFirstPhase, 1.0f, new MultiPhaseProgressMonitorWithETA("Testing 2 phases", 2, totalUnitsFirstPhase, 1.0f,
new float[] {2, 1}); new float[] {2, 1});
SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() { final SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
@Override @Override
public Object doInBackground() { public Object doInBackground() {
System.out.println("Running..."); System.out.println("Running..."); // NOPMD by Braids on 8/18/11 11:14 PM
for (int i = 0; i <= totalUnitsFirstPhase; i++) { for (int i = 0; i <= totalUnitsFirstPhase; i++) {
monitor.incrementUnitsCompletedThisPhase(1); monitor.incrementUnitsCompletedThisPhase(1);
System.out.print("\ri = " + i); System.out.print("\ri = " + i); // NOPMD by Braids on 8/18/11 11:14 PM
try { try {
Thread.sleep(1); Thread.sleep(1);
@@ -109,15 +117,15 @@ public class MultiPhaseProgressMonitorWithETA extends BaseProgressMonitor {
// blank // blank
} }
} }
System.out.println(); System.out.println(); // NOPMD by Braids on 8/18/11 11:14 PM
final int totalUnitsSecondPhase = 2000; final int totalUnitsSecondPhase = 2000; // NOPMD by Braids on 8/18/11 11:17 PM
monitor.markCurrentPhaseAsComplete(totalUnitsSecondPhase); monitor.markCurrentPhaseAsComplete(totalUnitsSecondPhase);
for (int i = 0; i <= totalUnitsSecondPhase; i++) { for (int i = 0; i <= totalUnitsSecondPhase; i++) {
monitor.incrementUnitsCompletedThisPhase(1); monitor.incrementUnitsCompletedThisPhase(1);
System.out.print("\ri = " + i); System.out.print("\ri = " + i); // NOPMD by Braids on 8/18/11 11:14 PM
try { try {
Thread.sleep(1); Thread.sleep(1);
@@ -128,8 +136,8 @@ public class MultiPhaseProgressMonitorWithETA extends BaseProgressMonitor {
monitor.markCurrentPhaseAsComplete(0); monitor.markCurrentPhaseAsComplete(0);
System.out.println(); System.out.println(); // NOPMD by Braids on 8/18/11 11:14 PM
System.out.println("Done!"); System.out.println("Done!"); // NOPMD by Braids on 8/18/11 11:14 PM
return null; return null;
} }
@@ -143,22 +151,22 @@ public class MultiPhaseProgressMonitorWithETA extends BaseProgressMonitor {
@Override @Override
/** /**
* @param numUnits cannot be higher than Integer.MAX_VALUE * @param numUnits cannot be higher than Integer.MAX_VALUE
* *
* @see net.slightlymagic.braids.util.progress_monitor.ProgressMonitor#setTotalUnitsThisPhase(long) * @see net.slightlymagic.braids.util.progress_monitor.ProgressMonitor#setTotalUnitsThisPhase(long)
*/ */
public void setTotalUnitsThisPhase(final long numUnits) { public final void setTotalUnitsThisPhase(final long numUnits) {
super.setTotalUnitsThisPhase(numUnits); super.setTotalUnitsThisPhase(numUnits);
if (numUnits > Integer.MAX_VALUE) { if (numUnits > Integer.MAX_VALUE) {
throw new IllegalArgumentException("numUnits must be <= " + Integer.MAX_VALUE); throw new IllegalArgumentException("numUnits must be <= " + Integer.MAX_VALUE);
} }
if (numUnits > 0) { if (numUnits > 0) {
// dialog must exist before we exit this method. // dialog must exist before we exit this method.
UtilFunctions.invokeInEventDispatchThreadAndWait(new Runnable() { UtilFunctions.invokeInEventDispatchThreadAndWait(new Runnable() { // NOPMD by Braids on 8/18/11 11:17 PM
public void run() { public void run() {
// (Re)create the progress bar. // (Re)create the progress bar.
if (dialog != null) { if (dialog != null) {
@@ -171,7 +179,7 @@ public class MultiPhaseProgressMonitorWithETA extends BaseProgressMonitor {
}); });
} }
SwingUtilities.invokeLater(new Runnable() { SwingUtilities.invokeLater(new Runnable() { // NOPMD by Braids on 8/18/11 11:18 PM
public void run() { public void run() {
dialog.setTitle(title); dialog.setTitle(title);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
@@ -181,25 +189,25 @@ public class MultiPhaseProgressMonitorWithETA extends BaseProgressMonitor {
dialog.setProgressRange(0, (int) numUnits); dialog.setProgressRange(0, (int) numUnits);
dialog.reset(); dialog.reset();
JProgressBar bar = dialog.getProgressBar(); final JProgressBar bar = dialog.getProgressBar();
bar.setString(""); bar.setString("");
bar.setStringPainted(true); bar.setStringPainted(true);
bar.setValue(0); bar.setValue(0);
} }
}); });
} }
@Override @Override
/** /**
* @see net.slightlymagic.braids.util.progress_monitor.ProgressMonitor#incrementUnitsCompletedThisPhase(long) * @see net.slightlymagic.braids.util.progress_monitor.ProgressMonitor#incrementUnitsCompletedThisPhase(long)
*/ */
public void incrementUnitsCompletedThisPhase(final long numUnits) { public final void incrementUnitsCompletedThisPhase(final long numUnits) {
super.incrementUnitsCompletedThisPhase(numUnits); super.incrementUnitsCompletedThisPhase(numUnits);
SwingUtilities.invokeLater(new Runnable() { SwingUtilities.invokeLater(new Runnable() { // NOPMD by Braids on 8/18/11 11:18 PM
public void run() { public void run() {
for (int i = 0 ; i < numUnits ; i++) { for (int i = 0; i < numUnits; i++) {
dialog.increment(); dialog.increment();
} }
} }
@@ -207,28 +215,28 @@ public class MultiPhaseProgressMonitorWithETA extends BaseProgressMonitor {
if (shouldUpdateUI()) { if (shouldUpdateUI()) {
if ((getNumPhases() > 1)) { if ((getNumPhases() > 1)) {
displayUpdate( displayUpdate(
"Phase " + getCurrentPhase() + ". " + "Phase " + getCurrentPhase() + ". "
//getUnitsCompletedSoFarThisPhase() + " units processed. " + //+ getUnitsCompletedSoFarThisPhase() + " units processed. "
//"Overall: " + getTotalPercentCompleteAsString() + "% complete, " + //+ "Overall: " + getTotalPercentCompleteAsString() + "% complete, "
"Overall ETA in " + getRelativeETAAsString() + "." + "Overall ETA in " + getRelativeETAAsString() + "."
); );
} }
else { else {
displayUpdate( displayUpdate(
//"Overall: " + //"Overall: " +
getUnitsCompletedSoFarThisPhase() + " units processed; " + getUnitsCompletedSoFarThisPhase() + " units processed; "
//"(" + getTotalPercentCompleteAsString() + "%); " + //+ "(" + getTotalPercentCompleteAsString() + "%); "
"ETA in " + getRelativeETAAsString() + "." + "ETA in " + getRelativeETAAsString() + "."
); );
} }
} }
if (getCurrentPhase() == getNumPhases() && if (getCurrentPhase() == getNumPhases()
getUnitsCompletedSoFarThisPhase() >= getTotalUnitsThisPhase()) && getUnitsCompletedSoFarThisPhase() >= getTotalUnitsThisPhase())
{ {
displayUpdate("Done!"); displayUpdate("Done!");
} }
} }
@@ -238,15 +246,15 @@ public class MultiPhaseProgressMonitorWithETA extends BaseProgressMonitor {
* *
* @param message the message to display * @param message the message to display
*/ */
public void displayUpdate(final String message) { public final void displayUpdate(final String message) {
final Runnable proc = new Runnable() { final Runnable proc = new Runnable() { // NOPMD by Braids on 8/18/11 11:18 PM
public void run() { public void run() {
// i've been having trouble getting the dialog to display its title. // i've been having trouble getting the dialog to display its title.
dialog.setTitle(title); dialog.setTitle(title);
JProgressBar bar = dialog.getProgressBar(); JProgressBar bar = dialog.getProgressBar();
bar.setString(message); bar.setString(message);
justUpdatedUI(); justUpdatedUI();
} }
@@ -263,7 +271,7 @@ public class MultiPhaseProgressMonitorWithETA extends BaseProgressMonitor {
@Override @Override
public final void dispose() { public final void dispose() {
SwingUtilities.invokeLater(new Runnable() { SwingUtilities.invokeLater(new Runnable() { // NOPMD by Braids on 8/18/11 11:18 PM
public void run() { public void run() {
getDialog().dispose(); getDialog().dispose();
} }
@@ -275,8 +283,8 @@ public class MultiPhaseProgressMonitorWithETA extends BaseProgressMonitor {
* @return the JDialog for the current phase; use this judiciously to * @return the JDialog for the current phase; use this judiciously to
* manipulate the dialog directly. * manipulate the dialog directly.
*/ */
public JDialog getDialog() { public final JDialog getDialog() {
return dialog; return dialog;
} }
} }

View File

@@ -1,7 +1,5 @@
package forge.view.swing; package forge.view.swing;
import java.lang.reflect.InvocationTargetException;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import javax.swing.UIManager; import javax.swing.UIManager;
@@ -28,7 +26,7 @@ import forge.view.swing.OldGuiNewGame.CardStackOffsetAction;
*/ */
public class ApplicationView implements FView { public class ApplicationView implements FView {
private SplashFrame splashFrame; private transient SplashFrame splashFrame;
/** /**
* The splashFrame field is guaranteed to exist when this constructor * The splashFrame field is guaranteed to exist when this constructor
@@ -39,13 +37,13 @@ public class ApplicationView implements FView {
// We must use invokeAndWait here to fulfill the constructor's // We must use invokeAndWait here to fulfill the constructor's
// contract. // contract.
UtilFunctions.invokeInEventDispatchThreadAndWait(new Runnable() { UtilFunctions.invokeInEventDispatchThreadAndWait(new Runnable() { // NOPMD by Braids on 8/18/11 11:37 PM
public void run() { public void run() {
splashFrame = new SplashFrame(); splashFrame = new SplashFrame();
} }
}); });
SwingUtilities.invokeLater(new Runnable() { SwingUtilities.invokeLater(new Runnable() { // NOPMD by Braids on 8/18/11 11:37 PM
public void run() { public void run() {
splashFrame.setVisible(true); splashFrame.setVisible(true);
} }
@@ -83,7 +81,10 @@ public class ApplicationView implements FView {
OldGuiNewGame.smoothLandCheckBox.setSelected(preferences.stackAiLand); OldGuiNewGame.smoothLandCheckBox.setSelected(preferences.stackAiLand);
OldGuiNewGame.devModeCheckBox.setSelected(preferences.developerMode); OldGuiNewGame.devModeCheckBox.setSelected(preferences.developerMode);
OldGuiNewGame.cardOverlay.setSelected(preferences.cardOverlay); OldGuiNewGame.cardOverlay.setSelected(preferences.cardOverlay);
// FindBugs doesn't like the next line.
ImageCache.scaleLargerThanOriginal = preferences.scaleLargerThanOriginal; ImageCache.scaleLargerThanOriginal = preferences.scaleLargerThanOriginal;
OldGuiNewGame.cardScale.setSelected(preferences.scaleLargerThanOriginal); OldGuiNewGame.cardScale.setSelected(preferences.scaleLargerThanOriginal);
CardStackOffsetAction.set(preferences.stackOffset); CardStackOffsetAction.set(preferences.stackOffset);
CardStackAction.setVal(preferences.maxStackSize); CardStackAction.setVal(preferences.maxStackSize);

View File

@@ -11,51 +11,55 @@ import javax.swing.SwingUtilities;
* Some general-purpose functions. * Some general-purpose functions.
*/ */
public final class UtilFunctions { public final class UtilFunctions {
/**
* Do not instantiate. /**
*/ * Do not instantiate.
private UtilFunctions() {;} */
private UtilFunctions() {
// empty
}
/** /**
* Throws a NullPointerException if param is null. * Throws a NullPointerException if param is null.
* *
* @param paramName the name of the parameter; may be null * @param paramName the name of the parameter; may be null
* @param param the parameter to test * @param param the parameter to test
*/ */
public static void checkNotNull(String paramName, Object param) { public static void checkNotNull(final String paramName, final Object param) {
if (param != null) return; if (param != null) {
return;
}
NullPointerException exn = null; NullPointerException exn = null;
if (paramName != null) { if (paramName == null) {
exn = new NullPointerException(paramName + " must not be null"); exn = new NullPointerException(); // NOPMD by Braids on 8/18/11 11:19 PM
} }
else { else {
// exn = new NullPointerException(paramName + " must not be null"); // NOPMD by Braids on 8/18/11 11:19 PM
exn = new NullPointerException(); }
}
// Doctor the exception to appear to come from the caller. // Doctor the exception to appear to come from the caller.
StackTraceElement[] trace = exn.getStackTrace(); final StackTraceElement[] trace = exn.getStackTrace();
int len = getSliceLength(trace, 1); final int len = getSliceLength(trace, 1);
exn.setStackTrace(slice(new StackTraceElement[len], trace, 1)); exn.setStackTrace(slice(new StackTraceElement[len], trace, 1));
throw exn; throw exn;
} }
/** /**
* Invoke the given Runnable in an Event Dispatch Thread and wait for it * Invoke the given Runnable in an Event Dispatch Thread and wait for it
* to finish; but <B>try to use SwingUtilities.invokeLater instead whenever * to finish; but <B>try to use SwingUtilities.invokeLater instead whenever
* feasible.</B> * feasible.</B>
* *
* Exceptions generated by SwingUtilities.invokeAndWait (if used), are * Exceptions generated by SwingUtilities.invokeAndWait (if used), are
* rethrown as RuntimeExceptions. * rethrown as RuntimeExceptions.
* *
* @see javax.swing.SwingUtilities#invokeLater(Runnable) * @see javax.swing.SwingUtilities#invokeLater(Runnable)
* *
* @param proc the Runnable to run * @param proc the Runnable to run
*/ */
public static void invokeInEventDispatchThreadAndWait(final Runnable proc) { public static void invokeInEventDispatchThreadAndWait(final Runnable proc) { // NOPMD by Braids on 8/18/11 11:19 PM
if (SwingUtilities.isEventDispatchThread()) { if (SwingUtilities.isEventDispatchThread()) {
// Just run in the current thread. // Just run in the current thread.
proc.run(); proc.run();
@@ -64,234 +68,271 @@ public final class UtilFunctions {
try { try {
SwingUtilities.invokeAndWait(proc); SwingUtilities.invokeAndWait(proc);
} catch (InterruptedException exn) { } catch (InterruptedException exn) {
throw new RuntimeException(exn); throw new RuntimeException(exn); // NOPMD by Braids on 8/18/11 11:19 PM
} catch (InvocationTargetException exn) { } catch (InvocationTargetException exn) {
throw new RuntimeException(exn); throw new RuntimeException(exn); // NOPMD by Braids on 8/18/11 11:19 PM
} }
} }
} }
/** /**
* Create an array from the (rest of) an iterator's output; * Create an array from the (rest of) an iterator's output;
* this function is horribly inefficient. * this function is horribly inefficient.
* *
* Please, only use it on small iterators. * Please, only use it on small iterators.
* *
* @param iter the iterator to traverse * @param <T> (inferred automatically)
* *
* @return an array of (the rest of) the iterator's values * @param iter the iterator to traverse
*/ *
public static <T> T[] iteratorToArray(Iterator<T> iter) { * @return an array of (the rest of) the iterator's values
ArrayList<T> list = new ArrayList<T>(); */
public static <T> T[] iteratorToArray(final Iterator<T> iter) {
final ArrayList<T> list = new ArrayList<T>();
T item; T item;
while (iter.hasNext()) { while (iter.hasNext()) {
item = iter.next(); item = iter.next();
list.add(item); list.add(item);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
T[] result = (T[]) list.toArray(); final T[] result = (T[]) list.toArray();
return result; return result;
} }
/** /**
* Returns the rightmost portion of an array, Python-style. * Returns the rightmost portion of an array, Python-style.
* *
* @param <T> (inferred automatically) * @param <T> (inferred automatically)
* *
* @param srcArray the array to copy (shallowly) * @param dstArray the array in which to place new items
* *
* @param startIndex if positive, the index (from the left) at which to * @param srcArray the array to copy (shallowly)
* start copying; if negative, we treat this as the index from the right. *
* For example, calling this with startIndex = -2 returns the last two * @param startIndexIn if positive, the index (from the left) at which to
* items in the array, if it has that many. * start copying; if negative, we treat this as the index from the right.
* * For example, calling this with startIndex = -2 returns the last two
* @return a shallow copy of array starting at startIndex; this may return * items in the array, if it has that many.
* an empty array if the startIndex is out of bounds. *
*/ * @return a shallow copy of array starting at startIndex; this may return
public static <T extends Object> T[] slice(T[] dstArray, T[] srcArray, * an empty array if the startIndex is out of bounds.
int startIndex) */
{ public static <T extends Object> T[] slice(final T[] dstArray, final T[] srcArray,
if (startIndex < 0) { final int startIndexIn)
startIndex = srcArray.length + startIndex; {
if (startIndex < 0) startIndex = 0; int startIndex = startIndexIn;
} if (startIndex < 0) {
startIndex = srcArray.length + startIndex;
if (startIndex < 0) {
startIndex = 0;
}
}
if (dstArray == null) { if (dstArray == null) {
throw new NullPointerException(); throw new NullPointerException(); // NOPMD by Braids on 8/18/11 11:19 PM
} }
if (srcArray == null) { if (srcArray == null) {
throw new NullPointerException(); throw new NullPointerException(); // NOPMD by Braids on 8/18/11 11:19 PM
} }
int resultLength = getSliceLength(srcArray, startIndex); final int resultLength = getSliceLength(srcArray, startIndex);
if (dstArray.length != resultLength) { if (dstArray.length != resultLength) {
throw new ArrayIndexOutOfBoundsException( throw new ArrayIndexOutOfBoundsException(
"First parameter must have length " + resultLength + ", but length is " + dstArray.length + "."); "First parameter must have length " + resultLength
} + ", but length is " + dstArray.length + ".");
}
int srcIx = startIndex; int srcIx = startIndex;
for (int dstIx = 0; for (int dstIx = 0;
dstIx < resultLength && srcIx < srcArray.length; dstIx < resultLength && srcIx < srcArray.length;
dstIx++, srcIx++) dstIx++, srcIx++)
{ {
dstArray[dstIx] = srcArray[srcIx]; dstArray[dstIx] = srcArray[srcIx];
} }
return dstArray; return dstArray;
} }
/** /**
* Get a slice's length in preparation for taking a slice. * Get a slice's length in preparation for taking a slice.
* *
* I do not like the fact that I have to use this function, but * I do not like the fact that I have to use this function, but
* Java left me with little choice. * Java left me with little choice.
* *
* @see #slice(Object[], Object[], int) * @see #slice(Object[], Object[], int)
* *
* @return the length of the array that would result from calling * @param <T> (inferred automatically)
* slice(Object[], Object[], int) with the given srcArray and *
* startIndex. * @param srcArray the array that would be copied (shallowly)
*/ *
public static <T> int getSliceLength(T[] srcArray, int startIndex) { * @param startIndexIn if positive, the index (from the left) at which
if (startIndex < 0) { * copying would start; if negative, we treat this as the index from the
startIndex = srcArray.length + startIndex; * right. For example, calling this with startIndex = -2 computes the
if (startIndex < 0) startIndex = 0; * length if slice would return the last two items in the array, if it has
} * that many.
*
* @return the length of the array that would result from calling
* slice(Object[], Object[], int) with the given srcArray and
* startIndex.
*/
public static <T> int getSliceLength(final T[] srcArray, final int startIndexIn) {
int startIndex = startIndexIn;
int resultLength = srcArray.length - startIndex; if (startIndex < 0) {
return resultLength; startIndex = srcArray.length + startIndex;
} if (startIndex < 0) {
startIndex = 0;
}
}
final int resultLength = srcArray.length - startIndex;
return resultLength;
}
/** /**
* Handles the boilerplate null and isinstance check for an equals method. * Handles the boilerplate null and isinstance check for an equals method.
* *
* Example: * Example:
* <pre> * <pre>
* public boolean equals(Object obj) { * public boolean equals(Object obj) {
* MyClassName that = checkNullOrNotInstance(this, obj); * MyClassName that = checkNullOrNotInstance(this, obj);
* if (that == null) { * if (that == null) {
* return false; * return false;
* } * }
* //... * //...
* } * }
* </pre> * </pre>
* *
* @param goodInstance a non-null instance of type T; looks neater than * @param <T> (inferred automatically)
* passing in goodInstance.getClass() *
* * @param goodInstance a non-null instance of type T; looks neater than
* @param obj the object to test * passing in goodInstance.getClass()
* *
* @return null if obj is null or not an instance of goodInstance's class; * @param obj the object to test
* otherwise, we return obj cast to goodInstance's type *
*/ * @return null if obj is null or not an instance of goodInstance's class;
public static <T> T checkNullOrNotInstance(T goodInstance, Object obj) { * otherwise, we return obj cast to goodInstance's type
if (goodInstance == null) { */
throw new NullPointerException("first parameter must not be null"); public static <T> T checkNullOrNotInstance(final T goodInstance, final Object obj) {
} if (goodInstance == null) {
throw new NullPointerException("first parameter must not be null"); // NOPMD by Braids on 8/18/11 11:19 PM
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Class<T> classT = (Class<T>) goodInstance.getClass(); final Class<T> classT = (Class<T>) goodInstance.getClass();
boolean viable = true; boolean viable = true;
if (obj == null) viable = false; if (obj == null) {
else if (!(classT.isInstance(obj))) viable = false; viable = false;
} else if (!(classT.isInstance(obj))) {
viable = false;
}
if (viable) { T result;
return classT.cast(obj); if (viable) {
} result = classT.cast(obj);
return null; } else {
} result = null;
}
return result;
}
/** /**
* Safely converts an object to a String. * Safely converts an object to a String.
* *
* @param obj to convert; may be null * @param obj to convert; may be null
* *
* @return "null" if obj is null, obj.toString() otherwise * @return "null" if obj is null, obj.toString() otherwise
*/ */
public static String safeToString(Object obj) { public static String safeToString(final Object obj) {
if (obj == null) { String result;
return "null";
}
else {
return obj.toString();
}
}
/** if (obj == null) {
* Remove nulls and duplicate items from the list. result = "null";
* }
* This may change the list's ordering. It uses the items' equals methods to else {
* determine equality. result = obj.toString();
* }
* Advantages over HashSet: This consumes no unnecessary heap-memory, nor
* does it require objects to implement hashCode. It is OK if
* (o1.equals(o2) does not imply o1.hashCode() == o2.hashCode()).
*
* Advantages over TreeSet: This does not require a comparator.
*
* Disadvantages over HashSet and TreeSet: This runs in O(n*n) time.
*
* @param list the list to modify; this is fastest with ArrayList.
*/
public static <T> void smartRemoveDuplicatesAndNulls(List<T> list)
{
// Get rid of pesky leading nulls.
smartRemoveDuplicatesAndNullsHelper(list, 0, null);
for (int earlierIx = 0; earlierIx < list.size(); earlierIx++) return result;
{ }
for (int laterIx = earlierIx + 1; laterIx < list.size(); laterIx++)
{
T itemAtEarlierIx = list.get(earlierIx);
smartRemoveDuplicatesAndNullsHelper(list, laterIx, /**
itemAtEarlierIx); * Remove nulls and duplicate items from the list.
} *
* This may change the list's ordering. It uses the items' equals methods to
* determine equality.
*
* Advantages over HashSet: This consumes no unnecessary heap-memory, nor
* does it require objects to implement hashCode. It is OK if
* (o1.equals(o2) does not imply o1.hashCode() == o2.hashCode()).
*
* Advantages over TreeSet: This does not require a comparator.
*
* Disadvantages over HashSet and TreeSet: This runs in O(n*n) time.
*
* @param <T> (inferred automatically)
*
* @param list the list to modify; this is fastest with ArrayList.
*/
public static <T> void smartRemoveDuplicatesAndNulls(final List<T> list) {
// Get rid of pesky leading nulls.
smartRemoveDuplicatesAndNullsHelper(list, 0, null);
} for (int earlierIx = 0; earlierIx < list.size(); earlierIx++) {
} for (int laterIx = earlierIx + 1; laterIx < list.size(); laterIx++)
{
final T itemAtEarlierIx = list.get(earlierIx);
/** smartRemoveDuplicatesAndNullsHelper(list, laterIx,
* Helper method for smartRemoveDuplicatesAndNulls that is subject to itemAtEarlierIx);
* change; if you call this directly, you do so at your own risk! }
*
* @param list the list to modify; if all items from startIx to the end
* are either null or equal to objSeenPreviously, then we truncate the
* list just before startIx.
*
* @param startIx the index to examine; we only move items within the range
* of [startIx, list.size()-1].
*
* @param objSeenPreviously the object with which to compare list[startIx];
* may be null.
*/
public static <T> void smartRemoveDuplicatesAndNullsHelper(
List<T> list, int startIx, T objSeenPreviously)
{
while (startIx < list.size() &&
(list.get(startIx) == null ||
list.get(startIx) == objSeenPreviously ||
list.get(startIx).equals(objSeenPreviously)))
{
int lastItemIx = list.size()-1;
// Overwrite the item at laterIx with the one at the end, }
// then delete the one at the end. }
list.set(startIx, list.get(lastItemIx));
list.remove(lastItemIx); /**
} * Helper method for smartRemoveDuplicatesAndNulls that is subject to
} * change; if you call this directly, you do so at your own risk!
*
* @param <T> (inferred automatically)
*
* @param list the list to modify; if all items from startIx to the end
* are either null or equal to objSeenPreviously, then we truncate the
* list just before startIx.
*
* @param startIx the index to examine; we only move items within the range
* of [startIx, list.size()-1].
*
* @param objSeenPreviously the object with which to compare list[startIx];
* may be null.
*/
public static <T> void smartRemoveDuplicatesAndNullsHelper(
final List<T> list, final int startIx, final T objSeenPreviously)
{
while (startIx < list.size()
&& (list.get(startIx) == null
|| list.get(startIx) == objSeenPreviously
|| list.get(startIx).equals(objSeenPreviously)))
{
final int lastItemIx = list.size() - 1;
// Overwrite the item at laterIx with the one at the end,
// then delete the one at the end.
list.set(startIx, list.get(lastItemIx));
list.remove(lastItemIx);
}
}
} }

View File

@@ -22,11 +22,17 @@ import java.util.TreeSet;
* @author Forge * @author Forge
* @version $Id$ * @version $Id$
*/ */
@Test(groups = {"UnitTest"}, timeOut = 5000) @Test(groups = {"UnitTest" }, timeOut = CardFactoryTest.DEFAULT_TEST_TIMEOUT_MS)
public class CardFactoryTest implements NewConstants { public class CardFactoryTest implements NewConstants {
private CardFactoryInterface factory; /** The default time to allow a test to run before TestNG ignores it. */
public static final int DEFAULT_TEST_TIMEOUT_MS = 5000; // NOPMD by Braids on 8/18/11 11:43 PM
private transient CardFactoryInterface factory;
/**
* Executed before each test method, as in JUnit.
*/
@BeforeMethod @BeforeMethod
public final void setUp() { public final void setUp() {
OldGuiNewGame.loadDynamicGamedata(); OldGuiNewGame.loadDynamicGamedata();
@@ -37,8 +43,8 @@ public class CardFactoryTest implements NewConstants {
* Just a quick test to see if Arc-Slogger is in the database, and if it * Just a quick test to see if Arc-Slogger is in the database, and if it
* has the correct owner. * has the correct owner.
*/ */
@Test(enabled = true, timeOut = 5000) @Test(enabled = true, timeOut = DEFAULT_TEST_TIMEOUT_MS)
public final void test_getCard_1() { public final void test_getCard_1() { // NOPMD by Braids on 8/18/11 11:39 PM
final Card card = factory.getCard("Arc-Slogger", null); final Card card = factory.getCard("Arc-Slogger", null);
Assert.assertNotNull(card, "card is not null"); Assert.assertNotNull(card, "card is not null");
Assert.assertNull(card.getOwner(), "card has correct owner"); Assert.assertNull(card.getOwner(), "card has correct owner");
@@ -47,19 +53,19 @@ public class CardFactoryTest implements NewConstants {
/** /**
* Make sure the method throws an exception when it's supposed to. * Make sure the method throws an exception when it's supposed to.
*/ */
@Test(enabled = true, timeOut = 5000) @Test(enabled = true, timeOut = DEFAULT_TEST_TIMEOUT_MS)
public final void test_getRandomCombinationWithoutRepetition_tooLarge() { public final void test_getRandomCombinationWithoutRepetition_tooLarge() { // NOPMD by Braids on 8/18/11 11:39 PM
BraidsAssertFunctions.assertThrowsException(IllegalArgumentException.class, BraidsAssertFunctions.assertThrowsException(IllegalArgumentException.class,
new ClumsyRunnable() { new ClumsyRunnable() {
public void run() throws Exception { public void run() throws Exception { // NOPMD by Braids on 8/18/11 11:40 PM
factory.getRandomCombinationWithoutRepetition(factory.size()); factory.getRandomCombinationWithoutRepetition(factory.size());
} }
}); });
BraidsAssertFunctions.assertThrowsException(IllegalArgumentException.class, BraidsAssertFunctions.assertThrowsException(IllegalArgumentException.class,
new ClumsyRunnable() { new ClumsyRunnable() {
public void run() throws Exception { public void run() throws Exception { // NOPMD by Braids on 8/18/11 11:40 PM
int largeDivisorForRandomCombo = 4; final int largeDivisorForRandomCombo = 4; // NOPMD by Braids on 8/18/11 11:41 PM
factory.getRandomCombinationWithoutRepetition(factory.size() / largeDivisorForRandomCombo); factory.getRandomCombinationWithoutRepetition(factory.size() / largeDivisorForRandomCombo);
} }
}); });
@@ -70,10 +76,10 @@ public class CardFactoryTest implements NewConstants {
* *
* This doesn't work with LazyCardFactory, so it is too slow to enable by default. * This doesn't work with LazyCardFactory, so it is too slow to enable by default.
*/ */
@Test(enabled = false, timeOut = 5000) @Test(enabled = false, timeOut = DEFAULT_TEST_TIMEOUT_MS)
public final void test_getRandomCombinationWithoutRepetition_oneTenth() { public final void test_getRandomCombinationWithoutRepetition_oneTenth() { // NOPMD by Braids on 8/18/11 11:39 PM
factory = new PreloadingCardFactory(ForgeProps.getFile(CARDSFOLDER)); factory = new PreloadingCardFactory(ForgeProps.getFile(CARDSFOLDER));
int divisor = 10; final int divisor = 10; // NOPMD by Braids on 8/18/11 11:41 PM
final CardList actual = factory.getRandomCombinationWithoutRepetition(factory.size() / divisor); final CardList actual = factory.getRandomCombinationWithoutRepetition(factory.size() / divisor);
final Set<String> cardNames = new TreeSet<String>(); final Set<String> cardNames = new TreeSet<String>();