Discussion:
[Freecol-developers] cleanup and optimizations (take #1)
e***@gr13.net
2017-01-19 02:30:44 UTC
Permalink
Hi folks,


here's a queue of cleanups and optimization patches that i've got in
incubation for quite a while. Most of them are about reducing temporary
allocations and callback chains in list handling.


--mtx
e***@gr13.net
2017-01-19 02:30:47 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.gitignore | 5 +++++
doc/.gitignore | 17 +++++++++++++++++
2 files changed, 22 insertions(+)
create mode 100644 doc/.gitignore

diff --git a/.gitignore b/.gitignore
index 5168e50365f..0a7c6619340 100644
--- a/.gitignore
+++ b/.gitignore
@@ -22,6 +22,7 @@ dist/
a/
b/
TESTS-TestSuites.xml
+freecol.jar

### Java template

@@ -167,3 +168,7 @@ $RECYCLE.BIN/

# Windows shortcuts
*.lnk
+
+# debian build outputs
+debian/*.log
+debian/jh_build_stamp
diff --git a/doc/.gitignore b/doc/.gitignore
new file mode 100644
index 00000000000..06ada190448
--- /dev/null
+++ b/doc/.gitignore
@@ -0,0 +1,17 @@
+FreeCol.4ct
+FreeCol.4dx
+FreeCol.4ix
+FreeCol.4tc
+FreeCol.aux
+FreeCol.css
+FreeCol.dvi
+FreeCol.html
+FreeCol.idv
+FreeCol.idx
+FreeCol.lg
+FreeCol.out
+FreeCol.pdf
+FreeCol.toc
+FreeCol.xref
+idxmake.dvi
+idxmake.log
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:30:45 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

taken from debian/ubuntu package
---
build.xml | 2 +-
doc/freecol.6 | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 84 insertions(+), 1 deletion(-)
create mode 100644 doc/freecol.6

diff --git a/build.xml b/build.xml
index 36e726022e2..a071b74af50 100644
--- a/build.xml
+++ b/build.xml
@@ -534,7 +534,7 @@
<fileset dir="${freecol.build.dir}" includes="TEST-net.sf.freecol.*" />
<fileset dir="${freecol.build.dir}" includes="dependencies.txt" />
<fileset dir="${freecol.doc.dir}"
- excludes="*.tex *.sty images/* specification.*" />
+ excludes="*.tex *.sty images/* specification.* freecol.6" />
</delete>
<delete quiet="true" file="${freecol.jar.file}"/>
<delete quiet="true" file="${freecol.metaserver.jar.file}"/>
diff --git a/doc/freecol.6 b/doc/freecol.6
new file mode 100644
index 00000000000..38439231e4d
--- /dev/null
+++ b/doc/freecol.6
@@ -0,0 +1,83 @@
+.\" Hey, EMACS: -*- nroff -*-
+.\" First parameter, NAME, should be all caps
+.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
+.\" other parameters are allowed: see man(7), man(1)
+.TH FREECOL 6 "July 28, 2004" GNU "FreeCol's Manpage"
+.\" Please adjust this date whenever revising the manpage.
+.\"
+.\" Some roff macros, for reference:
+.\" .nh disable hyphenation
+.\" .hy enable hyphenation
+.\" .ad l left justify
+.\" .ad b justify to both left and right margins
+.\" .nf disable filling
+.\" .fi enable filling
+.\" .br insert line break
+.\" .sp <n> insert n+1 empty lines
+.\" for manpage-specific macros, see man(7)
+.SH NAME
+freecol \- A free clone of Colonization
+.SH SYNOPSIS
+.B freecol
+.RI [OPTIONS]
+.SH DESCRIPTION
+This manual page documents briefly the
+.B freecol
+command.
+This manual page was written for the Debian distribution
+because the original program does not have a manual page.
+.PP
+.\" TeX users may be more comfortable with the \fB<whatever>\fP and
+.\" \fI<whatever>\fP escape sequences to invode bold face and italics,
+.\" respectively.
+\fBfreecol\fP is a free clone of the famous game Colonization. It's a
+turn based strategy game in which each player becomes leader of an
+European nation, fighting to obtain the independence of the mother country.
+.PP
+A multiplayer mode has been added to the original game.
+.SH OPTIONS
+A summary of options is included below.
+.TP
+.B \-\-freecol\-data DIR
+DIR should be the directory with FreeCol's data files, it
+has a subdirectory called
+.B images.
+.TP
+.B \-\-windowed
+Runs FreeCol in windowed mode instead of full screen mode.
+.TP
+.B \-\-no\-sound
+Runs FreeCol without sound.
+.TP
+.B \-\-usage
+Shows summary of options.
+.TP
+.B \-\-version
+Shows version of program.
+.TP
+.B \-\-server PORT
+Starts a stand-alone server on the specified port.
+.SH LICENSE
+FreeCol is available under GPL license terms.
+
+.SH JAVA-WRAPPERS NOTE
+
+This program is a shell script wrapper based on
+.BR java-wrappers (7).
+You therefore benefit from several features; please see the
+.BR java-wrappers (7)
+manual page.
+
+
+.SH SEE ALSO
+
+Homepage: http://freecol.sourceforge.net/
+
+.BR java-wrappers (7)
+
+.SH AUTHOR
+This manual page was written by Jean Lepropre
+<***@users.sourceforge.net>,
+for the Debian project (but may be used by others).
+
+It was updated by Vincent Fourmond <***@debian.org>
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:30:46 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/client/gui/dialog/ConfirmDeclarationDialog.java | 2 +-
src/net/sf/freecol/common/model/Map.java | 4 ++--
2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/dialog/ConfirmDeclarationDialog.java b/src/net/sf/freecol/client/gui/dialog/ConfirmDeclarationDialog.java
index 0626b6840ac..da841653b4e 100644
--- a/src/net/sf/freecol/client/gui/dialog/ConfirmDeclarationDialog.java
+++ b/src/net/sf/freecol/client/gui/dialog/ConfirmDeclarationDialog.java
@@ -126,7 +126,7 @@ public class ConfirmDeclarationDialog extends FreeColDialog<List<String>>

// based on the flag of Brazil, particularly the Provisional
// Flag of Republic of the United States of Brazil (November
- // 15–19, 1889)
+ // 15-19, 1889)
public static final Flag PORTUGUESE_FLAG
= new Flag(Background.FESSES, Decoration.NONE, UnionPosition.CANTON)
.setUnionColor(new Color(62, 64, 149))
diff --git a/src/net/sf/freecol/common/model/Map.java b/src/net/sf/freecol/common/model/Map.java
index 88d5c47bf9f..160d491a299 100644
--- a/src/net/sf/freecol/common/model/Map.java
+++ b/src/net/sf/freecol/common/model/Map.java
@@ -255,14 +255,14 @@ public class Map extends FreeColGameObject implements Location {
/**
* The latitude of the northern edge of the map. A negative value
* indicates northern latitude, a positive value southern
- * latitude. Thus, -30 equals 30°N, and 40 equals 40°S.
+ * latitude. Thus, -30 equals 30dgr N, and 40 equals 40dgr S.
*/
private int minimumLatitude = -90;

/**
* The latitude of the southern edge of the map. A negative value
* indicates northern latitude, a positive value southern
- * latitude. Thus, -30 equals 30°N, and 40 equals 40°S.
+ * latitude. Thus, -30 equals 30dgr N, and 40 equals 40dgr S.
*/
private int maximumLatitude = 90;
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:14 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/EuropeWas.java | 17 ++++++++++++++---
1 file changed, 14 insertions(+), 3 deletions(-)

diff --git a/src/net/sf/freecol/common/model/EuropeWas.java b/src/net/sf/freecol/common/model/EuropeWas.java
index 4f90c235880..a332ad56c74 100644
--- a/src/net/sf/freecol/common/model/EuropeWas.java
+++ b/src/net/sf/freecol/common/model/EuropeWas.java
@@ -59,9 +59,20 @@ public class EuropeWas {
* @return The newest {@code Unit} or null if none has been added.
*/
public Unit getNewUnit() {
- return (europe.getUnitCount() <= this.unitCount) ? null
- : maximize(europe.getUnits(),
- cachingIntComparator(Unit::getIdNumber));
+ if (europe.getUnitCount() <= this.unitCount)
+ return null;
+
+ int max_id = 0;
+ Unit max_unit = null;
+ for (Unit u : europe.getUnits()) {
+ int uid = u.getIdNumber();
+ if (uid > max_id) {
+ max_id = uid;
+ max_unit = u;
+ }
+ }
+
+ return max_unit;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:20 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Colony.java | 20 ++++++++++++++------
src/net/sf/freecol/common/model/UnitType.java | 4 ----
2 files changed, 14 insertions(+), 10 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index a71c95ad293..0c99aca0a93 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -1702,12 +1702,20 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return The best available defender type.
*/
public UnitType getBestDefenderType() {
- final Predicate<UnitType> defenderPred = ut ->
- ut.getDefence() > 0
- && !ut.isNaval()
- && ut.isAvailableTo(getOwner());
- return maximize(getSpecification().getUnitTypeList(), defenderPred,
- UnitType.defenceComparator);
+ UnitType max_ut = null;
+ double max_def = 0;
+
+ for (UnitType ut : getSpecification().getUnitTypeList()) {
+ double defence = ut.getDefence();
+ if (defence > 0 && !ut.isNaval() && ut.isAvailableTo(getOwner())) {
+ if (defence > max_def) {
+ max_ut = ut;
+ max_def = defence;
+ }
+ }
+ }
+
+ return max_ut;
}

/**
diff --git a/src/net/sf/freecol/common/model/UnitType.java b/src/net/sf/freecol/common/model/UnitType.java
index dbccfebc7bc..c741b421fc2 100644
--- a/src/net/sf/freecol/common/model/UnitType.java
+++ b/src/net/sf/freecol/common/model/UnitType.java
@@ -42,10 +42,6 @@ public final class UnitType extends BuildableType implements Consumer {

public static final String TAG = "unit-type";

- /** Comparator for defence ability. */
- public static final Comparator<UnitType> defenceComparator
- = Comparator.comparingDouble(UnitType::getDefence);
-
/** The default offence value. */
public static final int DEFAULT_OFFENCE = 0;
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:30:58 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/io/FreeColDirectories.java | 20 --------------------
1 file changed, 20 deletions(-)

diff --git a/src/net/sf/freecol/common/io/FreeColDirectories.java b/src/net/sf/freecol/common/io/FreeColDirectories.java
index db3b4ec9de9..2c611e9728a 100644
--- a/src/net/sf/freecol/common/io/FreeColDirectories.java
+++ b/src/net/sf/freecol/common/io/FreeColDirectories.java
@@ -27,11 +27,8 @@ import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
-import java.util.function.Function;
-import java.util.function.Predicate;
import java.util.List;
import java.util.Locale;
-import java.util.stream.Stream;
import javax.swing.filechooser.FileSystemView;

import net.sf.freecol.FreeCol;
@@ -50,10 +47,6 @@ public class FreeColDirectories {
// No logger! Many of these routines are called before logging is
// initialized.

- private static final Comparator<File> fileNameComparator
- = Comparator.comparing(File::getName);
-
-
private static final String AUTOSAVE_DIRECTORY = "autosave";

private static final String BASE_DIRECTORY = "base";
@@ -533,19 +526,6 @@ public class FreeColDirectories {
}
}

- /**
- * Collect files from a directory that match a predicate.
- *
- * @param dir The directory to load from.
- * @param pred A {@code Predicate} to match files with.
- * @return A list of {@code File}s.
- */
- private static List<File> collectFiles(File dir, Predicate<File> pred) {
- return transform(fileStream(dir), pred, Function.<File>identity(),
- fileNameComparator);
- }
-
-
// Main initialization/bootstrap routines.
// These need to be called early before the subsidiary directory
// accessors are used.
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:13 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Unit.java | 25 ++++++++++++-------------
src/net/sf/freecol/server/ai/REFAIPlayer.java | 7 +++++--
2 files changed, 17 insertions(+), 15 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index 737c629ea18..d20ac2928f6 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -2870,20 +2870,19 @@ public class Unit extends GoodsLocation
* @return The nearest {@code Colony}, or null if none found.
*/
public Colony getClosestColony(List<Colony> colonies) {
- return getClosestColony(colonies.stream());
- }
+ Colony best_colony = null;
+ int best_turns = 0;

- /**
- * Get the colony that can be reached by this unit in the least number
- * of turns.
- *
- * @param colonies A stream of {@code Colony}s.
- * @return The nearest {@code Colony}, or null if none found.
- */
- public Colony getClosestColony(Stream<Colony> colonies) {
- final Comparator<Colony> comp = cachingIntComparator(col ->
- (col == null) ? MANY_TURNS-1 : this.getTurnsToReach(col));
- return minimize(concat(Stream.of((Colony)null), colonies), comp);
+ for (Colony c : colonies) {
+ if (c == null) continue;
+ int turns = this.getTurnsToReach(c);
+ if (best_colony == null || turns < best_turns) {
+ best_colony = c;
+ best_turns = turns;
+ }
+ }
+
+ return best_colony;
}

/**
diff --git a/src/net/sf/freecol/server/ai/REFAIPlayer.java b/src/net/sf/freecol/server/ai/REFAIPlayer.java
index 0c73f5bedf3..eb613431d95 100644
--- a/src/net/sf/freecol/server/ai/REFAIPlayer.java
+++ b/src/net/sf/freecol/server/ai/REFAIPlayer.java
@@ -649,8 +649,11 @@ public class REFAIPlayer extends EuropeanAIPlayer {
}

// Go defend the nearest colony needing defence
- Colony best = u.getClosestColony(map(getBadlyDefended(),
- AIColony::getColony));
+ List<Colony> baddef = new ArrayList<>();
+ for (AIColony aic : getBadlyDefended())
+ baddef.add(aic.getColony());
+
+ Colony best = u.getClosestColony(baddef);
if (best != null
&& (m = getDefendSettlementMission(aiu, best)) != null) {
lb.add(" GO-DEFEND-", best.getName(), " " , m);
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:16 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/FreeColObject.java | 13 +++++++++++++
src/net/sf/freecol/common/model/Specification.java | 4 ++--
2 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/src/net/sf/freecol/common/model/FreeColObject.java b/src/net/sf/freecol/common/model/FreeColObject.java
index 61e359bda86..25a8506f749 100644
--- a/src/net/sf/freecol/common/model/FreeColObject.java
+++ b/src/net/sf/freecol/common/model/FreeColObject.java
@@ -389,6 +389,19 @@ public abstract class FreeColObject
}

/**
+ * Is any of the given abilities present in this object?
+ *
+ * @param id The object identifier.
+ * @return True if the ability is present.
+ */
+ public final boolean hasAnyAbility(String... abilities) {
+ for (String a : abilities)
+ if (hasAbility(id, null))
+ return true;
+ return false;
+ }
+
+ /**
* Is an ability present in this object?
*
* @param id The object identifier.
diff --git a/src/net/sf/freecol/common/model/Specification.java b/src/net/sf/freecol/common/model/Specification.java
index 9a11275f1be..6cf037897c5 100644
--- a/src/net/sf/freecol/common/model/Specification.java
+++ b/src/net/sf/freecol/common/model/Specification.java
@@ -1981,7 +1981,7 @@ public final class Specification {
String... abilities) {
return transform(allTypes.values(),
type -> resultType.isInstance(type)
- && any(abilities, a -> type.hasAbility(a)),
+ && type.hasAnyAbilities(abilities),
type -> resultType.cast(type));
}

@@ -1999,7 +1999,7 @@ public final class Specification {
String... abilities) {
return transform(allTypes.values(),
type -> resultType.isInstance(type)
- && none(abilities, a -> type.hasAbility(a)),
+ && !type.hasAnyAbility(abilities),
type -> resultType.cast(type));
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:18 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Colony.java | 15 ++++++++++++---
1 file changed, 12 insertions(+), 3 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index df4d3e387ef..a84496bbe5e 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -2622,9 +2622,18 @@ loop: for (WorkLocation wl : getWorkLocationsForProducing(goodsType)) {
// units outside the colony as well, use
// @see Tile#getDefendingUnit instead.
final CombatModel cm = getGame().getCombatModel();
- final Comparator<Unit> comp
- = cachingDoubleComparator(u -> cm.getDefencePower(attacker, u));
- return maximize(getUnits(), comp);
+
+ double max_defense = 0;
+ Unit max_unit = null;
+ for (Unit u : getUnits()) {
+ double defpwr = cm.getDefencePower(attacker, u);
+ if ((max_unit == null) || (defpwr > max_defense)) {
+ max_defense = defpwr;
+ max_unit = u;
+ }
+ }
+
+ return max_unit;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:24 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

Dont need the overhead of stream operations with locally allocated
comparator object - just scan over the list and find the max.
---
src/net/sf/freecol/common/model/ProductionType.java | 20 +++++++++++++++-----
1 file changed, 15 insertions(+), 5 deletions(-)

diff --git a/src/net/sf/freecol/common/model/ProductionType.java b/src/net/sf/freecol/common/model/ProductionType.java
index 2911fe78bde..068c96bba17 100644
--- a/src/net/sf/freecol/common/model/ProductionType.java
+++ b/src/net/sf/freecol/common/model/ProductionType.java
@@ -344,11 +344,21 @@ public class ProductionType extends FreeColSpecObject {
*/
public static ProductionType getBestProductionType(GoodsType goodsType,
Collection<ProductionType> types) {
- final Comparator<ProductionType> comp = cachingIntComparator(pt -> {
- AbstractGoods best = pt.getBestOutputFor(goodsType);
- return (best == null) ? Integer.MIN_VALUE : best.getAmount();
- });
- return maximize(types, comp);
+
+ int max_val = 0;
+ ProductionType max_pt = null;
+ for (ProductionType pt : types) {
+ AbstractGoods best = pt.getBestOutputFor(goodsType);
+ if (best == null)
+ continue;
+
+ int x = best.getAmount();
+ if (x > max_val) {
+ max_val = x;
+ max_pt = pt;
+ }
+ }
+ return max_pt;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:21 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Unit.java | 51 ++++++++++++++++++++-----------
1 file changed, 34 insertions(+), 17 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index d20ac2928f6..5be31dd2bc9 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -2997,12 +2997,6 @@ public class Unit extends GoodsLocation
final Tile srcTile = getTile();
final Tile dstTile = dst.getTile();
final int dstCont = (dstTile == null) ? -1 : dstTile.getContiguity();
- final Comparator<Settlement> settlementComparator
- = cachingIntComparator(s -> {
- PathNode p = findPath(s);
- return (p == null) ? INFINITY
- : p.getTotalTurns() + dstTile.getDistanceTo(s.getTile());
- });

int type;
if (isNaval()) {
@@ -3047,20 +3041,43 @@ public class Unit extends GoodsLocation
case 2:
// Ocean travel required, destination blocked.
// Find the closest available connected port.
- final Predicate<Settlement> portPredicate = s ->
- s != ignoreSrc && s != ignoreDst;
- sett = minimize(getOwner().getPorts(), portPredicate,
- settlementComparator);
- path = (sett == null) ? null : this.findPath(sett);
+ sett = null;
+ path = null;
+ int sett_turns = INFINITY;
+ for (Settlement s : getOwner().getPorts()) {
+ if (!(s != ignoreSrc && s != ignoreDst)) continue;
+
+ PathNode p = findPath(s);
+ int turns = (p == null ? INFINITY
+ : p.getTotalTurns() + dstTile.getDistanceTo(s.getTile()));
+
+ if (sett == null || turns < sett_turns) {
+ sett = s;
+ sett_turns = turns;
+ path = p;
+ }
+ }
+
break;
case 3:
// Land travel. Find nearby settlement with correct contiguity.
- final Predicate<Settlement> contiguityPred = s ->
- s != ignoreSrc && s != ignoreDst
- && s.getTile().getContiguity() == dstCont;
- sett = minimize(getOwner().getSettlements(), contiguityPred,
- settlementComparator);
- path = (sett == null) ? null : this.findPath(sett);
+ sett = null;
+ path = null;
+ sett_turns = INFINITY;
+ for (Settlement s : getOwner().getSettlements()) {
+ if (!(s != ignoreSrc && s != ignoreDst && s.getTile().getContiguity() == dstCont))
+ continue;
+
+ PathNode p = findPath(s);
+ int turns = (p == null ? INFINITY
+ : p.getTotalTurns() + dstTile.getDistanceTo(s.getTile()));
+
+ if (sett == null || turns < sett_turns) {
+ sett = s;
+ sett_turns = turns;
+ path = p;
+ }
+ }
break;
}
return (path != null) ? path
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:17 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Colony.java | 31 ++++++++++++++++++-----------
1 file changed, 19 insertions(+), 12 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index 93c1a4ed575..df4d3e387ef 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -2045,18 +2045,25 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return True if the goods can be produced.
*/
public boolean canProduce(GoodsType goodsType) {
- return (getNetProductionOf(goodsType) > 0)
- ? true // Obviously:-)
-
- // Breeding requires the breedable number to be present
- : (goodsType.isBreedable())
- ? getGoodsCount(goodsType) >= goodsType.getBreedingNumber()
-
- // Is there a work location that can produce the goods, with
- // positive generic production potential and all inputs satisfied?
- : any(getWorkLocationsForProducing(goodsType),
- wl -> wl.getGenericPotential(goodsType) > 0
- && all(wl.getInputs(), ag -> canProduce(ag.getType())));
+ if (getNetProductionOf(goodsType) > 0) return true; // Obviously:-)
+
+ // Breeding requires the breedable number to be present
+ if (goodsType.isBreedable())
+ return getGoodsCount(goodsType) >= goodsType.getBreedingNumber();
+
+ // Is there a work location that can produce the goods, with
+ // positive generic production potential and all inputs satisfied?
+loop: for (WorkLocation wl : getWorkLocationsForProducing(goodsType)) {
+ if (wl.getGenericPotential(goodsType) > 0) {
+ for (AbstractGoods ag : wl.getInputs()) {
+ if (!canProduce(ag.getType()))
+ continue loop;
+ }
+ return true;
+ }
+ }
+
+ return false;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:05 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/BaseProduction.java | 3 +--
src/net/sf/freecol/common/model/ProductionType.java | 14 ++++++++++++++
2 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/src/net/sf/freecol/common/model/BaseProduction.java b/src/net/sf/freecol/common/model/BaseProduction.java
index d0f81ee0db8..7a4297f36f2 100644
--- a/src/net/sf/freecol/common/model/BaseProduction.java
+++ b/src/net/sf/freecol/common/model/BaseProduction.java
@@ -49,8 +49,7 @@ public interface BaseProduction {
getAvailableProductionTypes(unitType == null));
}
if (productionType == null) return 0;
- AbstractGoods best = productionType.getOutput(goodsType);
- return (best == null) ? 0 : best.getAmount();
+ return productionType.getOutputAmount(goodsType);
}

/**
diff --git a/src/net/sf/freecol/common/model/ProductionType.java b/src/net/sf/freecol/common/model/ProductionType.java
index a971b951d87..c5f965205bf 100644
--- a/src/net/sf/freecol/common/model/ProductionType.java
+++ b/src/net/sf/freecol/common/model/ProductionType.java
@@ -227,6 +227,20 @@ public class ProductionType extends FreeColSpecObject {
}

/**
+ * Get the amount of goods of the given goods type in this production type.
+ *
+ * @param goodsType The {@code GoodsType} to check.
+ * @return The {@code AbstractGoods} output amount if any, otherwise 0
+ */
+ public final int getOutputAmount(GoodsType goodsType) {
+ if (outputs == null)
+ return 0;
+
+ AbstractGoods g = AbstractGoods.findByType(outputs, goodsType);
+ return (g == null ? 0 : g.getAmount());
+ }
+
+ /**
* Get the type of the most productive output.
*
* @return The {@code GoodsType} of the most productive output.
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:30:50 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
data/strings/FreeColMessages_de.properties | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/data/strings/FreeColMessages_de.properties b/data/strings/FreeColMessages_de.properties
index 2aedb55bde5..0037200b875 100644
--- a/data/strings/FreeColMessages_de.properties
+++ b/data/strings/FreeColMessages_de.properties
@@ -2071,7 +2071,7 @@ model.monarch.action.monarchMercenaries.yes=Wir akzeptieren
model.monarch.action.raiseTaxAct.text=Die von illoyalen Kolonisten von %newWorld% ausgeführten Akte des Widerstands lassen Uns keine andere Wahl als ein neues {{tag:%number%|0=Navigations|1=Tee|2=Woll|3=Hut|4=Sirup|5=Präge}}gesetz einzuführen, das eure Steuer auf %amount%% anhebt. Sofern ihr nicht einverstanden seid, werden Wir gezwungen sein eure %goods% zu boykottieren.
model.monarch.action.raiseTaxAct.no=Gib mir Freiheit oder den Tod!
model.monarch.action.raiseTaxAct.yes=Wir akzeptieren
-model.monarch.action.raiseTaxWar.text=Wir bedauern Ihnen mitteilen zu müssen, dass Wir aufgrund der jüngsten Rückschläge im Krieg gegen {{tag:country|%nation%}} keine andere Wahl haben, als die Steuern auf %amount%% anzugeben. Sofern ihr nicht einverstanden seid, werden Wir gezwungen sein eure %goods% zu boykottieren.
+model.monarch.action.raiseTaxWar.text=Wir bedauern Ihnen mitteilen zu müssen, dass Wir aufgrund der jüngsten Rückschläge im Krieg gegen {{tag:country|%nation%}} keine andere Wahl haben, als die Steuern auf %amount%% anzuheben. Sofern ihr nicht einverstanden seid, werden Wir gezwungen sein eure %goods% zu boykottieren.
model.monarch.action.raiseTaxWar.no=Wir weisen die Besteuerung zurück!
model.monarch.action.raiseTaxWar.yes=Wir akzeptieren
model.monarch.action.supportLand.text=Um Euch bei Euren kolonialen Kriegen zu unterstützen, hat sich die Krone dazu entschlossen, Euch einige erfahrene Truppen zur Verfügung zu stellen (%addition%).
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:00 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../sf/freecol/common/util/CollectionUtils.java | 26 ----------------------
1 file changed, 26 deletions(-)

diff --git a/src/net/sf/freecol/common/util/CollectionUtils.java b/src/net/sf/freecol/common/util/CollectionUtils.java
index 1a265516d81..03a7cf47c7f 100644
--- a/src/net/sf/freecol/common/util/CollectionUtils.java
+++ b/src/net/sf/freecol/common/util/CollectionUtils.java
@@ -733,32 +733,6 @@ public class CollectionUtils {
}

/**
- * Create a stream of files from a directory.
- *
- * @param dir The {@code File} that hopefully is a directory.
- * @return A stream of {@code File}s.
- */
- public static Stream<File> fileStream(File dir) {
- File[] files;
- return (dir == null || !dir.isDirectory()
- || (files = dir.listFiles()) == null)
- ? Stream.<File>empty()
- : Arrays.stream(files);
- }
-
- /**
- * Create a stream of files from a directory, that each match a predicate.
- *
- * @param dir The {@code File} that hopefully is a directory.
- * @param predicate The {@code Predicate} to match with.
- * @return A stream of matching {@code File}s.
- */
- public static Stream<File> fileStream(File dir,
- Predicate<? super File> predicate) {
- return fileStream(dir).filter(predicate);
- }
-
- /**
* Simple stream search for the first item that matches a predicate.
*
* @param <T> The array member type.
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:09 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Player.java | 4 +--
src/net/sf/freecol/common/model/UnitIterator.java | 41 ++++++++++++++---------
2 files changed, 28 insertions(+), 17 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Player.java b/src/net/sf/freecol/common/model/Player.java
index 0da6e80228f..cd2a584bc1f 100644
--- a/src/net/sf/freecol/common/model/Player.java
+++ b/src/net/sf/freecol/common/model/Player.java
@@ -359,11 +359,11 @@ public class Player extends FreeColGameObject implements Nameable {

/** An iterator for the player units that are still active this turn. */
private final UnitIterator nextActiveUnitIterator
- = new UnitIterator(this, Unit::couldMove);
+ = new UnitIterator(this, UnitIterator.Type.ACTIVE);

/** An iterator for the player units that have a destination to go to. */
private final UnitIterator nextGoingToUnitIterator
- = new UnitIterator(this, Unit::goingToDestination);
+ = new UnitIterator(this, UnitIterator.Type.GOING_TO);

/**
* The HighSeas is a Location that enables Units to travel between
diff --git a/src/net/sf/freecol/common/model/UnitIterator.java b/src/net/sf/freecol/common/model/UnitIterator.java
index 597fc22786f..9b14a6988ae 100644
--- a/src/net/sf/freecol/common/model/UnitIterator.java
+++ b/src/net/sf/freecol/common/model/UnitIterator.java
@@ -21,26 +21,27 @@ package net.sf.freecol.common.model;

import java.util.ArrayList;
import java.util.Collections;
+import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
-import java.util.function.Function;
-import java.util.function.Predicate;
-
-import javax.xml.stream.XMLStreamException;

import static net.sf.freecol.common.util.CollectionUtils.*;

-
/**
* An {@code Iterator} of {@link Unit}s that can be made active.
*/
public class UnitIterator implements Iterator<Unit> {

+ public enum Type {
+ ACTIVE,
+ GOING_TO
+ };
+
/** The player that owns the units. */
private final Player owner;

- /** The admission predicate. */
- private final Predicate<Unit> predicate;
+ /** The admission type. */
+ private final Type type;

/** The current cache of units. */
private final List<Unit> units = new ArrayList<>();
@@ -51,16 +52,23 @@ public class UnitIterator implements Iterator<Unit> {
*
* @param owner The {@code Player} that needs an iterator
* of it's units.
- * @param predicate A {@code Predicate} for deciding
+ * @param type the iterator's {@code Type} for deciding
* whether a {@code Unit} should be included in the
* {@code Iterator} or not.
*/
- public UnitIterator(Player owner, Predicate<Unit> predicate) {
+ public UnitIterator(Player owner, Type t) {
+ this.type = t;
this.owner = owner;
- this.predicate = predicate;
update();
}

+ private boolean testUnit(Unit u) {
+ switch (type) {
+ case ACTIVE: return u.couldMove();
+ case GOING_TO: return u.goingToDestination();
+ }
+ return false;
+ }

/**
* Update the internal units list with units that satisfy the
@@ -68,8 +76,11 @@ public class UnitIterator implements Iterator<Unit> {
*/
private final void update() {
this.units.clear();
- this.units.addAll(transform(owner.getUnits(), u -> predicate.test(u),
- Function.identity(), Unit.locComparator));
+ for (Unit u : owner.getUnits())
+ if (testUnit(u))
+ this.units.add(u);
+
+ Collections.sort(units, Unit.locComparator);
}

/**
@@ -79,7 +90,7 @@ public class UnitIterator implements Iterator<Unit> {
* @return True if the operation succeeds.
*/
public boolean setNext(Unit unit) {
- if (this.predicate.test(unit)) { // Of course, it has to be valid...
+ if (testUnit(unit)) { // Of course, it has to be valid...
final Unit sentinel = first(this.units);
while (!this.units.isEmpty()) {
if (this.units.get(0) == unit) return true;
@@ -119,9 +130,9 @@ public class UnitIterator implements Iterator<Unit> {
*/
@Override
public boolean hasNext() {
- // Try to find a unit that still satisfies the predicate.
+ // Try to find a unit that still satisfies the condition.
while (!this.units.isEmpty()) {
- if (predicate.test(this.units.get(0))) {
+ if (testUnit(this.units.get(0))) {
return true; // Still valid
}
this.units.remove(0);
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:30:55 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../sf/freecol/common/io/FreeColDirectories.java | 71 ++++++++++++----------
src/net/sf/freecol/tools/SaveGameValidator.java | 2 +-
2 files changed, 41 insertions(+), 32 deletions(-)

diff --git a/src/net/sf/freecol/common/io/FreeColDirectories.java b/src/net/sf/freecol/common/io/FreeColDirectories.java
index 901d06c5fe6..09432988dfb 100644
--- a/src/net/sf/freecol/common/io/FreeColDirectories.java
+++ b/src/net/sf/freecol/common/io/FreeColDirectories.java
@@ -50,9 +50,6 @@ public class FreeColDirectories {
// No logger! Many of these routines are called before logging is
// initialized.

- private static final Comparator<File> fileModificationComparator
- = Comparator.comparingLong(File::lastModified);
-
private static final Comparator<File> fileNameComparator
= Comparator.comparing(File::getName);

@@ -141,14 +138,6 @@ public class FreeColDirectories {
Utils.fileAnySuffix(f, MOD_FILE_SUFFIX, ZIP_FILE_SUFFIX)
|| Utils.directoryAllPresent(f, MOD_DESCRIPTOR_FILE_NAME);

- /**
- * Predicate to select readable files that look like saved games.
- * Public for SaveGameValidator.
- */
- public static final Predicate<File> saveGameFilter = f ->
- f.isFile() && f.canRead()
- && f.getName().endsWith(SAVE_GAME_SUFFIX);
-
/** Predicate to filter suitable candidates to be made into TCs. */
private static final Predicate<File> tcFileFilter = f ->
Utils.fileAnySuffix(f, TC_FILE_SUFFIX, ZIP_FILE_SUFFIX)
@@ -977,15 +966,18 @@ public class FreeColDirectories {
return new File(getDataDirectory(), MAPS_DIRECTORY);
}

+ public static boolean checkSavegameFile(File f) {
+ return f.isFile() && f.canRead()
+ && f.getName().endsWith(SAVE_GAME_SUFFIX);
+ }
+
/**
* Get the map files.
*
* @return A list of map files, or null on error.
*/
public static List<File> getMapFileList() {
- final File mapsDirectory = getMapsDirectory();
- return (mapsDirectory == null || !mapsDirectory.isDirectory()) ? null
- : collectFiles(mapsDirectory, saveGameFilter);
+ return getSavegameFileList(getMapsDirectory());
}

/**
@@ -1093,24 +1085,19 @@ public class FreeColDirectories {
* Gets the save game files in a given directory.
*
* @param directory The base directory, or the default locations if null.
- * @return A stream of save game {@code File}s.
- */
- public static Stream<File> getSavegameFiles(File directory) {
- return (directory == null)
- ? flatten(Stream.of(FreeColDirectories.getSaveDirectory(),
- FreeColDirectories.getAutosaveDirectory()),
- d -> fileStream(d, saveGameFilter))
- : fileStream(directory, saveGameFilter);
- }
-
- /**
- * Gets the save game files in a given directory.
- *
- * @param directory The base directory, or the default locations if null.
* @return A list of save game {@code File}s.
*/
public static List<File> getSavegameFileList(File directory) {
- return toList(getSavegameFiles(directory));
+ if ((directory == null) || (!directory.isDirectory()))
+ return Collections.<File>emptyList();
+
+ List<File> result = new ArrayList<>();
+ for (File walk : directory.listFiles())
+ if (checkSavegameFile(walk))
+ result.add(walk);
+
+ Collections.sort(result);
+ return result;
}

/**
@@ -1141,8 +1128,30 @@ public class FreeColDirectories {
* @return The recent save game {@code File}, or null if not found.
*/
public static File getLastSaveGameFile() {
- return maximize(getSavegameFiles(null),
- fileModificationComparator);
+ long last_mtime = -1;
+ File last_file = null;
+
+ for (File walk : getSaveDirectory().listFiles()) {
+ if (checkSavegameFile(walk)) {
+ long mtime = walk.lastModified();
+ if (mtime > last_mtime) {
+ last_mtime = mtime;
+ last_file = walk;
+ }
+ }
+ }
+
+ for (File walk : getAutosaveDirectory().listFiles()) {
+ if (checkSavegameFile(walk)) {
+ long mtime = walk.lastModified();
+ if (mtime > last_mtime) {
+ last_mtime = mtime;
+ last_file = walk;
+ }
+ }
+ }
+
+ return last_file;
}

/**
diff --git a/src/net/sf/freecol/tools/SaveGameValidator.java b/src/net/sf/freecol/tools/SaveGameValidator.java
index 936b56f33d7..ee0323a34b4 100644
--- a/src/net/sf/freecol/tools/SaveGameValidator.java
+++ b/src/net/sf/freecol/tools/SaveGameValidator.java
@@ -55,7 +55,7 @@ public class SaveGameValidator {
if (file.exists()) {
if (file.isDirectory()) {
allFiles.addAll(FreeColDirectories.getSavegameFileList(file));
- } else if (FreeColDirectories.saveGameFilter.test(file)) {
+ } else if (FreeColDirectories.checkSavegameFile(file)) {
allFiles.add(file);
}
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:03 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../freecol/client/control/InGameController.java | 4 +-
.../gui/panel/colopedia/GoodsDetailPanel.java | 2 +-
.../gui/panel/report/ReportCompactColonyPanel.java | 6 +--
src/net/sf/freecol/common/model/AbstractGoods.java | 63 ++++++++++++++++++----
src/net/sf/freecol/common/model/BuildQueue.java | 2 +-
src/net/sf/freecol/common/model/Building.java | 2 +-
src/net/sf/freecol/common/model/Colony.java | 7 ++-
.../sf/freecol/common/model/ProductionCache.java | 6 +--
.../sf/freecol/common/model/ProductionInfo.java | 6 +--
src/net/sf/freecol/common/model/ProductionMap.java | 6 +--
.../sf/freecol/common/model/ProductionType.java | 2 +-
src/net/sf/freecol/common/model/Role.java | 2 +-
.../sf/freecol/common/model/TradeRouteStop.java | 11 ++--
src/net/sf/freecol/common/model/WorkLocation.java | 6 +--
src/net/sf/freecol/server/model/ServerColony.java | 15 ++++--
.../sf/freecol/server/model/ServerColonyTest.java | 3 +-
16 files changed, 93 insertions(+), 50 deletions(-)

diff --git a/src/net/sf/freecol/client/control/InGameController.java b/src/net/sf/freecol/client/control/InGameController.java
index b164c8ce020..9d2f6239f91 100644
--- a/src/net/sf/freecol/client/control/InGameController.java
+++ b/src/net/sf/freecol/client/control/InGameController.java
@@ -1958,7 +1958,7 @@ public final class InGameController extends FreeColClientHolder {
// failed somewhere). If it is expected to load, reduce the
// loading amount by what is already on board.
for (Goods g : unit.getCompactGoods()) {
- AbstractGoods ag = find(toLoad, AbstractGoods.matches(g.getType()));
+ AbstractGoods ag = AbstractGoods.findByType(toLoad, g.getType());
if (ag == null) { // Excess goods on board, failed unload?
unexpected.addStringTemplate(g.getLabel());
} else {
@@ -2006,7 +2006,7 @@ public final class InGameController extends FreeColClientHolder {
turns += unit.getTurnsToReach(start, trs.getLocation());
int amountIn = trs.getImportAmount(type, turns),
amountOut = trs.getExportAmount(type, turns);
- if (none(trs.getCompactCargo(), AbstractGoods.matches(type))
+ if ((AbstractGoods.findByType(trs.getCompactCargo(),type) == null)
|| amountIn > amountOut) {
importAmount = amountIn;
unload = trs;
diff --git a/src/net/sf/freecol/client/gui/panel/colopedia/GoodsDetailPanel.java b/src/net/sf/freecol/client/gui/panel/colopedia/GoodsDetailPanel.java
index 9bc0e48c047..22268485a75 100644
--- a/src/net/sf/freecol/client/gui/panel/colopedia/GoodsDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/colopedia/GoodsDetailPanel.java
@@ -216,7 +216,7 @@ public class GoodsDetailPanel extends ColopediaGameObjectTypePanel<GoodsType> {
boolean result = false;
for (T bt : input) {
if (bt.needsGoodsToBuild()
- && any(bt.getRequiredGoods(), AbstractGoods.matches(type))) {
+ && AbstractGoods.anyIsType(bt.getRequiredGoods(), type)) {
output.add(bt);
result = true;
}
diff --git a/src/net/sf/freecol/client/gui/panel/report/ReportCompactColonyPanel.java b/src/net/sf/freecol/client/gui/panel/report/ReportCompactColonyPanel.java
index e9b87d002ef..9d046717dfa 100644
--- a/src/net/sf/freecol/client/gui/panel/report/ReportCompactColonyPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/report/ReportCompactColonyPanel.java
@@ -291,8 +291,7 @@ public final class ReportCompactColonyPanel extends ReportPanel
for (WorkLocation wl : colony.getWorkLocationsForProducing(goodsType)) {
ProductionInfo pi = colony.getProductionInfo(wl);
if (pi == null) continue;
- deficit = find(pi.getConsumptionDeficit(),
- AbstractGoods.matches(goodsType));
+ deficit = AbstractGoods.findByType(pi.getConsumptionDeficit(), goodsType);
if (deficit != null) {
status = ProductionStatus.CONSUMPTION;
extra = deficit.getAmount();
@@ -317,8 +316,7 @@ public final class ReportCompactColonyPanel extends ReportPanel
for (WorkLocation wl : colony.getWorkLocationsForProducing(goodsType)) {
ProductionInfo pi = colony.getProductionInfo(wl);
if (pi == null) continue;
- deficit = find(pi.getProductionDeficit(),
- AbstractGoods.matches(goodsType));
+ deficit = AbstractGoods.findByType(pi.getProductionDeficit(),goodsType);
if (deficit != null) {
status = ProductionStatus.PRODUCTION;
extra = deficit.getAmount();
diff --git a/src/net/sf/freecol/common/model/AbstractGoods.java b/src/net/sf/freecol/common/model/AbstractGoods.java
index 638588568ff..5d2e67ca790 100644
--- a/src/net/sf/freecol/common/model/AbstractGoods.java
+++ b/src/net/sf/freecol/common/model/AbstractGoods.java
@@ -19,9 +19,8 @@

package net.sf.freecol.common.model;

-import java.util.Collection;
import java.util.Comparator;
-import java.util.function.Predicate;
+import java.util.List;

import net.sf.freecol.common.model.GoodsType;
import static net.sf.freecol.common.util.CollectionUtils.*;
@@ -207,8 +206,8 @@ public class AbstractGoods extends FreeColObject implements Named {
* @return The goods count found, or zero if not found.
*/
public static int getCount(GoodsType type,
- Collection<? extends AbstractGoods> goods) {
- AbstractGoods ag = find(goods, matches(type));
+ List<? extends AbstractGoods> goods) {
+ AbstractGoods ag = AbstractGoods.findByType(goods, type);
return (ag == null) ? 0 : ag.getAmount();
}

@@ -225,15 +224,61 @@ public class AbstractGoods extends FreeColObject implements Named {
}

/**
- * A predicate maker to match by type.
+ * Check whether it is of the given {@link GoodsType}
*
- * @param key The key of type {@link GoodsType}
- * @return A suitable {@code Predicate}.
+ * @param gt The {@link GoodsType} to match against
+ * @return True if matching
*/
- public static final Predicate<? super AbstractGoods> matches(final GoodsType key) {
- return matchKey(key, AbstractGoods::getType);
+ public final boolean isType(GoodsType gt) {
+ if ((gt == null) || (type == null))
+ return false;
+
+ return (type == gt || type.equals(gt));
}

+ /**
+ * Check whether any in the list is of given {@link GoodsType}
+ */
+ public static boolean anyIsType(List<AbstractGoods> l, GoodsType gt) {
+ if (l != null)
+ for (AbstractGoods ag : l)
+ if (ag.isType(gt))
+ return true;
+
+ return false;
+ }
+
+ /**
+ * find any in list by type
+ */
+ public static AbstractGoods findByType(List<AbstractGoods> l, GoodsType gt) {
+ if (l != null)
+ for (AbstractGoods ag : l)
+ if (ag.getType() == gt)
+ return ag;
+
+ return false;
+ }
+
+ public static AbstractGoods findByType(List<AbstractGoods> l, AbstractGoods ag) {
+ return findByType(l, ag.getType());
+ }
+
+ /**
+ * find any in list by type
+ */
+ public static AbstractGoods findByType(List<AbstractGoods> l, GoodsType gt) {
+ if (l != null)
+ for (AbstractGoods ag : l)
+ if (ag.getType() == gt)
+ return ag;
+
+ return null;
+ }
+
+ public static AbstractGoods findByType(List<AbstractGoods> l, AbstractGoods ag) {
+ return findByType(l, ag.getType());
+ }

// Interface Named

diff --git a/src/net/sf/freecol/common/model/BuildQueue.java b/src/net/sf/freecol/common/model/BuildQueue.java
index 2614bcb29bb..b003844671e 100644
--- a/src/net/sf/freecol/common/model/BuildQueue.java
+++ b/src/net/sf/freecol/common/model/BuildQueue.java
@@ -169,7 +169,7 @@ public class BuildQueue<T extends BuildableType> implements Consumer {
.getBoolean(GameOptions.SAVE_PRODUCTION_OVERFLOW);
List<AbstractGoods> consumption = new ArrayList<>();
for (AbstractGoods ag : current.getRequiredGoodsList()) {
- AbstractGoods available = find(input, AbstractGoods.matches(ag.getType()));
+ AbstractGoods available = AbstractGoods.findByType(input, ag);
if (available != null
&& ag.getAmount() <= available.getAmount()) {
int amount = (overflow || ag.getType().isStorable())
diff --git a/src/net/sf/freecol/common/model/Building.java b/src/net/sf/freecol/common/model/Building.java
index b3774d3ffa9..aa6954a9085 100644
--- a/src/net/sf/freecol/common/model/Building.java
+++ b/src/net/sf/freecol/common/model/Building.java
@@ -473,7 +473,7 @@ public class Building extends WorkLocation
return true;
} else if (colony.getTotalProductionOf(goodsType) == 0
&& (bt = colony.getCurrentlyBuilding()) != null
- && any(bt.getRequiredGoods(), AbstractGoods.matches(goodsType))) {
+ && AbstractGoods.anyIsType(bt.getRequiredGoods(), goodsType)) {
return true;
}
}
diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index c9a05fd50cc..8d6851870b8 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -721,7 +721,7 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*/
public List<WorkLocation> getWorkLocationsForConsuming(GoodsType goodsType) {
return transform(getCurrentWorkLocations(),
- wl -> any(wl.getInputs(), AbstractGoods.matches(goodsType)));
+ wl -> AbstractGoods.anyIsType(wl.getInputs(), goodsType));
}

/**
@@ -733,7 +733,7 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*/
public List<WorkLocation> getWorkLocationsForProducing(GoodsType goodsType) {
return transform(getCurrentWorkLocations(),
- wl -> any(wl.getOutputs(), AbstractGoods.matches(goodsType)));
+ wl -> AbstractGoods.anyIsType(wl.getOutputs(), goodsType));
}

/**
@@ -904,8 +904,7 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
}
int production = productionCache.getNetProductionOf(type);
if (info != null) {
- AbstractGoods consumption = find(info.getConsumption(),
- AbstractGoods.matches(type));
+ AbstractGoods consumption = AbstractGoods.findByType(info.getConsumption(), type);
if (consumption != null) {
// add the amount the build queue itself will consume
production += consumption.getAmount();
diff --git a/src/net/sf/freecol/common/model/ProductionCache.java b/src/net/sf/freecol/common/model/ProductionCache.java
index 6250481df56..38433c0329f 100644
--- a/src/net/sf/freecol/common/model/ProductionCache.java
+++ b/src/net/sf/freecol/common/model/ProductionCache.java
@@ -224,8 +224,7 @@ public class ProductionCache {
public boolean isProducing(GoodsType goodsType) {
update();
return any(productionAndConsumption.values(),
- pi -> any(pi.getProduction(),
- AbstractGoods.matches(goodsType)));
+ pi -> AbstractGoods.anyIsType(pi.getProduction(), goodsType));
}

/**
@@ -237,8 +236,7 @@ public class ProductionCache {
public boolean isConsuming(GoodsType goodsType) {
update();
return any(productionAndConsumption.values(),
- pi -> any(pi.getConsumption(),
- AbstractGoods.matches(goodsType)));
+ pi -> AbstractGoods.anyIsType(pi.getConsumption(), goodsType));
}

/**
diff --git a/src/net/sf/freecol/common/model/ProductionInfo.java b/src/net/sf/freecol/common/model/ProductionInfo.java
index 0636cd50ac8..f330824da3c 100644
--- a/src/net/sf/freecol/common/model/ProductionInfo.java
+++ b/src/net/sf/freecol/common/model/ProductionInfo.java
@@ -92,8 +92,7 @@ public class ProductionInfo {
*/
public List<AbstractGoods> getProductionDeficit() {
final Function<AbstractGoods, AbstractGoods> mapper = ag -> {
- AbstractGoods agMax = find(this.maximumProduction,
- AbstractGoods.matches(ag.getType()));
+ AbstractGoods agMax = AbstractGoods.findByType(this.maximumProduction, ag);
int amount = (agMax == null) ? 0
: agMax.getAmount() - ag.getAmount();
return (amount <= 0) ? null
@@ -112,8 +111,7 @@ public class ProductionInfo {
*/
public List<AbstractGoods> getConsumptionDeficit() {
final Function<AbstractGoods, AbstractGoods> mapper = ag -> {
- AbstractGoods agMax = find(this.maximumConsumption,
- AbstractGoods.matches(ag.getType()));
+ AbstractGoods agMax = AbstractGoods.findByType(this.maximumConsumption, ag);
int amount = (agMax == null) ? 0
: agMax.getAmount() - ag.getAmount();
return (amount == 0) ? null
diff --git a/src/net/sf/freecol/common/model/ProductionMap.java b/src/net/sf/freecol/common/model/ProductionMap.java
index 271830369f5..6ee70f33efe 100644
--- a/src/net/sf/freecol/common/model/ProductionMap.java
+++ b/src/net/sf/freecol/common/model/ProductionMap.java
@@ -82,7 +82,7 @@ public class ProductionMap {
throw new IllegalArgumentException(goods.getType().getId() + " is not stored as "
+ root.getType());
} else {
- AbstractGoods leaf = find(leafs, AbstractGoods.matches(goods.getType()));
+ AbstractGoods leaf = AbstractGoods.findByType(leafs, goods.getType());
if (leaf != null) {
leaf.setAmount(leaf.getAmount() + goods.getAmount());
root.setAmount(root.getAmount() + goods.getAmount());
@@ -101,7 +101,7 @@ public class ProductionMap {
leaf.setAmount(Math.min(leaf.getAmount(), root.getAmount()));
}
} else {
- AbstractGoods leaf = find(leafs, AbstractGoods.matches(goods.getType()));
+ AbstractGoods leaf = AbstractGoods.findByType(leafs, goods.getType());
if (leaf != null) {
leaf.setAmount(leaf.getAmount() - consumed);
root.setAmount(root.getAmount() - consumed);
@@ -114,7 +114,7 @@ public class ProductionMap {
if (root.getType() == type) {
return root;
} else {
- AbstractGoods leaf = find(leafs, AbstractGoods.matches(type));
+ AbstractGoods leaf = AbstractGoods.findByType(leafs, type);
if (leaf != null) {
return new AbstractGoods(type, leaf.getAmount());
}
diff --git a/src/net/sf/freecol/common/model/ProductionType.java b/src/net/sf/freecol/common/model/ProductionType.java
index f6a769de9c0..a971b951d87 100644
--- a/src/net/sf/freecol/common/model/ProductionType.java
+++ b/src/net/sf/freecol/common/model/ProductionType.java
@@ -223,7 +223,7 @@ public class ProductionType extends FreeColSpecObject {
*/
public AbstractGoods getOutput(GoodsType goodsType) {
return (outputs == null) ? null
- : find(outputs, AbstractGoods.matches(goodsType));
+ : AbstractGoods.findByType(outputs, goodsType);
}

/**
diff --git a/src/net/sf/freecol/common/model/Role.java b/src/net/sf/freecol/common/model/Role.java
index 164faf659b9..4eb33ed7e7b 100644
--- a/src/net/sf/freecol/common/model/Role.java
+++ b/src/net/sf/freecol/common/model/Role.java
@@ -366,7 +366,7 @@ public class Role extends BuildableType {
}
}
result.addAll(transform(fromGoods,
- ag -> !any(toGoods, AbstractGoods.matches(ag.getType())),
+ ag -> !AbstractGoods.anyIsType(toGoods, ag.getType()),
ag -> new AbstractGoods(ag.getType(), -ag.getAmount())));
}
return result;
diff --git a/src/net/sf/freecol/common/model/TradeRouteStop.java b/src/net/sf/freecol/common/model/TradeRouteStop.java
index 844fcb8254c..aeccb14ad33 100644
--- a/src/net/sf/freecol/common/model/TradeRouteStop.java
+++ b/src/net/sf/freecol/common/model/TradeRouteStop.java
@@ -164,7 +164,7 @@ public class TradeRouteStop extends FreeColGameObject implements TradeLocation {
public List<AbstractGoods> getCompactCargo() {
List<AbstractGoods> result = new ArrayList<>();
for (GoodsType type : getCargo()) {
- AbstractGoods ag = find(result, AbstractGoods.matches(type));
+ AbstractGoods ag = AbstractGoods.findByType(result, type);
if (ag != null) {
ag.setAmount(ag.getAmount() + GoodsContainer.CARGO_SIZE);
} else {
@@ -218,10 +218,11 @@ public class TradeRouteStop extends FreeColGameObject implements TradeLocation {
// Look for goods to unload.
// For all goods the unit has loaded, and if the type of goods
// is not to be loaded here, and there is demand here, return true.
- final Predicate<Goods> unloadPred = g ->
- !any(stopGoods, AbstractGoods.matches(g.getType()))
- && getImportAmount(g.getType(), turns) > 0;
- if (any(unit.getCompactGoodsList(), unloadPred)) return true;
+ for (AbstractGoods g : stopGoods) {
+ GoodsType gt = g.getType();
+ if (!AbstractGoods.anyIsType(stopGoods, gt) && getImportAmount(gt, turns) > 0)
+ return true;
+ }

return false; // Otherwise no work here.
}
diff --git a/src/net/sf/freecol/common/model/WorkLocation.java b/src/net/sf/freecol/common/model/WorkLocation.java
index c76c2f5a35c..40d69537f04 100644
--- a/src/net/sf/freecol/common/model/WorkLocation.java
+++ b/src/net/sf/freecol/common/model/WorkLocation.java
@@ -435,7 +435,7 @@ public abstract class WorkLocation extends UnitLocation
* given {@code GoodsType}.
*/
public boolean produces(GoodsType goodsType) {
- return any(getOutputs(), AbstractGoods.matches(goodsType));
+ return AbstractGoods.anyIsType(getOutputs(), goodsType);
}

/**
@@ -521,7 +521,7 @@ public abstract class WorkLocation extends UnitLocation
if (info == null) return 0;
List<AbstractGoods> production = info.getMaximumProduction();
if (production != null) {
- AbstractGoods ag = find(production, AbstractGoods.matches(goodsType));
+ AbstractGoods ag = AbstractGoods.findByType(production, goodsType);
if (ag != null) return ag.getAmount();
}
return getTotalProductionOf(goodsType);
@@ -650,7 +650,7 @@ public abstract class WorkLocation extends UnitLocation
public AbstractGoods getProductionDeficit(GoodsType goodsType) {
ProductionInfo pi = getProductionInfo();
return (pi == null) ? null
- : find(pi.getProductionDeficit(), AbstractGoods.matches(goodsType));
+ : AbstractGoods.findByType(pi.getProductionDeficit(), goodsType);
}


diff --git a/src/net/sf/freecol/server/model/ServerColony.java b/src/net/sf/freecol/server/model/ServerColony.java
index 834c8b7c6ae..5c047e3c631 100644
--- a/src/net/sf/freecol/server/model/ServerColony.java
+++ b/src/net/sf/freecol/server/model/ServerColony.java
@@ -135,11 +135,16 @@ public class ServerColony extends Colony implements ServerModelObject {
*/
private boolean neededForBuildableType(GoodsType goodsType) {
final Specification spec = getSpecification();
- List<BuildableType> buildables = new ArrayList<>();
- buildables.addAll(spec.getBuildingTypeList());
- buildables.addAll(spec.getUnitTypesWithoutAbility(Ability.PERSON));
- return any(buildables, bt -> canBuild(bt)
- && any(bt.getRequiredGoods(), AbstractGoods.matches(goodsType)));
+
+ for (BuildableType bt : spec.getBuildingTypeList())
+ if (canBuild(bt) && AbstractGoods.anyIsType(bt.getRequiredGoods(), goodsType))
+ return true;
+
+ for (BuildableType bt : spec.getUnitTypesWithoutAbility(Ability.PERSON))
+ if (canBuild(bt) && AbstractGoods.anyIsType(bt.getRequiredGoods(), goodsType))
+ return true;
+
+ return false;
}

/**
diff --git a/test/src/net/sf/freecol/server/model/ServerColonyTest.java b/test/src/net/sf/freecol/server/model/ServerColonyTest.java
index e4c82f9f04e..b689d5a459b 100644
--- a/test/src/net/sf/freecol/server/model/ServerColonyTest.java
+++ b/test/src/net/sf/freecol/server/model/ServerColonyTest.java
@@ -121,8 +121,7 @@ public class ServerColonyTest extends FreeColTestCase {
// Set the food production of the center tile of the colony to 2
// This will be the only food production of the colony
AbstractGoods foodGoods
- = first(transform(colonyTile.getType().getPossibleProduction(true),
- AbstractGoods.matches(foodGoodsType)));
+ = AbstractGoods.findByType(colonyTile.getType().getPossibleProduction(true),foodGoodsType);
if (foodGoods != null) foodGoods.setAmount(2);

Unit unit = colony.getUnitList().get(0);
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:19 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../sf/freecol/client/gui/panel/ColonyPanel.java | 2 +-
.../freecol/client/gui/panel/QuickActionMenu.java | 2 +-
src/net/sf/freecol/common/model/Colony.java | 170 ++++++++++++++++-----
.../sf/freecol/common/model/ProductionType.java | 12 ++
src/net/sf/freecol/common/model/WorkLocation.java | 7 +
src/net/sf/freecol/server/ai/ColonyPlan.java | 4 +-
src/net/sf/freecol/server/ai/mission/Mission.java | 2 +-
src/net/sf/freecol/server/model/ServerColony.java | 11 +-
.../net/sf/freecol/common/model/ColonyTest.java | 2 +-
9 files changed, 165 insertions(+), 47 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/panel/ColonyPanel.java b/src/net/sf/freecol/client/gui/panel/ColonyPanel.java
index 4e4887b05b8..03a46e7f8bc 100644
--- a/src/net/sf/freecol/client/gui/panel/ColonyPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ColonyPanel.java
@@ -614,7 +614,7 @@ public final class ColonyPanel extends PortPanel
if (colony == null) return;

// Check for non-producing locations that can now produce.
- for (WorkLocation wl : colony.getCurrentWorkLocationsList()) {
+ for (WorkLocation wl : colony.getCurrentWorkLocations()) {
boolean change = false, check = wl.getProductionType() == null;
for (Unit unit : transform(wl.getUnits(), u ->
(check || !wl.produces(u.getWorkType())))) {
diff --git a/src/net/sf/freecol/client/gui/panel/QuickActionMenu.java b/src/net/sf/freecol/client/gui/panel/QuickActionMenu.java
index 8e59b38087b..62c7de17e91 100644
--- a/src/net/sf/freecol/client/gui/panel/QuickActionMenu.java
+++ b/src/net/sf/freecol/client/gui/panel/QuickActionMenu.java
@@ -333,7 +333,7 @@ public final class QuickActionMenu extends JPopupMenu {
int bestOwnedProd = bonus + bonusChange,
bestUnownedProd = bonus + bonusChange;
WorkLocation bestOwned = null, bestUnowned = null;
- for (WorkLocation wl : colony.getAllWorkLocationsList()) {
+ for (WorkLocation wl : colony.getAllWorkLocations()) {
int prod = 0;
switch (wl.getNoAddReason(unit)) {
case NONE:
diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index a84496bbe5e..a71c95ad293 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -47,7 +47,7 @@ import static net.sf.freecol.common.util.CollectionUtils.*;
import net.sf.freecol.common.option.GameOptions;
import net.sf.freecol.common.util.LogBuilder;
import net.sf.freecol.common.util.RandomChoice;
-
+import net.sf.freecol.common.util.Utils;

/**
* Represents a colony. A colony contains {@link Building}s and
@@ -455,7 +455,7 @@ public class Colony extends Settlement implements Nameable, TradeLocation {

Occupation best = new Occupation(null, null, null);
int bestAmount = 0;
- for (WorkLocation wl : getCurrentWorkLocationsList()) {
+ for (WorkLocation wl : getCurrentWorkLocations()) {
bestAmount = best.improve(unit, wl, bestAmount, workTypes, lb);
}

@@ -538,7 +538,7 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*
* @return The list of work locations.
*/
- public List<WorkLocation> getAllWorkLocationsList() {
+ public List<WorkLocation> getAllWorkLocations() {
List<WorkLocation> ret = new ArrayList<>();
synchronized (this.colonyTiles) {
ret.addAll(this.colonyTiles);
@@ -550,19 +550,22 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
}

/**
- * Gets a stream of every work location in this colony.
+ * Gets a list of every work location in this colony.
*
- * @return The stream of work locations.
+ * @return The list of work locations.
*/
- public Stream<WorkLocation> getAllWorkLocations() {
- Stream<WorkLocation> ret = Stream.<WorkLocation>empty();
+ public WorkLocation findWorkLocationById(String id) {
synchronized (this.colonyTiles) {
- ret = concat(ret, map(this.colonyTiles, ct -> (WorkLocation)ct));
+ for (ColonyTile walk : this.colonyTiles)
+ if (Utils.equals(id, walk.getId()))
+ return walk;
}
synchronized (this.buildingMap) {
- ret = concat(ret, map(this.buildingMap.values(), b -> (WorkLocation)b));
+ for (Building walk : this.buildingMap.values())
+ if (Utils.equals(id, walk.getId()))
+ return walk;
}
- return ret;
+ return null;
}

/**
@@ -571,36 +574,82 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*
* @return The list of available {@code WorkLocation}s.
*/
- public List<WorkLocation> getAvailableWorkLocationsList() {
- return transform(getAllWorkLocations(), WorkLocation::isAvailable);
+ public int countAvailableWorkLocations() {
+ int result = 0;
+ synchronized (this.colonyTiles) {
+ for (ColonyTile walk : this.colonyTiles)
+ if (walk.isAvailable())
+ result++;
+ }
+ synchronized (this.buildingMap) {
+ for (Building walk : this.buildingMap.values())
+ if (walk.isAvailable())
+ result++;
+ }
+ return result;
}

/**
- * Get a stream of all freely available work locations in this
- * colony.
+ * Count the freely available work locations in this colony.
*
- * @return The stream of available {@code WorkLocation}s.
+ * @return The list of available {@code WorkLocation}s.
*/
- public Stream<WorkLocation> getAvailableWorkLocations() {
- return getAvailableWorkLocationsList().stream();
+ public List<WorkLocation> getAvailableWorkLocations() {
+ List<WorkLocation> result = new ArrayList<>();
+ synchronized (this.colonyTiles) {
+ for (ColonyTile walk : this.colonyTiles)
+ if (walk.isAvailable())
+ result.add(walk);
+ }
+ synchronized (this.buildingMap) {
+ for (Building walk : this.buildingMap.values())
+ if (walk.isAvailable())
+ result.add(walk);
+ }
+ return result;
}

/**
- * Gets a list of all current work locations in this colony.
+ * Gets a list of all freely available work locations
+ * in this colony, that can add given unit.
*
- * @return The list of current {@code WorkLocation}s.
+ * @param unit The {@code Unit} about to be added.
+ * @param skip An optional WorkLocation to skip
+ * @return The list of available {@code WorkLocation}s.
*/
- public List<WorkLocation> getCurrentWorkLocationsList() {
- return transform(getAllWorkLocations(), WorkLocation::isCurrent);
+ public int getAvailableWorkLocationsCanAdd(Unit unit, WorkLocation skip) {
+ int result = 0;
+ synchronized (this.colonyTiles) {
+ for (ColonyTile walk : this.colonyTiles)
+ if (walk != skip && walk.isAvailable() && walk.canAdd(unit))
+ result++;
+ }
+ synchronized (this.buildingMap) {
+ for (Building walk : this.buildingMap.values())
+ if (walk != skip && walk.isAvailable() && walk.canAdd(unit))
+ result++;
+ }
+ return result;
}

/**
- * Get a stream of all current work locations in this colony.
+ * Gets a list of all current work locations in this colony.
*
- * @return The stream of current {@code WorkLocation}s.
+ * @return The list of current {@code WorkLocation}s.
*/
- public Stream<WorkLocation> getCurrentWorkLocations() {
- return getCurrentWorkLocationsList().stream();
+ public List<WorkLocation> getCurrentWorkLocations() {
+ List<WorkLocation> result = new ArrayList<>();
+ synchronized (this.colonyTiles) {
+ for (ColonyTile walk : this.colonyTiles)
+ if (walk.isCurrent())
+ result.add(walk);
+ }
+ synchronized (this.buildingMap) {
+ for (Building walk : this.buildingMap.values())
+ if (walk.isCurrent())
+ result.add(walk);
+ }
+ return result;
}

/**
@@ -664,7 +713,17 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* {@code Ability}, or null if not found.
*/
public WorkLocation getWorkLocationWithAbility(String ability) {
- return find(getCurrentWorkLocations(), wl -> wl.hasAbility(ability));
+ synchronized (this.colonyTiles) {
+ for (ColonyTile ct : this.colonyTiles)
+ if (ct.isCurrent() && ct.hasAbility(ability))
+ return ct;
+ }
+ synchronized (this.buildingMap) {
+ for (Building b : this.buildingMap.values())
+ if (b.isCurrent() && b.hasAbility(ability))
+ return b;
+ }
+ return null;
}

/**
@@ -693,7 +752,17 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* {@code Modifier}, or null if not found.
*/
public WorkLocation getWorkLocationWithModifier(String modifier) {
- return find(getCurrentWorkLocations(), wl -> wl.hasModifier(modifier));
+ synchronized (this.colonyTiles) {
+ for (WorkLocation walk : this.colonyTiles)
+ if (walk.isCurrent() && walk.hasModifier(modifier))
+ return walk;
+ }
+ synchronized (this.buildingMap) {
+ for (WorkLocation walk : this.buildingMap.values())
+ if (walk.isCurrent() && walk.hasModifier(modifier))
+ return walk;
+ }
+ return null;
}

/**
@@ -720,8 +789,18 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* the given type of goods.
*/
public List<WorkLocation> getWorkLocationsForConsuming(GoodsType goodsType) {
- return transform(getCurrentWorkLocations(),
- wl -> AbstractGoods.anyIsType(wl.getInputs(), goodsType));
+ List<WorkLocation> ret = new ArrayList<>();
+ synchronized (this.colonyTiles) {
+ for (WorkLocation walk : this.colonyTiles)
+ if (walk.isCurrent() && AbstractGoods.anyIsType(walk.getInputs(), goodsType))
+ ret.add(walk);
+ }
+ synchronized (this.buildingMap) {
+ for (WorkLocation walk : this.buildingMap.values())
+ if (walk.isCurrent() && AbstractGoods.anyIsType(walk.getInputs(), goodsType))
+ ret.add(walk);
+ }
+ return ret;
}

/**
@@ -732,8 +811,18 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* the given type of goods.
*/
public List<WorkLocation> getWorkLocationsForProducing(GoodsType goodsType) {
- return transform(getCurrentWorkLocations(),
- wl -> AbstractGoods.anyIsType(wl.getOutputs(), goodsType));
+ List<WorkLocation> result = new ArrayList<>();
+ synchronized (this.colonyTiles) {
+ for (WorkLocation walk : this.colonyTiles)
+ if (walk.isCurrent() && AbstractGoods.anyIsType(walk.getOutputs(), goodsType))
+ result.add(walk);
+ }
+ synchronized (this.buildingMap) {
+ for (WorkLocation walk : this.buildingMap.values())
+ if (walk.isCurrent() && AbstractGoods.anyIsType(walk.getOutputs(), goodsType))
+ result.add(walk);
+ }
+ return result;
}

/**
@@ -746,7 +835,17 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* the given type of goods, or null if not found.
*/
public WorkLocation getWorkLocationForProducing(GoodsType goodsType) {
- return first(getWorkLocationsForProducing(goodsType));
+ synchronized (this.colonyTiles) {
+ for (WorkLocation walk : this.colonyTiles)
+ if (walk.isCurrent() && AbstractGoods.anyIsType(walk.getOutputs(), goodsType))
+ return walk;
+ }
+ synchronized (this.buildingMap) {
+ for (WorkLocation walk : this.buildingMap.values())
+ if (walk.isCurrent() && AbstractGoods.anyIsType(walk.getOutputs(), goodsType))
+ return walk;
+ }
+ return null;
}

/**
@@ -1712,7 +1811,7 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
int result, v;
if (player.owns(this)) {
result = 0;
- for (WorkLocation wl : getAvailableWorkLocationsList()) {
+ for (WorkLocation wl : getAvailableWorkLocations()) {
v = wl.evaluateFor(player);
if (v == Integer.MIN_VALUE) return Integer.MIN_VALUE;
result += v;
@@ -2033,7 +2132,7 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* present.
*/
public void updateProductionTypes() {
- for (WorkLocation wl : getAvailableWorkLocationsList()) {
+ for (WorkLocation wl : getAvailableWorkLocations()) {
wl.updateProductionType();
}
}
@@ -2394,8 +2493,7 @@ loop: for (WorkLocation wl : getWorkLocationsForProducing(goodsType)) {
public <T extends FreeColObject> T getCorresponding(T fco) {
final String id = fco.getId();
return (fco instanceof WorkLocation)
- ? (T)find(getAllWorkLocations(),
- matchKeyEquals(id, WorkLocation::getId))
+ ? (T)findWorkLocationById(id)
: (fco instanceof Tile)
? (T)((getTile().getId().equals(id)) ? getTile()
: find(map(getColonyTiles(), ColonyTile::getWorkTile),
diff --git a/src/net/sf/freecol/common/model/ProductionType.java b/src/net/sf/freecol/common/model/ProductionType.java
index c5f965205bf..2911fe78bde 100644
--- a/src/net/sf/freecol/common/model/ProductionType.java
+++ b/src/net/sf/freecol/common/model/ProductionType.java
@@ -155,6 +155,18 @@ public class ProductionType extends FreeColSpecObject {
}

/**
+ * Check whether this production type can consume an {@code AbstractGoods}
+ */
+ public final boolean canConsume(AbstractGoods goods) {
+ if (inputs != null)
+ for (AbstractGoods walk : inputs)
+ if (walk.isType(goods.getType()))
+ return true;
+
+ return false;
+ }
+
+ /**
* Set the input goods.
*
* @param newInputs The new list of input {@code AbstractGoods}.
diff --git a/src/net/sf/freecol/common/model/WorkLocation.java b/src/net/sf/freecol/common/model/WorkLocation.java
index 40d69537f04..da1b7b157f7 100644
--- a/src/net/sf/freecol/common/model/WorkLocation.java
+++ b/src/net/sf/freecol/common/model/WorkLocation.java
@@ -418,6 +418,13 @@ public abstract class WorkLocation extends UnitLocation
}

/**
+ * Check whether this WorkLocation can consume an {@code AbstractGoods}
+ */
+ public final boolean canConsume(AbstractGoods ag) {
+ return (productionType == null ? false : productionType.canConsume(ag));
+ }
+
+ /**
* Get the {@code AbstractGoods} produced by this work location.
*
* @return A stream of {@code AbstractGoods} produced.
diff --git a/src/net/sf/freecol/server/ai/ColonyPlan.java b/src/net/sf/freecol/server/ai/ColonyPlan.java
index 1de387b5019..5db72192068 100644
--- a/src/net/sf/freecol/server/ai/ColonyPlan.java
+++ b/src/net/sf/freecol/server/ai/ColonyPlan.java
@@ -394,7 +394,7 @@ public class ColonyPlan {
*/
private Map<GoodsType, Map<WorkLocation, Integer>> createProductionMap() {
Map<GoodsType, Map<WorkLocation, Integer>> production = new HashMap<>();
- for (WorkLocation wl : colony.getAvailableWorkLocationsList()) {
+ for (WorkLocation wl : colony.getAvailableWorkLocations()) {
for (GoodsType g : spec().getGoodsTypeList()) {
int p = wl.getGenericPotential(g);
if (p > 0) {
@@ -1377,7 +1377,7 @@ public class ColonyPlan {
// starvation and add one worker.
if (col.getUnitCount() == 0) {
if (getFoodPlans().isEmpty()) {
-locations: for (WorkLocation wl : col.getAvailableWorkLocationsList()) {
+locations: for (WorkLocation wl : col.getAvailableWorkLocations()) {
for (Unit u : new ArrayList<>(workers)) {
for (GoodsType type : libertyGoodsTypes) {
if (wl.canAdd(u)
diff --git a/src/net/sf/freecol/server/ai/mission/Mission.java b/src/net/sf/freecol/server/ai/mission/Mission.java
index 32772c60fbd..ab9a28966e3 100644
--- a/src/net/sf/freecol/server/ai/mission/Mission.java
+++ b/src/net/sf/freecol/server/ai/mission/Mission.java
@@ -613,7 +613,7 @@ public abstract class Mission extends AIObject {
Colony colony = (Colony)s;
// Favour coastal
value += ((colony.isConnectedPort()) ? 10 : 0)
- + colony.getAvailableWorkLocationsList().size();
+ + colony.getAvailableWorkLocationCount();
}
return value;
});
diff --git a/src/net/sf/freecol/server/model/ServerColony.java b/src/net/sf/freecol/server/model/ServerColony.java
index 5c047e3c631..5b09be3c743 100644
--- a/src/net/sf/freecol/server/model/ServerColony.java
+++ b/src/net/sf/freecol/server/model/ServerColony.java
@@ -195,10 +195,11 @@ public class ServerColony extends Colony implements ServerModelObject {
public boolean ejectUnits(WorkLocation workLocation, List<Unit> units) {
if (units == null || units.isEmpty()) return false;
unit: for (Unit u : units) {
- for (WorkLocation wl : transform(getAvailableWorkLocations(),
- w -> w != workLocation && w.canAdd(u))) {
- u.setLocation(wl);//-vis: safe/colony
- continue unit;
+ for (WorkLocation wl : getAvailableWorkLocations()) {
+ if ((wl != workLocation) && wl.canAdd(u)) {
+ u.setLocation(wl);//-vis: safe/colony
+ continue unit;
+ }
}
u.setLocation(getTile());//-vis: safe/colony
}
@@ -547,7 +548,7 @@ public class ServerColony extends Colony implements ServerModelObject {
container.saveState();

// Check for learning by experience
- for (WorkLocation workLocation : getCurrentWorkLocationsList()) {
+ for (WorkLocation workLocation : getCurrentWorkLocations()) {
((ServerModelObject)workLocation).csNewTurn(random, lb, cs);
ProductionInfo productionInfo = getProductionInfo(workLocation);
if (productionInfo == null) continue;
diff --git a/test/src/net/sf/freecol/common/model/ColonyTest.java b/test/src/net/sf/freecol/common/model/ColonyTest.java
index 2d246878463..71b1827cb34 100644
--- a/test/src/net/sf/freecol/common/model/ColonyTest.java
+++ b/test/src/net/sf/freecol/common/model/ColonyTest.java
@@ -508,7 +508,7 @@ public class ColonyTest extends FreeColTestCase {
assertEquals(oct.getColony(), copied);
assertEquals(oct.getOwningSettlement(), copied);

- for (WorkLocation wl : colony.getAllWorkLocationsList()) {
+ for (WorkLocation wl : colony.getAllWorkLocations()) {
WorkLocation owl = copied.getCorresponding(wl);
assertNotNull(owl);
assertFalse(wl == owl);
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:04 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

Instead of expensive stream operations, just do it via trivial list
traversal. Also move that from the consumer logic to the FoundingFather
class and provide the key list as a static array.

FIXME: check whether the array can be autogenerate that list similar
to the implicit values() method.
---
src/net/sf/freecol/common/model/FoundingFather.java | 10 ++++++++++
.../freecol/common/networking/ChooseFoundingFatherMessage.java | 8 ++------
2 files changed, 12 insertions(+), 6 deletions(-)

diff --git a/src/net/sf/freecol/common/model/FoundingFather.java b/src/net/sf/freecol/common/model/FoundingFather.java
index f199b00a340..df81040eb5d 100644
--- a/src/net/sf/freecol/common/model/FoundingFather.java
+++ b/src/net/sf/freecol/common/model/FoundingFather.java
@@ -57,6 +57,16 @@ public class FoundingFather extends FreeColSpecObjectType {
public String getKey() {
return getEnumKey(this);
}
+
+ public static String[] getAllKeys() {
+ FoundingFatherType[] v = values();
+ String[] result = new String[v.length];
+ for (int x=0; x<v.length; x++)
+ result[x] = getEnumKey(v[x]);
+ return result;
+ }
+
+ public static final String[] allKeys = getAllKeys();
}

/** The type of this FoundingFather. */
diff --git a/src/net/sf/freecol/common/networking/ChooseFoundingFatherMessage.java b/src/net/sf/freecol/common/networking/ChooseFoundingFatherMessage.java
index 672698353af..3433971b4e2 100644
--- a/src/net/sf/freecol/common/networking/ChooseFoundingFatherMessage.java
+++ b/src/net/sf/freecol/common/networking/ChooseFoundingFatherMessage.java
@@ -44,10 +44,6 @@ public class ChooseFoundingFatherMessage extends AttributeMessage {

public static final String TAG = "chooseFoundingFather";
private static final String FOUNDING_FATHER_TAG = "foundingFather";
- private static final List<String> fatherKeys = Collections.<String>
- unmodifiableList(transform(FoundingFatherType.values(),
- alwaysTrue(), FoundingFatherType::getKey));
-

/**
* Create a new {@code ChooseFoundingFatherMessage} with the specified
@@ -74,7 +70,7 @@ public class ChooseFoundingFatherMessage extends AttributeMessage {
super(TAG, FOUNDING_FATHER_TAG, getStringAttribute(element, FOUNDING_FATHER_TAG));

final Specification spec = game.getSpecification();
- setFatherAttributes(transform(fatherKeys,
+ setFatherAttributes(transform(FoundingFatherType.allKeys,
k -> element.hasAttribute(k),
k -> spec.getFoundingFather(getStringAttribute(element, k))));
}
@@ -126,7 +122,7 @@ public class ChooseFoundingFatherMessage extends AttributeMessage {
*/
public final List<FoundingFather> getFathers(Game game) {
final Specification spec = game.getSpecification();
- return transform(fatherKeys, tid -> hasAttribute(tid),
+ return transform(FoundingFatherType.allKeys, tid -> hasAttribute(tid),
tid -> spec.getFoundingFather(getStringAttribute(tid)));
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:30:57 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/io/FreeColDirectories.java | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/src/net/sf/freecol/common/io/FreeColDirectories.java b/src/net/sf/freecol/common/io/FreeColDirectories.java
index a7b2496d587..db3b4ec9de9 100644
--- a/src/net/sf/freecol/common/io/FreeColDirectories.java
+++ b/src/net/sf/freecol/common/io/FreeColDirectories.java
@@ -133,12 +133,6 @@ public class FreeColDirectories {

public static final String MOD_DESCRIPTOR_FILE_NAME = "mod.xml";

- /** Predicate to filter suitable candidates to be made into TCs. */
- private static final Predicate<File> tcFileFilter = f ->
- Utils.fileAnySuffix(f, TC_FILE_SUFFIX, ZIP_FILE_SUFFIX)
- || Utils.directoryAllPresent(f, MOD_DESCRIPTOR_FILE_NAME,
- SPECIFICATION_FILE_NAME);
-
/**
* The directory containing automatically created save games. At
* program start, the path of this directory is based on the path
@@ -1182,7 +1176,13 @@ public class FreeColDirectories {
* @return A list of {@code File}s containing rulesets.
*/
public static List<File> getTcFileList() {
- return collectFiles(getRulesDirectory(), tcFileFilter);
+ List<File> result = new ArrayList<File>();
+ for (File f : getRulesDirectory().listFiles())
+ if (Utils.fileAnySuffix(f, TC_FILE_SUFFIX, ZIP_FILE_SUFFIX)
+ || Utils.directoryAllPresent(f, MOD_DESCRIPTOR_FILE_NAME, SPECIFICATION_FILE_NAME))
+ result.add(f);
+ Collections.sort(result);
+ return result;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:30:59 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/io/FreeColDirectories.java | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/src/net/sf/freecol/common/io/FreeColDirectories.java b/src/net/sf/freecol/common/io/FreeColDirectories.java
index 2c611e9728a..743acd01212 100644
--- a/src/net/sf/freecol/common/io/FreeColDirectories.java
+++ b/src/net/sf/freecol/common/io/FreeColDirectories.java
@@ -813,8 +813,12 @@ public class FreeColDirectories {
*/
public static List<String> getLanguageIdList() {
File[] files = getI18nDirectory().listFiles();
- return (files == null) ? Collections.<String>emptyList()
- : transform(files, f -> f.canRead(), f -> getLanguageId(f));
+ if (files == null) return Collections.<String>emptyList();
+ List<String> result = new ArrayList<>();
+ for (File f : files)
+ if (f.canRead())
+ result.add(getLanguageId(f));
+ return result;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:32 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../sf/freecol/common/model/IndianNationType.java | 49 +++++++++++++---------
1 file changed, 29 insertions(+), 20 deletions(-)

diff --git a/src/net/sf/freecol/common/model/IndianNationType.java b/src/net/sf/freecol/common/model/IndianNationType.java
index 838f9cd88e0..1f3e78959e2 100644
--- a/src/net/sf/freecol/common/model/IndianNationType.java
+++ b/src/net/sf/freecol/common/model/IndianNationType.java
@@ -23,8 +23,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
-import java.util.function.Function;
-import java.util.stream.Collectors;

import javax.xml.stream.XMLStreamException;

@@ -149,26 +147,37 @@ public class IndianNationType extends NationType {
* @return A random choice set of skills.
*/
public List<RandomChoice<UnitType>> generateSkillsForTile(Tile tile) {
- final List<RandomChoice<UnitType>> skills = getSkills();
- final Map<GoodsType, Integer> scale
- = transform(skills, alwaysTrue(), Function.identity(),
- Collectors.toMap(rc -> rc.getObject().getExpertProduction(),
- rc -> 1));
-
- for (Tile t: tile.getSurroundingTiles(1)) {
- forEachMapEntry(scale, e -> {
- GoodsType goodsType = e.getKey();
- scale.put(goodsType, e.getValue()
- + t.getPotentialProduction(goodsType, null));
- });
+ List<RandomChoice<UnitType>> sklist = skills;
+ if (sklist == null)
+ return Collections.<RandomChoice<UnitType>>emptyList();
+
+ /** transform from skills random-choices into temporary arrays for direct access **/
+ int sz = sklist.size();
+ GoodsType[] goods_types = new GoodsType[sz];
+ UnitType[] unit_types = new UnitType[sz];
+ int[] scales = new int[sz];
+ int[] probabilities = new int[sz];
+
+ int idx = 0;
+ for (RandomChoice<UnitType> rc : sklist) {
+ scales[idx] = 1;
+ probabilities[idx] = rc.getProbability();
+ unit_types[idx] = rc.getObject();
+ goods_types[idx] = unit_types[idx].getExpertProduction();
+ idx++;
}

- final Function<RandomChoice<UnitType>, RandomChoice<UnitType>> mapper = rc -> {
- UnitType ut = rc.getObject();
- int scaleValue = scale.get(ut.getExpertProduction());
- return new RandomChoice<>(ut, rc.getProbability() * scaleValue);
- };
- return transform(skills, alwaysTrue(), mapper);
+ /** sum up surrounding tiles **/
+ for (Tile t : tile.getSurroundingTiles(1))
+ for (int x=0; x<sz; x++)
+ scales[x] += t.getPotentialProduction(goods_types[x], null);
+
+ /** finally create the new random choice list **/
+ List<RandomChoice<UnitType>> choices = new ArrayList<RandomChoice<UnitType>>(sz);
+ for (int x=0; x<sz; x++)
+ choices.add(new RandomChoice<>(unit_types[x], probabilities[x] * scales[x]));
+
+ return choices;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:34 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/ResourceType.java | 15 +++++++++++----
1 file changed, 11 insertions(+), 4 deletions(-)

diff --git a/src/net/sf/freecol/common/model/ResourceType.java b/src/net/sf/freecol/common/model/ResourceType.java
index 923c81726b8..b2c4ced928b 100644
--- a/src/net/sf/freecol/common/model/ResourceType.java
+++ b/src/net/sf/freecol/common/model/ResourceType.java
@@ -76,10 +76,17 @@ public final class ResourceType extends FreeColSpecObjectType {
*/
public GoodsType getBestGoodsType() {
final Specification spec = getSpecification();
- final Comparator<Modifier> comp = cachingDoubleComparator(m ->
- spec.getInitialPrice(spec.getGoodsType(m.getId()))
- * (double)m.applyTo(100));
- Modifier best = maximize(getModifiers(), comp);
+ int best_price = 0;
+ Modifier best = null;
+ for (Modifier m : getModifiers()) {
+ int p = spec.getInitialPrice(spec.getGoodsType(m.getId()))
+ * (int)m.applyTo(100);
+ if (best == null || best_price < p) {
+ best = m;
+ best_price = p;
+ }
+ }
+
return (best == null) ? null : spec.getGoodsType(best.getId());
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:30:53 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

This map type eases accumulation of key->integer and key-double tuples by key,
w/o the ovead of streams and callacks to BinaryOperator objects.
---
.../gui/panel/report/ReportCompactColonyPanel.java | 35 ++++------
.../sf/freecol/common/util/CollectionUtils.java | 8 ---
src/net/sf/freecol/common/util/DoubleAccMap.java | 75 ++++++++++++++++++++++
src/net/sf/freecol/common/util/IntAccMap.java | 75 ++++++++++++++++++++++
4 files changed, 163 insertions(+), 30 deletions(-)
create mode 100644 src/net/sf/freecol/common/util/DoubleAccMap.java
create mode 100644 src/net/sf/freecol/common/util/IntAccMap.java

diff --git a/src/net/sf/freecol/client/gui/panel/report/ReportCompactColonyPanel.java b/src/net/sf/freecol/client/gui/panel/report/ReportCompactColonyPanel.java
index a987560ec43..e9b87d002ef 100644
--- a/src/net/sf/freecol/client/gui/panel/report/ReportCompactColonyPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/report/ReportCompactColonyPanel.java
@@ -71,6 +71,8 @@ import net.sf.freecol.common.model.UnitType;
import net.sf.freecol.common.model.WorkLocation;
import net.sf.freecol.common.model.WorkLocation.Suggestion;
import net.sf.freecol.common.resources.ResourceManager;
+import net.sf.freecol.common.util.IntAccMap;
+import net.sf.freecol.common.util.DoubleAccMap;
import static net.sf.freecol.common.util.CollectionUtils.*;


@@ -860,46 +862,35 @@ public final class ReportCompactColonyPanel extends ReportPanel
"newline, span, growx");

// Accumulate all the summaries
- Map<Region, Integer> rRegionMap = new HashMap<>();
+ IntAccMap<Region> rRegionMap = new IntAccMap<>();
List<TileImprovementSuggestion> rTileSuggestions = new ArrayList<>();
int rFamine = 0, rBonus = 0, rSizeChange = 0,
teacherLen = 0, improveLen = 0;
double rNewColonist = 0.0;
Map<GoodsType, ColonySummary.GoodsProduction> rProduction
= new HashMap<>();
- Map<UnitType, Integer> rTeachers = new HashMap<>();
+ IntAccMap<UnitType> rTeachers = new IntAccMap<>();
List<Unit> rNotWorking = new ArrayList<>();
List<UnitType> rCouldWork = new ArrayList<>();
- Map<UnitType, Integer> rImprove = new HashMap<>();
- Map<GoodsType, Double> rNeeded = new HashMap<>();
+ IntAccMap<UnitType> rImprove = new IntAccMap<>();
+ DoubleAccMap<GoodsType> rNeeded = new DoubleAccMap<>();
for (ColonySummary s : summaries) {
- accumulateToMap(rRegionMap, s.colony.getTile().getRegion(), 1,
- integerAccumulator);
+ rRegionMap.inc(s.colony.getTile().getRegion());
rTileSuggestions.addAll(s.tileSuggestions);
if (s.famine) rFamine++;
if (s.newColonist > 0) rNewColonist += s.newColonist;
rBonus += s.bonus;
rSizeChange += s.sizeChange;
- accumulateMap(rProduction, s.production,
- ColonySummary.goodsProductionAccumulator);
+ ColonySummary.accumulateGoodsProduction(rProduction, s.production);
teacherLen = Math.max(teacherLen, s.teachers.size());
- for (Unit u : s.teachers.keySet()) {
- accumulateToMap(rTeachers, u.getType(), 1, integerAccumulator);
- }
+ for (Unit u : s.teachers.keySet()) rTeachers.inc(u.getType());
rNotWorking.addAll(s.notWorking);
rCouldWork.addAll(s.couldWork);
improveLen = Math.max(improveLen, s.improve.size() + s.want.size());
- for (UnitType ut : s.improve.keySet()) {
- accumulateToMap(rImprove, ut, 1, integerAccumulator);
- }
- for (UnitType ut : s.want.keySet()) {
- accumulateToMap(rImprove, ut, 1, integerAccumulator);
- }
- if (s.needed != null && s.needed.getType().isStorable()) {
- accumulateToMap(rNeeded, s.needed.getType(),
- (double)s.needed.getAmount() / s.completeTurns,
- doubleAccumulator);
- }
+ for (UnitType ut : s.improve.keySet()) rImprove.inc(ut);
+ for (UnitType ut : s.want.keySet()) rImprove.inc(ut);
+ if (s.needed != null && s.needed.getType().isStorable())
+ rNeeded.addDouble(s.needed.getType(), (double)s.needed.getAmount() / s.completeTurns);
}
rNewColonist = Math.round(rNewColonist / summaries.size());

diff --git a/src/net/sf/freecol/common/util/CollectionUtils.java b/src/net/sf/freecol/common/util/CollectionUtils.java
index 7f911e72ad8..1a265516d81 100644
--- a/src/net/sf/freecol/common/util/CollectionUtils.java
+++ b/src/net/sf/freecol/common/util/CollectionUtils.java
@@ -58,14 +58,6 @@ public class CollectionUtils {
private static final double SUM_DOUBLE_DEFAULT = 0.0;
private static final double PRODUCT_DEFAULT = 1.0;

- /** Trivial integer accumulator. */
- public static final BinaryOperator<Integer> integerAccumulator
- = (i1, i2) -> i1 + i2;
-
- /** Trivial double accumulator. */
- public static final BinaryOperator<Double> doubleAccumulator
- = (d1, d2) -> d1 + d2;
-
public static final BinaryOperator<Double> doubleMultiplicator
= new BinaryOperator<Double>() {
public Double apply(Double d1, Double d2) {
diff --git a/src/net/sf/freecol/common/util/DoubleAccMap.java b/src/net/sf/freecol/common/util/DoubleAccMap.java
new file mode 100644
index 00000000000..258b9e9d154
--- /dev/null
+++ b/src/net/sf/freecol/common/util/DoubleAccMap.java
@@ -0,0 +1,75 @@
+/**
+ * Copyright (C) 2002-2017 The FreeCol Team
+ *
+ * This file is part of FreeCol.
+ *
+ * FreeCol is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * FreeCol is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with FreeCol. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.sf.freecol.common.util;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class DoubleAccMap<T> extends HashMap<T,Double>
+{
+ public double inc(T key) {
+ return addDouble(key, 1);
+ }
+
+ public double addDouble(T key, double value) {
+ if (!containsKey(key)) {
+ put(key, value);
+ return value;
+ }
+
+ Double oldval = get(key);
+ if (oldval == null) {
+ put(key, value);
+ return value;
+ }
+
+ double newval = oldval + value;
+ put(key, newval);
+ return newval;
+ }
+
+ public double mulDouble(T key, double value) {
+ if (!containsKey(key)) {
+ put(key, value);
+ return value;
+ }
+
+ Double oldval = get(key);
+ if (oldval == null) {
+ put(key, value);
+ return value;
+ }
+
+ double newval = oldval * value;
+ put(key, newval);
+ return newval;
+ }
+
+ public double getDouble(T key) {
+ if (!containsKey(key))
+ return 0;
+
+ Double val = get(key);
+ if (val == null)
+ return 0;
+
+ return val;
+ }
+}
diff --git a/src/net/sf/freecol/common/util/IntAccMap.java b/src/net/sf/freecol/common/util/IntAccMap.java
new file mode 100644
index 00000000000..5325c38058f
--- /dev/null
+++ b/src/net/sf/freecol/common/util/IntAccMap.java
@@ -0,0 +1,75 @@
+/**
+ * Copyright (C) 2002-2017 The FreeCol Team
+ *
+ * This file is part of FreeCol.
+ *
+ * FreeCol is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * FreeCol is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with FreeCol. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.sf.freecol.common.util;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class IntAccMap<T> extends HashMap<T,Integer>
+{
+ public int inc(T key) {
+ return addInt(key, 1);
+ }
+
+ public int addInt(T key, int value) {
+ if (!containsKey(key)) {
+ put(key, value);
+ return value;
+ }
+
+ Integer oldval = get(key);
+ if (oldval == null) {
+ put(key, value);
+ return value;
+ }
+
+ int newval = oldval + value;
+ put(key, newval);
+ return newval;
+ }
+
+ public int mulInt(T key, int value) {
+ if (!containsKey(key)) {
+ put(key, value);
+ return value;
+ }
+
+ Integer oldval = get(key);
+ if (oldval == null) {
+ put(key, value);
+ return value;
+ }
+
+ int newval = oldval * value;
+ put(key, newval);
+ return newval;
+ }
+
+ public int getInt(T key) {
+ if (!containsKey(key))
+ return 0;
+
+ Integer val = get(key);
+ if (val == null)
+ return 0;
+
+ return val;
+ }
+}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:10 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Player.java | 2 +-
src/net/sf/freecol/common/model/Unit.java | 7 +++++++
2 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/src/net/sf/freecol/common/model/Player.java b/src/net/sf/freecol/common/model/Player.java
index cd2a584bc1f..5aad8c26fdf 100644
--- a/src/net/sf/freecol/common/model/Player.java
+++ b/src/net/sf/freecol/common/model/Player.java
@@ -987,7 +987,7 @@ public class Player extends FreeColGameObject implements Nameable {
* world or a nation is in rebellion against us.
*/
public boolean isWorkForREF() {
- return (any(getUnits(), Unit::hasTile))
+ return Unit.anyHasTile(getUnits())
? true // Work to do still if there exists a unit in the new world
: !getRebels().isEmpty();
}
diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index e2a7394c377..820480f2b39 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -999,6 +999,13 @@ public class Unit extends GoodsLocation
return getTile() != null;
}

+ public static boolean anyHasTile(List<Unit> units) {
+ if (units != null)
+ for (Unit u : units)
+ if (u.hasTile()) return true;
+ return false;
+ }
+
/**
* Gets the work location this unit is working in.
*
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:30:54 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/client/FreeColClient.java | 38 +++++++++++++----
.../sf/freecol/common/io/FreeColDirectories.java | 49 +++-------------------
src/net/sf/freecol/common/util/Utils.java | 22 ++++------
3 files changed, 44 insertions(+), 65 deletions(-)

diff --git a/src/net/sf/freecol/client/FreeColClient.java b/src/net/sf/freecol/client/FreeColClient.java
index 6b295df85bf..6463aead100 100644
--- a/src/net/sf/freecol/client/FreeColClient.java
+++ b/src/net/sf/freecol/client/FreeColClient.java
@@ -64,6 +64,7 @@ import net.sf.freecol.common.networking.MessageHandler;
import net.sf.freecol.common.networking.ServerAPI;
import net.sf.freecol.common.resources.ResourceManager;
import net.sf.freecol.common.resources.ResourceMapping;
+import net.sf.freecol.common.util.Utils;
import static net.sf.freecol.common.util.CollectionUtils.*;
import net.sf.freecol.server.FreeColServer;
import net.sf.freecol.server.FreeColServer.ServerState;
@@ -993,19 +994,40 @@ public final class FreeColClient {
}

/**
+ * Remove out of date autosaves. This only removed generic autosaves, not
+ * the last-turn autosave, which can be useful for continuing the game on
+ * the next play-session.
+ */
+ public void removeOutdatedAutosaves() {
+ final ClientOptions co = getClientOptions();
+ final int validDays = co.getInteger(ClientOptions.AUTOSAVE_VALIDITY);
+ if (validDays <= 0L) return;
+ final long validMS = 1000L * 24L * 60L * 60L * validDays; // days to ms
+ final long timeNow = System.currentTimeMillis();
+ final String prefix = co.getText(ClientOptions.AUTO_SAVE_PREFIX);
+ final String last_suffix = co.getText(ClientOptions.LAST_TURN_NAME)
+ + FreeColDirectories.FREECOL_SAVE_SUFFIX;
+ final String prev_suffix = co.getText(ClientOptions.BEFORE_LAST_TURN_NAME)
+ + FreeColDirectories.FREECOL_SAVE_SUFFIX;
+ final File asd = FreeColDirectories.getAutosaveDirectory();
+
+ for (String n : asd.list()) {
+ // skip last and previous savegame
+ if (n.startsWith(prefix) && !n.endsWith(last_suffix) && !n.endsWith(prev_suffix)) {
+ File f = new File(asd, n);
+ if (f.lastModified() + validMS < timeNow)
+ Utils.deleteFile(f);
+ }
+ }
+ }
+
+ /**
* Quits the application without any questions.
*/
public void quit() {
stopServer();

- final ClientOptions co = getClientOptions();
- List<String> excludeSuffixes = new ArrayList<>(2);
- excludeSuffixes.add(co.getText(ClientOptions.LAST_TURN_NAME));
- excludeSuffixes.add(co.getText(ClientOptions.BEFORE_LAST_TURN_NAME));
- FreeColDirectories.removeOutdatedAutosaves(
- co.getText(ClientOptions.AUTO_SAVE_PREFIX),
- excludeSuffixes,
- co.getInteger(ClientOptions.AUTOSAVE_VALIDITY));
+ removeOutdatedAutosaves();

// Exit
int ret = 0;
diff --git a/src/net/sf/freecol/common/io/FreeColDirectories.java b/src/net/sf/freecol/common/io/FreeColDirectories.java
index 7fe01ca17f4..901d06c5fe6 100644
--- a/src/net/sf/freecol/common/io/FreeColDirectories.java
+++ b/src/net/sf/freecol/common/io/FreeColDirectories.java
@@ -709,49 +709,7 @@ public class FreeColDirectories {
return new File(getAutosaveDirectory(), name);
}

- /**
- * Get the autosave files.
- *
- * @param prefix The autosave file prefix.
- * @param pred A {@code Predicate} to select files with.
- * @return A list of of autosaved {@code File}s.
- */
- private static List<File> getAutosaveFiles(String prefix,
- Predicate<File> pred) {
- final String suffix = "." + FreeCol.FREECOL_SAVE_EXTENSION;
- final File asd = getAutosaveDirectory();
- final Predicate<File> fullPred = pred.and(f ->
- f.getName().startsWith(prefix) && f.getName().endsWith(suffix));
- return (asd == null) ? Collections.emptyList()
- : collectFiles(asd, fullPred);
- }
-
- /**
- * Remove out of date autosaves. This only removed generic autosaves, not
- * the last-turn autosave, which can be useful for continuing the game on
- * the next play-session.
- *
- * @param prefix The autosave file prefix.
- * @param excludeSuffixes Only files not ending with any of these prefixes
- * will be removed.
- * @param validDays Only files older than this amount of days will be removed.
- */
- public static void removeOutdatedAutosaves(String prefix,
- List<String> excludeSuffixes,
- long validDays) {
- if (validDays <= 0L) return;
- final long validMS = 1000L * 24L * 60L * 60L * validDays; // days to ms
- final long timeNow = System.currentTimeMillis();
- final Predicate<File> outdatedPred = f ->
- f.lastModified() + validMS < timeNow;
-
- final String extension = "." + FreeCol.FREECOL_SAVE_EXTENSION;
- final Predicate<File> suffixPred = f ->
- excludeSuffixes.stream().noneMatch(
- excludeSuffix -> f.getName().endsWith(excludeSuffix + extension));
-
- Utils.deleteFiles(getAutosaveFiles(prefix, outdatedPred.and(suffixPred)));
- }
+ public static final String FREECOL_SAVE_SUFFIX = "." + FreeCol.FREECOL_SAVE_EXTENSION;

/**
* Remove all autosave files.
@@ -759,7 +717,10 @@ public class FreeColDirectories {
* @param prefix The autosave file prefix.
*/
public static void removeAutosaves(String prefix) {
- Utils.deleteFiles(getAutosaveFiles(prefix, alwaysTrue()));
+ File asd = getAutosaveDirectory();
+ for (String n : asd.list())
+ if (n.startsWith(prefix))
+ Utils.deleteFile(new File(asd, n));
}

/**
diff --git a/src/net/sf/freecol/common/util/Utils.java b/src/net/sf/freecol/common/util/Utils.java
index 28d0dcfa98b..d2290e9dc1a 100644
--- a/src/net/sf/freecol/common/util/Utils.java
+++ b/src/net/sf/freecol/common/util/Utils.java
@@ -36,7 +36,6 @@ import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.CharBuffer;

-import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -293,20 +292,17 @@ public class Utils {
}

/**
- * Delete a list of files.
+ * Delete a file.
*
- * @param files The list of {@code File}s to delete.
+ * @param files The {@code File}s to delete.
*/
- public static void deleteFiles(List<File> files) {
- for (File f : files) {
- try {
- if (!f.delete()) {
- logger.warning("Failed to delete: " + f.getPath());
- }
- } catch (SecurityException ex) {
- logger.log(Level.WARNING, "Exception deleting: "
- + f.getPath(), ex);
- }
+ public static void deleteFile(File f) {
+ try {
+ if (!f.delete())
+ logger.warning("Failed to delete: " + f.getPath());
+ } catch (SecurityException ex) {
+ logger.log(Level.WARNING, "Exception deleting: "
+ + f.getPath(), ex);
}
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:26 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../client/gui/panel/report/LabourData.java | 2 +-
.../report/ReportContinentalCongressPanel.java | 6 +-
src/net/sf/freecol/common/debug/DebugUtils.java | 4 +-
.../sf/freecol/common/model/DiplomaticTrade.java | 10 +-
src/net/sf/freecol/common/model/Game.java | 18 +-
src/net/sf/freecol/common/model/HighScore.java | 2 +-
src/net/sf/freecol/common/model/Player.java | 201 ++++++++++++++-------
src/net/sf/freecol/server/ai/EuropeanAIPlayer.java | 2 +-
src/net/sf/freecol/server/model/ServerGame.java | 2 +-
src/net/sf/freecol/server/model/ServerPlayer.java | 19 +-
10 files changed, 169 insertions(+), 97 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/panel/report/LabourData.java b/src/net/sf/freecol/client/gui/panel/report/LabourData.java
index d8f7e215863..c903d0b681f 100644
--- a/src/net/sf/freecol/client/gui/panel/report/LabourData.java
+++ b/src/net/sf/freecol/client/gui/panel/report/LabourData.java
@@ -430,7 +430,7 @@ public class LabourData {
GoodsType expertProduction = unitData.getUnitType()
.getExpertProduction();
if (expertProduction != null) {
- for (Colony c : player.getColonyList()) {
+ for (Colony c : player.getColonies()) {
int net = c.getNetProductionOf(expertProduction);
if (unitData.details.containsKey(c)) {
unitData.getLocationData(c).netProduction = net;
diff --git a/src/net/sf/freecol/client/gui/panel/report/ReportContinentalCongressPanel.java b/src/net/sf/freecol/client/gui/panel/report/ReportContinentalCongressPanel.java
index 5bfbde184bd..0c0eb18d9cd 100644
--- a/src/net/sf/freecol/client/gui/panel/report/ReportContinentalCongressPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/report/ReportContinentalCongressPanel.java
@@ -37,6 +37,7 @@ import net.sf.freecol.client.gui.ImageLibrary;
import net.sf.freecol.client.gui.panel.*;
import net.sf.freecol.common.debug.FreeColDebugger;
import net.sf.freecol.common.i18n.Messages;
+import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.FoundingFather;
import net.sf.freecol.common.model.FoundingFather.FoundingFatherType;
import net.sf.freecol.common.model.GoodsType;
@@ -85,8 +86,9 @@ public final class ReportContinentalCongressPanel extends ReportPanel {
Messages.getDescription(currentFather));
recruitingPanel.add(currentFatherLabel);
for (GoodsType gt : getSpecification().getLibertyGoodsTypeList()) {
- int total = sum(player.getColonies(),
- c -> c.getNetProductionOf(gt));
+ int total = 0;
+ for (Colony c : player.getColonies())
+ total += c.getNetProductionOf(gt);
FreeColProgressBar progressBar = new FreeColProgressBar(gt, 0,
player.getTotalFoundingFatherCost(), player.getLiberty(),
total);
diff --git a/src/net/sf/freecol/common/debug/DebugUtils.java b/src/net/sf/freecol/common/debug/DebugUtils.java
index 13ddb27a316..c6edfadbd11 100644
--- a/src/net/sf/freecol/common/debug/DebugUtils.java
+++ b/src/net/sf/freecol/common/debug/DebugUtils.java
@@ -140,7 +140,7 @@ public class DebugUtils {
Player.class);
List<String> results = new ArrayList<>();
int fails = 0;
- for (Colony sColony : sPlayer.getColonyList()) {
+ for (Colony sColony : sPlayer.getColonies()) {
Colony.NoBuildReason reason
= sColony.getNoBuildReason(sBuildingType, null);
results.add(sColony.getName() + ": " + reason);
@@ -293,7 +293,7 @@ public class DebugUtils {
} catch (NumberFormatException x) {
return;
}
- for (Colony c : player.getColonyList()) {
+ for (Colony c : player.getColonies()) {
c.addLiberty(liberty);
sGame.getFreeColGameObject(c.getId(), Colony.class)
.addLiberty(liberty);
diff --git a/src/net/sf/freecol/common/model/DiplomaticTrade.java b/src/net/sf/freecol/common/model/DiplomaticTrade.java
index a7f636db2d6..ffb78d5805c 100644
--- a/src/net/sf/freecol/common/model/DiplomaticTrade.java
+++ b/src/net/sf/freecol/common/model/DiplomaticTrade.java
@@ -334,10 +334,12 @@ public class DiplomaticTrade extends FreeColGameObject {
* @return A list of {@code Colony}s offered in this trade.
*/
public List<Colony> getColoniesGivenBy(final Player player) {
- return transform(this.items,
- ti -> ti instanceof ColonyTradeItem
- && ti.getSource() == player,
- ti -> ti.getColony(player.getGame()));
+ final Game game = player.getGame();
+ List<Colony> result = new ArrayList<>();
+ for (TradeItem ti : this.items)
+ if (ti instanceof ColonyTradeItem && ti.getSource() == player)
+ result.add(ti.getColony(game));
+ return result;
}

/**
diff --git a/src/net/sf/freecol/common/model/Game.java b/src/net/sf/freecol/common/model/Game.java
index 3d4a14b5d6f..4c1c1004beb 100644
--- a/src/net/sf/freecol/common/model/Game.java
+++ b/src/net/sf/freecol/common/model/Game.java
@@ -33,7 +33,6 @@ import java.util.NoSuchElementException;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
-import java.util.stream.Stream;

import javax.xml.stream.XMLStreamException;

@@ -1053,20 +1052,13 @@ public class Game extends FreeColGameObject {
* Get all the colonies in the game.
*
* @param player An optional {@code Player} to omit.
- * @return A stream of all the {@code Colony}s in the game.
- */
- public Stream<Colony> getAllColonies(Player player) {
- return flatten(getLiveEuropeanPlayers(player), Player::getColonies);
- }
-
- /**
- * Get a list of all the colonies in the game.
- *
- * @param player An optional {@code Player} to omit.
* @return A list of all the {@code Colony}s in the game.
*/
- public List<Colony> getAllColoniesList(Player player) {
- return toList(getAllColonies(player));
+ public List<Colony> getAllColonies(Player player) {
+ List<Colony> result = new ArrayList<>();
+ for (Player p : getLiveEuropeanPlayers(player))
+ result.addAll(p.getColonies());
+ return result;
}

/**
diff --git a/src/net/sf/freecol/common/model/HighScore.java b/src/net/sf/freecol/common/model/HighScore.java
index 8d309bd7e79..09e51f328e7 100644
--- a/src/net/sf/freecol/common/model/HighScore.java
+++ b/src/net/sf/freecol/common/model/HighScore.java
@@ -164,7 +164,7 @@ public class HighScore extends FreeColObject {
this.playerName = player.getName();
this.nationId = player.getNationId();
this.nationTypeId = player.getNationType().getId();
- this.nColonies = count(player.getColonies());
+ this.nColonies = player.getSettlementCount();
this.nUnits = player.getUnitCount();
this.independenceTurn = (player.getPlayerType()
== Player.PlayerType.INDEPENDENT) ? game.getTurn().getNumber()
diff --git a/src/net/sf/freecol/common/model/Player.java b/src/net/sf/freecol/common/model/Player.java
index 2ea54dd6ad9..f0354687958 100644
--- a/src/net/sf/freecol/common/model/Player.java
+++ b/src/net/sf/freecol/common/model/Player.java
@@ -1270,13 +1270,19 @@ public class Player extends FreeColGameObject implements Nameable {
*
* @return The total immigration production.
*/
- public int getTotalImmigrationProduction() {
+ public final int getTotalImmigrationProduction() {
if (!isColonial()) return 0;

final List<GoodsType> immigrationGoodsTypes = getSpecification()
.getImmigrationGoodsTypeList();
- int production = sum(getColonies(),
- c -> sum(immigrationGoodsTypes, gt -> c.getTotalProductionOf(gt)));
+
+ int production = 0;
+ synchronized (this.settlements) {
+ for (Settlement s : this.settlements)
+ for (GoodsType gt : immigrationGoodsTypes)
+ production += s.getTotalProductionOf(gt);
+ }
+
final Europe europe = getEurope();
if (europe != null) production += europe.getImmigration(production);
return production;
@@ -1351,30 +1357,23 @@ public class Player extends FreeColGameObject implements Nameable {
}

/**
- * Gets how much liberty will be produced next turn if no colonies
- * are lost and nothing unexpected happens.
- *
- * @return The total amount of liberty this {@code Player}'s
- * {@code Colony}s will make next turn.
- */
- public int getLibertyProductionNextTurn() {
- final Specification spec = getSpecification();
- final List<GoodsType> goodsTypes = spec.getLibertyGoodsTypeList();
- int nextTurn = sum(getColonies(), c ->
- sum(goodsTypes, gt -> c.getTotalProductionOf(gt)));
- return (int)applyModifiers((float)nextTurn, getGame().getTurn(),
- Modifier.LIBERTY);
- }
-
- /**
* Gets the total percentage of rebels in all this player's colonies.
*
* @return The total percentage of rebels in all this player's colonies.
*/
- public int getSoL() {
- final List<Colony> colonies = getColonyList();
- return (colonies.isEmpty()) ? 0
- : sum(colonies, Colony::getSoL) / colonies.size();
+ public final int getSoL() {
+ synchronized (this.settlements) {
+ int total = 0;
+ int count = 0;
+
+ for (Settlement s : this.settlements)
+ if (s instanceof Colony) {
+ total += ((Colony)s).getSoL();
+ count++;
+ }
+
+ return (count == 0 ? 0 : total/count);
+ }
}

/**
@@ -1412,10 +1411,14 @@ public class Player extends FreeColGameObject implements Nameable {
*
* @param father The {@code FoundingFather} to add.
*/
- public void addFather(FoundingFather father) {
+ public final void addFather(FoundingFather father) {
foundingFathers.add(father);
addFeatures(father);
- for (Colony c : getColonyList()) c.invalidateCache();
+ synchronized (this.settlements) {
+ for (Settlement s : this.settlements)
+ if (s instanceof Colony)
+ ((Colony)s).invalidateCache();
+ }
}

/**
@@ -1612,11 +1615,14 @@ public class Player extends FreeColGameObject implements Nameable {
*
* @param amount The new tax amount.
*/
- public void setTax(int amount) {
+ public final void setTax(int amount) {
tax = amount;
- if (recalculateBellsBonus()) {
- for (Colony c : getColonyList()) c.invalidateCache();
- }
+ if (recalculateBellsBonus())
+ synchronized (this.settlements) {
+ for (Settlement s : this.settlements)
+ if (s instanceof Colony)
+ ((Colony)s).invalidateCache();
+ }
}

/**
@@ -2291,9 +2297,16 @@ public class Player extends FreeColGameObject implements Nameable {
*
* @return The number of port settlements this player has.
*/
- public int getNumberOfPorts() {
- return (!isEuropean()) ? 0
- : count(getColonies(), Colony::isConnectedPort);
+ public final int getNumberOfPorts() {
+ if (!isEuropean())
+ return 0;
+
+ synchronized (this.settlements) {
+ int x = 0;
+ for (Settlement s : this.settlements)
+ if (s.isConnectedPort()) x++;
+ return x;
+ }
}

/**
@@ -2301,10 +2314,18 @@ public class Player extends FreeColGameObject implements Nameable {
*
* @return A list of port {@code Colony}s.
*/
- public List<Colony> getPorts() {
- return (!isEuropean())
- ? Collections.<Colony>emptyList()
- : transform(getColonies(), Colony::isConnectedPort);
+ public final List<Colony> getPorts() {
+ if (!isEuropean())
+ return Collections.<Colony>emptyList();
+
+ synchronized (this.settlements) {
+ List<Colony> result = new ArrayList<>();
+ for (Settlement s : this.settlements)
+ if (s instanceof Colony && s.isConnectedPort())
+ result.add((Colony)s);
+
+ return result;
+ }
}

/**
@@ -2356,8 +2377,29 @@ public class Player extends FreeColGameObject implements Nameable {
*
* @return The sum of the units currently working in the colonies.
*/
- public int getColoniesPopulation() {
- return sum(getColonies(), Colony::getUnitCount);
+ public final int getColoniesPopulation() {
+ synchronized (this.settlements) {
+ int x = 0;
+ for (Settlement s : this.settlements)
+ if (s instanceof Colony)
+ x += ((Colony)s).getUnitCount();
+ return x;
+ }
+ }
+
+ /**
+ * Gets the sum of liberty produced by the player's coloniess.
+ *
+ * @return The sum of of liberty produced by the player's colonies..
+ */
+ public final int getColoniesLiberty() {
+ synchronized (this.settlements) {
+ int x = 0;
+ for (Settlement s : this.settlements)
+ if (s instanceof Colony)
+ x += ((Colony)s).getLiberty();
+ return x;
+ }
}

/**
@@ -2367,8 +2409,13 @@ public class Player extends FreeColGameObject implements Nameable {
* @return The {@code Colony} with the given name, or null if
* not found.
*/
- public Colony getColonyByName(String name) {
- return find(getColonies(), matchKeyEquals(name, Colony::getName));
+ public final Colony getColonyByName(String name) {
+ synchronized (this.settlements) {
+ for (Settlement s : this.settlements)
+ if (s instanceof Colony && Utils.equals(name, ((Colony)s).getName()))
+ return (Colony)s;
+ }
+ return null;
}

/**
@@ -2384,22 +2431,48 @@ public class Player extends FreeColGameObject implements Nameable {
}

/**
- * Get a stream of all colonies this player owns.
+ * Get a fresh list of all colonies this player owns.
*
- * @return A stream of the {@code Colony}s this player owns.
+ * @return A list of the {@code Colony}s this player owns.
*/
- public Stream<Colony> getColonies() {
- return getColonyList().stream();
+ public final List<Colony> getColonies() {
+ synchronized (this.settlements) {
+ List<Colony> result = new ArrayList<>();
+ for (Settlement s : this.settlements)
+ if (s instanceof Colony)
+ result.add((Colony)s);
+ return result;
+ }
}

/**
- * Get a fresh list of all colonies this player owns.
+ * Get the first colony.
*
- * @return A list of the {@code Colony}s this player owns.
+ * @return The first {@code Colony} or null.
*/
- public List<Colony> getColonyList() {
- return transform(getSettlements(), s -> s instanceof Colony,
- s -> (Colony)s);
+ public final Colony getFirstColony() {
+ synchronized (this.settlements) {
+ for (Settlement s : this.settlements)
+ if (s instanceof Colony)
+ return (Colony)s;
+ }
+ return null;
+ }
+
+ /**
+ * Get a list of all colonies this player owns, which can
+ * bombard enemy ships.
+ *
+ * @return A list of the {@code Colony}s then can bombard.
+ */
+ public final List<Colony> getColoniesCanBombard() {
+ synchronized (this.settlements) {
+ List<Colony> result = new ArrayList<>();
+ for (Settlement s : this.settlements)
+ if ((s instanceof Colony) && s.canBombardEnemyShip())
+ result.add((Colony)s);
+ return result;
+ }
}

/**
@@ -2408,9 +2481,10 @@ public class Player extends FreeColGameObject implements Nameable {
* @param comp A {@code Comparator} to operate on the colony list.
* @return A fresh list of the {@code Colony}s this player owns.
*/
- public List<Colony> getSortedColonies(Comparator<Colony> comp) {
- return transform(getSettlements(), s -> s instanceof Colony,
- s -> (Colony)s, comp);
+ public final List<Colony> getSortedColonies(Comparator<Colony> comp) {
+ List<Colony> result = getColonies();
+ Collections.sort(result, comp);
+ return result;
}

/**
@@ -2428,8 +2502,11 @@ public class Player extends FreeColGameObject implements Nameable {
* @return A list of the {@code IndianSettlement}s this player owns.
*/
public List<IndianSettlement> getIndianSettlementList() {
- return transform(getSettlements(), s -> s instanceof IndianSettlement,
- s -> (IndianSettlement)s);
+ List<IndianSettlement> result = new ArrayList<>();
+ for (Settlement s : this.settlements)
+ if (s instanceof IndianSettlement)
+ result.add((IndianSettlement)s);
+ return result;
}

/**
@@ -2441,10 +2518,11 @@ public class Player extends FreeColGameObject implements Nameable {
* missionary.
*/
public List<IndianSettlement> getIndianSettlementsWithMissionaryList(Player p) {
- final Predicate<Settlement> isPred = s ->
- s instanceof IndianSettlement
- && ((IndianSettlement)s).hasMissionary(p);
- return transform(getSettlements(), isPred, s -> (IndianSettlement)s);
+ List<IndianSettlement> result = new ArrayList<>();
+ for (Settlement s : this.settlements)
+ if ((s instanceof IndianSettlement) && ((IndianSettlement)s).hasMissionary(p))
+ result.add((IndianSettlement)s);
+ return result;
}

/**
@@ -2658,9 +2736,8 @@ public class Player extends FreeColGameObject implements Nameable {
* @return A suitable {@code Tile}.
*/
public Tile getFallbackTile() {
- Settlement settlement = first(getSettlements());
- return (settlement != null) ? settlement.getTile()
- : getEntryLocation().getTile();
+ return (this.settlements.size() == 0) ?
+ getEntryLocation().getTile() : this.settlements.get(0).getTile();
}

/**
@@ -2830,7 +2907,7 @@ public class Player extends FreeColGameObject implements Nameable {

// All other European settlements if can see all colonies.
if (hasAbility(Ability.SEE_ALL_COLONIES))
- for (Colony c : getGame().getAllColoniesList(this))
+ for (Colony c : getGame().getAllColonies(this))
vismap.setVisible(c);
}
}
diff --git a/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java b/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java
index be6f59c9eb0..ea707d51be6 100644
--- a/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java
+++ b/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java
@@ -536,7 +536,7 @@ public class EuropeanAIPlayer extends MissionAIPlayer {
enemies.clear();
enemies.addAll(preferred);
}
- List<Colony> colonies = player.getColonyList();
+ List<Colony> colonies = player.getColonies();
// Find a target to attack.
Location target = null;
// Few colonies? Attack the weakest European port
diff --git a/src/net/sf/freecol/server/model/ServerGame.java b/src/net/sf/freecol/server/model/ServerGame.java
index 75cc4db8c09..815f7660010 100644
--- a/src/net/sf/freecol/server/model/ServerGame.java
+++ b/src/net/sf/freecol/server/model/ServerGame.java
@@ -381,7 +381,7 @@ public class ServerGame extends Game implements ServerModelObject {
cs.add(See.perhaps().always(strongest), is);
}
});
- for (Colony c : weakest.getColonyList()) {
+ for (Colony c : weakest.getColonies()) {
updated.addAll(c.getOwnedTiles());
((ServerColony)c).csChangeOwner(strongest, false, cs);//-vis(both),-til
lb.add(" ", c.getName());
diff --git a/src/net/sf/freecol/server/model/ServerPlayer.java b/src/net/sf/freecol/server/model/ServerPlayer.java
index 53dc67c6c5c..745401de83a 100644
--- a/src/net/sf/freecol/server/model/ServerPlayer.java
+++ b/src/net/sf/freecol/server/model/ServerPlayer.java
@@ -35,7 +35,6 @@ import java.util.function.ToIntFunction;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
-import java.util.stream.Stream;

import net.sf.freecol.FreeCol;
import net.sf.freecol.common.FreeColException;
@@ -483,7 +482,7 @@ public class ServerPlayer extends Player implements ServerModelObject {
}

// Quick check for a colony. Do not log, this is the common case.
- if (any(getColonies())) return IS_ALIVE;
+ if (hasSettlements()) return IS_ALIVE;

// Do not kill the observing player during a debug run.
if (!isAI() && FreeColDebugger.getDebugRunTurns() >= 0) return IS_ALIVE;
@@ -835,7 +834,7 @@ public class ServerPlayer extends Player implements ServerModelObject {
public boolean updateScore() {
int oldScore = this.score;
this.score = sum(getUnits(), Unit::getScoreValue)
- + sum(getColonies(), Colony::getLiberty)
+ + getColoniesLiberty()
+ SCORE_FOUNDING_FATHER * count(getFathers());
int gold = getGold();
if (gold != GOLD_NOT_ACCOUNTED) {
@@ -1433,7 +1432,7 @@ public class ServerPlayer extends Player implements ServerModelObject {
public void csNaturalDisasters(Random random, ChangeSet cs,
int probability) {
if (randomInt(logger, "Natural disaster", random, 100) < probability) {
- List<Colony> colonies = getColonyList();
+ List<Colony> colonies = getColonies();
int size = colonies.size();
if (size <= 0) return;
// Randomly select a colony to start with, then generate
@@ -1868,7 +1867,7 @@ outer: for (Effect effect : effects) {
&& (atWarWith(u.getOwner()) || u.hasAbility(Ability.PIRACY)));
// For all colonies that are able to bombard, search neighbouring
// tiles for targets, and fire!
- for (Colony c : transform(getColonies(), Colony::canBombardEnemyShip)) {
+ for (Colony c : getColoniesCanBombard()) {
Tile tile = c.getTile();
for (Unit u : transform(flatten(tile.getSurroundingTiles(1, 1),
Tile::getUnits),
@@ -1933,7 +1932,7 @@ outer: for (Effect effect : effects) {
// Check for tiles that are now visible. They need to be
// explored, and always updated so that units are visible.
// *Requires that canSee[] has **not** been updated yet!*
- Stream<Colony> colonies = (hasAbility(Ability.SEE_ALL_COLONIES))
+ List<Colony> colonies = (hasAbility(Ability.SEE_ALL_COLONIES))
? getGame().getAllColonies(null)
: getColonies();
Set<Tile> tiles
@@ -1947,7 +1946,7 @@ outer: for (Effect effect : effects) {
cs.add(See.only(this), tiles);
visibilityChange = true;
} else if (Modifier.SOL.equals(m.getId())) {
- for (Colony c : getColonyList()) {
+ for (Colony c : getColonies()) {
c.addLiberty(0); // Kick the SoL and production bonus
c.invalidateCache();
}
@@ -1993,14 +1992,14 @@ outer: for (Effect effect : effects) {

case "model.event.freeBuilding":
BuildingType type = spec.getBuildingType(event.getValue());
- for (Colony c : getColonyList()) {
+ for (Colony c : getColonies()) {
((ServerColony)c).csFreeBuilding(type, cs);
}
break;

case "model.event.seeAllColonies":
visibilityChange = true;//-vis(this), can now see other colonies
- for (Colony colony : game.getAllColoniesList(null)) {
+ for (Colony colony : game.getAllColonies(null)) {
final Tile t = colony.getTile();
Set<Tile> tiles = new HashSet<>();
if (exploreTile(t)) {
@@ -4077,7 +4076,7 @@ outer: for (Effect effect : effects) {
= transform(mercs, au -> au.getType(spec).isNaval());
Tile dst;
if (naval.isEmpty()) { // Deliver to first settlement
- dst = first(getColonies()).getTile();
+ dst = getFirstColony().getTile();
createUnits(mercs, dst);//-vis: safe, in colony
cs.add(See.only(this), dst);
} else { // Let them sail in
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:31 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

Dont need the overhead of stream operations with locally allocated
comparator object - just scan over the list and find the max.
---
src/net/sf/freecol/common/model/ProductionType.java | 21 ++++++++++++++++-----
1 file changed, 16 insertions(+), 5 deletions(-)

diff --git a/src/net/sf/freecol/common/model/ProductionType.java b/src/net/sf/freecol/common/model/ProductionType.java
index 068c96bba17..58d1469f5db 100644
--- a/src/net/sf/freecol/common/model/ProductionType.java
+++ b/src/net/sf/freecol/common/model/ProductionType.java
@@ -24,7 +24,6 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
-import java.util.function.Predicate;

import javax.xml.stream.XMLStreamException;

@@ -368,10 +367,22 @@ public class ProductionType extends FreeColSpecObject {
* @return The best production.
*/
public AbstractGoods getBestOutputFor(GoodsType goodsType) {
- final Predicate<AbstractGoods> typePred = ag ->
- goodsType == null || ag.getType() == goodsType;
- return maximize(getOutputs(), typePred,
- AbstractGoods.ascendingAmountComparator);
+ if (outputs == null)
+ return null;
+
+ int max_amount = 0;
+ AbstractGoods max_ag = null;
+ for (AbstractGoods walk : outputs) {
+ if (goodsType == null || walk.getType() == goodsType) {
+ int a = walk.getAmount();
+ if (max_ag == null || a > max_amount) {
+ max_amount = a;
+ max_ag = walk;
+ }
+ }
+ }
+
+ return max_ag;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:02 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../client/gui/panel/report/ReportRequirementsPanel.java | 2 +-
src/net/sf/freecol/common/model/Building.java | 16 ++++++++--------
src/net/sf/freecol/common/model/ColonyTile.java | 10 +++++-----
src/net/sf/freecol/common/model/ProductionType.java | 16 ++++++++--------
src/net/sf/freecol/common/model/WorkLocation.java | 12 ++++++------
src/net/sf/freecol/server/model/ServerBuilding.java | 4 ++--
test/src/net/sf/freecol/common/model/BuildingTest.java | 2 +-
.../sf/freecol/common/model/ColonyProductionTest.java | 2 +-
.../net/sf/freecol/common/model/ProductionTypeTest.java | 4 ++--
9 files changed, 34 insertions(+), 34 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/panel/report/ReportRequirementsPanel.java b/src/net/sf/freecol/client/gui/panel/report/ReportRequirementsPanel.java
index b6823509b74..c95cfcfbf7a 100644
--- a/src/net/sf/freecol/client/gui/panel/report/ReportRequirementsPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/report/ReportRequirementsPanel.java
@@ -161,7 +161,7 @@ public final class ReportRequirementsPanel extends ReportPanel {
}

for (Building building : colony.getBuildings()) {
- for (AbstractGoods output : iterable(building.getOutputs())) {
+ for (AbstractGoods output : building.getOutputs()) {
GoodsType goodsType = output.getType();
UnitType expert = spec.getExpertForProducing(goodsType);

diff --git a/src/net/sf/freecol/common/model/Building.java b/src/net/sf/freecol/common/model/Building.java
index e07c180fc93..b3774d3ffa9 100644
--- a/src/net/sf/freecol/common/model/Building.java
+++ b/src/net/sf/freecol/common/model/Building.java
@@ -260,8 +260,8 @@ public class Building extends WorkLocation
// First, calculate the nominal production ratios.
if (canAutoProduce()) {
// Autoproducers are special
- for (AbstractGoods output : transform(getOutputs(),
- AbstractGoods::isPositive)) {
+ for (AbstractGoods output : getOutputs()) {
+ if (!output.isPositive()) continue;
final GoodsType goodsType = output.getType();
int available = getColony().getGoodsCount(goodsType);
if (available >= capacity) {
@@ -281,7 +281,7 @@ public class Building extends WorkLocation
}
}
} else {
- for (AbstractGoods output : iterable(getOutputs())) {
+ for (AbstractGoods output : getOutputs()) {
final GoodsType goodsType = output.getType();
float production = sum(getUnits(),
u -> getUnitProduction(u, goodsType));
@@ -299,7 +299,7 @@ public class Building extends WorkLocation
}

// Then reduce the minimum ratio if some input is in short supply.
- for (AbstractGoods input : iterable(getInputs())) {
+ for (AbstractGoods input : getInputs()) {
long required = (long)Math.floor(input.getAmount() * minimumRatio);
long available = getAvailable(input.getType(), inputs);
// Do not allow auto-production to go negative.
@@ -327,7 +327,7 @@ public class Building extends WorkLocation
// Check whether there is space enough to store the goods
// produced in order to avoid excess production.
if (avoidOverflow) {
- for (AbstractGoods output : iterable(getOutputs())) {
+ for (AbstractGoods output : getOutputs()) {
double production = output.getAmount() * minimumRatio;
if (production <= 0) continue;
double headroom = (double)capacity
@@ -346,7 +346,7 @@ public class Building extends WorkLocation
}

final double epsilon = 0.0001;
- for (AbstractGoods input : iterable(getInputs())) {
+ for (AbstractGoods input : getInputs()) {
GoodsType type = input.getType();
// maximize consumption
int consumption = (int)Math.floor(input.getAmount()
@@ -358,7 +358,7 @@ public class Building extends WorkLocation
result.addMaximumConsumption(new AbstractGoods(type, maximumConsumption));
}
}
- for (AbstractGoods output : iterable(getOutputs())) {
+ for (AbstractGoods output : getOutputs()) {
GoodsType type = output.getType();
// minimize production, but add a magic little something
// to counter rounding errors
@@ -612,7 +612,7 @@ public class Building extends WorkLocation
*/
@Override
public List<AbstractGoods> getConsumedGoods() {
- return toList(getInputs());
+ return getInputs();
}

/**
diff --git a/src/net/sf/freecol/common/model/ColonyTile.java b/src/net/sf/freecol/common/model/ColonyTile.java
index 7be9951cdff..6447fa597e3 100644
--- a/src/net/sf/freecol/common/model/ColonyTile.java
+++ b/src/net/sf/freecol/common/model/ColonyTile.java
@@ -160,7 +160,7 @@ public class ColonyTile extends WorkLocation {
final Colony colony = getColony();
ProductionInfo pi = new ProductionInfo();
if (isColonyCenterTile()) {
- forEach(getOutputs(), output -> {
+ for (AbstractGoods output : getOutputs()) {
boolean onlyNaturalImprovements = getSpecification()
.getBoolean(GameOptions.ONLY_NATURAL_IMPROVEMENTS)
&& !output.getType().isFoodType();
@@ -174,13 +174,13 @@ public class ColonyTile extends WorkLocation {
AbstractGoods production
= new AbstractGoods(output.getType(), potential);
pi.addProduction(production);
- });
+ }
} else {
- forEach(map(getOutputs(), AbstractGoods::getType),
- gt -> {
+ for (AbstractGoos ag : getOutputs()) {
+ GoodsType gt = ag.getType();
int n = sum(getUnits(), u -> getUnitProduction(u, gt));
if (n > 0) pi.addProduction(new AbstractGoods(gt, n));
- });
+ }
}
return pi;
}
diff --git a/src/net/sf/freecol/common/model/ProductionType.java b/src/net/sf/freecol/common/model/ProductionType.java
index 5cb3091e8cd..f6a769de9c0 100644
--- a/src/net/sf/freecol/common/model/ProductionType.java
+++ b/src/net/sf/freecol/common/model/ProductionType.java
@@ -21,10 +21,10 @@ package net.sf.freecol.common.model;

import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;
-import java.util.stream.Stream;

import javax.xml.stream.XMLStreamException;

@@ -149,9 +149,9 @@ public class ProductionType extends FreeColSpecObject {
*
* @return A stream of the input {@code AbstractGoods}.
*/
- public final Stream<AbstractGoods> getInputs() {
- return (inputs == null) ? Stream.<AbstractGoods>empty()
- : inputs.stream();
+ public final List<AbstractGoods> getInputs() {
+ return (inputs == null) ? Collections.<AbstractGoods>emptyList()
+ : inputs;
}

/**
@@ -177,11 +177,11 @@ public class ProductionType extends FreeColSpecObject {
/**
* Get the output goods.
*
- * @return A stream of the output {@code AbstractGoods}.
+ * @return A {@code List} of the output {@code AbstractGoods}.
*/
- public final Stream<AbstractGoods> getOutputs() {
- return (outputs == null) ? Stream.<AbstractGoods>empty()
- : outputs.stream();
+ public final List<AbstractGoods> getOutputs() {
+ return (outputs == null) ? Collections.<AbstractGoods>emptyList()
+ : outputs;
}

/**
diff --git a/src/net/sf/freecol/common/model/WorkLocation.java b/src/net/sf/freecol/common/model/WorkLocation.java
index 67e01daf317..c76c2f5a35c 100644
--- a/src/net/sf/freecol/common/model/WorkLocation.java
+++ b/src/net/sf/freecol/common/model/WorkLocation.java
@@ -410,10 +410,10 @@ public abstract class WorkLocation extends UnitLocation
/**
* Get the {@code AbstractGoods} consumed by this work location.
*
- * @return A stream of {@code AbstractGoods} consumed.
+ * @return A {@code List} of {@code AbstractGoods} consumed.
*/
- public Stream<AbstractGoods> getInputs() {
- return (productionType == null) ? Stream.<AbstractGoods>empty()
+ public List<AbstractGoods> getInputs() {
+ return (productionType == null) ? Collections.<AbstractGoods>emptyList()
: productionType.getInputs();
}

@@ -422,8 +422,8 @@ public abstract class WorkLocation extends UnitLocation
*
* @return A stream of {@code AbstractGoods} produced.
*/
- public Stream<AbstractGoods> getOutputs() {
- return (productionType == null) ? Stream.<AbstractGoods>empty()
+ public List<AbstractGoods> getOutputs() {
+ return (productionType == null) ? Collections.<AbstractGoods>emptyList()
: productionType.getOutputs();
}

@@ -444,7 +444,7 @@ public abstract class WorkLocation extends UnitLocation
* @return True if there are any inputs.
*/
public boolean hasInputs() {
- return any(getInputs());
+ return getInputs().size() > 0;
}

/**
diff --git a/src/net/sf/freecol/server/model/ServerBuilding.java b/src/net/sf/freecol/server/model/ServerBuilding.java
index e815be6337a..7691ff96981 100644
--- a/src/net/sf/freecol/server/model/ServerBuilding.java
+++ b/src/net/sf/freecol/server/model/ServerBuilding.java
@@ -219,8 +219,8 @@ public class ServerBuilding extends Building implements ServerModelObject {
*/
public void csCheckMissingInput(ProductionInfo pi, ChangeSet cs) {
if (!canAutoProduce() && pi.getProduction().isEmpty()) {
- for (GoodsType gt : transform(getInputs(), alwaysTrue(),
- AbstractGoods::getType)) {
+ for (AbstractGoods ag : getInputs()) {
+ GoodsType gt = ag.getType();
cs.addMessage(getOwner(),
new ModelMessage(ModelMessage.MessageType.MISSING_GOODS,
"model.building.notEnoughInput",
diff --git a/test/src/net/sf/freecol/common/model/BuildingTest.java b/test/src/net/sf/freecol/common/model/BuildingTest.java
index e76063613d7..ec8585015e5 100644
--- a/test/src/net/sf/freecol/common/model/BuildingTest.java
+++ b/test/src/net/sf/freecol/common/model/BuildingTest.java
@@ -990,7 +990,7 @@ public class BuildingTest extends FreeColTestCase {
for (Building building : colony.getBuildings()) {
clearWorkLocation(building);
unit.setLocation(building);
- for (AbstractGoods output : iterable(building.getOutputs())) {
+ for (AbstractGoods output : building.getOutputs()) {
GoodsType outputType = output.getType();
for (UnitType type : transform(spec().getUnitTypeList(),
ut -> (building.getType().canAdd(ut)
diff --git a/test/src/net/sf/freecol/common/model/ColonyProductionTest.java b/test/src/net/sf/freecol/common/model/ColonyProductionTest.java
index 0ced7597b5b..3914b710a60 100644
--- a/test/src/net/sf/freecol/common/model/ColonyProductionTest.java
+++ b/test/src/net/sf/freecol/common/model/ColonyProductionTest.java
@@ -221,7 +221,7 @@ public class ColonyProductionTest extends FreeColTestCase {
Unit unit = colony.getFirstUnit();
unit.setLocation(colony.getWorkLocationFor(unit, bellsType));

- List<AbstractGoods> outputs = toList(pasture.getOutputs());
+ List<AbstractGoods> outputs = pasture.getOutputs();
assertEquals(1, outputs.size());
assertEquals(horsesType, outputs.get(0).getType());

diff --git a/test/src/net/sf/freecol/common/model/ProductionTypeTest.java b/test/src/net/sf/freecol/common/model/ProductionTypeTest.java
index 060952cc380..876fdf4220d 100644
--- a/test/src/net/sf/freecol/common/model/ProductionTypeTest.java
+++ b/test/src/net/sf/freecol/common/model/ProductionTypeTest.java
@@ -216,14 +216,14 @@ public class ProductionTypeTest extends FreeColTestCase {
Map<GoodsType, Integer> outputs,
List<ProductionType> productionTypes) {
for (ProductionType productionType : productionTypes) {
- for (AbstractGoods ag : toList(productionType.getInputs())) {
+ for (AbstractGoods ag : productionType.getInputs()) {
Integer i = inputs.get(ag.getType());
assertNotNull("Input expected for " + ag.getType(), i);
assertEquals("Input amount mismatch for " + ag.getType(),
i.intValue(), ag.getAmount());
inputs.remove(ag.getType());
}
- for (AbstractGoods ag : toList(productionType.getOutputs())) {
+ for (AbstractGoods ag : productionType.getOutputs()) {
Integer i = outputs.get(ag.getType());
assertNotNull("Output expected for " + ag.getType(), i);
assertEquals("Output amount mismatch for " + ag.getType(),
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:30:49 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

We have several places which are just interested in Player's ports
instead of all colonies. Instead of filtering the lists ourselves,
just ask Player for ports instead of all colonies.
---
src/net/sf/freecol/common/model/Unit.java | 4 ++--
src/net/sf/freecol/server/ai/EuropeanAIPlayer.java | 4 ++--
src/net/sf/freecol/server/ai/REFAIPlayer.java | 4 ++--
3 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index c3a7d55a5f9..e2a7394c377 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -3021,8 +3021,8 @@ public class Unit extends GoodsLocation
// Ocean travel required, destination blocked.
// Find the closest available connected port.
final Predicate<Settlement> portPredicate = s ->
- s != ignoreSrc && s != ignoreDst && s.isConnectedPort();
- sett = minimize(getOwner().getSettlements(), portPredicate,
+ s != ignoreSrc && s != ignoreDst;
+ sett = minimize(getOwner().getPorts(), portPredicate,
settlementComparator);
path = (sett == null) ? null : this.findPath(sett);
break;
diff --git a/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java b/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java
index e0c6907413d..43931858669 100644
--- a/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java
+++ b/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java
@@ -549,8 +549,8 @@ public class EuropeanAIPlayer extends MissionAIPlayer {
: score / (stockade.getLevel() + 1.5);
});
target = maximize(flatten(enemies, Player::isEuropean,
- Player::getColonies),
- Colony::isConnectedPort, targetScore);
+ Player::getPorts),
+ targetScore);
}
// Otherwise attack something near a weak colony
if (target == null && !colonies.isEmpty()) {
diff --git a/src/net/sf/freecol/server/ai/REFAIPlayer.java b/src/net/sf/freecol/server/ai/REFAIPlayer.java
index 8cad3d5a4e9..0c73f5bedf3 100644
--- a/src/net/sf/freecol/server/ai/REFAIPlayer.java
+++ b/src/net/sf/freecol/server/ai/REFAIPlayer.java
@@ -188,14 +188,14 @@ public class REFAIPlayer extends EuropeanAIPlayer {
= new CachingFunction<Colony, PathNode>(c ->
unit.findPath(carrier, c, carrier, null));
final Predicate<Colony> portPred = c ->
- (!port || c.isConnectedPort()) && pathMapper.apply(c) != null;
+ pathMapper.apply(c) != null;
final Function<Colony, TargetTuple> newTupleMapper = c -> {
PathNode path = pathMapper.apply(c);
return new TargetTuple(c, path,
UnitSeekAndDestroyMission.scorePath(aiu, path));
};
final List<TargetTuple> targets
- = transform(flatten(player.getRebels(), Player::getColonies),
+ = transform(flatten(player.getRebels(), (port ? Player::getPorts : Player::getColonies)),
portPred, newTupleMapper);

// Increase score for drydock/s, musket and tools suppliers,
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:39 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../freecol/client/gui/panel/report/ReportMilitaryPanel.java | 2 +-
src/net/sf/freecol/common/model/IndianSettlement.java | 2 +-
src/net/sf/freecol/common/model/Monarch.java | 2 +-
src/net/sf/freecol/common/model/Settlement.java | 2 +-
src/net/sf/freecol/common/model/Specification.java | 11 +----------
src/net/sf/freecol/common/model/Unit.java | 2 +-
test/src/net/sf/freecol/common/model/RoleTest.java | 2 +-
7 files changed, 7 insertions(+), 16 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/panel/report/ReportMilitaryPanel.java b/src/net/sf/freecol/client/gui/panel/report/ReportMilitaryPanel.java
index 58225a8e084..c3fcbe45fa3 100644
--- a/src/net/sf/freecol/client/gui/panel/report/ReportMilitaryPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/report/ReportMilitaryPanel.java
@@ -123,7 +123,7 @@ public final class ReportMilitaryPanel extends ReportUnitPanel {

// Report unit types that are inherently reportable, and units
// with military roles.
- final List<Role> militaryRoles = spec.getMilitaryRolesList();
+ final List<Role> militaryRoles = spec.getMilitaryRoles();
for (UnitType ut : spec.getUnitTypeList()) {
if (reportable(ut)) {
tryUnitRole(ut, Specification.DEFAULT_ROLE_ID);
diff --git a/src/net/sf/freecol/common/model/IndianSettlement.java b/src/net/sf/freecol/common/model/IndianSettlement.java
index e3b8e3e6122..72b71b8a2f5 100644
--- a/src/net/sf/freecol/common/model/IndianSettlement.java
+++ b/src/net/sf/freecol/common/model/IndianSettlement.java
@@ -822,7 +822,7 @@ public class IndianSettlement extends Settlement implements TradeLocation {
final Specification spec = getSpecification();
final UnitType unitType = getFirstUnit().getType();
final List<Role> militaryRoles = Role.getAvailableRoles(getOwner(),
- unitType, spec.getMilitaryRolesList());
+ unitType, spec.getMilitaryRoles());

if (type.getMilitary()) { // Retain enough goods to fully arm
return sum(getOwnedUnits(),
diff --git a/src/net/sf/freecol/common/model/Monarch.java b/src/net/sf/freecol/common/model/Monarch.java
index 02e9135fd0c..8ea6afe28a7 100644
--- a/src/net/sf/freecol/common/model/Monarch.java
+++ b/src/net/sf/freecol/common/model/Monarch.java
@@ -311,7 +311,7 @@ public final class Monarch extends FreeColGameObject implements Named {
mercenaryTypes.add(unitType);
}
}
- for (Role r : spec.getMilitaryRolesList()) {
+ for (Role r : spec.getMilitaryRoles()) {
boolean ok = r.isAvailableTo(player, first(landTypes));
boolean armed = r.hasAbility(Ability.ARMED);
boolean mounted = r.hasAbility(Ability.MOUNTED);
diff --git a/src/net/sf/freecol/common/model/Settlement.java b/src/net/sf/freecol/common/model/Settlement.java
index deb26d6f2d8..7b43c2eafca 100644
--- a/src/net/sf/freecol/common/model/Settlement.java
+++ b/src/net/sf/freecol/common/model/Settlement.java
@@ -427,7 +427,7 @@ public abstract class Settlement extends GoodsLocation
final Role role = unit.getRole();

// Get the military roles that are superior to the current role
- List<Role> military = spec.getMilitaryRolesList();
+ List<Role> military = spec.getMilitaryRoles();
int index = military.indexOf(role);
if (index >= 0) military = military.subList(0, index);

diff --git a/src/net/sf/freecol/common/model/Specification.java b/src/net/sf/freecol/common/model/Specification.java
index 4154bc6b0c8..3e7b5364044 100644
--- a/src/net/sf/freecol/common/model/Specification.java
+++ b/src/net/sf/freecol/common/model/Specification.java
@@ -1660,7 +1660,7 @@ public final class Specification {
*
* @return An unmodifiable list of military {@code Role}s.
*/
- public List<Role> getMilitaryRolesList() {
+ public List<Role> getMilitaryRoles() {
if (this.militaryRoles == null) {
this.militaryRoles = Collections.<Role>unmodifiableList(
transform(this.roles, Role::isOffensive, Function.identity(),
@@ -1670,15 +1670,6 @@ public final class Specification {
}

/**
- * Get the available military roles as a stream.
- *
- * @return A stream of military {@code Role}s.
- */
- public Stream<Role> getMilitaryRoles() {
- return getMilitaryRolesList().stream();
- }
-
- /**
* Gets the roles suitable for a REF unit.
*
* @param naval If true, choose roles for naval units, if not, land units.
diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index e4e545a8559..b4f875550ec 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -1782,7 +1782,7 @@ public class Unit extends GoodsLocation
if (!hasAbility(Ability.CAPTURE_EQUIPMENT)) return null;
final Specification spec = getSpecification();
final Role oldRole = getRole();
- return find(getAvailableRoles(spec.getMilitaryRolesList()),
+ return find(getAvailableRoles(spec.getMilitaryRoles()),
r -> any(r.getRoleChanges(), rc ->
rc.getFrom(spec) == oldRole && rc.getCapture(spec) == role));
}
diff --git a/test/src/net/sf/freecol/common/model/RoleTest.java b/test/src/net/sf/freecol/common/model/RoleTest.java
index 983bd21ab79..76fc899f942 100644
--- a/test/src/net/sf/freecol/common/model/RoleTest.java
+++ b/test/src/net/sf/freecol/common/model/RoleTest.java
@@ -130,7 +130,7 @@ public class RoleTest extends FreeColTestCase {

public void testMilitaryRoles() {
final Game game = getStandardGame();
- final List<Role> military = spec().getMilitaryRolesList();
+ final List<Role> military = spec().getMilitaryRoles();

List<Role> expectedRoles = new ArrayList<>();
expectedRoles.add(dragoon);
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:15 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Colony.java | 29 +++++++++++++++++++----------
1 file changed, 19 insertions(+), 10 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index 8d6851870b8..93c1a4ed575 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -1808,19 +1808,28 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
return null; // No automatic assignment
final GoodsType expertProduction
= teacher.getType().getExpertProduction();
- final Predicate<Unit> teacherPred = u ->
- u.getTeacher() == null && u.canBeStudent(teacher);
// Always pick the student with the least skill first.
// Break ties by favouring the one working in the teacher's trade,
// otherwise first applicant wins.
- final Comparator<Unit> skillComparator
- = Comparator.comparingInt(Unit::getSkillLevel);
- final Comparator<Unit> tradeComparator
- = Comparator.comparingInt(u ->
- (u.getWorkType() == expertProduction) ? 0 : 1);
- final Comparator<Unit> fullComparator
- = skillComparator.thenComparing(tradeComparator);
- return minimize(getUnits(), teacherPred, fullComparator);
+ Unit min_unit = null;
+ int min_skill = Integer.MAX_VALUE;
+
+ for (Unit u : getUnits()) {
+ if (!(u.getTeacher() == null && u.canBeStudent(teacher)))
+ continue;
+
+ int level = u.getSkillLevel();
+ if ((min_unit == null) || (level < min_skill)) {
+ min_unit = u;
+ min_skill = level;
+ } else if ((level == min_skill) &&
+ (min_unit.getWorkType() != expertProduction) &&
+ (u.getWorkType() == expertProduction)) {
+ min_unit = u;
+ }
+ }
+
+ return min_unit;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:42 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Specification.java | 29 ++++------------------
src/net/sf/freecol/common/model/Unit.java | 14 +----------
src/net/sf/freecol/common/model/UnitWas.java | 2 +-
3 files changed, 7 insertions(+), 38 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Specification.java b/src/net/sf/freecol/common/model/Specification.java
index 950ea4d0049..0ca84faa35c 100644
--- a/src/net/sf/freecol/common/model/Specification.java
+++ b/src/net/sf/freecol/common/model/Specification.java
@@ -1661,28 +1661,6 @@ public final class Specification {
}

/**
- * Gets the roles suitable for a REF unit.
- *
- * @param naval If true, choose roles for naval units, if not, land units.
- * @return A list of {@code Role}s suitable for REF units.
- */
- public List<Role> getREFRolesList(boolean naval) {
- return transform(((naval) ? Stream.of(getDefaultRole())
- : getMilitaryRoles()),
- r -> r.requiresAbility(Ability.REF_UNIT));
- }
-
- /**
- * Gets the roles suitable for a REF unit as a stream.
- *
- * @param naval If true, choose roles for naval units, if not, land units.
- * @return A stream of {@code Role}s suitable for REF units.
- */
- public Stream<Role> getREFRoles(boolean naval) {
- return getREFRolesList(naval).stream();
- }
-
- /**
* Get a role with an ability.
*
* @param id The ability identifier to look for.
@@ -1692,7 +1670,10 @@ public final class Specification {
* ability, or null if none found.
*/
public Role getRoleWithAbility(String id, List<Role> roles) {
- return find(getRoles(), r -> r.hasAbility(id));
+ for (Role r : this.roles)
+ if (r.hasAbility(id))
+ return r;
+ return null;
}

/**
@@ -2030,7 +2011,7 @@ public final class Specification {
}

StrCat cat = new StrCat(" ");
- for (Role r : getRoles())
+ for (Role r : this.roles)
cat.add(r.getId());

logger.info("Loading role backward compatibility fragment: "
diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index 3f8b9b971c8..7aa3266f0fd 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -884,24 +884,12 @@ public class Unit extends GoodsLocation
* available roles are used.
* @return A list of available {@code Role}s.
*/
- public List<Role> getAvailableRolesList(List<Role> roles) {
+ public List<Role> getAvailableRoles(List<Role> roles) {
if (roles == null) roles = getSpecification().getRoles();
return transform(roles, r -> roleIsAvailable(r));
}

/**
- * Filter a list of roles to return only those available to this unit,
- * returning a stream.
- *
- * @param roles The list of {@code Role}s to filter, if null all
- * available roles are used.
- * @return A stream of available {@code Role}s.
- */
- public Stream<Role> getAvailableRoles(List<Role> roles) {
- return getAvailableRolesList(roles).stream();
- }
-
- /**
* Get a military role for this unit.
*
* @return A military {@code Role}, or null if none found.
diff --git a/src/net/sf/freecol/common/model/UnitWas.java b/src/net/sf/freecol/common/model/UnitWas.java
index e6c5597a9f8..e482a6d87ca 100644
--- a/src/net/sf/freecol/common/model/UnitWas.java
+++ b/src/net/sf/freecol/common/model/UnitWas.java
@@ -201,7 +201,7 @@ public class UnitWas implements Comparable<UnitWas> {
// we can still try our best by using the amount of equipment
// the unit needs as a secondary criterion (favouring the
// least equipped).
- List<Role> roles = this.unit.getAvailableRolesList(null);
+ List<Role> roles = this.unit.getAvailableRoles(null);
int cmp = ((UnitLocation)uw.loc).getUnitCapacity()
- ((UnitLocation)this.loc).getUnitCapacity();
if (cmp == 0) {
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:25 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../client/gui/dialog/SelectDestinationDialog.java | 16 +-
src/net/sf/freecol/client/gui/menu/DebugMenu.java | 2 +-
.../client/gui/panel/FindSettlementPanel.java | 2 +-
.../sf/freecol/client/gui/panel/PlayersTable.java | 2 +-
.../gui/panel/colopedia/NationDetailPanel.java | 4 +-
.../gui/panel/report/ReportForeignAffairPanel.java | 2 +-
src/net/sf/freecol/common/debug/DebugUtils.java | 4 +-
src/net/sf/freecol/common/model/Game.java | 185 +++++++++++----------
src/net/sf/freecol/common/model/Operand.java | 2 +-
src/net/sf/freecol/common/model/Player.java | 14 +-
src/net/sf/freecol/common/model/Tile.java | 2 +-
.../common/networking/AddPlayerMessage.java | 10 --
.../sf/freecol/common/networking/ChangeSet.java | 4 +-
.../sf/freecol/common/networking/LoginMessage.java | 2 +-
src/net/sf/freecol/server/FreeColServer.java | 14 +-
src/net/sf/freecol/server/ai/EuropeanAIPlayer.java | 2 +-
src/net/sf/freecol/server/ai/NativeAIPlayer.java | 2 +-
.../freecol/server/control/InGameController.java | 2 +-
.../freecol/server/control/PreGameController.java | 2 +-
.../server/generator/SimpleMapGenerator.java | 6 +-
src/net/sf/freecol/server/model/ServerGame.java | 2 +-
src/net/sf/freecol/server/model/ServerPlayer.java | 12 +-
.../freecol/common/model/FoundingFatherTest.java | 4 +-
test/src/net/sf/freecol/common/model/GameTest.java | 4 +-
.../freecol/common/model/UnitChangeTypeTest.java | 2 +-
.../net/sf/freecol/util/test/FreeColTestCase.java | 2 +-
26 files changed, 157 insertions(+), 148 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/dialog/SelectDestinationDialog.java b/src/net/sf/freecol/client/gui/dialog/SelectDestinationDialog.java
index 05208c71936..f9c10d55aee 100644
--- a/src/net/sf/freecol/client/gui/dialog/SelectDestinationDialog.java
+++ b/src/net/sf/freecol/client/gui/dialog/SelectDestinationDialog.java
@@ -30,7 +30,6 @@ import java.util.Map.Entry;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Logger;
-import java.util.stream.Stream;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
@@ -459,14 +458,13 @@ public final class SelectDestinationDialog extends FreeColDialog<Location>
// of accessible settlement locations and do a bulk path search
// to determine the travel times, and create Destinations from
// the results.
- final Predicate<Player> tradePred = p ->
- p.hasContacted(player) && (canTrade || !p.isEuropean());
- final Function<Player, Stream<Location>> settlementTileMapper = p ->
- transform(p.getSettlements(),
- s -> canReach.test(s) && s.hasContacted(p),
- s -> (Location)s.getTile()).stream();
- List<Location> locs = toList(flatten(game.getLivePlayers(player),
- tradePred, settlementTileMapper));
+ List<Location> locs = new ArrayList<>();
+ for (Player op : game.getLivePlayers(player))
+ if (op.hasContacted(player) && (canTrade || !op.isEuropean()))
+ for (Settlement s : op.getSettlements())
+ if (canReach.test(s) && s.hasContacted(op))
+ locs.add(s.getTile());
+
MultipleAdjacentDecider md = new MultipleAdjacentDecider(locs);
unit.search(unit.getLocation(), md.getGoalDecider(), null,
FreeColObject.INFINITY, null);
diff --git a/src/net/sf/freecol/client/gui/menu/DebugMenu.java b/src/net/sf/freecol/client/gui/menu/DebugMenu.java
index e683bcc7c02..d56f8002c62 100644
--- a/src/net/sf/freecol/client/gui/menu/DebugMenu.java
+++ b/src/net/sf/freecol/client/gui/menu/DebugMenu.java
@@ -154,7 +154,7 @@ public class DebugMenu extends JMenu {
});
this.add(cvpMenu);
cvpMenu.addSeparator();
- for (Player p : game.getLiveEuropeanPlayerList()) {
+ for (Player p : game.getLiveEuropeanPlayers()) {
final JRadioButtonMenuItem cv2
= Utility.localizedRadioButtonMenuItem(p.getCountryLabel(),
FreeColDebugger.debugDisplayColonyValuePlayer() == p);
diff --git a/src/net/sf/freecol/client/gui/panel/FindSettlementPanel.java b/src/net/sf/freecol/client/gui/panel/FindSettlementPanel.java
index 606dcc5fc39..d17db5b1c88 100644
--- a/src/net/sf/freecol/client/gui/panel/FindSettlementPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/FindSettlementPanel.java
@@ -160,7 +160,7 @@ public final class FindSettlementPanel extends FreeColPanel
= new DefaultListModel<>();
Object selected = this.settlementList.getSelectedValue();

- for (Player player : getGame().getLivePlayerList()) {
+ for (Player player : getGame().getLivePlayers()) {
boolean ok;
switch (displayListOption) {
case ONLY_NATIVES:
diff --git a/src/net/sf/freecol/client/gui/panel/PlayersTable.java b/src/net/sf/freecol/client/gui/panel/PlayersTable.java
index 0c30f39d1ca..bf5524512a7 100644
--- a/src/net/sf/freecol/client/gui/panel/PlayersTable.java
+++ b/src/net/sf/freecol/client/gui/panel/PlayersTable.java
@@ -458,7 +458,7 @@ public final class PlayersTable extends JTable {
*/
public void update() {
for (Nation n : this.nations) nationMap.put(n, null);
- for (Player p : thisPlayer.getGame().getLivePlayerList()) {
+ for (Player p : thisPlayer.getGame().getLivePlayers()) {
nationMap.put(p.getNation(), p);
}
fireTableDataChanged();
diff --git a/src/net/sf/freecol/client/gui/panel/colopedia/NationDetailPanel.java b/src/net/sf/freecol/client/gui/panel/colopedia/NationDetailPanel.java
index 26b6524f5dd..47436a5c929 100644
--- a/src/net/sf/freecol/client/gui/panel/colopedia/NationDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/colopedia/NationDetailPanel.java
@@ -79,8 +79,8 @@ public class NationDetailPanel extends ColopediaGameObjectTypePanel<Nation> {
if (getId().equals(id)) return;

Nation nation = getSpecification().getNation(id);
- Player player = CollectionUtils.find(getGame().getLivePlayers(),
- p -> p.getNation() == nation);
+ Player player = getGame().getLivePlayerByNation(nation);
+
NationType currentNationType = (player == null) ? nation.getType()
: player.getNationType();

diff --git a/src/net/sf/freecol/client/gui/panel/report/ReportForeignAffairPanel.java b/src/net/sf/freecol/client/gui/panel/report/ReportForeignAffairPanel.java
index f9937dc24bd..3d5c283098b 100644
--- a/src/net/sf/freecol/client/gui/panel/report/ReportForeignAffairPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/report/ReportForeignAffairPanel.java
@@ -79,7 +79,7 @@ public final class ReportForeignAffairPanel extends ReportPanel {
"[align top]"));

int n;
- for (Player enemy : getGame().getLiveEuropeanPlayerList()) {
+ for (Player enemy : getGame().getLiveEuropeanPlayers()) {
NationSummary ns = igc().getNationSummary(enemy);
if (ns == null) continue;

diff --git a/src/net/sf/freecol/common/debug/DebugUtils.java b/src/net/sf/freecol/common/debug/DebugUtils.java
index 98799254bc0..13ddb27a316 100644
--- a/src/net/sf/freecol/common/debug/DebugUtils.java
+++ b/src/net/sf/freecol/common/debug/DebugUtils.java
@@ -735,7 +735,7 @@ public class DebugUtils {
List<Unit> toEurope = new ArrayList<>();
List<Unit> toAmerica = new ArrayList<>();
HashMap<String,List<Unit>> units = new HashMap<>();
- for (Player tp : sGame.getLiveEuropeanPlayerList()) {
+ for (Player tp : sGame.getLiveEuropeanPlayers()) {
Player p = sGame.getFreeColGameObject(tp.getId(), Player.class);
if (p.getEurope() == null) continue;
inEurope.clear();
@@ -1135,7 +1135,7 @@ public class DebugUtils {
LogBuilder lb = new LogBuilder(256);
lb.add(sis.getName(), "\n\nAlarm\n");
Player mostHated = sis.getMostHated();
- for (Player p : sGame.getLiveEuropeanPlayerList()) {
+ for (Player p : sGame.getLiveEuropeanPlayers()) {
Tension tension = sis.getAlarm(p);
lb.add(Messages.message(p.getNationLabel()),
" ", ((tension == null) ? "(none)"
diff --git a/src/net/sf/freecol/common/model/Game.java b/src/net/sf/freecol/common/model/Game.java
index f079c5c54c4..3d4a14b5d6f 100644
--- a/src/net/sf/freecol/common/model/Game.java
+++ b/src/net/sf/freecol/common/model/Game.java
@@ -22,6 +22,8 @@ package net.sf.freecol.common.model;
import java.lang.ref.WeakReference;
import java.io.StringReader;
import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
@@ -31,7 +33,6 @@ import java.util.NoSuchElementException;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
-import java.util.function.Predicate;
import java.util.stream.Stream;

import javax.xml.stream.XMLStreamException;
@@ -510,59 +511,46 @@ public class Game extends FreeColGameObject {
/**
* Get all the players in the game.
*
- * @return The list of {@code Player}s.
+ * @return The {@code Collection} of {@code Player}s.
*/
- public List<Player> getPlayerList() {
+ public Collection<Player> getPlayers() {
return this.players;
}

/**
- * Get all the players in the game as a stream.
- *
- * @return The list of {@code Player}s.
- */
- public Stream<Player> getPlayers() {
- return this.players.stream();
- }
-
- /**
* Sort the players list.
*
* @param comparator The {@code Comparator} to sort with.
*/
public void sortPlayers(Comparator<Player> comparator) {
- this.players.sort(comparator);
- }
-
- /**
- * Get players in the game.
- *
- * @param predicate A {@code Predicate} to select suitable players with.
- * @return A list of {@code Player}s.
- */
- public List<Player> getPlayerList(Predicate<Player> predicate) {
- return transform(this.players, predicate);
+ Collections.sort(this.players, comparator);
}

/**
- * Get players in the game.
+ * Get a {@code Player} identified by its nation.
*
- * @param predicate A {@code Predicate} to select suitable players with.
- * @return The stream of {@code Player}s.
+ * @param nation The {@code Nation} to search for.
+ * @return The {@code Player} of the given nation, or null if
+ * not found.
*/
- public Stream<Player> getPlayers(Predicate<Player> predicate) {
- return getPlayerList(predicate).stream();
+ public Player getPlayerByNation(Nation nation) {
+ return getPlayerByNationId(nation.getId());
}

/**
- * Get a {@code Player} identified by its nation.
+ * Get alive {@code Player} identified by its nation.
*
* @param nation The {@code Nation} to search for.
* @return The {@code Player} of the given nation, or null if
- * not found.
+ * not found or already dead.
*/
- public Player getPlayerByNation(Nation nation) {
- return getPlayerByNationId(nation.getId());
+ public final Player getLivePlayerByNation(Nation nation) {
+ if (this.players == null)
+ for (Player p : this.players)
+ if (!p.isUnknownEnemy() && !p.isDead() && p.getNation() == nation)
+ return p;
+
+ return null;
}

/**
@@ -573,7 +561,25 @@ public class Game extends FreeColGameObject {
* not found.
*/
public Player getPlayerByNationId(String nationId) {
- return find(this.players, matchKeyEquals(nationId, Player::getNationId));
+ if ((players != null) || (nationId != null))
+ {
+ for (Player walk : players) {
+ if (walk == null)
+ continue;
+ if (nationId.equals(walk.getNationId()))
+ return walk;
+ }
+ }
+ return null;
+ }
+
+ private static void addPlayerNotExcluded(List<Player> result,
+ Player player,
+ Player[] exclude) {
+ for (Player e : exclude)
+ if (e == player) return;
+
+ result.add(player);
}

/**
@@ -581,72 +587,62 @@ public class Game extends FreeColGameObject {
* excluding supplied ones.
*
* @param exclude The {@code Player}s to exclude.
- * @return A list of live {@code Player}s, without the excluded ones.
+ * @return A {@code Collection} of live {@code Player}s, without the excluded ones.
*/
- public List<Player> getLivePlayerList(final Player... exclude) {
- final Predicate<Player> livePred = p ->
- !p.isUnknownEnemy() && !p.isDead() && !any(exclude, matchKey(p));
- return getPlayerList(livePred);
- }
+ public Collection<Player> getLivePlayers(final Player... exclude) {
+ List<Player> result = new ArrayList<>();

- /**
- * Get a stream of the live players in the game, optionally excluding
- * supplied ones.
- *
- * @param exclude The {@code Player}s to exclude.
- * @return A stream of live {@code Player}s, without the
- * excluded ones.
- */
- public Stream<Player> getLivePlayers(final Player... exclude) {
- return getLivePlayerList(exclude).stream();
+ for (Player p : this.players)
+ if (p.isLive())
+ addPlayerNotExcluded(result, p, exclude);
+
+ return result;
}

/**
* Get a list of the live European players in this game.
*
* @param exclude {@code Player}s to exclude.
- * @return A list of live European {@code Player}s in this game,
+ * @return A {@code Collection} of live European {@code Player}s in this game,
* without the excluded ones.
*/
- public List<Player> getLiveEuropeanPlayerList(final Player... exclude) {
- final Predicate<Player> europeanPred = p ->
- !p.isUnknownEnemy() && !p.isDead() && p.isEuropean()
- && !any(exclude, matchKey(p));
- return getPlayerList(europeanPred);
+ public List<Player> getLiveEuropeanPlayers(final Player... exclude) {
+ List<Player> result = new ArrayList<>();
+
+ for (Player p : this.players)
+ if (p.isLiveEuropean())
+ addPlayerNotExcluded(result, p, exclude);
+
+ return result;
}

/**
- * Get a stream of the live European players in this game.
+ * Get a list of the live European players in this game.
*
* @param exclude {@code Player}s to exclude.
- * @return A stream of live European {@code Player}s in this game,
+ * @return A {@code Collection} of live European {@code Player}s in this game,
* without the excluded ones.
*/
- public Stream<Player> getLiveEuropeanPlayers(final Player... exclude) {
- return getLiveEuropeanPlayerList(exclude).stream();
+ public List<Player> getLiveEuropeanPlayers(List<Player> exclude) {
+ Player[] array = new Player[exclude.size()];
+ exclude.toArray(array);
+ return getLiveEuropeanPlayers(array);
}

/**
* Get a list of the live native players in this game.
*
* @param exclude {@code Player}s to exclude.
- * @return A list of live native {@code Player}s in this game.
+ * @return A {@code Collection} of live native {@code Player}s in this game.
*/
- public List<Player> getLiveNativePlayerList(final Player... exclude) {
- final Predicate<Player> nativePred = p ->
- !p.isUnknownEnemy() && !p.isDead() && p.isIndian()
- && !any(exclude, matchKey(p));
- return getPlayerList(nativePred);
- }
+ public Collection<Player> getLiveNativePlayers(final Player... exclude) {
+ List<Player> result = new ArrayList<>();

- /**
- * Get a stream of the live native players in this game.
- *
- * @param exclude {@code Player}s to exclude.
- * @return A stream of live native {@code Player}s in this game.
- */
- public Stream<Player> getLiveNativePlayers(final Player... exclude) {
- return getLiveNativePlayerList(exclude).stream();
+ for (Player p : this.players)
+ if (p.isLiveNative())
+ addPlayerNotExcluded(result, p, exclude);
+
+ return result;
}

/**
@@ -697,7 +693,10 @@ public class Game extends FreeColGameObject {
* @return The {@code Player} or null if none found.
*/
public Player getPlayerByName(String name) {
- return find(players, matchKeyEquals(name, Player::getName));
+ for (Player p : players)
+ if (Utils.equals(name, p.getName()))
+ return p;
+ return null;
}

/**
@@ -785,7 +784,10 @@ public class Game extends FreeColGameObject {
* @return True if an undead player is present.
*/
public boolean isInRevengeMode() {
- return any(getPlayers(), Player::isUndead);
+ for (Player p : this.players)
+ if (p.isUndead())
+ return true;
+ return false;
}

/**
@@ -822,10 +824,12 @@ public class Game extends FreeColGameObject {
*/
public void setMap(Map newMap) {
if (this.map != newMap) {
- for (HighSeas hs : transform(getLivePlayers(), alwaysTrue(),
- Player::getHighSeas, toListNoNulls())) {
- hs.removeDestination(this.map);
- hs.addDestination(newMap);
+ for (Player p : getLivePlayers()) {
+ HighSeas hs = p.getHighSeas();
+ if (hs != null) {
+ hs.removeDestination(this.map);
+ hs.addDestination(newMap);
+ }
}
}
this.map = newMap;
@@ -1039,7 +1043,10 @@ public class Game extends FreeColGameObject {
* @return True if all players are ready to launch.
*/
public boolean allPlayersReadyToLaunch() {
- return all(getLiveEuropeanPlayerList(), Player::isReady);
+ for (Player p : this.players)
+ if (p.isLiveEuropean() && (!p.isReady()))
+ return false;
+ return true;
}

/**
@@ -1049,7 +1056,7 @@ public class Game extends FreeColGameObject {
* @return A stream of all the {@code Colony}s in the game.
*/
public Stream<Colony> getAllColonies(Player player) {
- return flatten(getLiveEuropeanPlayerList(player), Player::getColonies);
+ return flatten(getLiveEuropeanPlayers(player), Player::getColonies);
}

/**
@@ -1220,9 +1227,10 @@ public class Game extends FreeColGameObject {
if (map != null) {
result = Math.min(result, getMap().checkIntegrity(fix));
}
- for (Player player : getPlayerList()) {
+
+ for (Player player : this.players)
result = Math.min(result, player.checkIntegrity(fix));
- }
+
return result;
}

@@ -1337,7 +1345,8 @@ public class Game extends FreeColGameObject {

nationOptions.toXML(xw);

- List<Player> players = sort(getPlayers());
+ List<Player> players = new ArrayList<>(this.players);
+ Collections.sort(players);
Player unknown = getUnknownEnemy();
if (unknown != null) players.add(unknown);
for (Player p : players) p.toXML(xw);
@@ -1402,9 +1411,9 @@ public class Game extends FreeColGameObject {

// Make sure all work locations have rational default production
// now that all tiles are defined.
- for (Colony c : getAllColoniesList(null)) {
- c.updateProductionTypes();
- }
+ for (Player p : getLiveEuropeanPlayers(players))
+ for (Colony c : p.getColonies())
+ c.updateProductionTypes();
}

/**
diff --git a/src/net/sf/freecol/common/model/Operand.java b/src/net/sf/freecol/common/model/Operand.java
index 10d0f5099b5..97f4ee76b21 100644
--- a/src/net/sf/freecol/common/model/Operand.java
+++ b/src/net/sf/freecol/common/model/Operand.java
@@ -200,7 +200,7 @@ public class Operand extends Scope {
result = game.getSpecification().getInteger(getType());
break;
default:
- for (Player player : game.getLivePlayerList()) {
+ for (Player player : game.getLivePlayers()) {
switch (this.operandType) {
case UNITS:
result += ourCount(player.getUnitList());
diff --git a/src/net/sf/freecol/common/model/Player.java b/src/net/sf/freecol/common/model/Player.java
index 5aad8c26fdf..2ea54dd6ad9 100644
--- a/src/net/sf/freecol/common/model/Player.java
+++ b/src/net/sf/freecol/common/model/Player.java
@@ -727,6 +727,18 @@ public class Player extends FreeColGameObject implements Nameable {
|| playerType == PlayerType.ROYAL;
}

+ public final boolean isLive() {
+ return (!isUnknownEnemy() && !isDead());
+ }
+
+ public final boolean isLiveEuropean() {
+ return (!isUnknownEnemy() && !isDead() && isEuropean());
+ }
+
+ public final boolean isLiveNative() {
+ return (!isUnknownEnemy() && !isDead() && isIndian());
+ }
+
/**
* Is this a native player?
*
@@ -2812,7 +2824,7 @@ public class Player extends FreeColGameObject implements Nameable {

// All missions if using enhanced missionaries.
if (spec.getBoolean(GameOptions.ENHANCED_MISSIONARIES))
- for (Player other : getGame().getLiveNativePlayerList(this))
+ for (Player other : getGame().getLiveNativePlayers(this))
for (IndianSettlement is : getIndianSettlementsWithMissionaryList(this))
vismap.setVisible(is);

diff --git a/src/net/sf/freecol/common/model/Tile.java b/src/net/sf/freecol/common/model/Tile.java
index 4d48060133d..d1e3d205e15 100644
--- a/src/net/sf/freecol/common/model/Tile.java
+++ b/src/net/sf/freecol/common/model/Tile.java
@@ -2497,7 +2497,7 @@ public final class Tile extends UnitLocation implements Named, Ownable {

// Save the cached tiles to saved games.
if (xw.validForSave() && cachedTiles != null) {
- for (Player p : getGame().getLiveEuropeanPlayerList()) {
+ for (Player p : getGame().getLiveEuropeanPlayers()) {
Tile t = getCachedTile(p);
if (t == null) continue;

diff --git a/src/net/sf/freecol/common/networking/AddPlayerMessage.java b/src/net/sf/freecol/common/networking/AddPlayerMessage.java
index 2faa743fcae..b7f7dc7fc68 100644
--- a/src/net/sf/freecol/common/networking/AddPlayerMessage.java
+++ b/src/net/sf/freecol/common/networking/AddPlayerMessage.java
@@ -75,16 +75,6 @@ public class AddPlayerMessage extends DOMMessage {
// Public interface

/**
- * Get the attached players.
- *
- * @return The list of {@code Player}s to add.
- */
- public List<Player> getPlayers() {
- return this.players;
- }
-
-
- /**
* Handle a "addPlayer"-message.
*
* @param server The {@code FreeColServer} handling the message.
diff --git a/src/net/sf/freecol/common/networking/ChangeSet.java b/src/net/sf/freecol/common/networking/ChangeSet.java
index 665f6be59bb..48bef9f74cb 100644
--- a/src/net/sf/freecol/common/networking/ChangeSet.java
+++ b/src/net/sf/freecol/common/networking/ChangeSet.java
@@ -1610,7 +1610,7 @@ public class ChangeSet {
* @return The updated {@code ChangeSet}.
*/
public ChangeSet addGlobalHistory(Game game, HistoryEvent history) {
- for (Player p : game.getLiveEuropeanPlayerList()) {
+ for (Player p : game.getLiveEuropeanPlayers()) {
addHistory((ServerPlayer)p, history);
}
return this;
@@ -1626,7 +1626,7 @@ public class ChangeSet {
*/
public ChangeSet addGlobalMessage(Game game, ServerPlayer omit,
ModelMessage message) {
- for (Player p : game.getLiveEuropeanPlayerList()) {
+ for (Player p : game.getLiveEuropeanPlayers()) {
if (p == (Player)omit) continue;
addMessage((ServerPlayer)p, message);
}
diff --git a/src/net/sf/freecol/common/networking/LoginMessage.java b/src/net/sf/freecol/common/networking/LoginMessage.java
index 7b1a9300688..3e68f687fa0 100644
--- a/src/net/sf/freecol/common/networking/LoginMessage.java
+++ b/src/net/sf/freecol/common/networking/LoginMessage.java
@@ -194,7 +194,7 @@ public class LoginMessage extends DOMMessage {
}

// Complete initialization...
- serverPlayer.initialize(game, game.getLivePlayerList().isEmpty(),
+ serverPlayer.initialize(game, game.getLivePlayers().isEmpty(),
nation);

// ... but override player name.
diff --git a/src/net/sf/freecol/server/FreeColServer.java b/src/net/sf/freecol/server/FreeColServer.java
index 0a44c339c6a..2ded50a8033 100644
--- a/src/net/sf/freecol/server/FreeColServer.java
+++ b/src/net/sf/freecol/server/FreeColServer.java
@@ -600,7 +600,7 @@ public final class FreeColServer {
public void endGame() {
changeServerState(ServerState.END_GAME);
ChangeSet cs = new ChangeSet();
- for (Player p : getGame().getLiveEuropeanPlayerList()) {
+ for (Player p : getGame().getLiveEuropeanPlayers()) {
ServerPlayer sp = (ServerPlayer)p;
if (sp.isAdmin()) continue;
sp.send(new ChangeSet()
@@ -1151,7 +1151,7 @@ public final class FreeColServer {
int savegameVersion = fis.getSavegameVersion();
// @compat 0.10.x
if (savegameVersion < 12) {
- for (Player p : serverGame.getPlayerList()) {
+ for (Player p : serverGame.getPlayers()) {
p.setReady(true); // Players in running game must be ready
// @compat 0.10.5
if (p.isIndian()) {
@@ -1221,7 +1221,7 @@ public final class FreeColServer {

serverGame.sortPlayers(Player.playerComparator);

- for (Player player : serverGame.getLivePlayerList()) {
+ for (Player player : serverGame.getLivePlayers()) {
if (player.isAI()) {
ServerPlayer aiPlayer = (ServerPlayer)player;
addAIConnection(aiPlayer);
@@ -1308,14 +1308,14 @@ public final class FreeColServer {
// Initial stances and randomizations for all players.
spec.generateDynamicOptions();
Random random = getServerRandom();
- for (Player player : serverGame.getLivePlayerList()) {
+ for (Player player : serverGame.getLivePlayers()) {
((ServerPlayer)player).randomizeGame(random);
if (player.isIndian()) {
// Indian players know about each other, but
// European colonial players do not.
final int alarm = (Tension.Level.HAPPY.getLimit()
+ Tension.Level.CONTENT.getLimit()) / 2;
- for (Player other : serverGame.getLiveNativePlayerList(player)) {
+ for (Player other : serverGame.getLiveNativePlayers(player)) {
player.setStance(other, Stance.PEACE);
for (IndianSettlement is : player.getIndianSettlementList()) {
is.setAlarm(other, new Tension(alarm));
@@ -1364,7 +1364,7 @@ public final class FreeColServer {
* @param reveal If true, reveal, if false, hide.
*/
public void exploreMapForAllPlayers(boolean reveal) {
- for (Player player : getGame().getLiveEuropeanPlayerList()) {
+ for (Player player : getGame().getLiveEuropeanPlayers()) {
((ServerPlayer)player).exploreMap(reveal);
}

@@ -1379,7 +1379,7 @@ public final class FreeColServer {
fogOfWarSetting.setValue(FreeColDebugger.getNormalGameFogOfWar());
}

- for (Player player : getGame().getLiveEuropeanPlayerList()) {
+ for (Player player : getGame().getLiveEuropeanPlayers()) {
((ServerPlayer)player).getConnection().sendReconnect();
}
}
diff --git a/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java b/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java
index 43931858669..be6f59c9eb0 100644
--- a/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java
+++ b/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java
@@ -1468,7 +1468,7 @@ public class EuropeanAIPlayer extends MissionAIPlayer {
final ServerPlayer serverPlayer = (ServerPlayer)getPlayer();
lb.mark();

- for (Player p : getGame().getLivePlayerList(serverPlayer)) {
+ for (Player p : getGame().getLivePlayers(serverPlayer)) {
Stance newStance = determineStance(p);
if (newStance != serverPlayer.getStance(p)) {
if (newStance == Stance.WAR && peaceHolds(p)) {
diff --git a/src/net/sf/freecol/server/ai/NativeAIPlayer.java b/src/net/sf/freecol/server/ai/NativeAIPlayer.java
index abdb56014b5..4121139630e 100644
--- a/src/net/sf/freecol/server/ai/NativeAIPlayer.java
+++ b/src/net/sf/freecol/server/ai/NativeAIPlayer.java
@@ -166,7 +166,7 @@ public class NativeAIPlayer extends MissionAIPlayer {
final ServerPlayer serverPlayer = (ServerPlayer)getPlayer();
lb.mark();

- for (Player p : getGame().getLivePlayerList(serverPlayer)) {
+ for (Player p : getGame().getLivePlayers(serverPlayer)) {
Stance newStance = determineStance(p);
if (newStance != serverPlayer.getStance(p)) {
getAIMain().getFreeColServer().getInGameController()
diff --git a/src/net/sf/freecol/server/control/InGameController.java b/src/net/sf/freecol/server/control/InGameController.java
index 2931e3ceb8e..79c8f30ceca 100644
--- a/src/net/sf/freecol/server/control/InGameController.java
+++ b/src/net/sf/freecol/server/control/InGameController.java
@@ -987,7 +987,7 @@ public final class InGameController extends Controller {
}
serverPlayer.addSettlement(settlement);
settlement.placeSettlement(true);//-vis(serverPlayer),-til
- for (Player p : getGame().getLivePlayerList(serverPlayer)) {
+ for (Player p : getGame().getLivePlayers(serverPlayer)) {
((IndianSettlement)settlement).setAlarm(p, (p.isIndian())
? new Tension(Tension.Level.CONTENT.getLimit())
: serverPlayer.getTension(p));//-til
diff --git a/src/net/sf/freecol/server/control/PreGameController.java b/src/net/sf/freecol/server/control/PreGameController.java
index ea5e5ecb23c..21b53176ed4 100644
--- a/src/net/sf/freecol/server/control/PreGameController.java
+++ b/src/net/sf/freecol/server/control/PreGameController.java
@@ -103,7 +103,7 @@ public final class PreGameController extends Controller {

// Check that no two players have the same nation
List<Nation> nations = new ArrayList<>();
- for (Player p : game.getLivePlayerList()) {
+ for (Player p : game.getLivePlayers()) {
final Nation nation = spec.getNation(p.getNationId());
if (nations.contains(nation)) {
setLaunching(false);
diff --git a/src/net/sf/freecol/server/generator/SimpleMapGenerator.java b/src/net/sf/freecol/server/generator/SimpleMapGenerator.java
index e94ad3b5f4d..b1261092a9a 100644
--- a/src/net/sf/freecol/server/generator/SimpleMapGenerator.java
+++ b/src/net/sf/freecol/server/generator/SimpleMapGenerator.java
@@ -234,7 +234,7 @@ public class SimpleMapGenerator implements MapGenerator {

private boolean importIndianSettlements(Map map, LogBuilder lb) {
// First make sure all the players are present.
- for (Player iPlayer : importGame.getLiveNativePlayerList()) {
+ for (Player iPlayer : importGame.getLiveNativePlayers()) {
Player indian = game.getPlayerByNationId(iPlayer.getNationId());
if (indian == null) {
Nation nation = spec.getNation(iPlayer.getNationId());
@@ -334,7 +334,7 @@ public class SimpleMapGenerator implements MapGenerator {
List<Player> indians = new ArrayList<>();
HashMap<String, Territory> territoryMap = new HashMap<>();

- for (Player player : game.getLiveNativePlayerList()) {
+ for (Player player : game.getLiveNativePlayers()) {
switch (player.getNationType().getNumberOfSettlements()) {
case HIGH:
shares += 4;
@@ -1071,7 +1071,7 @@ public class SimpleMapGenerator implements MapGenerator {
// Decorate the map.
makeNativeSettlements(map, lb);
makeLostCityRumours(map, lb);
- createEuropeanUnits(map, game.getLiveEuropeanPlayerList(), lb);
+ createEuropeanUnits(map, game.getLiveEuropeanPlayers(), lb);
return map;
}
}
diff --git a/src/net/sf/freecol/server/model/ServerGame.java b/src/net/sf/freecol/server/model/ServerGame.java
index 6fecadf2deb..75cc4db8c09 100644
--- a/src/net/sf/freecol/server/model/ServerGame.java
+++ b/src/net/sf/freecol/server/model/ServerGame.java
@@ -635,7 +635,7 @@ public class ServerGame extends Game implements ServerModelObject {
@Override
public void csNewTurn(Random random, LogBuilder lb, ChangeSet cs) {
lb.add("GAME ", getId(), ", ");
- for (Player player : getLivePlayerList()) {
+ for (Player player : getLivePlayers()) {
((ServerPlayer)player).csNewTurn(random, lb, cs);
}

diff --git a/src/net/sf/freecol/server/model/ServerPlayer.java b/src/net/sf/freecol/server/model/ServerPlayer.java
index 7546bc597cf..53dc67c6c5c 100644
--- a/src/net/sf/freecol/server/model/ServerPlayer.java
+++ b/src/net/sf/freecol/server/model/ServerPlayer.java
@@ -632,7 +632,7 @@ public class ServerPlayer extends Player implements ServerModelObject {
cs.addDead(this);

// Clean up missions and remove tension/alarm/stance.
- for (Player other : getGame().getLivePlayerList(this)) {
+ for (Player other : getGame().getLivePlayers(this)) {
if (isEuropean() && other.isIndian()) {
for (IndianSettlement is : other.getIndianSettlementList()) {
ServerIndianSettlement sis = (ServerIndianSettlement)is;
@@ -1668,7 +1668,7 @@ outer: for (Effect effect : effects) {

// Do not need to update the clients here, these changes happen
// while it is not their turn.
- for (Player p : getGame().getLiveEuropeanPlayerList(this)) {
+ for (Player p : getGame().getLiveEuropeanPlayers(this)) {
Market market = p.getMarket();
if (market != null) market.addGoodsToMarket(type, amount);
}
@@ -1765,7 +1765,7 @@ outer: for (Effect effect : effects) {
for (IndianSettlement is : allSettlements) {
java.util.Map<Player, Tension.Level> oldLevel = new HashMap<>();
oldLevels.put(is, oldLevel);
- for (Player enemy : game.getLiveEuropeanPlayerList(this)) {
+ for (Player enemy : game.getLiveEuropeanPlayers(this)) {
Tension alarm = is.getAlarm(enemy);
oldLevel.put(enemy,
(alarm == null) ? null : alarm.getLevel());
@@ -1775,7 +1775,7 @@ outer: for (Effect effect : effects) {
// Do the settlement alarms first.
for (IndianSettlement is : allSettlements) {
java.util.Map<Player, Integer> extra = new HashMap<>();
- for (Player enemy : game.getLiveEuropeanPlayerList(this)) {
+ for (Player enemy : game.getLiveEuropeanPlayers(this)) {
extra.put(enemy, 0);
}

@@ -1959,7 +1959,7 @@ outer: for (Effect effect : effects) {
String eventId = event.getId();
switch (eventId) {
case "model.event.resetBannedMissions":
- for (Player p : game.getLiveNativePlayerList()) {
+ for (Player p : game.getLiveNativePlayers()) {
if (p.missionsBanned(this)) {
p.removeMissionBan(this);
cs.add(See.only(this), p);
@@ -4477,7 +4477,7 @@ outer: for (Effect effect : effects) {
Stance sta = getStance(s);
boolean war = sta == Stance.WAR;
if (sta == Stance.UNCONTACTED) continue;
- for (Player p : game.getLiveEuropeanPlayerList(this)) {
+ for (Player p : game.getLiveEuropeanPlayers(this)) {
ServerPlayer sp = (ServerPlayer) p;
if (p == s || !p.hasContacted(this)
|| !p.hasContacted(s)) continue;
diff --git a/test/src/net/sf/freecol/common/model/FoundingFatherTest.java b/test/src/net/sf/freecol/common/model/FoundingFatherTest.java
index e559c879424..a9bea46ee66 100644
--- a/test/src/net/sf/freecol/common/model/FoundingFatherTest.java
+++ b/test/src/net/sf/freecol/common/model/FoundingFatherTest.java
@@ -126,7 +126,7 @@ public class FoundingFatherTest extends FreeColTestCase {
// this feature is not used at the moment
Game game = getGame();
for (FoundingFather father : spec().getFoundingFathers()) {
- for (Player player : game.getPlayerList()) {
+ for (Player player : game.getPlayers()) {
assertEquals(player.getNationId(), player.isEuropean(),
father.isAvailableTo(player));
}
@@ -151,7 +151,7 @@ public class FoundingFatherTest extends FreeColTestCase {
scopes.add(dutchScope);
scopes.add(frenchScope);
newFather.setScopes(scopes);
- for (Player player : game.getPlayerList()) {
+ for (Player player : game.getPlayers()) {
assertEquals(player.getNationId(),
(player == french || player == dutch),
newFather.isAvailableTo(player));
diff --git a/test/src/net/sf/freecol/common/model/GameTest.java b/test/src/net/sf/freecol/common/model/GameTest.java
index b2a74a30cc1..1b89092d44c 100644
--- a/test/src/net/sf/freecol/common/model/GameTest.java
+++ b/test/src/net/sf/freecol/common/model/GameTest.java
@@ -65,8 +65,8 @@ public class GameTest extends FreeColTestCase {
players.sort(Player.playerComparator);
game.sortPlayers(Player.playerComparator);
assertEquals(spec().getNations().size() - counter,
- count(game.getPlayers()));
- assertEquals(players, game.getPlayerList());
+ game.getPlayers().size());
+ assertEquals(players, game.getPlayers());
}

public void testTurn() {
diff --git a/test/src/net/sf/freecol/common/model/UnitChangeTypeTest.java b/test/src/net/sf/freecol/common/model/UnitChangeTypeTest.java
index 2af6e1874d1..7fe346b7553 100644
--- a/test/src/net/sf/freecol/common/model/UnitChangeTypeTest.java
+++ b/test/src/net/sf/freecol/common/model/UnitChangeTypeTest.java
@@ -41,7 +41,7 @@ public class UnitChangeTypeTest extends FreeColTestCase {
assertEquals("Education has no scopes", 0, count(uct.getScopes()));

// empty scope applies to all players
- for (Player player : getStandardGame().getPlayerList()) {
+ for (Player player : getStandardGame().getPlayers()) {
assertTrue("Empty scopes apply to all players",
uct.appliesTo(player));
}
diff --git a/test/src/net/sf/freecol/util/test/FreeColTestCase.java b/test/src/net/sf/freecol/util/test/FreeColTestCase.java
index 61b885a2ce7..68a1fc90f60 100644
--- a/test/src/net/sf/freecol/util/test/FreeColTestCase.java
+++ b/test/src/net/sf/freecol/util/test/FreeColTestCase.java
@@ -460,7 +460,7 @@ public class FreeColTestCase extends TestCase {
map.resetHighSeasCount();
if (exploredByAll) {
map.forEachTile(t -> {
- for (Player p : game.getLiveEuropeanPlayerList()) {
+ for (Player p : game.getLiveEuropeanPlayers()) {
t.setExplored(p, true);
}
});
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:51 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

The getAllTiles() is now only used in the map generator, where we finally
wanna have a List anyways, so using Stream is just unnecessary overhead.
---
src/net/sf/freecol/common/model/Map.java | 15 +++++++++------
.../sf/freecol/server/generator/SimpleMapGenerator.java | 2 +-
test/src/net/sf/freecol/common/model/MapTest.java | 2 +-
3 files changed, 11 insertions(+), 8 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Map.java b/src/net/sf/freecol/common/model/Map.java
index 715ffbdf195..e402e703323 100644
--- a/src/net/sf/freecol/common/model/Map.java
+++ b/src/net/sf/freecol/common/model/Map.java
@@ -35,7 +35,6 @@ import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
-import java.util.stream.Stream;

import javax.swing.ImageIcon;
import javax.xml.stream.XMLStreamException;
@@ -1949,13 +1948,17 @@ public class Map extends FreeColGameObject implements Location {
}

/**
- * Get a stream of all the tiles in the map using an underlying
- * WholeMapIterator.
+ * Get a list of all the tiles in the map
*
- * @return A {@code Stream} of all tiles of the map.
+ * @return A {@code List} of all tiles of the map.
*/
- public Stream<Tile> getAllTiles() {
- return toStream(new WholeMapIterator());
+ public List<Tile> getAllTiles() {
+ List<Tile> result = new ArrayList<>();
+ for (Tile[] tl : tiles)
+ for (Tile t : tl)
+ if (t != null)
+ result.add(t);
+ return result;
}

/**
diff --git a/src/net/sf/freecol/server/generator/SimpleMapGenerator.java b/src/net/sf/freecol/server/generator/SimpleMapGenerator.java
index b287cc9b705..bae22187a34 100644
--- a/src/net/sf/freecol/server/generator/SimpleMapGenerator.java
+++ b/src/net/sf/freecol/server/generator/SimpleMapGenerator.java
@@ -400,7 +400,7 @@ public class SimpleMapGenerator implements MapGenerator {
// order picking out as many as possible suitable tiles for
// native settlements such that can be guaranteed at least one
// layer of surrounding tiles to own.
- List<Tile> allTiles = toList(map.getAllTiles());
+ List<Tile> allTiles = map.getAllTiles();
randomShuffle(logger, "All tile shuffle", allTiles, random);
final int minDistance
= spec.getRangeOption(GameOptions.SETTLEMENT_NUMBER).getValue();
diff --git a/test/src/net/sf/freecol/common/model/MapTest.java b/test/src/net/sf/freecol/common/model/MapTest.java
index 443ce092733..c0040d13079 100644
--- a/test/src/net/sf/freecol/common/model/MapTest.java
+++ b/test/src/net/sf/freecol/common/model/MapTest.java
@@ -189,7 +189,7 @@ public class MapTest extends FreeColTestCase {
}

int i = 0;
- for (Tile t : toList(map.getAllTiles())) {
+ for (Tile t : map.getAllTiles()) {
i++;
assertTrue(allTiles.remove(t));
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:27 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../client/gui/dialog/EditSettlementDialog.java | 2 +-
.../client/gui/panel/report/ReportIndianPanel.java | 2 +-
src/net/sf/freecol/common/model/Player.java | 74 ++++++++++++++--------
.../sf/freecol/common/model/SimpleCombatModel.java | 4 +-
src/net/sf/freecol/server/FreeColServer.java | 4 +-
src/net/sf/freecol/server/ai/NativeAIPlayer.java | 8 +--
src/net/sf/freecol/server/model/ServerGame.java | 9 +--
src/net/sf/freecol/server/model/ServerPlayer.java | 18 +++---
.../freecol/server/generator/MapGeneratorTest.java | 2 +-
9 files changed, 71 insertions(+), 52 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/dialog/EditSettlementDialog.java b/src/net/sf/freecol/client/gui/dialog/EditSettlementDialog.java
index 8cde7a524bb..9ac37076c90 100644
--- a/src/net/sf/freecol/client/gui/dialog/EditSettlementDialog.java
+++ b/src/net/sf/freecol/client/gui/dialog/EditSettlementDialog.java
@@ -228,7 +228,7 @@ public final class EditSettlementDialog extends FreeColDialog<IndianSettlement>
if (this.capital.isSelected() && !is.isCapital()) {
// make sure we downgrade the old capital
for (IndianSettlement indianSettlement
- : is.getOwner().getIndianSettlementList()) {
+ : is.getOwner().getIndianSettlements()) {
indianSettlement.setCapital(false);
}
is.setCapital(true);
diff --git a/src/net/sf/freecol/client/gui/panel/report/ReportIndianPanel.java b/src/net/sf/freecol/client/gui/panel/report/ReportIndianPanel.java
index b01ab6ee434..a531adaa804 100644
--- a/src/net/sf/freecol/client/gui/panel/report/ReportIndianPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/report/ReportIndianPanel.java
@@ -94,7 +94,7 @@ public final class ReportIndianPanel extends ReportPanel {
private void buildIndianAdvisorPanel(Player player, Player opponent) {
final NationSummary ns = igc().getNationSummary(opponent);
List<IndianSettlement> nativeSettlements
- = opponent.getIndianSettlementList();
+ = opponent.getIndianSettlements();
String numSettlements = String.valueOf(nativeSettlements.size())
+ " / " + ((ns == null) ? "?"
: String.valueOf(ns.getNumberOfSettlements()));
diff --git a/src/net/sf/freecol/common/model/Player.java b/src/net/sf/freecol/common/model/Player.java
index f0354687958..1714d5ec7f7 100644
--- a/src/net/sf/freecol/common/model/Player.java
+++ b/src/net/sf/freecol/common/model/Player.java
@@ -2426,8 +2426,12 @@ public class Player extends FreeColGameObject implements Nameable {
* or null if not found.
*/
public IndianSettlement getIndianSettlementByName(String name) {
- return find(getIndianSettlements(),
- matchKeyEquals(name, IndianSettlement::getName));
+ synchronized (this.settlements) {
+ for (Settlement s : this.settlements)
+ if (s instanceof IndianSettlement && Utils.equals(name, ((IndianSettlement)s).getName()))
+ return (IndianSettlement)s;
+ }
+ return null;
}

/**
@@ -2488,25 +2492,35 @@ public class Player extends FreeColGameObject implements Nameable {
}

/**
- * Get a stream of all the indian settlements this player owns.
+ * Get a list of all the IndianSettlements this player owns.
*
- * @return A stream of the {@code IndianSettlement}s this player owns.
+ * @return A list of the {@code IndianSettlement}s this player owns.
*/
- public Stream<IndianSettlement> getIndianSettlements() {
- return getIndianSettlementList().stream();
+ public List<IndianSettlement> getIndianSettlements() {
+ synchronized (this.settlements) {
+ List<IndianSettlement> result = new ArrayList<>();
+ for (Settlement s : this.settlements)
+ if (s instanceof IndianSettlement)
+ result.add((IndianSettlement)s);
+ return result;
+ }
}

/**
- * Get a list of all the IndianSettlements this player owns.
+ * Get a list of all the IndianSettlements this player owns, that have
+ * been contacted by given player.
*
- * @return A list of the {@code IndianSettlement}s this player owns.
+ * @return A list of this player's {@code IndianSettlement}s, that have
+ * been contacted by given player.
*/
- public List<IndianSettlement> getIndianSettlementList() {
- List<IndianSettlement> result = new ArrayList<>();
- for (Settlement s : this.settlements)
- if (s instanceof IndianSettlement)
- result.add((IndianSettlement)s);
- return result;
+ public List<IndianSettlement> getIndianSettlementsContacted(Player player) {
+ synchronized (this.settlements) {
+ List<IndianSettlement> result = new ArrayList<>();
+ for (Settlement s : this.settlements)
+ if (s instanceof IndianSettlement && s.hasContacted(player))
+ result.add((IndianSettlement)s);
+ return result;
+ }
}

/**
@@ -2517,24 +2531,32 @@ public class Player extends FreeColGameObject implements Nameable {
* @return A list of the {@code IndianSettlement}s with a matching
* missionary.
*/
- public List<IndianSettlement> getIndianSettlementsWithMissionaryList(Player p) {
- List<IndianSettlement> result = new ArrayList<>();
- for (Settlement s : this.settlements)
- if ((s instanceof IndianSettlement) && ((IndianSettlement)s).hasMissionary(p))
- result.add((IndianSettlement)s);
- return result;
+ public List<IndianSettlement> getIndianSettlementsWithMissionary(Player p) {
+ synchronized (this.settlements) {
+ List<IndianSettlement> result = new ArrayList<>();
+ for (Settlement s : this.settlements)
+ if ((s instanceof IndianSettlement) && ((IndianSettlement)s).hasMissionary(p))
+ result.add((IndianSettlement)s);
+ return result;
+ }
}

/**
- * Get a stream of all indian settlements owned by this player with
+ * Check whether player has an indian settlements owned by this player with
* a missionary from a given player.
*
* @param p The {@code Player}.
- * @return A stream of the {@code IndianSettlement}s with a matching
- * missionary.
+ * @return A True if there player has an indian settlement with missionary
+ * from given player.
*/
- public Stream<IndianSettlement> getIndianSettlementsWithMissionary(Player p) {
- return getIndianSettlementsWithMissionaryList(p).stream();
+ public final boolean hasIndianSettlementsWithMissionary(Player p) {
+ synchronized (this.settlements) {
+ List<IndianSettlement> result = new ArrayList<>();
+ for (Settlement s : this.settlements)
+ if ((s instanceof IndianSettlement) && ((IndianSettlement)s).hasMissionary(p))
+ return true;
+ return false;
+ }
}

/**
@@ -2902,7 +2924,7 @@ public class Player extends FreeColGameObject implements Nameable {
// All missions if using enhanced missionaries.
if (spec.getBoolean(GameOptions.ENHANCED_MISSIONARIES))
for (Player other : getGame().getLiveNativePlayers(this))
- for (IndianSettlement is : getIndianSettlementsWithMissionaryList(this))
+ for (IndianSettlement is : getIndianSettlementsWithMissionary(this))
vismap.setVisible(is);

// All other European settlements if can see all colonies.
diff --git a/src/net/sf/freecol/common/model/SimpleCombatModel.java b/src/net/sf/freecol/common/model/SimpleCombatModel.java
index 64fc90d4cb1..a536559adcb 100644
--- a/src/net/sf/freecol/common/model/SimpleCombatModel.java
+++ b/src/net/sf/freecol/common/model/SimpleCombatModel.java
@@ -794,10 +794,8 @@ public class SimpleCombatModel extends CombatModel {
lose++;
}
} else if (r >= 1.0 - winner.getBurnProbability()) {
- if (any(transform(loserPlayer.getIndianSettlements(),
- s -> s.hasMissionary(winnerPlayer)))) {
+ if (loserPlayer.hasIndianSettlementsWithMissionary(winnerPlayer))
crs.add(CombatResult.BURN_MISSIONS);
- }
}
}
if (settlement.getUnitCount() + tile.getUnitCount() <= lose) {
diff --git a/src/net/sf/freecol/server/FreeColServer.java b/src/net/sf/freecol/server/FreeColServer.java
index 2ded50a8033..c056fed241a 100644
--- a/src/net/sf/freecol/server/FreeColServer.java
+++ b/src/net/sf/freecol/server/FreeColServer.java
@@ -1155,7 +1155,7 @@ public final class FreeColServer {
p.setReady(true); // Players in running game must be ready
// @compat 0.10.5
if (p.isIndian()) {
- for (IndianSettlement is : p.getIndianSettlementList()) {
+ for (IndianSettlement is : p.getIndianSettlements()) {
((ServerIndianSettlement)is).updateMostHated();
}
}
@@ -1317,7 +1317,7 @@ public final class FreeColServer {
+ Tension.Level.CONTENT.getLimit()) / 2;
for (Player other : serverGame.getLiveNativePlayers(player)) {
player.setStance(other, Stance.PEACE);
- for (IndianSettlement is : player.getIndianSettlementList()) {
+ for (IndianSettlement is : player.getIndianSettlements()) {
is.setAlarm(other, new Tension(alarm));
}
}
diff --git a/src/net/sf/freecol/server/ai/NativeAIPlayer.java b/src/net/sf/freecol/server/ai/NativeAIPlayer.java
index 4121139630e..237002960c0 100644
--- a/src/net/sf/freecol/server/ai/NativeAIPlayer.java
+++ b/src/net/sf/freecol/server/ai/NativeAIPlayer.java
@@ -140,7 +140,7 @@ public class NativeAIPlayer extends MissionAIPlayer {

// Give defensive missions up to the minimum expected defence,
// leave the rest with the default wander-hostile mission.
- for (IndianSettlement is : player.getIndianSettlementList()) {
+ for (IndianSettlement is : player.getIndianSettlements()) {
List<Unit> units = is.getAllUnitsList();
while (units.size() > is.getRequiredDefenders()) {
Unit u = units.remove(0);
@@ -189,7 +189,7 @@ public class NativeAIPlayer extends MissionAIPlayer {
private void secureSettlements(int[] randoms, LogBuilder lb) {
int randomIdx = 0;
List<IndianSettlement> settlements
- = getPlayer().getIndianSettlementList();
+ = getPlayer().getIndianSettlements();
for (IndianSettlement is : settlements) {
// Spread arms and horses between camps
// FIXME: maybe make this dependent on difficulty level?
@@ -467,7 +467,7 @@ public class NativeAIPlayer extends MissionAIPlayer {
int randomIdx = 0;
lb.mark();

- for (IndianSettlement is : player.getIndianSettlementList()) {
+ for (IndianSettlement is : player.getIndianSettlements()) {
// Do not bring gifts all the time.
if (randoms[randomIdx++] >= giftProbability) continue;

@@ -567,7 +567,7 @@ public class NativeAIPlayer extends MissionAIPlayer {
int randomIdx = 0;
lb.mark();

- for (IndianSettlement is : player.getIndianSettlementList()) {
+ for (IndianSettlement is : player.getIndianSettlements()) {
// Do not demand tribute all of the time.
if (randoms[randomIdx++] >= demandProbability) continue;

diff --git a/src/net/sf/freecol/server/model/ServerGame.java b/src/net/sf/freecol/server/model/ServerGame.java
index 815f7660010..a9899897bf5 100644
--- a/src/net/sf/freecol/server/model/ServerGame.java
+++ b/src/net/sf/freecol/server/model/ServerGame.java
@@ -50,6 +50,7 @@ import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.GoodsLocation;
import net.sf.freecol.common.model.HighSeas;
import net.sf.freecol.common.model.HistoryEvent;
+import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Limit;
import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.ModelMessage;
@@ -367,9 +368,8 @@ public class ServerGame extends Game implements ServerModelObject {
Set<Tile> updated = new HashSet<>();
ServerPlayer strongest = (ServerPlayer)strongAI;
ServerPlayer weakest = (ServerPlayer)weakAI;
- forEach(flatten(getLiveNativePlayers(),
- p -> p.getIndianSettlementsWithMissionary(weakest)),
- is -> {
+ for (Player p : getLiveNativePlayers()) {
+ for (IndianSettlement is : p.getIndianSettlementsWithMissionary(weakest)) {
lb.add(" ", is.getName(), "(mission)");
is.getTile().cacheUnseen(strongest);//+til
tiles.add(is.getTile());
@@ -380,7 +380,8 @@ public class ServerGame extends Game implements ServerModelObject {
is.getTile().updateIndianSettlement(strongest);
cs.add(See.perhaps().always(strongest), is);
}
- });
+ }
+ }
for (Colony c : weakest.getColonies()) {
updated.addAll(c.getOwnedTiles());
((ServerColony)c).csChangeOwner(strongest, false, cs);//-vis(both),-til
diff --git a/src/net/sf/freecol/server/model/ServerPlayer.java b/src/net/sf/freecol/server/model/ServerPlayer.java
index 745401de83a..d904f23ffe2 100644
--- a/src/net/sf/freecol/server/model/ServerPlayer.java
+++ b/src/net/sf/freecol/server/model/ServerPlayer.java
@@ -633,7 +633,7 @@ public class ServerPlayer extends Player implements ServerModelObject {
// Clean up missions and remove tension/alarm/stance.
for (Player other : getGame().getLivePlayers(this)) {
if (isEuropean() && other.isIndian()) {
- for (IndianSettlement is : other.getIndianSettlementList()) {
+ for (IndianSettlement is : other.getIndianSettlements()) {
ServerIndianSettlement sis = (ServerIndianSettlement)is;
if (is.hasMissionary(this)) sis.csKillMissionary(null, cs);
is.getTile().cacheUnseen();//+til
@@ -1384,9 +1384,9 @@ public class ServerPlayer extends Player implements ServerModelObject {
// Propagate tension change as settlement alarm to all
// settlements except the one that originated it (if any).
if (isIndian()) {
- for (IndianSettlement is : transform(getIndianSettlements(),
- i -> i != origin && i.hasContacted(player))) {
- ((ServerIndianSettlement)is).csModifyAlarm(player, add,
+ for (IndianSettlement is : getIndianSettlementsContacted(player)) {
+ if (is != origin)
+ ((ServerIndianSettlement)is).csModifyAlarm(player, add,
false, cs);//+til
}
}
@@ -1758,7 +1758,7 @@ outer: for (Effect effect : effects) {
// The simple way to do it is just to save all old tension
// levels and check if they have changed after applying
// all the changes.
- List<IndianSettlement> allSettlements = getIndianSettlementList();
+ List<IndianSettlement> allSettlements = getIndianSettlements();
java.util.Map<IndianSettlement,
java.util.Map<Player, Tension.Level>> oldLevels = new HashMap<>();
for (IndianSettlement is : allSettlements) {
@@ -1970,8 +1970,7 @@ outer: for (Effect effect : effects) {
for (Player p : transform(game.getLiveNativePlayers(),
p -> p.hasContacted(this))) {
p.setTension(this, new Tension(Tension.TENSION_MIN));
- for (IndianSettlement is : transform(p.getIndianSettlements(),
- is -> is.hasContacted(this))) {
+ for (IndianSettlement is : p.getIndianSettlementsContacted(this)) {
is.getTile().cacheUnseen();//+til
is.setAlarm(this, new Tension(Tension.TENSION_MIN));//-til
cs.add(See.only(this), is);
@@ -2557,8 +2556,7 @@ outer: for (Effect effect : effects) {
// FIXME: just the tension
cs.add(See.perhaps().always(this), defenderPlayer);
csChangeStance(Stance.PEACE, defenderPlayer, true, cs);
- for (IndianSettlement is : transform(defenderPlayer.getIndianSettlements(),
- is -> is.hasContacted(this))) {
+ for (IndianSettlement is : defenderPlayer.getIndianSettlements()) {
is.getAlarm(this).setValue(Tension.SURRENDERED);
// Only update attacker with settlements that have
// been seen, as contact can occur with its members.
@@ -2704,7 +2702,7 @@ outer: for (Effect effect : effects) {

// Burn down the missions
boolean here = is.hasMissionary(attackerPlayer);
- for (IndianSettlement s : nativePlayer.getIndianSettlementsWithMissionaryList(attackerPlayer)) {
+ for (IndianSettlement s : nativePlayer.getIndianSettlementsWithMissionary(attackerPlayer)) {
((ServerIndianSettlement)s).csKillMissionary(null, cs);
}
// Backtrack on updating this tile, avoiding duplication in csCombat
diff --git a/test/src/net/sf/freecol/server/generator/MapGeneratorTest.java b/test/src/net/sf/freecol/server/generator/MapGeneratorTest.java
index aea6944b7c8..2960c83a78f 100644
--- a/test/src/net/sf/freecol/server/generator/MapGeneratorTest.java
+++ b/test/src/net/sf/freecol/server/generator/MapGeneratorTest.java
@@ -178,7 +178,7 @@ public class MapGeneratorTest extends FreeColTestCase {
// has at least one settlement.
int settlements = 0;
int capitals = 0;
- for (IndianSettlement s : p.getIndianSettlementList()) {
+ for (IndianSettlement s : p.getIndianSettlements()) {
settlements++;
if (s.isCapital()) capitals++;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:38 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Effect.java | 4 ++--
src/net/sf/freecol/common/model/Feature.java | 23 +++++++---------------
.../common/model/FreeColSpecObjectType.java | 13 ++----------
src/net/sf/freecol/common/model/Modifier.java | 2 +-
src/net/sf/freecol/common/model/Scoped.java | 14 +++----------
5 files changed, 15 insertions(+), 41 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Effect.java b/src/net/sf/freecol/common/model/Effect.java
index 7bef985a94c..ce4e765032e 100644
--- a/src/net/sf/freecol/common/model/Effect.java
+++ b/src/net/sf/freecol/common/model/Effect.java
@@ -85,7 +85,7 @@ public class Effect extends FreeColSpecObjectType {
setId(template.getId());
setSpecification(template.getSpecification());
this.probability = template.probability;
- setScopes(template.getScopeList());
+ setScopes(template.getScopes());
addFeatures(template);
}

@@ -141,7 +141,7 @@ public class Effect extends FreeColSpecObjectType {
StringBuilder sb = new StringBuilder(32);
sb.append('[').append(getId())
.append(" probability=").append(probability).append('%');
- for (Scope scope : getScopeList()) sb.append(' ').append(scope);
+ for (Scope scope : getScopes()) sb.append(' ').append(scope);
sb.append(']');
return sb.toString();
}
diff --git a/src/net/sf/freecol/common/model/Feature.java b/src/net/sf/freecol/common/model/Feature.java
index e6db8b432b6..b16441dc280 100644
--- a/src/net/sf/freecol/common/model/Feature.java
+++ b/src/net/sf/freecol/common/model/Feature.java
@@ -22,7 +22,6 @@ package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-import java.util.stream.Stream;

import javax.xml.stream.XMLStreamException;

@@ -90,7 +89,7 @@ public abstract class Feature extends FreeColSpecObject
this.lastTurn = other.lastTurn;
this.duration = other.duration;
this.temporary = other.temporary;
- setScopes(other.getScopeList());
+ setScopes(other.getScopes());
}

/**
@@ -274,17 +273,9 @@ public abstract class Feature extends FreeColSpecObject
/**
* {@inheritDoc}
*/
- public final List<Scope> getScopeList() {
+ public final List<Scope> getScopes() {
return (this.scopes == null) ? Collections.<Scope>emptyList()
- : new ArrayList<>(this.scopes);
- }
-
- /**
- * {@inheritDoc}
- */
- public final Stream<Scope> getScopes() {
- return (this.scopes == null) ? Stream.<Scope>empty()
- : getScopeList().stream();
+ : this.scopes;
}

/**
@@ -356,7 +347,7 @@ public abstract class Feature extends FreeColSpecObject
protected void writeChildren(FreeColXMLWriter xw) throws XMLStreamException {
super.writeChildren(xw);

- for (Scope scope : getScopeList()) scope.toXML(xw);
+ for (Scope scope : getScopes()) scope.toXML(xw);
}

/**
@@ -445,8 +436,8 @@ public abstract class Feature extends FreeColSpecObject
} else if (lastTurn.getNumber() != feature.lastTurn.getNumber()) {
return false;
}
- List<Scope> tScopes = getScopeList();
- List<Scope> fScopes = feature.getScopeList();
+ List<Scope> tScopes = getScopes();
+ List<Scope> fScopes = feature.getScopes();
if (tScopes.size() != fScopes.size()
// Not very efficient, but we do not expect many scopes
|| any(this.scopes, s -> !feature.scopes.contains(s))
@@ -470,7 +461,7 @@ public abstract class Feature extends FreeColSpecObject
hash += 31 * ((temporary) ? 1 : 0);
// FIXME: is this safe? It is an easy way to ignore
// the order of scope elements.
- hash += sum(getScopeList(), s -> Utils.hashCode(s));
+ hash += sum(getScopes(), s -> Utils.hashCode(s));
return hash;
}
}
diff --git a/src/net/sf/freecol/common/model/FreeColSpecObjectType.java b/src/net/sf/freecol/common/model/FreeColSpecObjectType.java
index 6ef06babaed..2b0725d73e1 100644
--- a/src/net/sf/freecol/common/model/FreeColSpecObjectType.java
+++ b/src/net/sf/freecol/common/model/FreeColSpecObjectType.java
@@ -22,7 +22,6 @@ package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-import java.util.stream.Stream;

import javax.xml.stream.XMLStreamException;

@@ -183,7 +182,7 @@ public abstract class FreeColSpecObjectType extends FreeColSpecObject
/**
* {@inheritDoc}
*/
- public final List<Scope> getScopeList() {
+ public final List<Scope> getScopes() {
return (this.scopes == null) ? Collections.<Scope>emptyList()
: this.scopes;
}
@@ -191,14 +190,6 @@ public abstract class FreeColSpecObjectType extends FreeColSpecObject
/**
* {@inheritDoc}
*/
- public final Stream<Scope> getScopes() {
- return (this.scopes == null) ? Stream.<Scope>empty()
- : this.scopes.stream();
- }
-
- /**
- * {@inheritDoc}
- */
public final void setScopes(List<Scope> scopes) {
this.scopes = scopes;
}
@@ -260,7 +251,7 @@ public abstract class FreeColSpecObjectType extends FreeColSpecObject

for (Modifier modifier : getSortedModifiers()) modifier.toXML(xw);

- for (Scope scope : getScopeList()) scope.toXML(xw);
+ for (Scope scope : getScopes()) scope.toXML(xw);
}

/**
diff --git a/src/net/sf/freecol/common/model/Modifier.java b/src/net/sf/freecol/common/model/Modifier.java
index 345e5b8386c..14bcf8eea27 100644
--- a/src/net/sf/freecol/common/model/Modifier.java
+++ b/src/net/sf/freecol/common/model/Modifier.java
@@ -653,7 +653,7 @@ public class Modifier extends Feature {
if (modifierIndex >= DEFAULT_MODIFIER_INDEX) {
sb.append(" index=").append(modifierIndex);
}
- List<Scope> scopes = getScopeList();
+ List<Scope> scopes = getScopes();
if (!scopes.isEmpty()) {
sb.append(" [");
for (Scope s : scopes) sb.append(' ').append(s);
diff --git a/src/net/sf/freecol/common/model/Scoped.java b/src/net/sf/freecol/common/model/Scoped.java
index 163dab2d196..edc72983454 100644
--- a/src/net/sf/freecol/common/model/Scoped.java
+++ b/src/net/sf/freecol/common/model/Scoped.java
@@ -20,7 +20,6 @@
package net.sf.freecol.common.model;

import java.util.List;
-import java.util.stream.Stream;

import static net.sf.freecol.common.util.CollectionUtils.*;

@@ -31,18 +30,11 @@ import static net.sf.freecol.common.util.CollectionUtils.*;
public interface Scoped {

/**
- * Get the scopes applicable to this effect.
- *
- * @return A list of {@code Scope}s.
- */
- public List<Scope> getScopeList();
-
- /**
* Get the scopes applicable to this effect as a stream.
*
- * @return A stream of {@code Scope}s.
+ * @return A {@code} list of {@code Scope}s.
*/
- public Stream<Scope> getScopes();
+ public List<Scope> getScopes();

/**
* Set the scopes for this object.
@@ -65,7 +57,7 @@ public interface Scoped {
* @return True if this effect applies.
*/
default boolean appliesTo(FreeColObject object) {
- List<Scope> scopes = getScopeList();
+ List<Scope> scopes = getScopes();
return (scopes == null || scopes.isEmpty()) ? true
: any(scopes, s -> s.appliesTo(object));
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:30:56 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/io/FreeColDirectories.java | 18 +++++++++++-------
1 file changed, 11 insertions(+), 7 deletions(-)

diff --git a/src/net/sf/freecol/common/io/FreeColDirectories.java b/src/net/sf/freecol/common/io/FreeColDirectories.java
index 09432988dfb..a7b2496d587 100644
--- a/src/net/sf/freecol/common/io/FreeColDirectories.java
+++ b/src/net/sf/freecol/common/io/FreeColDirectories.java
@@ -133,11 +133,6 @@ public class FreeColDirectories {

public static final String MOD_DESCRIPTOR_FILE_NAME = "mod.xml";

- /** Predicate to filter suitable candidates to be made into mods. */
- private static final Predicate<File> modFileFilter = f ->
- Utils.fileAnySuffix(f, MOD_FILE_SUFFIX, ZIP_FILE_SUFFIX)
- || Utils.directoryAllPresent(f, MOD_DESCRIPTOR_FILE_NAME);
-
/** Predicate to filter suitable candidates to be made into TCs. */
private static final Predicate<File> tcFileFilter = f ->
Utils.fileAnySuffix(f, TC_FILE_SUFFIX, ZIP_FILE_SUFFIX)
@@ -1002,6 +997,11 @@ public class FreeColDirectories {
locale);
}

+ private static boolean checkModFile(File f) {
+ return (Utils.fileAnySuffix(f, MOD_FILE_SUFFIX, ZIP_FILE_SUFFIX)
+ || Utils.directoryAllPresent(f, MOD_DESCRIPTOR_FILE_NAME));
+ }
+
/**
* Get a list of the standard and current user mod files.
*
@@ -1009,8 +1009,12 @@ public class FreeColDirectories {
*/
public static List<File> getModFileList() {
List<File> ret = new ArrayList<>();
- ret.addAll(collectFiles(getStandardModsDirectory(), modFileFilter));
- ret.addAll(collectFiles(getUserModsDirectory(), modFileFilter));
+ for (File f : getStandardModsDirectory().listFiles())
+ if (checkModFile(f)) ret.add(f);
+
+ for (File f : getUserModsDirectory().listFiles())
+ if (checkModFile(f)) ret.add(f);
+
return ret;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:01 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

The old approach required lots locking (for each individual test)
and lots of memory (array of arrays of boolean). Replacing this by
an memory efficient BitSet, which is allocated and computed on-demand
and just dropped for invalidation.

Additionally only hold a lock when the visibility map needs to be
recomputed. The lock is held on the Player object itself, so we dont
need an additional lock object anymore (note: the visibility map may
be null). For now, it's the only case for that (other parts lock
referred objects), so there's no risk of penalty by this global lock.
---
src/net/sf/freecol/common/model/Map.java | 7 +
src/net/sf/freecol/common/model/Player.java | 218 +++++++++++++++++-----------
2 files changed, 138 insertions(+), 87 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Map.java b/src/net/sf/freecol/common/model/Map.java
index 23e2ff817d9..c631ca607e1 100644
--- a/src/net/sf/freecol/common/model/Map.java
+++ b/src/net/sf/freecol/common/model/Map.java
@@ -388,6 +388,13 @@ public class Map extends FreeColGameObject implements Location {
}

/**
+ * Get the tiles of this map
+ */
+ public final Tile[][] getTiles() {
+ return this.tiles;
+ }
+
+ /**
* Gets the width of this map.
*
* @return The width of this map.
diff --git a/src/net/sf/freecol/common/model/Player.java b/src/net/sf/freecol/common/model/Player.java
index 95b91976081..5573d56cc4b 100644
--- a/src/net/sf/freecol/common/model/Player.java
+++ b/src/net/sf/freecol/common/model/Player.java
@@ -22,6 +22,7 @@ package net.sf.freecol.common.model;
import java.awt.Color;

import java.util.ArrayList;
+import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
@@ -127,6 +128,68 @@ public class Player extends FreeColGameObject implements Nameable {
}
}

+ /**
+ * VisibilityMap - holds a bitmap for the visible tiles
+ *
+ * note: semantically, composition instead of inheritance would
+ * be more correct. OTOH, it would require yet another instance.
+ * as its just an private internal class, we can afford being a
+ * bit unclean to save a bit of memory.
+ */
+ private class TileVisibilityMap extends BitSet {
+ private int width;
+ private int height;
+ private BitSet bits = new BitSet();
+
+ protected TileVisibilityMap(int w, int h) {
+ width = w;
+ height = h;
+ }
+
+ /** hope the compiler inlines it **/
+ private final int bitid(int x, int y) {
+ return y * width + x;
+ }
+
+ /** trivial case: mark visible via coordinates **/
+ protected final void setVisible(int x, int y) {
+ bits.set(bitid(x,y));
+ }
+
+ /** mark an individual tile visible **/
+ protected final void setVisible(Tile t) {
+ if (t != null) {
+ bits.set(bitid(t.getX(), t.getY()));
+ t.seeTile(Player.this);
+ }
+ }
+
+ /** mark a whole set of tiles visible **/
+ protected final void setVisible(Set<Tile> st) {
+ if (st != null)
+ for (Tile t : st)
+ setVisible(t);
+ }
+
+ /** mark an settlement and its surrounding visible **/
+ protected final void setVisible(Settlement s) {
+ if (s != null)
+ setVisible(s.getVisibleTiles());
+ }
+
+ /** mark an unit and is surrounding visible - only when the
+ unit is on the map (skipping those in Europe) **/
+ protected final void setVisible(Unit u) {
+ if ((u != null) && (u.getLocation() instanceof Tile))
+ setVisible(u.getVisibleTiles());
+ }
+
+ /** check whether a tile is visible **/
+ protected final boolean isVisible(Tile t) {
+ return (t == null ? false
+ : bits.get(bitid(t.getX(), t.getY())));
+ }
+ }

//
// Constants
@@ -286,11 +349,7 @@ public class Player extends FreeColGameObject implements Nameable {
protected final List<Settlement> settlements = new ArrayList<>();

/** The tiles the player can see. */
- private boolean[][] canSeeTiles = null;
- /** Are the canSeeTiles valid or do they need to be recalculated? */
- private boolean canSeeValid = false;
- /** Do not access canSeeTiles without taking canSeeLock. */
- private final Object canSeeLock = new Object();
+ private TileVisibilityMap visibilityMap = null;

/** A container for the abilities and modifiers of this type. */
protected final FeatureContainer featureContainer = new FeatureContainer();
@@ -2611,16 +2670,15 @@ public class Player extends FreeColGameObject implements Nameable {
* @return True if this player can see the given {@code Tile}.
*/
public boolean canSee(Tile tile) {
- if (tile == null) return false;

- do {
- synchronized (canSeeLock) {
- if (canSeeValid) {
- return canSeeTiles[tile.getX()][tile.getY()];
- }
- }
- } while (resetCanSeeTiles());
- return false;
+ /** the visibility map is allocated on-demand and killed on invalidation **/
+ TileVisibilityMap vismap = visibilityMap;
+
+ /** if we dont have a map yet, create a new one, while holding a lock **/
+ if (vismap == null)
+ vismap = makeCanSeeTiles(getGame().getMap());
+
+ return vismap.isVisible(tile);
}

/**
@@ -2628,7 +2686,7 @@ public class Player extends FreeColGameObject implements Nameable {
*
* This method should be used to invalidate the current
* {@code canSeeTiles} when something significant changes.
- * The method {@link #resetCanSeeTiles} will be called whenever it
+ * The method {@link #makeCanSeeTiles} will be called whenever it
* is needed.
*
* So what is "significant"? Looking at the makeCanSeeTiles routine
@@ -2665,30 +2723,7 @@ public class Player extends FreeColGameObject implements Nameable {
* By convention, we try to avoid cs* routines being -vis.
*/
public void invalidateCanSeeTiles() {
- synchronized (canSeeLock) {
- canSeeValid = false;
- }
- }
-
- /**
- * Resets this player's "can see"-tiles. This is done by setting
- * all the tiles within each {@link Unit} and {@link Settlement}s
- * line of sight visible. The other tiles are made invisible.
- *
- * Use {@link #invalidateCanSeeTiles} whenever possible.
- *
- * @return True if successful.
- */
- private boolean resetCanSeeTiles() {
- Map map = getGame().getMap();
- if (map == null) return false;
-
- boolean[][] cST = makeCanSeeTiles(map);
- synchronized (canSeeLock) {
- canSeeTiles = cST;
- canSeeValid = true;
- }
- return true;
+ visibilityMap = null;
}

/**
@@ -2713,65 +2748,74 @@ public class Player extends FreeColGameObject implements Nameable {
*
* @param map The {@code Map} to use.
* @return A canSeeTiles array.
+ *
+ * note: theoretically we could do completely without a lock,
+ * which could cause the bitmap generation twice, while one
+ * copy just being thrown away. even though still semantically
+ * correct, it's just a waste of resources w/o any gain.
*/
- private boolean[][] makeCanSeeTiles(Map map) {
+ private synchronized TileVisibilityMap makeCanSeeTiles(Map map) {
+
+ /* ugh, dont have a map yet ? */
+ if (map == null) {
+ TileVisibilityMap vismap = new TileVisibilityMap(1,1);
+ visibilityMap = vismap;
+ return vismap;
+ }
+
+ TileVisibilityMap vismap = new TileVisibilityMap(map.getWidth(), map.getHeight());
+
final Specification spec = getSpecification();
// Simple case when there is no fog of war: a tile is
// visible once it is explored.
if (!spec.getBoolean(GameOptions.FOG_OF_WAR)) {
- boolean[][] cST = (canSeeTiles != null) ? canSeeTiles
- : new boolean[map.getWidth()][map.getHeight()];
- getGame().getMap().forEachTile(t -> {
- cST[t.getX()][t.getY()] = hasExplored(t);
- });
- return cST;
- }
+ Tile[][] tiles = map.getTiles();

- // When there is fog, have to trace all locations where the
- // player has units, settlements, (optionally) missions, and
- // extra visibility.
- // Set the PET for visible tiles to the tile itself.
- boolean[][] cST = new boolean[map.getWidth()][map.getHeight()];
-
- // Only consider units directly on the map, not those on a
- // carrier or in Europe.
- for (Unit unit : transform(getUnits(),
- u -> u.getLocation() instanceof Tile)) {
- // All the units.
- for (Tile t : unit.getVisibleTiles()) {
- cST[t.getX()][t.getY()] = true;
- t.seeTile(this);
- }
- }
- // All the settlements.
- for (Settlement settlement : getSettlementList()) {
- for (Tile t : settlement.getVisibleTiles()) {
- cST[t.getX()][t.getY()] = true;
- t.seeTile(this);
- }
- }
- // All missions if using enhanced missionaries.
- if (isEuropean()
- && spec.getBoolean(GameOptions.ENHANCED_MISSIONARIES)) {
- for (Player other : getGame().getLiveNativePlayerList(this)) {
- for (Tile t : iterable(flatten(getIndianSettlementsWithMissionary(this),
- is -> is.getVisibleTiles().stream()))) {
- cST[t.getX()][t.getY()] = true;
- t.seeTile(this);
- }
+ for (int x=0; x<tiles.length; x++) {
+ Tile[] col = tiles[x];
+
+ if (col == null) // can columns be null at all ?
+ continue;
+
+ for (int y=0; y<col.length; y++)
+ if ((col[y] != null) && (col[y].isExplored()))
+ vismap.setVisible(x, y);
}
}
- // All other European settlements if can see all colonies.
- if (isEuropean() && hasAbility(Ability.SEE_ALL_COLONIES)) {
- for (Tile t : iterable(flatten(getGame().getAllColonies(this),
- c -> c.getVisibleTiles().stream()))) {
- cST[t.getX()][t.getY()] = true;
- t.seeTile(this);
+ else
+ {
+ // player has units, settlements, (optionally) missions, and
+ // extra visibility.
+ // Set the PET for visible tiles to the tile itself.
+
+ // Only consider units directly on the map, not those on a
+ // carrier or in Europe.
+ for (Unit unit : getUnits())
+ vismap.setVisible(unit);
+
+ // All the settlements.
+ for (Settlement settlement : getSettlementList())
+ vismap.setVisible(settlement);
+
+ if (isEuropean()) {
+
+ // All missions if using enhanced missionaries.
+ if (spec.getBoolean(GameOptions.ENHANCED_MISSIONARIES))
+ for (Player other : getGame().getLiveNativePlayerList(this))
+ for (IndianSettlement is : getIndianSettlementsWithMissionaryList(this))
+ vismap.setVisible(is);
+
+ // All other European settlements if can see all colonies.
+ if (hasAbility(Ability.SEE_ALL_COLONIES))
+ for (Colony c : getGame().getAllColoniesList(this))
+ vismap.setVisible(c);
}
}
- return cST;
- }

+ // finally update the current visibility map
+ visibilityMap = vismap;
+ return vismap;
+ }

//
// Foreign relations
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:30:51 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

We have several places where lists are walked and names/strings derived
from the list elements are collected in a comma-separated list (string).

Instead of using expensive stream operations (with lots of callbacks),
just loop over the list and collect in a specialized string buffer.
---
src/net/sf/freecol/FreeCol.java | 7 ++-
src/net/sf/freecol/client/gui/ModifierFormat.java | 24 +++++---
.../gui/panel/colopedia/ResourcesDetailPanel.java | 12 ++--
.../sf/freecol/common/debug/FreeColDebugger.java | 11 +++-
src/net/sf/freecol/common/model/Specification.java | 16 ++++--
.../sf/freecol/common/networking/LoginMessage.java | 21 +++----
src/net/sf/freecol/common/util/Introspector.java | 7 ++-
src/net/sf/freecol/common/util/StrCat.java | 67 ++++++++++++++++++++++
8 files changed, 128 insertions(+), 37 deletions(-)
create mode 100644 src/net/sf/freecol/common/util/StrCat.java

diff --git a/src/net/sf/freecol/FreeCol.java b/src/net/sf/freecol/FreeCol.java
index bc69506005c..b746b8ccd9a 100644
--- a/src/net/sf/freecol/FreeCol.java
+++ b/src/net/sf/freecol/FreeCol.java
@@ -57,6 +57,7 @@ import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.option.OptionGroup;
import static net.sf.freecol.common.util.CollectionUtils.*;
import net.sf.freecol.common.util.LogBuilder;
+import net.sf.freecol.common.util.StrCat;
import net.sf.freecol.server.FreeColServer;

import org.apache.commons.cli.CommandLine;
@@ -995,8 +996,10 @@ public final class FreeCol {
* @return A list of advantage types.
*/
private static String getValidAdvantages() {
- return transform(Advantages.values(), alwaysTrue(),
- a -> Messages.getName(a), Collectors.joining(","));
+ StrCat cat = new StrCat(",");
+ for (Advantages walk : Advantages.values())
+ cat.add(Messages.getName(walk));
+ return cat.toString();
}

/**
diff --git a/src/net/sf/freecol/client/gui/ModifierFormat.java b/src/net/sf/freecol/client/gui/ModifierFormat.java
index c15c78808dd..60e20895276 100644
--- a/src/net/sf/freecol/client/gui/ModifierFormat.java
+++ b/src/net/sf/freecol/client/gui/ModifierFormat.java
@@ -20,8 +20,6 @@
package net.sf.freecol.client.gui;

import java.text.DecimalFormat;
-import java.util.function.Function;
-import java.util.stream.Collectors;

import javax.swing.JLabel;

@@ -36,6 +34,7 @@ import net.sf.freecol.common.model.Named;
import net.sf.freecol.common.model.Scope;
import net.sf.freecol.common.model.Turn;
import static net.sf.freecol.common.util.CollectionUtils.*;
+import net.sf.freecol.common.util.StrCat;


public class ModifierFormat {
@@ -115,14 +114,23 @@ public class ModifierFormat {
}

public static String getFeatureAsString(Feature feature) {
- return Messages.getName(feature) + ":"
- + ((!feature.hasScope()) ? ""
- : transform(feature.getScopes(), isNotNull(),
- Scope::getFeatureString, Collectors.joining(",")));
+ if (!feature.hasScope())
+ return Messages.getName(feature);
+
+ StrCat cat = new StrCat(",");
+ cat.append(Messages.getName(feature)).append(":");
+
+ for (Scope scope : feature.getScopes())
+ if (scope != null)
+ cat.add(scope.getFeatureString());
+
+ return cat.toString();
}

public static String getModifierAsString(Modifier modifier) {
- return transform(getModifierStrings(modifier), isNotNull(),
- Function.identity(), Collectors.joining());
+ StringBuilder sb = new StringBuilder();
+ for (String s : getModifierStrings(modifier))
+ if (s != null) sb.append(s);
+ return sb.toString();
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/colopedia/ResourcesDetailPanel.java b/src/net/sf/freecol/client/gui/panel/colopedia/ResourcesDetailPanel.java
index 1dee2d4e3fd..eea89593a5d 100644
--- a/src/net/sf/freecol/client/gui/panel/colopedia/ResourcesDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/colopedia/ResourcesDetailPanel.java
@@ -20,7 +20,6 @@
package net.sf.freecol.client.gui.panel.colopedia;

import java.util.List;
-import java.util.stream.Collectors;

import javax.swing.JButton;
import javax.swing.JLabel;
@@ -39,6 +38,7 @@ import net.sf.freecol.common.model.Modifier;
import net.sf.freecol.common.model.ResourceType;
import net.sf.freecol.common.model.Scope;
import net.sf.freecol.common.model.Specification;
+import net.sf.freecol.common.util.StrCat;
import static net.sf.freecol.common.util.CollectionUtils.*;


@@ -93,11 +93,11 @@ public class ResourcesDetailPanel
for (Modifier modifier : mods) {
String text = ModifierFormat.getModifierAsString(modifier);
if (modifier.hasScope()) {
- String scopes = transform(modifier.getScopes(),
- isNotNull(Scope::getType),
- s -> Messages.getName(spec.findType(s.getType())),
- Collectors.joining(", "));
- if (!scopes.isEmpty()) text += " (" + scopes + ")";
+ StrCat cat = new StrCat(", ");
+ for (Scope s : modifier.getScopes())
+ cat.add(Messages.getName(spec.findType(s.getType())));
+ if (!cat.isEmpty())
+ text += " (" + cat.toString() + ")";
}

GoodsType goodsType = spec.getGoodsType(modifier.getId());
diff --git a/src/net/sf/freecol/common/debug/FreeColDebugger.java b/src/net/sf/freecol/common/debug/FreeColDebugger.java
index b5bfbb4192c..4299a513e8d 100644
--- a/src/net/sf/freecol/common/debug/FreeColDebugger.java
+++ b/src/net/sf/freecol/common/debug/FreeColDebugger.java
@@ -28,13 +28,13 @@ import java.io.PrintStream;

import java.util.Locale;
import java.util.logging.Logger;
-import java.util.stream.Collectors;

import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.common.io.FreeColDirectories;
import net.sf.freecol.common.model.Player;
import static net.sf.freecol.common.util.CollectionUtils.*;
import net.sf.freecol.common.util.LogBuilder;
+import net.sf.freecol.common.util.StrCat;
import net.sf.freecol.server.FreeColServer;


@@ -134,8 +134,13 @@ public class FreeColDebugger {
* @return A string containing the modes as csv.
*/
public static String getDebugModes() {
- return transform(DebugMode.values(), m -> isInDebugMode(m),
- DebugMode::toString, Collectors.joining(","));
+ StrCat cat = new StrCat(",");
+
+ for (DebugMode m : DebugMode.values())
+ if (isInDebugMode(m))
+ cat.add(m.toString());
+
+ return cat.toString();
}

/**
diff --git a/src/net/sf/freecol/common/model/Specification.java b/src/net/sf/freecol/common/model/Specification.java
index 58e698ba9da..9a11275f1be 100644
--- a/src/net/sf/freecol/common/model/Specification.java
+++ b/src/net/sf/freecol/common/model/Specification.java
@@ -34,7 +34,6 @@ import java.util.function.Predicate;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
-import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.xml.stream.XMLStreamException;
@@ -59,6 +58,7 @@ import net.sf.freecol.common.option.StringOption;
import net.sf.freecol.common.option.TextOption;
import net.sf.freecol.common.option.UnitListOption;
import static net.sf.freecol.common.util.CollectionUtils.*;
+import net.sf.freecol.common.util.StrCat;


/**
@@ -2043,10 +2043,13 @@ public final class Specification {
return;
}

+ StrCat cat = new StrCat(" ");
+ for (Role r : getRoles())
+ cat.add(r.getId());
+
logger.info("Loading role backward compatibility fragment: "
+ ROLES_COMPAT_FILE_NAME + " with roles: "
- + transform(getRoles(), alwaysTrue(), Role::getId,
- Collectors.joining(" ")));
+ + cat.toString());
}
// end @compat 0.10.x

@@ -3035,10 +3038,13 @@ public final class Specification {
return;
}

+ StrCat cat = new StrCat(" ");
+ for (UnitChangeType uct : getUnitChangeTypeList())
+ cat.add(uct.getId());
+
logger.info("Loading unit-change-types backward compatibility fragment: "
+ UNIT_CHANGE_TYPES_COMPAT_FILE_NAME + " with changes: "
- + transform(getUnitChangeTypeList(), alwaysTrue(),
- UnitChangeType::getId, Collectors.joining(" ")));
+ + cat.toString());
}
}

diff --git a/src/net/sf/freecol/common/networking/LoginMessage.java b/src/net/sf/freecol/common/networking/LoginMessage.java
index f7a1be4b0ff..7b1a9300688 100644
--- a/src/net/sf/freecol/common/networking/LoginMessage.java
+++ b/src/net/sf/freecol/common/networking/LoginMessage.java
@@ -19,8 +19,6 @@

package net.sf.freecol.common.networking;

-import java.util.stream.Collectors;
-
import net.sf.freecol.FreeCol;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.Nation;
@@ -29,6 +27,7 @@ import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.networking.AddPlayerMessage;
import net.sf.freecol.common.networking.ErrorMessage;
import net.sf.freecol.common.networking.SetAIMessage;
+import net.sf.freecol.common.util.StrCat;
import static net.sf.freecol.common.util.CollectionUtils.*;
import net.sf.freecol.server.FreeColServer;
import net.sf.freecol.server.FreeColServer.ServerState;
@@ -229,13 +228,14 @@ public class LoginMessage extends DOMMessage {
game = freeColServer.getGame(); // Restoring from existing game.
present = getPlayerByName(game);
if (present == null) {
+ StrCat cat = new StrCat(", ");
+ for (Player p : game.getLiveEuropeanPlayers())
+ cat.add(p.getName());
+
return ChangeSet.clientError((ServerPlayer)null, StringTemplate
.template("server.userNameNotPresent")
.addName("%name%", userName)
- .addName("%names%",
- transform(game.getLiveEuropeanPlayers(),
- alwaysTrue(), Player::getName,
- Collectors.joining(", "))));
+ .addName("%names%", cat.toString()));
} else if (present.isConnected()) {
// Another player already connected on the name
return ChangeSet.clientError((ServerPlayer)null, StringTemplate
@@ -265,13 +265,14 @@ public class LoginMessage extends DOMMessage {
game = freeColServer.getGame(); // Restoring from existing game.
present = getPlayerByName(game);
if (present == null) {
+ StrCat cat = new StrCat(", ");
+ for (Player p : game.getLiveEuropeanPlayers())
+ cat.add(p.getName());
+
return ChangeSet.clientError((ServerPlayer)null, StringTemplate
.template("server.userNameNotPresent")
.addName("%name%", userName)
- .addName("%names%",
- transform(game.getLiveEuropeanPlayers(),
- alwaysTrue(), Player::getName,
- Collectors.joining(", "))));
+ .addName("%names%", cat.toString()));
} else if (present.isAI()) { // Allow to join over AI player
present.setAI(false);
freeColServer.sendToAll(new SetAIMessage(present, false),
diff --git a/src/net/sf/freecol/common/util/Introspector.java b/src/net/sf/freecol/common/util/Introspector.java
index 0e6e5ae5094..0edc686b534 100644
--- a/src/net/sf/freecol/common/util/Introspector.java
+++ b/src/net/sf/freecol/common/util/Introspector.java
@@ -23,7 +23,6 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
-import java.util.stream.Collectors;

import static net.sf.freecol.common.util.CollectionUtils.*;
import static net.sf.freecol.common.util.StringUtils.*;
@@ -347,10 +346,12 @@ public class Introspector {
try {
constructor = messageClass.getDeclaredConstructor(types);
} catch (NoSuchMethodException | SecurityException ex) {
+ StrCat cat = new StrCat(",");
+ for (Class cls : types)
+ cat.add(cls.getName());
throw new IntrospectorException("Unable to find constructor "
+ lastPart(tag, ".") + "("
- + transform(types, alwaysTrue(), Class::getName,
- Collectors.joining(","))
+ + cat.toString()
+ ")", ex);
}
T instance;
diff --git a/src/net/sf/freecol/common/util/StrCat.java b/src/net/sf/freecol/common/util/StrCat.java
new file mode 100644
index 00000000000..eb7b64b6d1e
--- /dev/null
+++ b/src/net/sf/freecol/common/util/StrCat.java
@@ -0,0 +1,67 @@
+/**
+ * Copyright (C) 2002-2016 The FreeCol Team
+ *
+ * This file is part of FreeCol.
+ *
+ * FreeCol is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * FreeCol is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with FreeCol. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.sf.freecol.common.util;
+
+
+import java.lang.StringBuilder;
+
+
+public class StrCat {
+ private String delimiter = ", ";
+ private int counter = 0;
+ private StringBuilder sb = new StringBuilder();
+
+ public StrCat(String d) {
+ delimiter = d;
+ }
+
+ public final boolean isEmpty() {
+ return counter == 0;
+ }
+
+ /**
+ * directly add a string to the underlying buffer, w/o any
+ * any delimiter. also dont count that as an element.
+ */
+ public final StrCat append(String s) {
+ sb.append(s);
+ return this;
+ }
+
+ /**
+ * add another element and fill the delimiter
+ * in between it's not the first one.
+ */
+ public final void add(String s) {
+ if ((s == null) || s.equals("")) return;
+
+ if (counter == 0) {
+ sb.append(s);
+ } else {
+ sb.append(delimiter);
+ sb.append(s);
+ }
+ counter++;
+ }
+
+ public final String toString() {
+ return sb.toString();
+ }
+}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:06 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

Retrieval of currently movable units semantically fits better into
the Player object instead of outer business logic.

Also simplifying the code flow by using a plain loop instead of
lamdas and Stream magic - the benefit of potential parallelization
is pretty hypothetical here, as the tests are pretty trivial,
compared to the overhead of Streams w/ lamdas (IOW: callbacks).

OTOH, we could optimize further by not using getters internally
within Unit or at least make them final, so the compiler can
inline them.
---
src/net/sf/freecol/client/control/InGameController.java | 8 +++++++-
src/net/sf/freecol/common/model/Player.java | 11 +++++++++++
2 files changed, 18 insertions(+), 1 deletion(-)

diff --git a/src/net/sf/freecol/client/control/InGameController.java b/src/net/sf/freecol/client/control/InGameController.java
index 9d2f6239f91..5380aec31f4 100644
--- a/src/net/sf/freecol/client/control/InGameController.java
+++ b/src/net/sf/freecol/client/control/InGameController.java
@@ -778,7 +778,13 @@ public final class InGameController extends FreeColClientHolder {
private boolean doEndTurn(boolean showDialog) {
final Player player = getMyPlayer();
if (showDialog) {
- List<Unit> units = transform(player.getUnits(), Unit::couldMove);
+ /** we could check for movable units first, before retrieving
+ a list of them - that would save unnecessary list allocation
+ in case there none left, but at the cost of having to loop
+ through the list twice, if there are some. the worst case
+ would be just the last unit in the list is movable - then
+ we'd end up w/ two full list scans instead of just one. **/
+ List<Unit> units = player.getMovableUnits();
if (!units.isEmpty()) {
// Modal dialog takes over
getGUI().showEndTurnDialog(units,
diff --git a/src/net/sf/freecol/common/model/Player.java b/src/net/sf/freecol/common/model/Player.java
index 5573d56cc4b..0da6e80228f 100644
--- a/src/net/sf/freecol/common/model/Player.java
+++ b/src/net/sf/freecol/common/model/Player.java
@@ -1923,6 +1923,17 @@ public class Player extends FreeColGameObject implements Nameable {
}

/**
+ * Retrieve a list of still movable units
+ */
+ public final List<Unit> getMovableUnits() {
+ List<Unit> result = new ArrayList<>();
+ for (Unit u : this.units)
+ if (u.couldMove())
+ result.add(u);
+ return result;
+ }
+
+ /**
* Get the number of units a player has.
*
* @return The number of units.
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:30:52 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../sf/freecol/common/util/CollectionUtils.java | 384 ++++++++++++++++-----
1 file changed, 297 insertions(+), 87 deletions(-)

diff --git a/src/net/sf/freecol/common/util/CollectionUtils.java b/src/net/sf/freecol/common/util/CollectionUtils.java
index ec7662fee93..7f911e72ad8 100644
--- a/src/net/sf/freecol/common/util/CollectionUtils.java
+++ b/src/net/sf/freecol/common/util/CollectionUtils.java
@@ -34,7 +34,6 @@ import java.util.Map.Entry;
import java.util.Set;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
-import java.util.function.DoubleBinaryOperator;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
@@ -67,6 +66,12 @@ public class CollectionUtils {
public static final BinaryOperator<Double> doubleAccumulator
= (d1, d2) -> d1 + d2;

+ public static final BinaryOperator<Double> doubleMultiplicator
+ = new BinaryOperator<Double>() {
+ public Double apply(Double d1, Double d2) {
+ return d1 * d2;
+ }};
+
/** Useful comparators for mapEntriesBy* */
public static final Comparator<Integer> ascendingIntegerComparator
= Comparator.comparingInt(i -> i);
@@ -436,6 +441,12 @@ public class CollectionUtils {
return stream.allMatch(predicate);
}

+ public static final Predicate alwaysTruePred
+ = new Predicate() {
+ public boolean test(Object o) {
+ return true;
+ }};
+
/**
* Helper to create a predicate which is always true.
*
@@ -443,7 +454,7 @@ public class CollectionUtils {
* @return The always valid predicate for the stream type.
*/
public static <T> Predicate<T> alwaysTrue() {
- return (T t) -> true;
+ return alwaysTruePred;
}

/**
@@ -613,7 +624,7 @@ public class CollectionUtils {
*/
public static <T> int count(T[] array,
Predicate<? super T> predicate) {
- return count_internal(Arrays.stream(array), predicate);
+ return (array == null ? 0 : (int)(Arrays.<T>stream(array).filter(predicate).count()));
}

/**
@@ -637,7 +648,7 @@ public class CollectionUtils {
*/
public static <T> int count(Collection<T> c,
Predicate<? super T> predicate) {
- return count_internal(c.stream(), predicate);
+ return (c == null ? 0 : (int)(c.stream().filter(predicate).count()));
}

/**
@@ -648,7 +659,7 @@ public class CollectionUtils {
* @return The number of items that matched.
*/
public static <T> int count(Stream<T> stream) {
- return (stream == null) ? 0 : count_internal(stream, alwaysTrue());
+ return (stream == null) ? 0 : (int)stream.count();
}

/**
@@ -661,20 +672,7 @@ public class CollectionUtils {
*/
public static <T> int count(Stream<T> stream,
Predicate<? super T> predicate) {
- return (stream == null) ? 0 : count_internal(stream, predicate);
- }
-
- /**
- * Implement count().
- *
- * @param <T> The stream member type.
- * @param stream The {@code Stream} to check.
- * @param predicate A {@code Predicate} to test with.
- * @return The number of items that matched.
- */
- private static <T> int count_internal(Stream<T> stream,
- Predicate<? super T> predicate) {
- return (int)stream.filter(predicate).count();
+ return (stream == null) ? 0 : (int)stream.filter(predicate).count();
}

/**
@@ -920,7 +918,7 @@ public class CollectionUtils {
*/
public static <T, R> Stream<R> flatten(T[] array,
Function<? super T, ? extends Stream<? extends R>> mapper) {
- return flatten_internal(Arrays.stream(array), alwaysTrue(), mapper);
+ return flatten_internal(Arrays.stream(array), mapper);
}

/**
@@ -950,7 +948,7 @@ public class CollectionUtils {
*/
public static <T, R> Stream<R> flatten(Collection<T> c,
Function<? super T, ? extends Stream<? extends R>> mapper) {
- return flatten_internal(c.stream(), alwaysTrue(), mapper);
+ return flatten_internal(c.stream(), mapper);
}

/**
@@ -981,7 +979,7 @@ public class CollectionUtils {
public static <T, R> Stream<R> flatten(Stream<T> stream,
Function<? super T, ? extends Stream<? extends R>> mapper) {
return (stream == null) ? Stream.<R>empty()
- : flatten_internal(stream, alwaysTrue(), mapper);
+ : flatten_internal(stream, mapper);
}

/**
@@ -1018,6 +1016,20 @@ public class CollectionUtils {
}

/**
+ * Flatten the members of a stream.
+ *
+ * @param <T> The stream member type.
+ * @param <R> The resulting stream member type.
+ * @param stream The {@code Stream} to flatten.
+ * @param mapper A mapping {@code Function} to apply.
+ * @return A stream of the mapped stream.
+ */
+ private static <T, R> Stream<R> flatten_internal(Stream<T> stream,
+ Function<? super T, ? extends Stream<? extends R>> mapper) {
+ return stream.filter(predicate).flatMap(mapper);
+ }
+
+ /**
* Apply a consumer to the entries of a map.
*
* @param <K> The map key type.
@@ -1333,7 +1345,7 @@ public class CollectionUtils {
* @return The maximum value found, or zero if the input is empty.
*/
public static <T> int max(T[] array, ToIntFunction<T> tif) {
- return max_internal(Arrays.stream(array), alwaysTrue(), tif);
+ return max_internal(Arrays.stream(array), tif);
}

/**
@@ -1359,7 +1371,7 @@ public class CollectionUtils {
* @return The maximum value found, or zero if the input is empty.
*/
public static <T> int max(Collection<T> c, ToIntFunction<T> tif) {
- return max_internal(c.stream(), alwaysTrue(), tif);
+ return max_internal(c.stream(), tif);
}

/**
@@ -1386,7 +1398,7 @@ public class CollectionUtils {
*/
public static <T> int max(Stream<T> stream, ToIntFunction<T> tif) {
return (stream == null) ? MAX_DEFAULT
- : max_internal(stream, alwaysTrue(), tif);
+ : max_internal(stream, tif);
}

/**
@@ -1421,6 +1433,20 @@ public class CollectionUtils {
}

/**
+ * Implement max.
+ *
+ * @param <T> The stream member type.
+ * @param stream The {@code Stream} to check.
+ * @param tif A {@code ToIntFunction} to map the stream to int with.
+ * @return The maximum value found, or zero if the input is empty.
+ */
+ private static <T> int max_internal(Stream<T> stream,
+ ToIntFunction<T> tif) {
+ return stream.mapToInt(tif).max()
+ .orElse(MAX_DEFAULT);
+ }
+
+ /**
* Find the selected member of an array that maximizes according
* to a given comparison.
*
@@ -1430,7 +1456,7 @@ public class CollectionUtils {
* @return The maximal value found, or null if none present.
*/
public static <T> T maximize(T[] array, Comparator<? super T> comparator) {
- return maximize_internal(Arrays.stream(array), alwaysTrue(),
+ return maximize_internal(Arrays.stream(array),
comparator);
}

@@ -1460,7 +1486,7 @@ public class CollectionUtils {
*/
public static <T> T maximize(Collection<T> c,
Comparator<? super T> comparator) {
- return maximize_internal(c.stream(), alwaysTrue(), comparator);
+ return maximize_internal(c.stream(), comparator);
}

/**
@@ -1491,7 +1517,7 @@ public class CollectionUtils {
public static <T> T maximize(Stream<T> stream,
Comparator<? super T> comparator) {
return (stream == null) ? null
- : maximize_internal(stream, alwaysTrue(), comparator);
+ : maximize_internal(stream, comparator);
}

/**
@@ -1516,6 +1542,20 @@ public class CollectionUtils {
*
* @param <T> The collection member type.
* @param stream The {@code Stream} to maximize from.
+ * @param comparator A {@code Comparator} to compare with.
+ * @return The maximal value found, or null if none present.
+ */
+ private static <T> T maximize_internal(Stream<T> stream,
+ Comparator<? super T> comparator) {
+ return stream.collect(Collectors.maxBy(comparator))
+ .orElse(null);
+ }
+
+ /**
+ * Implement maximize.
+ *
+ * @param <T> The collection member type.
+ * @param stream The {@code Stream} to maximize from.
* @param predicate A {@code Predicate} to match with.
* @param comparator A {@code Comparator} to compare with.
* @return The maximal value found, or null if none present.
@@ -1536,7 +1576,7 @@ public class CollectionUtils {
* @return The minimum value found, or zero if the input is empty.
*/
public static <T> int min(T[] array, ToIntFunction<T> tif) {
- return min_internal(Arrays.stream(array), alwaysTrue(), tif);
+ return min_internal(Arrays.stream(array), tif);
}

/**
@@ -1562,7 +1602,7 @@ public class CollectionUtils {
* @return The minimum value found, or zero if the input is empty.
*/
public static <T> int min(Collection<T> c, ToIntFunction<T> tif) {
- return min_internal(c.stream(), alwaysTrue(), tif);
+ return min_internal(c.stream(), tif);
}

/**
@@ -1589,7 +1629,7 @@ public class CollectionUtils {
*/
public static <T> int min(Stream<T> stream, ToIntFunction<T> tif) {
return (stream == null) ? MIN_DEFAULT
- : min_internal(stream, alwaysTrue(), tif);
+ : min_internal(stream, tif);
}

/**
@@ -1613,6 +1653,20 @@ public class CollectionUtils {
*
* @param <T> The stream member type.
* @param stream The {@code Stream} to check.
+ * @param tif A {@code ToIntFunction} to map the stream to int with.
+ * @return The minimum value found, or zero if the input is empty.
+ */
+ private static <T> int min_internal(Stream<T> stream,
+ ToIntFunction<T> tif) {
+ return stream.mapToInt(tif).min()
+ .orElse(MIN_DEFAULT);
+ }
+
+ /**
+ * Implement min.
+ *
+ * @param <T> The stream member type.
+ * @param stream The {@code Stream} to check.
* @param predicate A {@code Predicate} to match with.
* @param tif A {@code ToIntFunction} to map the stream to int with.
* @return The minimum value found, or zero if the input is empty.
@@ -1635,7 +1689,7 @@ public class CollectionUtils {
*/
public static <T> T minimize(T[] array,
Comparator<? super T> comparator) {
- return minimize_internal(Arrays.stream(array), alwaysTrue(),
+ return minimize_internal(Arrays.stream(array),
comparator);
}

@@ -1665,7 +1719,7 @@ public class CollectionUtils {
*/
public static <T> T minimize(Collection<T> c,
Comparator<? super T> comparator) {
- return minimize_internal(c.stream(), alwaysTrue(), comparator);
+ return minimize_internal(c.stream(), comparator);
}

/**
@@ -1696,7 +1750,7 @@ public class CollectionUtils {
public static <T> T minimize(Stream<T> stream,
Comparator<? super T> comparator) {
return (stream == null) ? null
- : minimize_internal(stream, alwaysTrue(), comparator);
+ : minimize_internal(stream, comparator);
}

/**
@@ -1726,6 +1780,21 @@ public class CollectionUtils {
* @return The minimal value found, or null if none present.
*/
private static <T> T minimize_internal(Stream<T> stream,
+ Comparator<? super T> comparator) {
+ return stream.collect(Collectors.minBy(comparator))
+ .orElse(null);
+ }
+
+ /**
+ * Implement minimize.
+ *
+ * @param <T> The stream member type.
+ * @param stream The {@code Stream} to minimize from.
+ * @param predicate A {@code Predicate} to match with.
+ * @param comparator A {@code Comparator} to compare with.
+ * @return The minimal value found, or null if none present.
+ */
+ private static <T> T minimize_internal(Stream<T> stream,
Predicate<? super T> predicate,
Comparator<? super T> comparator) {
return stream.filter(predicate).collect(Collectors.minBy(comparator))
@@ -1825,7 +1894,7 @@ public class CollectionUtils {
* @return The product of the values found.
*/
public static <T> double product(T[] array, ToDoubleFunction<T> tdf) {
- return product_internal(Arrays.stream(array), alwaysTrue(), tdf);
+ return product_internal(Arrays.stream(array), tdf);
}

/**
@@ -1852,7 +1921,7 @@ public class CollectionUtils {
*/
public static <T> double product(Collection<T> c,
ToDoubleFunction<T> tdf) {
- return product_internal(c.stream(), alwaysTrue(), tdf);
+ return product_internal(c.stream(), tdf);
}

/**
@@ -1881,7 +1950,7 @@ public class CollectionUtils {
public static <T> double product(Stream<T> stream,
ToDoubleFunction<T> tdf) {
return (stream == null) ? PRODUCT_DEFAULT
- : product_internal(stream, alwaysTrue(), tdf);
+ : product_internal(stream, tdf);
}

/**
@@ -1903,6 +1972,20 @@ public class CollectionUtils {
/**
* Take the product of the members of a stream.
*
+ * @param <T> The stream member type.
+ * @param stream The {@code Stream} to multiply.
+ * @param tdf A {@code ToDoubleFunction} to convert members to double.
+ * @return The product of the values found.
+ */
+ public static <T> double product_internal(Stream<T> stream,
+ ToDoubleFunction<T> tdf) {
+ return stream.mapToDouble(tdf)
+ .reduce(PRODUCT_DEFAULT, doubleMultiplicator);
+ }
+
+ /**
+ * Take the product of the members of a stream.
+ *
* @param predicate A {@code Predicate} to match with.
* @param <T> The stream member type.
* @param stream The {@code Stream} to multiply.
@@ -1912,9 +1995,8 @@ public class CollectionUtils {
public static <T> double product_internal(Stream<T> stream,
Predicate<? super T> predicate,
ToDoubleFunction<T> tdf) {
- final DoubleBinaryOperator mult = (d1, d2) -> d1 * d2;
return stream.filter(predicate).mapToDouble(tdf)
- .reduce(PRODUCT_DEFAULT, mult);
+ .reduce(PRODUCT_DEFAULT, doubleMultiplicator);
}

/**
@@ -2046,7 +2128,7 @@ public class CollectionUtils {
*/
private static <T> List<T> sort_internal(Stream<T> stream,
Comparator<? super T> comparator) {
- return stream.sorted(comparator).collect(Collectors.toList());
+ return stream.sorted(comparator).collect(Collectors.<T>toList());
}

/**
@@ -2058,7 +2140,7 @@ public class CollectionUtils {
* @return The sum of the values found.
*/
public static <T> int sum(T[] array, ToIntFunction<T> tif) {
- return sum_internal(Arrays.stream(array), alwaysTrue(), tif);
+ return sum_internal(Arrays.stream(array), tif);
}

/**
@@ -2084,7 +2166,7 @@ public class CollectionUtils {
* @return The sum of the values found.
*/
public static <T> int sum(Collection<T> c, ToIntFunction<T> tif) {
- return sum_internal(c.stream(), alwaysTrue(), tif);
+ return sum_internal(c.stream(), tif);
}

/**
@@ -2111,7 +2193,7 @@ public class CollectionUtils {
*/
public static <T> int sum(Stream<T> stream, ToIntFunction<T> tif) {
return (stream == null) ? SUM_DEFAULT
- : sum_internal(stream, alwaysTrue(), tif);
+ : sum_internal(stream, tif);
}

/**
@@ -2134,6 +2216,19 @@ public class CollectionUtils {
*
* @param <T> The stream member type.
* @param stream The {@code Stream} to sum.
+ * @param tif A {@code ToIntFunction} to convert members to an int.
+ * @return The sum of the values found.
+ */
+ private static <T> int sum_internal(Stream<T> stream,
+ ToIntFunction<T> tif) {
+ return stream.mapToInt(tif).sum();
+ }
+
+ /**
+ * Take the sum of the members of a stream.
+ *
+ * @param <T> The stream member type.
+ * @param stream The {@code Stream} to sum.
* @param predicate A {@code Predicate} to match with.
* @param tif A {@code ToIntFunction} to convert members to an int.
* @return The sum of the values found.
@@ -2154,7 +2249,7 @@ public class CollectionUtils {
* @return The sum of the values found.
*/
public static <T> double sumDouble(T[] array, ToDoubleFunction<T> tdf) {
- return sumDouble_internal(Arrays.stream(array), alwaysTrue(), tdf);
+ return sumDouble_internal(Arrays.stream(array), tdf);
}

/**
@@ -2184,7 +2279,7 @@ public class CollectionUtils {
*/
public static <T> double sumDouble(Collection<T> c,
ToDoubleFunction<T> tdf) {
- return sumDouble_internal(c.stream(), alwaysTrue(), tdf);
+ return sumDouble_internal(c.stream(), tdf);
}

/**
@@ -2215,7 +2310,7 @@ public class CollectionUtils {
public static <T> double sumDouble(Stream<T> stream,
ToDoubleFunction<T> tdf) {
return (stream == null) ? SUM_DOUBLE_DEFAULT
- : sumDouble_internal(stream, alwaysTrue(), tdf);
+ : sumDouble_internal(stream, tdf);
}

/**
@@ -2250,6 +2345,19 @@ public class CollectionUtils {
}

/**
+ * Take the sum of the members of a stream.
+ *
+ * @param <T> The stream member type.
+ * @param stream The {@code Stream} to sum.
+ * @param tdf A {@code ToIntFunction} to convert members to a double.
+ * @return The sum of the values found.
+ */
+ private static <T> double sumDouble_internal(Stream<T> stream,
+ ToDoubleFunction<T> tdf) {
+ return stream.mapToDouble(tdf).sum();
+ }
+
+ /**
* Make a collector that takes lists and appends them.
*
* @param <T> The list member type.
@@ -2303,7 +2411,7 @@ public class CollectionUtils {
* @return A list of the stream contents.
*/
private static <T> List<T> toList_internal(Stream<T> stream) {
- return stream.collect(Collectors.toList());
+ return stream.collect(Collectors.<T>toList());
}

/**
@@ -2352,9 +2460,7 @@ public class CollectionUtils {
*/
public static <T> List<T> transform(T[] array,
Predicate<? super T> predicate) {
- return transform_internal(Arrays.stream(array), predicate,
- Function.<T>identity(), null,
- Collectors.toList());
+ return Arrays.<T>stream(array).filter(predicate).collect(Collectors.<T>toList());
}

/**
@@ -2370,8 +2476,21 @@ public class CollectionUtils {
public static <T,R> List<R> transform(T[] array,
Predicate<? super T> predicate,
Function<? super T, ? extends R> mapper) {
- return transform_internal(Arrays.stream(array), predicate, mapper,
- null, Collectors.toList());
+ return Arrays.<T>stream(array).filter(predicate).map(mapper).collect(Collectors.<R>toList());
+ }
+
+ /**
+ * Transform the contents of an array.
+ *
+ * @param <T> The array member type.
+ * @param <R> The resulting collection member type.
+ * @param array The array to transform.
+ * @param mapper A function to transform the selected items.
+ * @return The result of collecting the mapped predicate matches.
+ */
+ public static <T,R> List<R> transform(T[] array,
+ Function<? super T, ? extends R> mapper) {
+ return Arrays.<T>stream(array).map(mapper).collect(Collectors.<R>toList());
}

/**
@@ -2390,8 +2509,24 @@ public class CollectionUtils {
Predicate<? super T> predicate,
Function<? super T, ? extends R> mapper,
Collector<R,?,C> collector) {
- return transform_internal(Arrays.stream(array), predicate, mapper,
- null, collector);
+ return Arrays.<T>stream(array).filter(predicate).map(mapper).collect(collector);
+ }
+
+ /**
+ * Transform the contents of an array.
+ *
+ * @param <T> The array member type.
+ * @param <R> The resulting collection member type.
+ * @param <C> The resulting collection type.
+ * @param array The array to transform.
+ * @param mapper A function to transform the selected items.
+ * @param collector A {@code Collector} to collect the items.
+ * @return The result of collecting the mapped predicate matches.
+ */
+ public static <T,R,C> C transform(T[] array,
+ Function<? super T, ? extends R> mapper,
+ Collector<R,?,C> collector) {
+ return Arrays.<T>stream(array).map(mapper).collect(collector);
}

/**
@@ -2409,8 +2544,25 @@ public class CollectionUtils {
Predicate<? super T> predicate,
Function<? super T, ? extends R> mapper,
Comparator<? super R> comparator) {
- return transform_internal(Arrays.stream(array), predicate, mapper,
- comparator, Collectors.toList());
+ return Arrays.<T>stream(array).filter(predicate).map(mapper)
+ .sorted(comparator).collect(Collectors.<R>toList());
+ }
+
+ /**
+ * Transform the contents of an array and sort the result.
+ *
+ * @param <T> The array member type.
+ * @param <R> The resulting collection member type.
+ * @param array The array to transform.
+ * @param mapper A function to transform the selected items.
+ * @param comparator A {@code Comparator} to sort the items.
+ * @return A list of sorted mapped predicate matches.
+ */
+ public static <T,R> List<R> transform(T[] array,
+ Function<? super T, ? extends R> mapper,
+ Comparator<? super R> comparator) {
+ return Arrays.<T>stream(array).map(mapper)
+ .sorted(comparator).collect(Collectors.<R>toList());
}

/**
@@ -2423,8 +2575,7 @@ public class CollectionUtils {
*/
public static <T> List<T> transform(Collection<T> c,
Predicate<? super T> predicate) {
- return transform_internal(c.stream(), predicate, Function.<T>identity(),
- null, Collectors.toList());
+ return c.stream().filter(predicate).collect(Collectors.<T>toList());
}

/**
@@ -2440,8 +2591,21 @@ public class CollectionUtils {
public static <T,R> List<R> transform(Collection<T> c,
Predicate<? super T> predicate,
Function<? super T, ? extends R> mapper) {
- return transform_internal(c.stream(), predicate, mapper, null,
- Collectors.toList());
+ return c.stream().filter(predicate).map(mapper).collect(Collectors.<R>toList());
+ }
+
+ /**
+ * Transform the contents of a collection.
+ *
+ * @param <T> The collection member type.
+ * @param <R> The resulting collection member type.
+ * @param c The {@code Collection} to transform.
+ * @param mapper A function to transform the selected items.
+ * @return The result of collecting the mapped predicate matches.
+ */
+ public static <T,R> List<R> transform(Collection<T> c,
+ Function<? super T, ? extends R> mapper) {
+ return c.stream().map(mapper).collect(Collectors.<R>toList());
}

/**
@@ -2459,8 +2623,23 @@ public class CollectionUtils {
Predicate<? super T> predicate,
Function<? super T, ? extends R> mapper,
Comparator<? super R> comparator) {
- return transform_internal(c.stream(), predicate, mapper, comparator,
- Collectors.toList());
+ return c.stream().filter(predicate).map(mapper).sorted(comparator).collect(Collectors.<R>toList());
+ }
+
+ /**
+ * Transform the contents of a collection and sort the result.
+ *
+ * @param <T> The collection member type.
+ * @param <R> The resulting collection member type.
+ * @param c The {@code Collection} to transform.
+ * @param mapper A function to transform the selected items.
+ * @param comparator A {@code Comparator} to sort the results.
+ * @return A list of sorted mapped predicate matches.
+ */
+ public static <T,R> List<R> transform(Collection<T> c,
+ Function<? super T, ? extends R> mapper,
+ Comparator<? super R> comparator) {
+ return c.stream().map(mapper).sorted(comparator).collect(Collectors.<R>toList());
}

/**
@@ -2479,8 +2658,24 @@ public class CollectionUtils {
Predicate<? super T> predicate,
Function<? super T, ? extends R> mapper,
Collector<R,?,C> collector) {
- return transform_internal(c.stream(), predicate, mapper, null,
- collector);
+ return c.stream().filter(predicate).map(mapper).collect(collector);
+ }
+
+ /**
+ * Transform the contents of a collection.
+ *
+ * @param <T> The collection member type.
+ * @param <R> The resulting collection member type.
+ * @param <C> The resulting collection type.
+ * @param c The {@code Collection} to transform.
+ * @param mapper A function to transform the selected items.
+ * @param collector A {@code Collector} to aggregate the results.
+ * @return The result of collecting the mapped predicate matches.
+ */
+ public static <T,R,C> C transform(Collection<T> c,
+ Function<? super T, ? extends R> mapper,
+ Collector<R,?,C> collector) {
+ return c.stream().map(mapper).collect(collector);
}

/**
@@ -2493,9 +2688,7 @@ public class CollectionUtils {
*/
public static <T> List<T> transform(Stream<T> stream,
Predicate<? super T> predicate) {
- final Stream<T> s = (stream == null) ? Stream.<T>empty() : stream;
- return transform_internal(s, predicate, Function.<T>identity(),
- null, Collectors.toList());
+ return stream.filter(predicate).collect(Collectors.<T>toList());
}

/**
@@ -2511,9 +2704,21 @@ public class CollectionUtils {
public static <T,R> List<R> transform(Stream<T> stream,
Predicate<? super T> predicate,
Function<? super T, ? extends R> mapper) {
- final Stream<T> s = (stream == null) ? Stream.<T>empty() : stream;
- return transform_internal(s, predicate, mapper, null,
- Collectors.toList());
+ return stream.filter(predicate).map(mapper).collect(Collectors.<R>toList());
+ }
+
+ /**
+ * Transform the contents of a stream.
+ *
+ * @param <T> The stream member type.
+ * @param <R> The resulting collection member type.
+ * @param stream The {@code Stream} to transform.
+ * @param mapper A function to transform the selected items.
+ * @return The result of collecting the mapped predicate matches.
+ */
+ public static <T,R> List<R> transform(Stream<T> stream,
+ Function<? super T, ? extends R> mapper) {
+ return stream.map(mapper).collect(Collectors.<R>toList());
}

/**
@@ -2530,10 +2735,24 @@ public class CollectionUtils {
public static <T,R> List<R> transform(Stream<T> stream,
Predicate<? super T> predicate,
Function<? super T, ? extends R> mapper,
+ Comparator<R> comparator) {
+ return stream.filter(predicate).map(mapper).sorted(comparator).collect(Collectors.<R>toList());
+ }
+
+ /**
+ * Transform the contents of a stream.
+ *
+ * @param <T> The collection member type.
+ * @param <R> The resulting collection member type.
+ * @param stream The {@code Stream} to transform.
+ * @param mapper A function to transform the selected items.
+ * @param comparator A {@code Comparator} to sort the results.
+ * @return A list of sorted mapped predicate matches.
+ */
+ public static <T,R> List<R> transform(Stream<T> stream,
+ Function<? super T, ? extends R> mapper,
Comparator<? super R> comparator) {
- final Stream<T> s = (stream == null) ? Stream.<T>empty() : stream;
- return transform_internal(s, predicate, mapper, comparator,
- Collectors.toList());
+ return stream.map(mapper).sorted(comparator).collect(Collectors.<R>toList());
}

/**
@@ -2552,32 +2771,23 @@ public class CollectionUtils {
Predicate<? super T> predicate,
Function<? super T, ? extends R> mapper,
Collector<R,?,C> collector) {
- final Stream<T> s = (stream == null) ? Stream.<T>empty() : stream;
- return transform_internal(s, predicate, mapper, null, collector);
+ return stream.filter(predicate).map(mapper).collect(collector);
}

/**
- * Underlying implementation for the transform functions.
+ * Transform the contents of a stream.
*
- * @param <T> The stream member type.
+ * @param <T> The collection member type.
* @param <R> The resulting collection member type.
* @param <C> The resulting collection type.
* @param stream The {@code Stream} to transform.
- * @param predicate A {@code Predicate} to select the items.
* @param mapper A function to transform the selected items.
- * @param comparator An optional {@code Comparator} to sort
- * the results.
* @param collector A {@code Collector} to aggregate the results.
* @return The result of collecting the mapped predicate matches.
*/
- private static <T,R,C> C transform_internal(Stream<T> stream,
- Predicate<? super T> predicate,
+ public static <T,R,C> C transform(Stream<T> stream,
Function<? super T, ? extends R> mapper,
- Comparator<? super R> comparator,
Collector<R,?,C> collector) {
- return (comparator == null)
- ? stream.filter(predicate).map(mapper).collect(collector)
- : stream.filter(predicate).map(mapper)
- .sorted(comparator).collect(collector);
+ return stream.map(mapper).collect(collector);
}
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:07 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/NativeTradeItem.java | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/net/sf/freecol/common/model/NativeTradeItem.java b/src/net/sf/freecol/common/model/NativeTradeItem.java
index 910a7e14b78..0b255aca87c 100644
--- a/src/net/sf/freecol/common/model/NativeTradeItem.java
+++ b/src/net/sf/freecol/common/model/NativeTradeItem.java
@@ -159,7 +159,11 @@ public class NativeTradeItem extends GoodsTradeItem {
* @return A suitable {@code Predicate}.
*/
public Predicate<NativeTradeItem> goodsMatcher() {
- return matchKeyEquals(this.getGoods(), NativeTradeItem::getGoods);
+ return new Predicate<NativeTradeItem>() {
+ public boolean test(NativeTradeItem i) {
+ return NativeTradeItem.this.getGoods().equals(i.getGoods());
+ }
+ };
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:11 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Unit.java | 16 ++++++++++++++--
1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index 820480f2b39..b8e5ffa53e5 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -2654,8 +2654,20 @@ public class Unit extends GoodsLocation
// Owner has no settlements. If it is the REF, start from a
// rebel colony. Prefer the closest port.
if (owner.isREF()) {
- return minimize(flatten(owner.getRebels(), Player::getSettlements),
- settlementStartComparator);
+ Settlement best = null;
+ int best_dist = INFINITY;
+ for (Player p : owner.getRebels()) {
+ for (Settlement s : p.getSettlements()) {
+ int hsc = s.getTile().getHighSeasCount();
+ if (hsc < 0) hsc = INFINITY;
+ if (best == null || hsc < best_dist) {
+ best = s;
+ best_dist = hsc;
+ }
+ }
+ }
+
+ return best;
}

// Desperately find the nearest land to the entry location.
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:28 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../freecol/client/gui/panel/FindSettlementPanel.java | 2 +-
src/net/sf/freecol/common/model/Game.java | 8 ++++++--
src/net/sf/freecol/common/model/Operand.java | 6 +++---
src/net/sf/freecol/common/model/Player.java | 18 ++++++++++--------
src/net/sf/freecol/common/model/Unit.java | 2 +-
src/net/sf/freecol/server/ai/EuropeanAIPlayer.java | 2 +-
src/net/sf/freecol/server/model/ServerPlayer.java | 6 +++---
test/src/net/sf/freecol/common/model/ColonyTest.java | 2 +-
8 files changed, 26 insertions(+), 20 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/panel/FindSettlementPanel.java b/src/net/sf/freecol/client/gui/panel/FindSettlementPanel.java
index d17db5b1c88..718d7d1baf7 100644
--- a/src/net/sf/freecol/client/gui/panel/FindSettlementPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/FindSettlementPanel.java
@@ -177,7 +177,7 @@ public final class FindSettlementPanel extends FreeColPanel
break;
}
if (ok) {
- for (Settlement s : player.getSettlementList()) {
+ for (Settlement s : player.getSettlements()) {
model.addElement(s);
}
}
diff --git a/src/net/sf/freecol/common/model/Game.java b/src/net/sf/freecol/common/model/Game.java
index 4c1c1004beb..c98265b33e8 100644
--- a/src/net/sf/freecol/common/model/Game.java
+++ b/src/net/sf/freecol/common/model/Game.java
@@ -1070,8 +1070,12 @@ public class Game extends FreeColGameObject {
* specified name (the settlement might not be visible to a client).
*/
public Settlement getSettlementByName(String name) {
- return find(flatten(getLivePlayers(), Player::getSettlements),
- matchKeyEquals(name, Settlement::getName));
+ for (Player p : this.players)
+ if (p.isLive())
+ for (Settlement s : p.getSettlements())
+ if (Utils.equals(name, s.getName()))
+ return s;
+ return null;
}

/**
diff --git a/src/net/sf/freecol/common/model/Operand.java b/src/net/sf/freecol/common/model/Operand.java
index 97f4ee76b21..a91ecd4034f 100644
--- a/src/net/sf/freecol/common/model/Operand.java
+++ b/src/net/sf/freecol/common/model/Operand.java
@@ -210,7 +210,7 @@ public class Operand extends Scope {
c -> ourCount(c.getBuildings()));
break;
case SETTLEMENTS:
- result += ourCount(player.getSettlementList());
+ result += ourCount(player.getSettlements());
break;
case FOUNDING_FATHERS:
result += ourCount(player.getFathers());
@@ -249,11 +249,11 @@ public class Operand extends Scope {
return sum(player.getColonies(), c -> ourCount(c.getBuildings()));
case SETTLEMENTS:
if (methodName == null) {
- return ourCount(player.getSettlementList())
+ return ourCount(player.getSettlements())
+ spec.getInteger(GameOptions.SETTLEMENT_LIMIT_MODIFIER);
}
final String methodValue = getMethodValue();
- return count(player.getSettlementList(),
+ return count(player.getSettlements(),
s -> String.valueOf(s.invokeMethod(methodName,
Boolean.class, Boolean.FALSE)).equals(methodValue));
case FOUNDING_FATHERS:
diff --git a/src/net/sf/freecol/common/model/Player.java b/src/net/sf/freecol/common/model/Player.java
index 1714d5ec7f7..feeff525076 100644
--- a/src/net/sf/freecol/common/model/Player.java
+++ b/src/net/sf/freecol/common/model/Player.java
@@ -2253,21 +2253,23 @@ public class Player extends FreeColGameObject implements Nameable {
/**
* Gets a the settlements this player owns.
*
- * @return The list of {@code Settlements} this player owns.
+ * @return The list of {@code Settlement}s this player owns.
*/
- public List<Settlement> getSettlementList() {
+ public List<Settlement> getSettlements() {
synchronized (this.settlements) {
return new ArrayList<>(this.settlements);
}
}

/**
- * Get a stream of the settlements this player owns.
+ * Gets the first settlement this player owns.
*
- * @return The strean of {@code Settlements} this player owns.
+ * @return The first {@code Settlement} this player owns.
*/
- public Stream<Settlement> getSettlements() {
- return getSettlementList().stream();
+ public Settlement getFirstSettlement() {
+ synchronized (this.settlements) {
+ return this.settlements.get(0);
+ }
}

/**
@@ -2916,7 +2918,7 @@ public class Player extends FreeColGameObject implements Nameable {
vismap.setVisible(unit);

// All the settlements.
- for (Settlement settlement : getSettlementList())
+ for (Settlement settlement : getSettlements())
vismap.setVisible(settlement);

if (isEuropean()) {
@@ -3381,7 +3383,7 @@ public class Player extends FreeColGameObject implements Nameable {
* @return True if the player has no settlements (on the map) yet.
*/
private boolean hasZeroSettlements() {
- List<Settlement> settlements = getSettlementList();
+ List<Settlement> settlements = getSettlements();
return settlements.isEmpty()
|| (settlements.size() == 1
&& settlements.get(0).getTile().getSettlement() == null);
diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index 5be31dd2bc9..e4e545a8559 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -2648,7 +2648,7 @@ public class Unit extends GoodsLocation
final Player owner = getOwner();
Settlement sett = minimize(owner.getSettlements(),
settlementStartComparator);
- if (sett == null) sett = first(owner.getSettlements());
+ if (sett == null) sett = owner.getFirstSettlement();
if (sett != null) return sett;

// Owner has no settlements. If it is the REF, start from a
diff --git a/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java b/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java
index ea707d51be6..61f71351dd8 100644
--- a/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java
+++ b/src/net/sf/freecol/server/ai/EuropeanAIPlayer.java
@@ -1338,7 +1338,7 @@ public class EuropeanAIPlayer extends MissionAIPlayer {
if (!player.canBuildColonies()) return 0;

int nColonies = 0, nPorts = 0, nWorkers = 0, nEuropean = 0;
- for (Settlement settlement : player.getSettlementList()) {
+ for (Settlement settlement : player.getSettlements()) {
nColonies++;
if (settlement.isConnectedPort()) nPorts++;
nWorkers += count(settlement.getAllUnitsList(), Unit::isPerson);
diff --git a/src/net/sf/freecol/server/model/ServerPlayer.java b/src/net/sf/freecol/server/model/ServerPlayer.java
index d904f23ffe2..d1cd92e0666 100644
--- a/src/net/sf/freecol/server/model/ServerPlayer.java
+++ b/src/net/sf/freecol/server/model/ServerPlayer.java
@@ -645,7 +645,7 @@ public class ServerPlayer extends Player implements ServerModelObject {
}

// Remove settlements. Update formerly owned tiles.
- List<Settlement> settlements = getSettlementList();
+ List<Settlement> settlements = getSettlements();
while (!settlements.isEmpty()) {
csDisposeSettlement(settlements.remove(0), cs);
}
@@ -950,7 +950,7 @@ public class ServerPlayer extends Player implements ServerModelObject {
}
invalidateCanSeeTiles();//+vis(this)
if (!reveal) {
- for (Settlement s : getSettlementList()) exploreForSettlement(s);
+ for (Settlement s : getSettlements()) exploreForSettlement(s);
for (Unit u : getUnitList()) exploreForUnit(u);
}
return result;
@@ -4360,7 +4360,7 @@ outer: for (Effect effect : effects) {
final Game game = getGame();

// Settlements
- List<Settlement> settlements = getSettlementList();
+ List<Settlement> settlements = getSettlements();
int newSoL = 0, newImmigration = getImmigration();
for (Settlement settlement : settlements) {
((ServerModelObject)settlement).csNewTurn(random, lb, cs);
diff --git a/test/src/net/sf/freecol/common/model/ColonyTest.java b/test/src/net/sf/freecol/common/model/ColonyTest.java
index 71b1827cb34..fe2c1803eca 100644
--- a/test/src/net/sf/freecol/common/model/ColonyTest.java
+++ b/test/src/net/sf/freecol/common/model/ColonyTest.java
@@ -494,7 +494,7 @@ public class ColonyTest extends FreeColTestCase {
assertEquals(colony.getName(), copied.getName());
// Note: we can not check that player.hasSettlement(copied) is false
// because it too will use FCGO.equals().
- for (Settlement s : player.getSettlementList()) {
+ for (Settlement s : player.getSettlements()) {
assertFalse(s == copied);
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:23 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../common/model/pathfinding/CostDeciders.java | 34 +++++++++++-----------
1 file changed, 17 insertions(+), 17 deletions(-)

diff --git a/src/net/sf/freecol/common/model/pathfinding/CostDeciders.java b/src/net/sf/freecol/common/model/pathfinding/CostDeciders.java
index 5fa82b1d58a..2f83cd2d892 100644
--- a/src/net/sf/freecol/common/model/pathfinding/CostDeciders.java
+++ b/src/net/sf/freecol/common/model/pathfinding/CostDeciders.java
@@ -19,8 +19,6 @@

package net.sf.freecol.common.model.pathfinding;

-import java.util.function.Predicate;
-
import net.sf.freecol.common.model.Ability;
import net.sf.freecol.common.model.Europe;
import net.sf.freecol.common.model.Location;
@@ -185,23 +183,25 @@ public final class CostDeciders {
Location newLocation, int movesLeft) {
int cost = super.getCost(unit, oldLocation, newLocation, movesLeft);
Tile tile = newLocation.getTile();
- if (cost != ILLEGAL_MOVE && cost != Map.INFINITY && tile != null) {
- if (tile.isDangerousToShip(unit)) {
- cost = ILLEGAL_MOVE;
- } else {
- // Move might end if there is a credible naval
- // threat in an adjacent tile.
- final Player owner = unit.getOwner();
- final Predicate<Unit> threatPred = u ->
- (u.getOwner() != owner
- && (u.hasAbility(Ability.PIRACY)
- || (u.getOwner().atWarWith(owner)
- && u.isOffensiveUnit())));
- if (any(flatten(tile.getSurroundingTiles(1,1),
- Tile::getUnits),
- threatPred)) {
+
+ if (cost == ILLEGAL_MOVE || cost == Map.INFINITY && tile == null)
+ return cost;
+
+ if (tile.isDangerousToShip(unit))
+ return ILLEGAL_MOVE;
+
+ // Move might end if there is a credible naval
+ // threat in an adjacent tile.
+ final Player owner = unit.getOwner();
+ for (Tile t : tile.getSurroundingTiles(1,1)) {
+ for (Unit u : t.getUnits()) {
+ if (u.getOwner() != owner
+ && (u.hasAbility(Ability.PIRACY) ||
+ (u.getOwner().atWarWith(owner) && u.isOffensiveUnit())
+ )) {
this.movesLeft = 0;
this.newTurns++;
+ return cost;
}
}
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:02 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/EquipmentType.java | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/src/net/sf/freecol/common/model/EquipmentType.java b/src/net/sf/freecol/common/model/EquipmentType.java
index 09136a237d3..a56dedaed4a 100644
--- a/src/net/sf/freecol/common/model/EquipmentType.java
+++ b/src/net/sf/freecol/common/model/EquipmentType.java
@@ -22,7 +22,6 @@ package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import java.util.function.Predicate;

import javax.xml.stream.XMLStreamException;

@@ -277,9 +276,12 @@ public class EquipmentType extends BuildableType {

super.readChildren(xr);

- final Predicate<Modifier> militaryPred = m ->
- Modifier.OFFENCE.equals(m.getId()) || Modifier.DEFENCE.equals(m.getId());
- militaryEquipment = any(getModifiers(), militaryPred);
+ for (Modifier m : getModifiers()) {
+ if (Modifier.OFFENCE.equals(m.getId()) || Modifier.DEFENCE.equals(m.getId())) {
+ militaryEquipment = true;
+ break;
+ }
+ }
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:57 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/NativeTrade.java | 29 ++++++++++++++++++++++
src/net/sf/freecol/server/ai/NativeAIPlayer.java | 6 ++---
.../freecol/server/control/InGameController.java | 9 +++----
3 files changed, 35 insertions(+), 9 deletions(-)

diff --git a/src/net/sf/freecol/common/model/NativeTrade.java b/src/net/sf/freecol/common/model/NativeTrade.java
index 28b8e65d0ae..17b356615a5 100644
--- a/src/net/sf/freecol/common/model/NativeTrade.java
+++ b/src/net/sf/freecol/common/model/NativeTrade.java
@@ -360,6 +360,13 @@ public class NativeTrade extends FreeColGameObject {
this.item = nti;
}

+ private static NativeTradeItem findMatchingItem(List<NativeTradeItem> items, NativeTradeItem i) {
+ for (NativeTradeItem nt : items)
+ if (nt.getGoods().equals(i.getGoods()))
+ return nt;
+ return null;
+ }
+
/**
* Get the list of items the unit is able to offer the settlement.
*
@@ -372,6 +379,17 @@ public class NativeTrade extends FreeColGameObject {
}

/**
+ * Find a item the unit is able to offer the settlement.
+ *
+ * Note: some of these items might be currently invalid.
+ *
+ * @return A {@code NativeTradeItem} the unit might sell.
+ */
+ public NativeTradeItem findUnitToSettlement(NativeTradeItem i) {
+ return findMatchingItem(this.unitToSettlement, i);
+ }
+
+ /**
* Get the list of items the settlement is able to offer the unit.
*
* Note: some of these items might be currently invalid.
@@ -383,6 +401,17 @@ public class NativeTrade extends FreeColGameObject {
}

/**
+ * Find an item the settlement is able to offer the unit.
+ *
+ * Note: some of these items might be currently invalid.
+ *
+ * @return A {@code NativeTradeItem} the unit might buy.
+ */
+ public NativeTradeItem findSettlementToUnit(NativeTradeItem i) {
+ return findMatchingItem(this.settlementToUnit, i);
+ }
+
+ /**
* Add an item to the unit list of items.
*
* @param nti The {@code NativeTradeItem} to add.
diff --git a/src/net/sf/freecol/server/ai/NativeAIPlayer.java b/src/net/sf/freecol/server/ai/NativeAIPlayer.java
index feb3558edcc..87be4e3bac9 100644
--- a/src/net/sf/freecol/server/ai/NativeAIPlayer.java
+++ b/src/net/sf/freecol/server/ai/NativeAIPlayer.java
@@ -897,7 +897,7 @@ public class NativeAIPlayer extends MissionAIPlayer {
}
if (anger < 0) return NativeTradeAction.NAK_HOSTILE;
updateTrade(nt, anger);
- ours = find(nt.getSettlementToUnit(), nt.getItem().goodsMatcher());
+ ours = nt.findSettlementToUnit(nt.getItem());
if (ours == null) return NativeTradeAction.NAK_INVALID;
if (nt.getItem().priceIsSet()
&& nt.getItem().getPrice() >= ours.getPrice()) {
@@ -932,7 +932,7 @@ public class NativeAIPlayer extends MissionAIPlayer {
}
if (anger < 0) return NativeTradeAction.NAK_HOSTILE;
updateTrade(nt, anger);
- ours = find(nt.getUnitToSettlement(), nt.getItem().goodsMatcher());
+ ours = nt.findUnitToSettlement(nt.getItem());
if (ours == null) return NativeTradeAction.NAK_INVALID;
if (nt.getItem().priceIsSet()
&& nt.getItem().getPrice() <= ours.getPrice()) {
@@ -949,7 +949,7 @@ public class NativeAIPlayer extends MissionAIPlayer {
return NativeTradeAction.ACK_SELL_HAGGLE;

case GIFT:
- ours = find(nt.getUnitToSettlement(), nt.getItem().goodsMatcher());
+ ours = nt.findUnitToSettlement(nt.getItem());
if (ours == null) return NativeTradeAction.NAK_INVALID;
return (is.canAdd(nt.getItem().getGoods()))
? NativeTradeAction.ACK_GIFT
diff --git a/src/net/sf/freecol/server/control/InGameController.java b/src/net/sf/freecol/server/control/InGameController.java
index 72a2eed515f..4b1f6cc7a04 100644
--- a/src/net/sf/freecol/server/control/InGameController.java
+++ b/src/net/sf/freecol/server/control/InGameController.java
@@ -2965,8 +2965,7 @@ public final class InGameController extends Controller {
return serverPlayer.clientError("Null purchase: " + nt);
} else if (!nt.canBuy()) {
return serverPlayer.clientError("Can not buy: " + nt);
- } else if (find(nt.getSettlementToUnit(),
- item.goodsMatcher()) == null) {
+ } else if (nt.findSettlementToUnit(item) == null) {
return serverPlayer.clientError("Item missing for "
+ action + ": " + nt);
}
@@ -2982,8 +2981,7 @@ public final class InGameController extends Controller {
return serverPlayer.clientError("Null sale: " + nt);
} else if (!nt.canSell()) {
return serverPlayer.clientError("Can not sell: " + nt);
- } else if (find(nt.getUnitToSettlement(),
- item.goodsMatcher()) == null) {
+ } else if (nt.findUnitToSettlement(item) == null) {
return serverPlayer.clientError("Item missing for "
+ action + ": " + nt);
}
@@ -2999,8 +2997,7 @@ public final class InGameController extends Controller {
return serverPlayer.clientError("Null gift: " + nt);
} else if (!nt.canGift()) {
return serverPlayer.clientError("Can not gift: " + nt);
- } else if (find(nt.getUnitToSettlement(),
- item.goodsMatcher()) == null) {
+ } else if (nt.findUnitToSettlement(item) == null) {
return serverPlayer.clientError("Item missing for "
+ action + ": " + nt);
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:44 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/client/gui/panel/InfoPanel.java | 6 +++---
src/net/sf/freecol/common/model/ColonyTile.java | 9 ++++++---
src/net/sf/freecol/common/model/TileType.java | 8 +++++---
3 files changed, 14 insertions(+), 9 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/panel/InfoPanel.java b/src/net/sf/freecol/client/gui/panel/InfoPanel.java
index 86bef8aeebb..cec6a3269b4 100644
--- a/src/net/sf/freecol/client/gui/panel/InfoPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/InfoPanel.java
@@ -31,6 +31,7 @@ import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.logging.Logger;
+import java.util.Collections;

import javax.swing.ImageIcon;
import javax.swing.JButton;
@@ -170,9 +171,8 @@ public final class InfoPanel extends FreeColPanel {
.addAmount("%cost%", tile.getType().getBasicMoveCost()/3));
add(moveLabel, "span " + PRODUCTION);

- List<AbstractGoods> produce
- = sort(tile.getType().getPossibleProduction(true),
- AbstractGoods.descendingAmountComparator);
+ List<AbstractGoods> produce = tile.getType().getPossibleProduction(true);
+ Collections.sort(produce, AbstractGoods.descendingAmountComparator);
if (produce.isEmpty()) {
add(new JLabel(), "span " + PRODUCTION);
} else {
diff --git a/src/net/sf/freecol/common/model/ColonyTile.java b/src/net/sf/freecol/common/model/ColonyTile.java
index 2d8c3572bec..e69f75d25aa 100644
--- a/src/net/sf/freecol/common/model/ColonyTile.java
+++ b/src/net/sf/freecol/common/model/ColonyTile.java
@@ -217,10 +217,13 @@ public class ColonyTile extends WorkLocation {
}

// Tile type change.
- final Stream<AbstractGoods> newProd
+ final List<AbstractGoods> newProd
= newType.getPossibleProduction(true);
- int food = sum(newProd, AbstractGoods::isFoodType,
- AbstractGoods::getAmount);
+ int food = 0;
+ for (AbstractGoods ag : newProd)
+ if (ag.isFoodType())
+ food += ag.getAmount();
+
// Get the current food production. Otherwise for goods
// that are being passively produced and consumed, check
// if production remains in surplus following a negative change.
diff --git a/src/net/sf/freecol/common/model/TileType.java b/src/net/sf/freecol/common/model/TileType.java
index 21893cf7829..860b36c4371 100644
--- a/src/net/sf/freecol/common/model/TileType.java
+++ b/src/net/sf/freecol/common/model/TileType.java
@@ -360,9 +360,11 @@ public final class TileType extends FreeColSpecObjectType
* @param unattended Select unattended production.
* @return A stream of produced {@code AbstractGoods}.
*/
- public Stream<AbstractGoods> getPossibleProduction(boolean unattended) {
- return flatten(getAvailableProductionTypes(unattended),
- pt -> pt.getOutputs());
+ public List<AbstractGoods> getPossibleProduction(boolean unattended) {
+ List<AbstractGoods> result = new ArrayList<>();
+ for (ProductionType pt : getAvailableProductionTypes(unattended))
+ result.addAll(pt.getOutputs());
+ return result;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:54 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../gui/panel/colopedia/BuildingDetailPanel.java | 2 +-
src/net/sf/freecol/common/model/Ability.java | 3 +++
src/net/sf/freecol/common/model/Building.java | 2 +-
src/net/sf/freecol/common/model/Colony.java | 12 ++++++---
src/net/sf/freecol/common/model/Europe.java | 16 ++++++------
.../sf/freecol/common/model/FeatureContainer.java | 16 ++++++------
src/net/sf/freecol/common/model/FreeColObject.java | 20 +++++++--------
src/net/sf/freecol/common/model/Specification.java | 10 ++++----
src/net/sf/freecol/common/model/Tile.java | 2 +-
src/net/sf/freecol/common/model/Unit.java | 29 ++++++++++++----------
10 files changed, 63 insertions(+), 49 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/panel/colopedia/BuildingDetailPanel.java b/src/net/sf/freecol/client/gui/panel/colopedia/BuildingDetailPanel.java
index 22880927c2c..9e7f21ff76d 100644
--- a/src/net/sf/freecol/client/gui/panel/colopedia/BuildingDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/colopedia/BuildingDetailPanel.java
@@ -243,7 +243,7 @@ public class BuildingDetailPanel
}
});

- for (Ability ability : iterable(buildingType.getAbilities())) {
+ for (Ability ability : buildingType.getAbilities()) {
JComponent component = getAbilityComponent(ability);
if (component != null) {
labels.add(component);
diff --git a/src/net/sf/freecol/common/model/Ability.java b/src/net/sf/freecol/common/model/Ability.java
index 0b67de495cc..9320f6125dc 100644
--- a/src/net/sf/freecol/common/model/Ability.java
+++ b/src/net/sf/freecol/common/model/Ability.java
@@ -19,6 +19,8 @@

package net.sf.freecol.common.model;

+import java.util.List;
+import java.util.ArrayList;
import javax.xml.stream.XMLStreamException;

import net.sf.freecol.common.io.FreeColXMLReader;
@@ -408,6 +410,7 @@ public final class Ability extends Feature {
public static final String UPGRADE_CONVERT
= "model.ability.upgradeConvert";

+ public static final List<Ability> EMPTY_LIST = new ArrayList<>();

/** The ability value. */
private boolean value = true;
diff --git a/src/net/sf/freecol/common/model/Building.java b/src/net/sf/freecol/common/model/Building.java
index 46f5f95ee18..f3b13dea0cd 100644
--- a/src/net/sf/freecol/common/model/Building.java
+++ b/src/net/sf/freecol/common/model/Building.java
@@ -641,7 +641,7 @@ public class Building extends WorkLocation
* {@inheritDoc}
*/
@Override
- public Stream<Ability> getAbilities(String id, FreeColSpecObjectType type,
+ public List<Ability> getAbilities(String id, FreeColSpecObjectType type,
Turn turn) {
// Buildings have no abilities independent of their type (for now).
return getType().getAbilities(id, type, turn);
diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index 0fd5cfc0c2b..dcf6e936bd5 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -2528,12 +2528,16 @@ loop: for (WorkLocation wl : getWorkLocationsForProducing(goodsType)) {
* {@inheritDoc}
*/
@Override
- public Stream<Ability> getAbilities(String id, FreeColSpecObjectType type,
+ public List<Ability> getAbilities(String id, FreeColSpecObjectType type,
Turn turn) {
if (turn == null) turn = getGame().getTurn();
- return concat(super.getAbilities(id, type, turn),
- ((owner == null) ? Stream.<Ability>empty()
- : owner.getAbilities(id, type, turn)));
+ List<Ability> result = super.getAbilities(id, type, turn);
+ if (owner != null) {
+ result = new ArrayList<>(result);
+ result.addAll(owner.getAbilities(id, type, turn));
+ }
+
+ return result;
}


diff --git a/src/net/sf/freecol/common/model/Europe.java b/src/net/sf/freecol/common/model/Europe.java
index 839a60a9655..92f5f70af16 100644
--- a/src/net/sf/freecol/common/model/Europe.java
+++ b/src/net/sf/freecol/common/model/Europe.java
@@ -24,7 +24,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;
-import java.util.stream.Stream;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
@@ -505,13 +504,16 @@ public class Europe extends UnitLocation
* {@inheritDoc}
*/
@Override
- public Stream<Ability> getAbilities(String id, FreeColSpecObjectType fcgot,
+ public List<Ability> getAbilities(String id, FreeColSpecObjectType fcgot,
Turn turn) {
- return concat(super.getAbilities(id, fcgot, turn),
- // Always able to dress a missionary.
- ((id == null || Ability.DRESS_MISSIONARY.equals(id))
- ? Stream.of(ABILITY_DRESS_MISSIONARY)
- : Stream.<Ability>empty()));
+ List<Ability> result = super.getAbilities(id, fcgot, turn);
+
+ if (id == null || Ability.DRESS_MISSIONARY.equals(id)) {
+ result = new ArrayList<>(result);
+ result.add(ABILITY_DRESS_MISSIONARY);
+ }
+
+ return result;
}


diff --git a/src/net/sf/freecol/common/model/FeatureContainer.java b/src/net/sf/freecol/common/model/FeatureContainer.java
index 3c5dbabe661..7091faaaf6e 100644
--- a/src/net/sf/freecol/common/model/FeatureContainer.java
+++ b/src/net/sf/freecol/common/model/FeatureContainer.java
@@ -18,6 +18,7 @@
*/
package net.sf.freecol.common.model;

+import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
@@ -104,9 +105,9 @@ public final class FeatureContainer {
* @param abilities A stream of {@code Ability}s to check.
* @return True if the abilities are `satisfied'.
*/
- public static boolean hasAbility(Stream<Ability> abilities) {
+ public static boolean hasAbility(List<Ability> abilities) {
boolean ret = false;
- for (Ability ability : iterable(abilities)) {
+ for (Ability ability : abilities) {
if (!ability.getValue()) return false;
ret = true;
}
@@ -135,7 +136,7 @@ public final class FeatureContainer {
* @return True if the key is present.
*/
public boolean containsAbilityKey(String key) {
- return first(getAbilities(key, null, null)) != null;
+ return getAbilities(key, null, null).size() > 0;
}

/**
@@ -146,9 +147,9 @@ public final class FeatureContainer {
* @param fcgot An optional {@code FreeColSpecObjectType} the
* ability applies to.
* @param turn An optional applicable {@code Turn}.
- * @return A stream of abilities.
+ * @return A list of abilities.
*/
- public Stream<Ability> getAbilities(String id, FreeColSpecObjectType fcgot,
+ public List<Ability> getAbilities(String id, FreeColSpecObjectType fcgot,
Turn turn) {
Set<Ability> result = new HashSet<>();
if (abilitiesPresent()) {
@@ -164,7 +165,8 @@ public final class FeatureContainer {
}
removeInPlace(result, a -> !a.appliesTo(fcgot, turn));
}
- return result.stream();
+
+ return new ArrayList<>(result);
}

/**
@@ -504,7 +506,7 @@ public final class FeatureContainer {
StringBuilder sb = new StringBuilder(256);
sb.append("[FeatureContainer");
int siz = sb.length();
- for (Ability ability : iterable(getAbilities(null, null, null))) {
+ for (Ability ability : getAbilities(null, null, null)) {
sb.append(' ').append(ability);
}
if (sb.length() > siz) {
diff --git a/src/net/sf/freecol/common/model/FreeColObject.java b/src/net/sf/freecol/common/model/FreeColObject.java
index 25a8506f749..e93de77f818 100644
--- a/src/net/sf/freecol/common/model/FreeColObject.java
+++ b/src/net/sf/freecol/common/model/FreeColObject.java
@@ -434,7 +434,7 @@ public abstract class FreeColObject
* @return True if the key is present.
*/
public boolean containsAbilityKey(String key) {
- return first(getAbilities(key, null, null)) != null;
+ return getAbilities(key, null, null).size() > 0;
}

/**
@@ -449,9 +449,9 @@ public abstract class FreeColObject
/**
* Gets a copy of the abilities of this object.
*
- * @return A stream of abilities.
+ * @return A set of abilities.
*/
- public final Stream<Ability> getAbilities() {
+ public final List<Ability> getAbilities() {
return getAbilities(null);
}

@@ -459,9 +459,9 @@ public abstract class FreeColObject
* Gets the set of abilities with the given identifier from this object.
*
* @param id The object identifier.
- * @return A stream of abilities.
+ * @return A list of abilities.
*/
- public final Stream<Ability> getAbilities(String id) {
+ public final List<Ability> getAbilities(String id) {
return getAbilities(id, null);
}

@@ -471,9 +471,9 @@ public abstract class FreeColObject
* @param id The object identifier.
* @param fcgot An optional {@code FreeColSpecObjectType} the
* ability applies to.
- * @return A stream of abilities.
+ * @return A list of abilities.
*/
- public final Stream<Ability> getAbilities(String id,
+ public final List<Ability> getAbilities(String id,
FreeColSpecObjectType fcgot) {
return getAbilities(id, fcgot, null);
}
@@ -487,13 +487,13 @@ public abstract class FreeColObject
* @param fcgot An optional {@code FreeColSpecObjectType} the
* ability applies to.
* @param turn An optional applicable {@code Turn}.
- * @return A set of abilities.
+ * @return A list of abilities.
*/
- public Stream<Ability> getAbilities(String id,
+ public List<Ability> getAbilities(String id,
FreeColSpecObjectType fcgot,
Turn turn) {
FeatureContainer fc = getFeatureContainer();
- return (fc == null) ? Stream.<Ability>empty()
+ return (fc == null) ? Ability.EMPTY_LIST
: fc.getAbilities(id, fcgot, turn);
}

diff --git a/src/net/sf/freecol/common/model/Specification.java b/src/net/sf/freecol/common/model/Specification.java
index 0ca84faa35c..0f949a02da3 100644
--- a/src/net/sf/freecol/common/model/Specification.java
+++ b/src/net/sf/freecol/common/model/Specification.java
@@ -631,8 +631,8 @@ public final class Specification {

// Apply the customs on coast restriction
boolean customsOnCoast = getBoolean(GameOptions.CUSTOMS_ON_COAST);
- for (Ability a : iterable(getBuildingType("model.building.customHouse")
- .getAbilities(Ability.COASTAL_ONLY))) {
+ for (Ability a : getBuildingType("model.building.customHouse")
+ .getAbilities(Ability.COASTAL_ONLY)) {
a.setValue(customsOnCoast);
}

@@ -922,9 +922,9 @@ public final class Specification {
* @param id The object identifier to look for.
* @return A stream of {@code Ability}s.
*/
- public Stream<Ability> getAbilities(String id) {
+ public List<Ability> getAbilities(String id) {
List<Ability> result = allAbilities.get(id);
- return (result == null) ? Stream.<Ability>empty() : result.stream();
+ return (result == null ? Collections.<Ability>emptyList() : result);
}

/**
@@ -2225,7 +2225,7 @@ public final class Specification {
}

// Ambush terrain ability not present in older specs.
- if (first(getAbilities(Ability.AMBUSH_TERRAIN)) == null){
+ if (getAbilities(Ability.AMBUSH_TERRAIN).size() == 0) {
Ability ambush = new Ability(Ability.AMBUSH_TERRAIN, null, true);
addAbility(ambush);
for (TileType tt : transform(getTileTypeList(), tt ->
diff --git a/src/net/sf/freecol/common/model/Tile.java b/src/net/sf/freecol/common/model/Tile.java
index fab54bf459d..d524ed49f88 100644
--- a/src/net/sf/freecol/common/model/Tile.java
+++ b/src/net/sf/freecol/common/model/Tile.java
@@ -2349,7 +2349,7 @@ public final class Tile extends UnitLocation implements Named, Ownable {
* {@inheritDoc}
*/
@Override
- public Stream<Ability> getAbilities(String id,
+ public List<Ability> getAbilities(String id,
FreeColSpecObjectType fcgot,
Turn turn) {
// Delegate to type
diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index 0660ebe3ac4..d49e7a004e6 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -4185,23 +4185,26 @@ public class Unit extends GoodsLocation
* {@inheritDoc}
*/
@Override
- public Stream <Ability> getAbilities(String id, FreeColSpecObjectType fcgot,
+ public List<Ability> getAbilities(String id, FreeColSpecObjectType fcgot,
Turn turn) {
final Player owner = getOwner();
final UnitType unitType = getType();

- return concat(
- // UnitType abilities always apply.
- unitType.getAbilities(id),
+ ArrayList<Ability> result = new ArrayList<>();

- // Roles apply with qualification.
- role.getAbilities(id, fcgot, turn),
+ // UnitType abilities always apply.
+ result.addAll(unitType.getAbilities(id));

- // The player's abilities require more qualification.
- owner.getAbilities(id, fcgot, turn),
+ // Roles apply with qualification.
+ result.addAll(role.getAbilities(id, fcgot, turn));

- // Location abilities may apply.
- getLocationAbilities(id, turn));
+ // The player's abilities require more qualification.
+ result.addAll(owner.getAbilities(id, fcgot, turn));
+
+ // Location abilities may apply.
+ result.addAll(getLocationAbilities(id, turn));
+
+ return result;
}

/**
@@ -4219,13 +4222,13 @@ public class Unit extends GoodsLocation
* @param turn The turn that applies.
* @return A stream of {@code Ability}s found.
*/
- private Stream<Ability> getLocationAbilities(String id, Turn turn) {
+ private List<Ability> getLocationAbilities(String id, Turn turn) {
final UnitType unitType = getType();
final Settlement settlement = getSettlement();
if (settlement != null) {
return settlement.getAbilities(id, unitType, turn);
}
- if (!isInEurope()) return Stream.<Ability>empty();
+ if (!isInEurope()) return Ability.EMPTY_LIST;

// @compat 0.10.x
// Europe is special. It makes sense here to do:
@@ -4238,7 +4241,7 @@ public class Unit extends GoodsLocation
: (loc instanceof Unit) ? (Europe)((Unit)loc).getLocation()
: null;
// end @compat 0.10.x
- return (europe == null) ? Stream.<Ability>empty()
+ return (europe == null) ? Ability.EMPTY_LIST
: europe.getAbilities(id, getType(), turn);
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:12 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Unit.java | 25 +++++++++++++++++--------
1 file changed, 17 insertions(+), 8 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index b8e5ffa53e5..737c629ea18 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -2796,14 +2796,23 @@ public class Unit extends GoodsLocation
public PathNode findPathToNeighbour(Location start, Tile end, Unit carrier,
CostDecider costDecider) {
final Player owner = getOwner();
- final Predicate<Tile> endPred = t ->
- (isTileAccessible(t)
- && (t.getFirstUnit() == null || owner.owns(t.getFirstUnit())));
-
- Tile best = minimize(end.getSurroundingTiles(1, 1), endPred,
- getPathComparator(start, carrier, costDecider));
- return (best == null) ? null
- : this.findPath(start, best, carrier, costDecider);
+
+ PathNode best_path = null;
+ int best_turns = 0;
+ for (Tile t : end.getSurroundingTiles(1, 1)) {
+ if (isTileAccessible(t)
+ && (t.getFirstUnit() == null || owner.owns(t.getFirstUnit()))) {
+ PathNode p = this.findPath(start, t, carrier, costDecider);
+ if (p == null) continue;
+ int turns = p.getTotalTurns();
+ if (best_path == null || turns < best_turns) {
+ best_path = p;
+ best_turns = turns;
+ }
+ }
+ }
+
+ return best_path;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:07 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Settlement.java | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Settlement.java b/src/net/sf/freecol/common/model/Settlement.java
index 3e17e75cd45..c4371da780d 100644
--- a/src/net/sf/freecol/common/model/Settlement.java
+++ b/src/net/sf/freecol/common/model/Settlement.java
@@ -433,8 +433,11 @@ public abstract class Settlement extends GoodsLocation

// To succeed, there must exist an available role for the unit
// where the extra equipment for the role is present.
- return find(unit.getAvailableRoles(military),
- r -> canProvideGoods(unit.getGoodsDifference(r, 1)));
+ for (Role r : unit.getAvailableRoles(military))
+ if (canProvideGoods(unit.getGoodsDifference(r, 1)))
+ return r;
+
+ return null;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:22 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

Instead of several list operations w/ lambda callbacks, do it in one pass.

Note: the previous implementation used an caching function - but the
cache was quite unlikely to hit, as the surrounding tiles are fed in just
once anyways.
---
.../common/model/pathfinding/GoalDeciders.java | 67 ++++++++++++++--------
1 file changed, 42 insertions(+), 25 deletions(-)

diff --git a/src/net/sf/freecol/common/model/pathfinding/GoalDeciders.java b/src/net/sf/freecol/common/model/pathfinding/GoalDeciders.java
index 6928b82be9f..9a729f9b9ab 100644
--- a/src/net/sf/freecol/common/model/pathfinding/GoalDeciders.java
+++ b/src/net/sf/freecol/common/model/pathfinding/GoalDeciders.java
@@ -23,8 +23,6 @@ import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
-import java.util.function.Predicate;
-import java.util.function.ToDoubleFunction;

import net.sf.freecol.common.model.Ability;
import net.sf.freecol.common.model.FreeColObject;
@@ -312,6 +310,29 @@ public final class GoalDeciders {
public PathNode getGoal() { return goal; }
@Override
public boolean hasSubGoals() { return true; }
+
+ private boolean isDanger(Tile t, Player owner, Unit u) {
+ Settlement settlement = t.getSettlement();
+ return (settlement != null
+ && !owner.owns(settlement)
+ && settlement.hasAbility(Ability.BOMBARD_SHIPS)
+ && (owner.atWarWith(settlement.getOwner())
+ || u.hasAbility(Ability.PIRACY)));
+ };
+
+ private double getDangerBonus(Tile t, Player owner, Unit u) {
+ for (Tile walk : t.getSurroundingTiles(1, 1))
+ if (isDanger(walk, owner, u))
+ return 0.0;
+
+ return NO_DANGER_BONUS;
+ }
+
+ private double getTileScore(Tile t, Player owner, Unit u, Map map) {
+ return (t.getDefenceValue() / (1.0 + map.getDistance(target, t))
+ + getDangerBonus(t, owner, u));
+ }
+
@Override
public boolean check(Unit u, PathNode pathNode) {
final Tile tile = pathNode.getTile();
@@ -320,30 +341,26 @@ public final class GoalDeciders {

final Player owner = u.getOwner();
final Map map = u.getGame().getMap();
- final Predicate<Tile> dockPred = t ->
- t.isHighSeasConnected() && !t.isLand();
- final Predicate<Tile> dangerPred = t -> {
- Settlement settlement = t.getSettlement();
- return (settlement != null
- && !owner.owns(settlement)
- && settlement.hasAbility(Ability.BOMBARD_SHIPS)
- && (owner.atWarWith(settlement.getOwner())
- || u.hasAbility(Ability.PIRACY)));
- };
- final ToDoubleFunction<Tile> tileScorer = cacheDouble(t ->
- (t.getDefenceValue() / (1.0 + map.getDistance(target, t))
- + ((none(t.getSurroundingTiles(1, 1), dangerPred))
- ? NO_DANGER_BONUS : 0.0)));
- Tile best = maximize(tile.getSurroundingTiles(1, 1), dockPred,
- Comparator.comparingDouble(tileScorer));
- double score;
- if (best != null
- && (score = tileScorer.applyAsDouble(best)) > bestScore) {
- bestScore = score;
- goal = pathNode;
- return true;
+
+ Tile best = null;
+ double best_score = -1.0;
+ for (Tile walk : tile.getSurroundingTiles(1, 1)) {
+ if (!walk.isHighSeasConnected() || walk.isLand())
+ continue;
+
+ double sc = getTileScore(tile, owner, u, map);
+ if (sc > best_score) {
+ best_score = sc;
+ best = walk;
+ }
}
- return false;
+
+ if ((best == null) || (best_score <= bestScore))
+ return false;
+
+ bestScore = best_score;
+ goal = pathNode;
+ return true;
}
};
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:35 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Map.java | 11 ++++++++++-
1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/src/net/sf/freecol/common/model/Map.java b/src/net/sf/freecol/common/model/Map.java
index c631ca607e1..8e107169d71 100644
--- a/src/net/sf/freecol/common/model/Map.java
+++ b/src/net/sf/freecol/common/model/Map.java
@@ -658,7 +658,16 @@ public class Map extends FreeColGameObject implements Location {
* @return The closest tile found (may be null if the list is empty).
*/
public Tile getClosestTile(Tile tile, Collection<Tile> tiles) {
- return minimize(tiles, cachingIntComparator(t -> getDistance(t, tile)));
+ int min_dist = Integer.MAX_VALUE;
+ Tile best = null;
+ for (Tile t : tiles) {
+ int dist = getDistance(t, tile);
+ if (best == null || dist < min_dist) {
+ best = t;
+ min_dist = dist;
+ }
+ }
+ return best;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:37 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Tile.java | 19 +++++++++++++------
1 file changed, 13 insertions(+), 6 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Tile.java b/src/net/sf/freecol/common/model/Tile.java
index ab0485296ef..ecb8dacb3df 100644
--- a/src/net/sf/freecol/common/model/Tile.java
+++ b/src/net/sf/freecol/common/model/Tile.java
@@ -1781,12 +1781,19 @@ public final class Tile extends UnitLocation implements Named, Ownable {
* @return The {@code AbstractGoods} to produce.
*/
public AbstractGoods getBestFoodProduction() {
- final Comparator<AbstractGoods> goodsComp
- = Comparator.comparingInt(ag ->
- getPotentialProduction(ag.getType(), null));
- return maximize(flatten(getType().getAvailableProductionTypes(true),
- pt -> pt.getOutputs()),
- AbstractGoods::isFoodType, goodsComp);
+ AbstractGoods best_ag = null;
+ int best_pot = 0;
+ for (ProductionType pt : getType().getAvailableProductionTypes(true))
+ for (AbstractGoods ag : pt.getOutputs())
+ if (ag.isFoodType()) {
+ int pot = getPotentialProduction(ag.getType(), null);
+ if (best_ag == null || best_pot < pot) {
+ best_ag = ag;
+ best_pot = pot;
+ }
+ }
+
+ return best_ag;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:08 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/BuildableType.java | 15 ++++++++++++---
1 file changed, 12 insertions(+), 3 deletions(-)

diff --git a/src/net/sf/freecol/common/model/BuildableType.java b/src/net/sf/freecol/common/model/BuildableType.java
index f8d55245006..2d947d92bab 100644
--- a/src/net/sf/freecol/common/model/BuildableType.java
+++ b/src/net/sf/freecol/common/model/BuildableType.java
@@ -128,6 +128,13 @@ public abstract class BuildableType extends FreeColSpecObjectType {
requiredAbilities.put(tag, value);
}

+ private boolean checkAnyAvail(FreeColObject[] fco, String key) {
+ for (FreeColObject o : fco)
+ if (o.hasAbility(key))
+ return true;
+ return false;
+ }
+
/**
* Is this buildable available to a given FreeColObject?
*
@@ -135,9 +142,11 @@ public abstract class BuildableType extends FreeColSpecObjectType {
* @return True if the buildable is available.
*/
public boolean isAvailableTo(FreeColObject... fco) {
- return (requiredAbilities == null) ? true
- : all(requiredAbilities.entrySet(),
- e -> e.getValue() == any(fco, o -> o.hasAbility(e.getKey())));
+ if (requiredAbilities != null)
+ for (Map.Entry<String, Boolean> e : requiredAbilities.entrySet())
+ if (e.getValue() != checkAnyAvail(fco, e.getKey()))
+ return false;
+ return true;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:16 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/WorkLocation.java | 15 +++++++++++----
1 file changed, 11 insertions(+), 4 deletions(-)

diff --git a/src/net/sf/freecol/common/model/WorkLocation.java b/src/net/sf/freecol/common/model/WorkLocation.java
index 48d52a459e3..74362e90ac3 100644
--- a/src/net/sf/freecol/common/model/WorkLocation.java
+++ b/src/net/sf/freecol/common/model/WorkLocation.java
@@ -544,10 +544,17 @@ public abstract class WorkLocation extends UnitLocation
public UnitType getExpertUnitType() {
final Specification spec = getSpecification();
ProductionType pt = getBestProductionType(false, null);
- return (pt == null) ? null
- : find(map(pt.getOutputs(),
- ag -> spec.getExpertForProducing(ag.getType())),
- isNotNull());
+
+ if (pt == null)
+ return null;
+
+ for (AbstractGoods ag : pt.getOutputs()) {
+ UnitType ut = spec.getExpertForProducing(ag.getType());
+ if (ut != null)
+ return ut;
+ }
+
+ return null;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:30 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/TradeRouteStop.java | 10 ++++------
1 file changed, 4 insertions(+), 6 deletions(-)

diff --git a/src/net/sf/freecol/common/model/TradeRouteStop.java b/src/net/sf/freecol/common/model/TradeRouteStop.java
index aeccb14ad33..dd7092a626b 100644
--- a/src/net/sf/freecol/common/model/TradeRouteStop.java
+++ b/src/net/sf/freecol/common/model/TradeRouteStop.java
@@ -21,7 +21,6 @@ package net.sf.freecol.common.model;

import java.util.ArrayList;
import java.util.List;
-import java.util.function.Predicate;
import java.util.logging.Logger;

import javax.xml.stream.XMLStreamException;
@@ -209,11 +208,10 @@ public class TradeRouteStop extends FreeColGameObject implements TradeLocation {
// Look for goods to load.
// If there is space on the unit to load some more of this goods
// type and there is some available at the stop, return true.
-
- final Predicate<AbstractGoods> loadPred = ag ->
- unit.getGoodsCount(ag.getType()) < ag.getAmount()
- && getExportAmount(ag.getType(), turns) > 0;
- if (any(stopGoods, loadPred)) return true;
+ for (AbstractGoods ag : stopGoods)
+ if (unit.getGoodsCount(ag.getType()) < ag.getAmount()
+ && getExportAmount(ag.getType(), turns) > 0)
+ return true;

// Look for goods to unload.
// For all goods the unit has loaded, and if the type of goods
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:36 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Settlement.java | 16 +++++++++++++---
src/net/sf/freecol/common/model/Tile.java | 4 ----
2 files changed, 13 insertions(+), 7 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Settlement.java b/src/net/sf/freecol/common/model/Settlement.java
index 04aafe5234b..deb26d6f2d8 100644
--- a/src/net/sf/freecol/common/model/Settlement.java
+++ b/src/net/sf/freecol/common/model/Settlement.java
@@ -326,9 +326,19 @@ public abstract class Settlement extends GoodsLocation
* @return A high seas count, INFINITY if not connected.
*/
public int getHighSeasCount() {
- Tile best = minimize(getTile().getSurroundingTiles(1, 1),
- Tile.isSeaTile, Tile.highSeasComparator);
- return (best == null) ? INFINITY : best.getHighSeasCount();
+ int best_hsc = 0;
+ Tile best_tile = null;
+ for (Tile t : getTile().getSurroundingTiles(1, 1)) {
+ if (!t.isLand() && t.getHighSeasCount() >= 0) {
+ int hsc = t.getHighSeasCount();
+ if (best_tile == null || hsc < best_hsc) {
+ best_tile = t;
+ best_hsc = hsc;
+ }
+ }
+ }
+
+ return (best_tile == null) ? INFINITY : best_hsc;
}

/**
diff --git a/src/net/sf/freecol/common/model/Tile.java b/src/net/sf/freecol/common/model/Tile.java
index d1e3d205e15..ab0485296ef 100644
--- a/src/net/sf/freecol/common/model/Tile.java
+++ b/src/net/sf/freecol/common/model/Tile.java
@@ -65,10 +65,6 @@ public final class Tile extends UnitLocation implements Named, Ownable {
public static final Comparator<Tile> highSeasComparator
= Comparator.comparingInt(Tile::getHighSeasCount);

- /** Predicate to identify ordinary sea tiles. */
- public static final Predicate<Tile> isSeaTile = t ->
- !t.isLand() && t.getHighSeasCount() >= 0;
-
/**
* Information that is internal to the native settlements, and only
* updated on close contact.
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:53 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/IndianSettlement.java | 13 +++++++------
1 file changed, 7 insertions(+), 6 deletions(-)

diff --git a/src/net/sf/freecol/common/model/IndianSettlement.java b/src/net/sf/freecol/common/model/IndianSettlement.java
index c30d0bb59f0..459c6865e5a 100644
--- a/src/net/sf/freecol/common/model/IndianSettlement.java
+++ b/src/net/sf/freecol/common/model/IndianSettlement.java
@@ -38,6 +38,7 @@ import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.io.FreeColXMLReader;
import net.sf.freecol.common.io.FreeColXMLWriter;
import net.sf.freecol.common.option.GameOptions;
+import net.sf.freecol.common.util.IntAccMap;
import static net.sf.freecol.common.util.CollectionUtils.*;
import static net.sf.freecol.common.util.RandomUtils.*;

@@ -1095,12 +1096,12 @@ public class IndianSettlement extends Settlement implements TradeLocation {
* @param random A pseudo-random number source.
*/
public void addRandomGoods(Random random) {
- HashMap<GoodsType, Integer> goodsMap = new HashMap<>();
- for (AbstractGoods ag : iterable(flatten(getOwnedTiles(),
- t -> t.getSortedPotential().stream()))) {
- accumulateToMap(goodsMap, ag.getType().getStoredAs(),
- ag.getAmount(), (a, b) -> a + b);
- }
+ IntAccMap<GoodsType> goodsMap = new IntAccMap<>();
+
+ for (Tile t : getOwnedTiles())
+ for (AbstractGoods ag : t.getSortedPotential())
+ goodsMap.addInt(ag.getType().getStoredAs(), ag.getAmount());
+
double d = randomInt(logger, "Goods at " + getName(), random, 10)
* 0.1 + 1.0;
forEachMapEntry(goodsMap, e -> {
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:19 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/NationType.java | 16 ++++++++++++----
1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/src/net/sf/freecol/common/model/NationType.java b/src/net/sf/freecol/common/model/NationType.java
index 4ed0c7a2ef1..60dc2b1eeab 100644
--- a/src/net/sf/freecol/common/model/NationType.java
+++ b/src/net/sf/freecol/common/model/NationType.java
@@ -131,8 +131,12 @@ public abstract class NationType extends FreeColSpecObjectType {
* @return The settlement type.
*/
public SettlementType getSettlementType(boolean isCapital) {
- return find(getSettlementTypes(),
- matchKey(isCapital, SettlementType::isCapital));
+ if (settlementTypes != null)
+ for (SettlementType st : settlementTypes)
+ if (st.isCapital() == isCapital)
+ return st;
+
+ return null;
}

/**
@@ -142,8 +146,12 @@ public abstract class NationType extends FreeColSpecObjectType {
* @return The settlement type.
*/
public SettlementType getSettlementType(String id) {
- return find(getSettlementTypes(),
- matchKeyEquals(id, FreeColObject::getId));
+ if (settlementTypes != null)
+ for (SettlementType st : settlementTypes)
+ if (st.getId().equals(id))
+ return st;
+
+ return null;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:10 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Tension.java | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Tension.java b/src/net/sf/freecol/common/model/Tension.java
index 9fed15b7749..e2f65c2a4ab 100644
--- a/src/net/sf/freecol/common/model/Tension.java
+++ b/src/net/sf/freecol/common/model/Tension.java
@@ -145,8 +145,10 @@ public class Tension implements Named {
* @return The current level.
*/
public final Level getLevel() {
- return find(Level.values(), level -> value <= level.getLimit(),
- Level.HATEFUL);
+ for (Level level : Level.values())
+ if (value <= level.getLimit())
+ return level;
+ return Level.HATEFUL;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:40 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../freecol/client/gui/panel/colopedia/GoodsDetailPanel.java | 2 +-
src/net/sf/freecol/common/model/GoodsType.java | 2 +-
src/net/sf/freecol/common/model/Specification.java | 11 +----------
src/net/sf/freecol/common/model/Unit.java | 2 +-
4 files changed, 4 insertions(+), 13 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/panel/colopedia/GoodsDetailPanel.java b/src/net/sf/freecol/client/gui/panel/colopedia/GoodsDetailPanel.java
index 22268485a75..d07ee78b57c 100644
--- a/src/net/sf/freecol/client/gui/panel/colopedia/GoodsDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/colopedia/GoodsDetailPanel.java
@@ -157,7 +157,7 @@ public class GoodsDetailPanel extends ColopediaGameObjectTypePanel<GoodsType> {
}
}
List<Role> roles = new ArrayList<>();
- allTypes = filterBuildables(getSpecification().getRolesList(),
+ allTypes = filterBuildables(getSpecification().getRoles(),
roles, type);
if (!roles.isEmpty()) {
panel.add(Utility.localizedLabel("colopedia.goods.equipment"),
diff --git a/src/net/sf/freecol/common/model/GoodsType.java b/src/net/sf/freecol/common/model/GoodsType.java
index 5402f534154..a4f2d98cc66 100644
--- a/src/net/sf/freecol/common/model/GoodsType.java
+++ b/src/net/sf/freecol/common/model/GoodsType.java
@@ -501,7 +501,7 @@ public final class GoodsType extends FreeColSpecObjectType {
List<BuildableType> buildableTypes = new ArrayList<>();
buildableTypes.addAll(spec.getBuildingTypeList());
buildableTypes.addAll(spec.getUnitTypeList());
- buildableTypes.addAll(spec.getRolesList());
+ buildableTypes.addAll(spec.getRoles());
forEach(flatten(buildableTypes, BuildableType::getRequiredGoods),
ag -> ag.getType().buildingMaterial = true);

diff --git a/src/net/sf/freecol/common/model/Specification.java b/src/net/sf/freecol/common/model/Specification.java
index 3e7b5364044..950ea4d0049 100644
--- a/src/net/sf/freecol/common/model/Specification.java
+++ b/src/net/sf/freecol/common/model/Specification.java
@@ -1622,20 +1622,11 @@ public final class Specification {
*
* @return A list of available {@code Role}s.
*/
- public List<Role> getRolesList() {
+ public List<Role> getRoles() {
return this.roles;
}

/**
- * Get all the available roles as a stream.
- *
- * @return A stream of available {@code Role}s.
- */
- public Stream<Role> getRoles() {
- return getRolesList().stream();
- }
-
- /**
* Get a role by identifier.
*
* @param id The object identifier.
diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index b4f875550ec..90be94f59a1 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -885,7 +885,7 @@ public class Unit extends GoodsLocation
* @return A list of available {@code Role}s.
*/
public List<Role> getAvailableRolesList(List<Role> roles) {
- if (roles == null) roles = getSpecification().getRolesList();
+ if (roles == null) roles = getSpecification().getRoles();
return transform(roles, r -> roleIsAvailable(r));
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:33 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../gui/panel/colopedia/UnitDetailPanel.java | 57 +++++++++++-----------
.../sf/freecol/common/model/IndianNationType.java | 9 ++++
2 files changed, 38 insertions(+), 28 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/panel/colopedia/UnitDetailPanel.java b/src/net/sf/freecol/client/gui/panel/colopedia/UnitDetailPanel.java
index 7ded9ea3b1b..566a9d1b34a 100644
--- a/src/net/sf/freecol/client/gui/panel/colopedia/UnitDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/colopedia/UnitDetailPanel.java
@@ -135,38 +135,39 @@ public class UnitDetailPanel extends ColopediaGameObjectTypePanel<UnitType> {
panel.add(Utility.localizedLabel("colopedia.unit.skill"));
panel.add(new JLabel(Integer.toString(type.getSkill())), "right");

- List<BuildingType> schools = transform(spec.getBuildingTypeList(),
- bt -> bt.hasAbility(Ability.TEACH) && bt.canAdd(type));
- if (!schools.isEmpty()) {
- panel.add(Utility.localizedLabel("colopedia.unit.school"), "newline");
- int count = 0;
- for (BuildingType school : schools) {
- JButton label = getButton(school);
- if (count > 0 && count % 3 == 0) {
- panel.add(label, "skip");
- } else {
- panel.add(label);
- }
- count++;
+ int count = 0;
+
+ for (BuildingType school : spec.getBuildingTypeList()) {
+ if (!school.hasAbility(Ability.TEACH) || !school.canAdd(type))
+ continue;
+
+ if (count == 0)
+ panel.add(Utility.localizedLabel("colopedia.unit.school"), "newline");
+
+ JButton label = getButton(school);
+ if (count > 0 && count % 3 == 0) {
+ panel.add(label, "skip");
+ } else {
+ panel.add(label);
}
+ count++;
}

- List<IndianNationType> nations
- = transform(spec.getIndianNationTypes(),
- nt -> any(nt.getSkills(),
- matchKey(type, RandomChoice::getObject)));
- if (!nations.isEmpty()) {
- panel.add(Utility.localizedLabel("colopedia.unit.natives"), "newline");
- int count = 0;
- for (IndianNationType nation : nations) {
- JButton label = getButton(nation);
- if (count > 0 && count % 3 == 0) {
- panel.add(label, "skip");
- } else {
- panel.add(label);
- }
- count++;
+ count = 0;
+ for (IndianNationType nt : spec.getIndianNationTypes()) {
+ if (!nt.hasSkill(type))
+ continue;
+
+ if (count == 0)
+ panel.add(Utility.localizedLabel("colopedia.unit.natives"), "newline");
+
+ JButton label = getButton(nt);
+ if (count > 0 && count % 3 == 0) {
+ panel.add(label, "skip");
+ } else {
+ panel.add(label);
}
+ count++;
}

}
diff --git a/src/net/sf/freecol/common/model/IndianNationType.java b/src/net/sf/freecol/common/model/IndianNationType.java
index 1f3e78959e2..139d3addb4b 100644
--- a/src/net/sf/freecol/common/model/IndianNationType.java
+++ b/src/net/sf/freecol/common/model/IndianNationType.java
@@ -128,6 +128,15 @@ public class IndianNationType extends NationType {
: skills;
}

+ public boolean hasSkill(UnitType t) {
+ if (skills != null)
+ for (RandomChoice<UnitType> walk : skills)
+ if (walk.getObject() == t)
+ return true;
+
+ return true;
+ }
+
/**
* Add a skill.
*
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:18 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../gui/panel/report/ReportCompactColonyPanel.java | 7 +++----
src/net/sf/freecol/common/model/Colony.java | 18 ++++++++----------
2 files changed, 11 insertions(+), 14 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/panel/report/ReportCompactColonyPanel.java b/src/net/sf/freecol/client/gui/panel/report/ReportCompactColonyPanel.java
index 37c750b553f..d4010c5bcc8 100644
--- a/src/net/sf/freecol/client/gui/panel/report/ReportCompactColonyPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/report/ReportCompactColonyPanel.java
@@ -500,7 +500,7 @@ public final class ReportCompactColonyPanel extends ReportPanel
if (!s.colony.getTile().isCoastland()) {
key = "annotation.inland";
t.add(Messages.message("report.colony.annotation.inland"));
- } else if ((building = s.colony.getWorkLocationWithAbility(Ability.PRODUCE_IN_WATER, Building.class)) == null) {
+ } else if ((building = s.colony.getBuildingWithAbility(Ability.PRODUCE_IN_WATER)) == null) {
key = "annotation.coastal";
t.add(Messages.message("report.colony.annotation.coastal"));
} else {
@@ -510,7 +510,7 @@ public final class ReportCompactColonyPanel extends ReportPanel
if (ResourceManager.hasResource(key))
annotations += ResourceManager.getString(key);

- if ((building = s.colony.getWorkLocationWithAbility(Ability.EXPORT, Building.class)) != null) {
+ if ((building = s.colony.getBuildingWithAbility(Ability.EXPORT)) != null) {
annotations += "*";
t.add(Messages.message(building.getLabel()));
}
@@ -753,8 +753,7 @@ public final class ReportCompactColonyPanel extends ReportPanel
// places.
// Colour: cAlarm if completion is blocked, otherwise cPlain.
int empty = 0;
- Building school = s.colony.getWorkLocationWithAbility(Ability.TEACH,
- Building.class);
+ Building school = s.colony.getBuildingWithAbility(Ability.TEACH);
if (school != null) empty = school.getType().getWorkPlaces();
for (Entry<Unit, Integer> e
: mapEntriesByValue(s.teachers, descendingIntegerComparator)) {
diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index 86107881814..78564a13144 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -732,20 +732,18 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
}

/**
- * Gets a work location of a specific class with a given ability.
+ * Gets a buildingg with a given ability.
*
- * @param <T> The actual return type.
* @param ability An ability key.
- * @param returnClass The expected subclass.
- * @return A {@code WorkLocation} with the required
+ * @return A {@code Building} with the required
* {@code Ability}, or null if not found.
*/
- public <T extends WorkLocation> T getWorkLocationWithAbility(String ability,
- Class<T> returnClass) {
- WorkLocation wl = getWorkLocationWithAbility(ability);
- try {
- if (wl != null) return returnClass.cast(wl);
- } catch (ClassCastException cce) {};
+ public Building getBuildingWithAbility(String ability) {
+ synchronized (this.buildingMap) {
+ for (Building b : this.buildingMap.values())
+ if (b.isCurrent() && b.hasAbility(ability))
+ return b;
+ }
return null;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:29 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../sf/freecol/client/gui/panel/PlayersTable.java | 11 ++++++----
src/net/sf/freecol/common/model/Game.java | 17 +++++++++------
src/net/sf/freecol/common/model/Nation.java | 7 ++++--
src/net/sf/freecol/common/model/NationOptions.java | 12 ++++++++---
src/net/sf/freecol/common/model/Specification.java | 25 ++++++++++++----------
5 files changed, 45 insertions(+), 27 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/panel/PlayersTable.java b/src/net/sf/freecol/client/gui/panel/PlayersTable.java
index bf5524512a7..50b3b835959 100644
--- a/src/net/sf/freecol/client/gui/panel/PlayersTable.java
+++ b/src/net/sf/freecol/client/gui/panel/PlayersTable.java
@@ -26,10 +26,10 @@ import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

+import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.function.Predicate;

import javax.swing.AbstractCellEditor;
import javax.swing.DefaultCellEditor;
@@ -445,9 +445,12 @@ public final class PlayersTable extends JTable {
this.preGameController = preGameController;
this.nationOptions = nationOptions;
this.thisPlayer = thisPlayer;
- final Predicate<Nation> nationPred = n -> !n.isUnknownEnemy()
- && nationOptions.getNations().get(n) != null;
- this.nations = transform(spec.getNations(), nationPred);
+
+ this.nations = new ArrayList<>();
+ for (Nation n : spec.getNations())
+ if (!n.isUnknownEnemy() && nationOptions.getNations().get(n) != null)
+ this.nations.add(n);
+
for (Nation n : this.nations) this.nationMap.put(n, null);
this.nationMap.put(thisPlayer.getNation(), thisPlayer);
}
diff --git a/src/net/sf/freecol/common/model/Game.java b/src/net/sf/freecol/common/model/Game.java
index c98265b33e8..7a2eab3e712 100644
--- a/src/net/sf/freecol/common/model/Game.java
+++ b/src/net/sf/freecol/common/model/Game.java
@@ -858,10 +858,11 @@ public class Game extends FreeColGameObject {
* @return A vacant {@code Nation} or null if none found.
*/
public Nation getVacantNation() {
- Entry<Nation, NationState> entry
- = find(nationOptions.getNations().entrySet(),
- matchKey(NationState.AVAILABLE, Entry::getValue));
- return (entry == null) ? null : entry.getKey();
+ for (Entry<Nation, NationState> e : nationOptions.getNations().entrySet())
+ if (e.getValue() == NationState.AVAILABLE)
+ return e.getKey();
+
+ return null;
}

/**
@@ -870,9 +871,11 @@ public class Game extends FreeColGameObject {
* @return A list of available {@code Nation}s.
*/
public final List<Nation> getVacantNations() {
- return transform(nationOptions.getNations().entrySet(),
- matchKey(NationState.AVAILABLE, Entry::getValue),
- Entry::getKey);
+ List<Nation> result = new ArrayList<>();
+ for (Entry<Nation, NationState> e : nationOptions.getNations().entrySet())
+ if (NationState.AVAILABLE == e.getValue())
+ result.add(e.getKey());
+ return result;
}

/**
diff --git a/src/net/sf/freecol/common/model/Nation.java b/src/net/sf/freecol/common/model/Nation.java
index 61126b5d6e6..efbaa55b448 100644
--- a/src/net/sf/freecol/common/model/Nation.java
+++ b/src/net/sf/freecol/common/model/Nation.java
@@ -175,8 +175,11 @@ public class Nation extends FreeColSpecObjectType {
* @return The rebel {@code Nation}, or null if not applicable.
*/
public final Nation getRebelNation() {
- return find(getSpecification().getEuropeanNations(),
- matchKey(this, Nation::getREFNation));
+ for (Nation n : getSpecification().getEuropeanNations())
+ if (n == this)
+ return n;
+
+ return null;
}

/**
diff --git a/src/net/sf/freecol/common/model/NationOptions.java b/src/net/sf/freecol/common/model/NationOptions.java
index 977df9cbeb1..c86948305de 100644
--- a/src/net/sf/freecol/common/model/NationOptions.java
+++ b/src/net/sf/freecol/common/model/NationOptions.java
@@ -318,9 +318,15 @@ public class NationOptions extends FreeColSpecObject {
StringBuilder sb = new StringBuilder(128);
sb.append(NATIONAL_ADVANTAGES_TAG).append(": ")
.append(nationalAdvantages).append('\n');
- forEachMapEntry(nations,
- e -> sb.append(' ').append(e.getKey().getId())
- .append(' ').append(e.getValue()).append('\n'));
+
+ for (Map.Entry<Nation, NationState> e : nations.entrySet()) {
+ sb.append(' ');
+ sb.append(e.getKey().getId());
+ sb.append(' ');
+ sb.append(e.getValue());
+ sb.append('\n');
+ }
+
return sb.toString();
}
}
diff --git a/src/net/sf/freecol/common/model/Specification.java b/src/net/sf/freecol/common/model/Specification.java
index 6cf037897c5..4154bc6b0c8 100644
--- a/src/net/sf/freecol/common/model/Specification.java
+++ b/src/net/sf/freecol/common/model/Specification.java
@@ -548,7 +548,11 @@ public final class Specification {
nationTypes.clear();
nationTypes.addAll(indianNationTypes);
nationTypes.addAll(europeanNationTypes);
- REFNationTypes.addAll(transform(europeanNationTypes, NationType::isREF));
+
+ for (EuropeanNationType nt : europeanNationTypes)
+ if (nt.isREF())
+ REFNationTypes.add(nt);
+
europeanNationTypes.removeAll(REFNationTypes);

experts.clear();
@@ -2102,8 +2106,8 @@ public final class Specification {
});

// Nation FOUND_COLONY -> FOUNDS_COLONIES
- for (EuropeanNationType ent : transform(europeanNationTypes,
- nt -> nt.hasAbility(Ability.FOUND_COLONY))) {
+ for (EuropeanNationType ent : europeanNationTypes) {
+ if (!ent.hasAbility(Ability.FOUND_COLONY)) continue;
ent.removeAbilities(Ability.FOUND_COLONY);
ent.addAbility(new Ability(Ability.FOUNDS_COLONIES, ent, true));
}
@@ -2169,10 +2173,9 @@ public final class Specification {
// ability to have man-o-war. Older specs used
// INDEPENDENCE_DECLARED but we can not directly use that or
// the REF gets access to colonialRegulars.
- for (NationType ent : transform(europeanNationTypes,
- nt -> nt.isREF() && !nt.hasAbility(Ability.INDEPENDENT_NATION))) {
- ent.addAbility(new Ability(Ability.INDEPENDENT_NATION));
- }
+ for (NationType ent : europeanNationTypes)
+ if (ent.isREF() && !ent.hasAbility(Ability.INDEPENDENT_NATION))
+ ent.addAbility(new Ability(Ability.INDEPENDENT_NATION));

// Resource type modifiers had the wrong priority
forEach(flatten(resourceTypeList, ResourceType::getModifiers), m -> {
@@ -2209,10 +2212,10 @@ public final class Specification {
}

// European nation type production modifier indexes moved to the spec
- for (Modifier mod : transform(flatten(europeanNationTypes,
- EuropeanNationType::getModifiers), goodsPred)) {
- mod.setModifierIndex(Modifier.NATION_PRODUCTION_INDEX);
- }
+ for (EuropeanNationType ent : europeanNationTypes)
+ for (Modifier m : ent.getModifiers())
+ if (allTypes.get(m.getId()) instanceof GoodsType)
+ m.setModifierIndex(Modifier.NATION_PRODUCTION_INDEX);

// TownHall, Chapel et al now have unattended production types
// (replacing modifiers).
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:20 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Building.java | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Building.java b/src/net/sf/freecol/common/model/Building.java
index f3b13dea0cd..85a1703e33d 100644
--- a/src/net/sf/freecol/common/model/Building.java
+++ b/src/net/sf/freecol/common/model/Building.java
@@ -116,8 +116,9 @@ public class Building extends WorkLocation
colony.addFeatures(buildingType);

// Colonists which can't work here must be put outside
- eject.addAll(transform(getUnits(),
- u -> !canAddType(u.getType())));
+ for (Unit u : getUnits())
+ if (!canAddType(u.getType()))
+ eject.add(u);
}

// Colonists exceding units limit must be put outside
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:21 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Colony.java | 62 +++++++++++++----------------
1 file changed, 27 insertions(+), 35 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index 78564a13144..e960164fd84 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -29,7 +29,6 @@ import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Function;
-import java.util.function.Predicate;
import java.util.function.ToIntFunction;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -2244,15 +2243,15 @@ loop: for (WorkLocation wl : getWorkLocationsForProducing(goodsType)) {
t -> new TileImprovementSuggestion(t, null, INFINITY));

// Consider improvements for all available colony tiles.
- for (final ColonyTile ct : transform(getColonyTiles(),
- WorkLocation::isAvailable)) {
- final ToIntFunction<TileImprovementType> improve = cacheInt(ti ->
- ct.improvedBy(ti));
- result.addAll(transform(spec.getTileImprovementTypeList(),
- ti -> !ti.isNatural() && improve.applyAsInt(ti) > 0,
- ti -> new TileImprovementSuggestion(ct.getWorkTile(),
- ti, improve.applyAsInt(ti))));
- }
+ for (final ColonyTile ct : getColonyTiles())
+ if (ct.isAvailable())
+ for (TileImprovementType ti : spec.getTileImprovementTypeList())
+ if (!ti.isNatural()) {
+ int improved = ct.improvedBy(ti);
+ if (improved > 0)
+ result.add(new TileImprovementSuggestion(ct.getWorkTile(), ti, improved));
+ }
+
result.sort(TileImprovementSuggestion.descendingAmountComparator);
return result;
}
@@ -2365,42 +2364,35 @@ loop: for (WorkLocation wl : getWorkLocationsForProducing(goodsType)) {
// Add a message for goods required for the current building if any.
BuildableType currentlyBuilding = getCurrentlyBuilding();
if (currentlyBuilding != null) {
- final Function<AbstractGoods, StringTemplate> bMapper = ag ->
- StringTemplate.template("model.colony.buildableNeedsGoods")
+ for (AbstractGoods ag : currentlyBuilding.getRequiredGoods())
+ if (ag.getType() == goodsType && amount < ag.getAmount())
+ result.add(StringTemplate.template("model.colony.buildableNeedsGoods")
.addName("%colony%", getName())
.addNamed("%buildable%", currentlyBuilding)
.addAmount("%amount%", ag.getAmount() - amount)
- .addNamed("%goodsType%", goodsType);
- result.addAll(transform(currentlyBuilding.getRequiredGoods(),
- ag -> ag.getType() == goodsType
- && amount < ag.getAmount(),
- bMapper));
+ .addNamed("%goodsType%", goodsType));
}

// Add insufficient production messages for each production location
// that has a deficit in producing the goods type.
- final Function<WorkLocation, ProductionInfo> piMapper = wl ->
- getProductionInfo(wl);
- final Predicate<WorkLocation> prodPred = isNotNull(piMapper);
- final Function<WorkLocation, StringTemplate> pMapper = wl ->
- getInsufficientProductionMessage(getProductionInfo(wl),
- wl.getProductionDeficit(goodsType));
- result.addAll(transform(getWorkLocationsForProducing(goodsType),
- prodPred, pMapper, toListNoNulls()));
+ for (WorkLocation wl : getWorkLocationsForProducing(goodsType)) {
+ ProductionInfo pi = getProductionInfo(wl);
+ if (pi != null)
+ result.add(getInsufficientProductionMessage(
+ pi, wl.getProductionDeficit(goodsType)));
+ }

// Add insufficient production messages for each consumption
// location for the goods type where there is a consequent
// deficit in production of a dependent goods.
- final Function<WorkLocation, List<StringTemplate>> cMapper = wl -> {
- final ProductionInfo info = getProductionInfo(wl);
- final Function<AbstractGoods, StringTemplate> gMapper = ag ->
- getInsufficientProductionMessage(info,
- wl.getProductionDeficit(ag.getType()));
- return transform(wl.getOutputs(), AbstractGoods::isStorable,
- gMapper, toListNoNulls());
- };
- result.addAll(transform(getWorkLocationsForConsuming(goodsType),
- prodPred, cMapper, toAppendedList()));
+ for (WorkLocation wl : getWorkLocationsForConsuming(goodsType)) {
+ ProductionInfo pi = getProductionInfo(wl);
+ if (pi != null)
+ for (AbstractGoods ag : wl.getOutputs())
+ if (ag.isStorable())
+ result.add(getInsufficientProductionMessage(pi,
+ wl.getProductionDeficit(ag.getType())));
+ }

return result;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:23 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Role.java | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Role.java b/src/net/sf/freecol/common/model/Role.java
index fe67d564451..ddc132bf18c 100644
--- a/src/net/sf/freecol/common/model/Role.java
+++ b/src/net/sf/freecol/common/model/Role.java
@@ -353,9 +353,11 @@ public class Role extends BuildableType {
result.add(new AbstractGoods(ag.getType(), amount));
}
}
- result.addAll(transform(fromGoods,
- ag -> !AbstractGoods.anyIsType(toGoods, ag.getType()),
- ag -> new AbstractGoods(ag.getType(), -ag.getAmount())));
+ for (AbstractGoods ag : fromGoods) {
+ GoodsType gt = ag.getType();
+ if (!AbstractGoods.anyIsType(toGoods, gt))
+ result.add(new AbstractGoods(gt, -ag.getAmount()));
+ }
}
return result;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:15 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/UnitLocation.java | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/src/net/sf/freecol/common/model/UnitLocation.java b/src/net/sf/freecol/common/model/UnitLocation.java
index e29cce93f0a..7bbbf03f480 100644
--- a/src/net/sf/freecol/common/model/UnitLocation.java
+++ b/src/net/sf/freecol/common/model/UnitLocation.java
@@ -250,7 +250,10 @@ public abstract class UnitLocation extends FreeColGameObject implements Location
* @return A suitable carrier or null if none found.
*/
public Unit getCarrierForUnit(Unit unit) {
- return find(getUnits(), u -> u.couldCarry(unit));
+ for (Unit u : getUnits())
+ if (u.couldCarry(unit))
+ return u;
+ return null;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:24 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/SimpleCombatModel.java | 10 ++++------
1 file changed, 4 insertions(+), 6 deletions(-)

diff --git a/src/net/sf/freecol/common/model/SimpleCombatModel.java b/src/net/sf/freecol/common/model/SimpleCombatModel.java
index a536559adcb..ed992f0ff23 100644
--- a/src/net/sf/freecol/common/model/SimpleCombatModel.java
+++ b/src/net/sf/freecol/common/model/SimpleCombatModel.java
@@ -298,9 +298,8 @@ public class SimpleCombatModel extends CombatModel {
// Goods penalty always applies
int goodsCount = attacker.getGoodsSpaceTaken();
if (goodsCount > 0) {
- result.addAll(transform(spec.getModifiers(Modifier.CARGO_PENALTY),
- alwaysTrue(),
- m -> new Modifier(m).setValue(m.getValue() * goodsCount)));
+ for (Modifier m : spec.getModifiers(Modifier.CARGO_PENALTY))
+ result.add(new Modifier(m).setValue(m.getValue() * goodsCount));
}
}

@@ -489,9 +488,8 @@ public class SimpleCombatModel extends CombatModel {
// Cargo penalty always applies
int goodsCount = defender.getVisibleGoodsCount();
if (goodsCount > 0) {
- result.addAll(transform(spec.getModifiers(Modifier.CARGO_PENALTY),
- alwaysTrue(),
- m -> new Modifier(m).setValue(m.getValue() * goodsCount)));
+ for (Modifier m : spec.getModifiers(Modifier.CARGO_PENALTY))
+ result.add(new Modifier(m).setValue(m.getValue() * goodsCount));
}
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:48 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Player.java | 25 +++++++++++++++++--------
1 file changed, 17 insertions(+), 8 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Player.java b/src/net/sf/freecol/common/model/Player.java
index 29991c4778e..078de0a8011 100644
--- a/src/net/sf/freecol/common/model/Player.java
+++ b/src/net/sf/freecol/common/model/Player.java
@@ -1772,14 +1772,23 @@ public class Player extends FreeColGameObject implements Nameable {
*/
public Goods getMostValuableGoods() {
if (!isEuropean()) return null;
- final Predicate<Goods> boycottPred = g ->
- getArrears(g.getType()) <= 0 && hasTraded(g.getType());
- final Comparator<Goods> tradedValueComp = Comparator.comparingInt(g ->
- market.getSalePrice(g.getType(),
- Math.min(g.getAmount(), GoodsContainer.CARGO_SIZE)));
- return maximize(flatten(getColonies(),
- c -> c.getCompactGoods().stream()),
- boycottPred, tradedValueComp);
+
+ Goods picked_goods = null;
+ int picked_price = 0;
+
+ for (Colony c : getColonies()) {
+ for (Goods g : c.getCompactGoods()) {
+ GoodsType gt = g.getType();
+ if (getArrears(gt) <= 0 && hasTraded(gt)) {
+ int myprice = market.getSalePrice(gt, Math.min(g.getAmount(), GoodsContainer.CARGO_SIZE));
+ if (myprice > picked_price) {
+ picked_price = myprice;
+ picked_goods = g;
+ }
+ }
+ }
+ }
+ return picked_goods;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:56 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

[javac] /home/nekrad/src/packaging/pkg/freecol.git/src/net/sf/freecol/common/model/Specification.java:1782: error: no suitable met
hod found for add(Option)
[javac] result.add(o);
[javac] ^
[javac] method Collection.add(OptionGroup) is not applicable
[javac] (argument mismatch; Option cannot be converted to OptionGroup)
[javac] method List.add(OptionGroup) is not applicable
[javac] (argument mismatch; Option cannot be converted to OptionGroup)

Broken-by: d42604670fe2599836032f0f9190d2cf68b290f8
---
src/net/sf/freecol/common/model/Specification.java | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/net/sf/freecol/common/model/Specification.java b/src/net/sf/freecol/common/model/Specification.java
index 0f949a02da3..698b311cd5c 100644
--- a/src/net/sf/freecol/common/model/Specification.java
+++ b/src/net/sf/freecol/common/model/Specification.java
@@ -2098,7 +2098,8 @@ public final class Specification {
}

// Fix all other UnitListOptions
- List<Option> todo = new ArrayList<>(getDifficultyLevels());
+ List<Option> todo = new ArrayList<>();
+ for (OptionGroup og : getDifficultyLevels()) todo.add(og);
while (!todo.isEmpty()) {
Option o = todo.remove(0);
if (o instanceof OptionGroup) {
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:12 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../sf/freecol/common/model/TileItemContainer.java | 52 +++++++++++++---------
1 file changed, 30 insertions(+), 22 deletions(-)

diff --git a/src/net/sf/freecol/common/model/TileItemContainer.java b/src/net/sf/freecol/common/model/TileItemContainer.java
index 55fb144822b..7092436474b 100644
--- a/src/net/sf/freecol/common/model/TileItemContainer.java
+++ b/src/net/sf/freecol/common/model/TileItemContainer.java
@@ -21,7 +21,6 @@ package net.sf.freecol.common.model;

import java.util.ArrayList;
import java.util.List;
-import java.util.function.Predicate;
import java.util.logging.Logger;
import java.util.stream.Stream;

@@ -250,10 +249,13 @@ public class TileItemContainer extends FreeColGameObject {
*/
public TileImprovement getImprovement(TileImprovementType type) {
synchronized (tileItems) {
- return (TileImprovement)find(tileItems,
- ti -> (ti instanceof TileImprovement
- && ((TileImprovement)ti).getType() == type));
+ for (TileItem ti : tileItems) {
+ if (ti instanceof TileImprovement
+ && ((TileImprovement)ti).getType() == type)
+ return (TileImprovement)ti;
+ }
}
+ return null;
}

/**
@@ -293,25 +295,18 @@ public class TileItemContainer extends FreeColGameObject {
}

/**
- * Find a tile item matching a predicate.
- *
- * @param pred The {@code Predicate} to match.
- * @return The {@code TileItem} found, or null if none present.
- */
- private TileItem findTileItem(Predicate<TileItem> pred) {
- synchronized (tileItems) {
- return find(tileItems, pred);
- }
- }
-
- /**
* Gets any lost city rumour in this container.
*
* @return A {@code LostCityRumour} item if any, or null if
* not found.
*/
public final LostCityRumour getLostCityRumour() {
- return (LostCityRumour)findTileItem(ti -> ti instanceof LostCityRumour);
+ synchronized (tileItems) {
+ for (TileItem ti : tileItems)
+ if (ti instanceof LostCityRumour)
+ return (LostCityRumour)ti;
+ }
+ return null;
}

/**
@@ -320,7 +315,12 @@ public class TileItemContainer extends FreeColGameObject {
* @return A {@code Resource} item, or null is none found.
*/
public final Resource getResource() {
- return (Resource)findTileItem(ti -> ti instanceof Resource);
+ synchronized (tileItems) {
+ for (TileItem ti : tileItems)
+ if (ti instanceof Resource)
+ return (Resource)ti;
+ }
+ return null;
}

/**
@@ -330,8 +330,12 @@ public class TileItemContainer extends FreeColGameObject {
* not found.
*/
public TileImprovement getRoad() {
- return (TileImprovement)findTileItem(ti ->
- ti instanceof TileImprovement && ((TileImprovement)ti).isRoad());
+ synchronized (tileItems) {
+ for (TileItem ti : tileItems)
+ if (ti instanceof TileImprovement && ((TileImprovement)ti).isRoad())
+ return (TileImprovement)ti;
+ }
+ return null;
}

/**
@@ -341,8 +345,12 @@ public class TileItemContainer extends FreeColGameObject {
* not found.
*/
public TileImprovement getRiver() {
- return (TileImprovement)findTileItem(ti ->
- ti instanceof TileImprovement && ((TileImprovement)ti).isRiver());
+ synchronized (tileItems) {
+ for (TileItem ti : tileItems)
+ if (ti instanceof TileImprovement && ((TileImprovement)ti).isRiver())
+ return (TileImprovement)ti;
+ }
+ return null;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:26 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Unit.java | 17 +++++++----------
1 file changed, 7 insertions(+), 10 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index ee066fffa0f..41a21952375 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -3699,21 +3699,18 @@ public class Unit extends GoodsLocation
Set<Modifier> result = new HashSet<>();

// UnitType modifiers always apply
- result.addAll(transform(unitType.getModifiers(id, fcgot, turn),
- alwaysTrue(),
- m -> m.setModifierIndex((m.getType() == Modifier.ModifierType.ADDITIVE)
+ for (Modifier m : unitType.getModifiers(id, fcgot, turn))
+ result.add(m.setModifierIndex((m.getType() == Modifier.ModifierType.ADDITIVE)
? Modifier.UNIT_ADDITIVE_COMBAT_INDEX
- : Modifier.UNIT_NORMAL_COMBAT_INDEX)));
+ : Modifier.UNIT_NORMAL_COMBAT_INDEX));

// The player's modifiers may not all apply
- result.addAll(transform(owner.getModifiers(id, fcgot, turn),
- alwaysTrue(),
- m -> m.setModifierIndex(Modifier.GENERAL_COMBAT_INDEX)));
+ for (Modifier m : owner.getModifiers(id, fcgot, turn))
+ result.add(m.setModifierIndex(Modifier.GENERAL_COMBAT_INDEX));

// Role modifiers apply
- result.addAll(transform(role.getModifiers(id, fcgot, turn),
- alwaysTrue(),
- m -> m.setModifierIndex(Modifier.ROLE_COMBAT_INDEX)));
+ for (Modifier m : role.getModifiers(id, fcgot, turn))
+ result.add(m.setModifierIndex(Modifier.ROLE_COMBAT_INDEX));

return result;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:55 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../sf/freecol/common/model/IndianSettlement.java | 27 ++++++++++++----------
1 file changed, 15 insertions(+), 12 deletions(-)

diff --git a/src/net/sf/freecol/common/model/IndianSettlement.java b/src/net/sf/freecol/common/model/IndianSettlement.java
index 459c6865e5a..16a225275df 100644
--- a/src/net/sf/freecol/common/model/IndianSettlement.java
+++ b/src/net/sf/freecol/common/model/IndianSettlement.java
@@ -27,7 +27,6 @@ import java.util.Map.Entry;
import java.util.Random;
import java.util.function.Function;
import java.util.function.Predicate;
-import java.util.function.ToIntFunction;
import java.util.logging.Logger;
import java.util.stream.Collectors;

@@ -1054,17 +1053,21 @@ public class IndianSettlement extends Settlement implements TradeLocation {
* none suitable.
*/
private GoodsType goodsToMake() {
- final ToIntFunction<GoodsType> deficit = cacheInt(gt ->
- getWantedGoodsAmount(gt) - getGoodsCount(gt));
- final Predicate<GoodsType> goodsPred = gt ->
- gt.isRawMaterial()
- && gt.getOutputType() != null
- && !gt.getOutputType().isBreedable()
- && gt.getOutputType().isStorable()
- && deficit.applyAsInt(gt) < 0
- && deficit.applyAsInt(gt.getOutputType()) > 0;
- final Comparator<GoodsType> comp = Comparator.comparingInt(deficit);
- return maximize(getSpecification().getGoodsTypeList(), goodsPred, comp);
+ int best_deficit = Integer.MIN_VALUE;
+ GoodsType best_gt = null;
+ for (GoodsType gt : getSpecification().getGoodsTypeList()) {
+ if (!gt.isRawMaterial()) continue;
+ GoodsType ot = gt.getOutputType();
+ if (ot == null || ot.isBreedable() || !ot.isStorable()) continue;
+ int deficit = getWantedGoodsAmount(gt) - getGoodsCount(gt);
+ if (!(deficit < 0 && (getWantedGoodsAmount(ot) - getGoodsCount(ot) > 0)))
+ continue;
+ if ((best_gt == null) || (deficit > best_deficit)) {
+ best_gt = gt;
+ best_deficit = deficit;
+ }
+ }
+ return best_gt;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:30 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/option/LanguageOption.java | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/net/sf/freecol/common/option/LanguageOption.java b/src/net/sf/freecol/common/option/LanguageOption.java
index 52ba6bf0d32..753355dbe39 100644
--- a/src/net/sf/freecol/common/option/LanguageOption.java
+++ b/src/net/sf/freecol/common/option/LanguageOption.java
@@ -214,7 +214,11 @@ public class LanguageOption extends AbstractOption<LanguageOption.Language> {
* @return The corresponding language, or null if none found.
*/
private Language getLanguage(String key) {
- return find(languages, l -> key.equals(l.getKey()));
+ for (Language walk : this.languages)
+ if (key.equals(walk.getKey()))
+ return walk;
+
+ return null;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:43 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../freecol/client/gui/panel/BuildQueuePanel.java | 2 +-
.../client/gui/panel/ConstructionPanel.java | 2 +-
.../gui/panel/colopedia/BuildingDetailPanel.java | 2 +-
.../gui/panel/colopedia/UnitDetailPanel.java | 2 +-
src/net/sf/freecol/common/model/BuildQueue.java | 4 ++--
src/net/sf/freecol/common/model/BuildableType.java | 18 +++---------------
src/net/sf/freecol/common/model/Colony.java | 6 +++---
src/net/sf/freecol/common/model/Role.java | 22 +++++-----------------
src/net/sf/freecol/common/model/Unit.java | 2 +-
src/net/sf/freecol/server/ai/AIColony.java | 6 +++---
src/net/sf/freecol/server/ai/ColonyPlan.java | 2 +-
.../server/ai/mission/PioneeringMission.java | 2 +-
src/net/sf/freecol/server/model/ServerPlayer.java | 2 +-
.../net/sf/freecol/common/model/CombatTest.java | 4 ++--
.../sf/freecol/common/model/SettlementTest.java | 2 +-
.../sf/freecol/common/model/SpecificationTest.java | 22 +++++++++++-----------
.../sf/freecol/server/ai/StandardAIPlayerTest.java | 2 +-
.../server/ai/mission/PioneeringMissionTest.java | 2 +-
.../server/control/InGameControllerTest.java | 8 ++++----
.../sf/freecol/server/model/ServerColonyTest.java | 2 +-
20 files changed, 45 insertions(+), 69 deletions(-)

diff --git a/src/net/sf/freecol/client/gui/panel/BuildQueuePanel.java b/src/net/sf/freecol/client/gui/panel/BuildQueuePanel.java
index b68c3b05add..63ed8d18f74 100644
--- a/src/net/sf/freecol/client/gui/panel/BuildQueuePanel.java
+++ b/src/net/sf/freecol/client/gui/panel/BuildQueuePanel.java
@@ -494,7 +494,7 @@ public class BuildQueuePanel extends FreeColPanel implements ItemListener {
}

ImageLibrary lib = getImageLibrary();
- List<AbstractGoods> required = value.getRequiredGoodsList();
+ List<AbstractGoods> required = value.getRequiredGoods();
int size = required.size();
for (int i = 0; i < size; i++) {
AbstractGoods goods = required.get(i);
diff --git a/src/net/sf/freecol/client/gui/panel/ConstructionPanel.java b/src/net/sf/freecol/client/gui/panel/ConstructionPanel.java
index 3cd59dca2d7..b2b5b031b5f 100644
--- a/src/net/sf/freecol/client/gui/panel/ConstructionPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ConstructionPanel.java
@@ -186,7 +186,7 @@ public class ConstructionPanel extends MigPanel
label1.setFont(font);
add(label1);

- for (AbstractGoods ag : buildable.getRequiredGoodsList()) {
+ for (AbstractGoods ag : buildable.getRequiredGoods()) {
int amountNeeded = ag.getAmount();
int amountAvailable = colony.getGoodsCount(ag.getType());
int amountProduced = colony.getAdjustedNetProductionOf(ag.getType());
diff --git a/src/net/sf/freecol/client/gui/panel/colopedia/BuildingDetailPanel.java b/src/net/sf/freecol/client/gui/panel/colopedia/BuildingDetailPanel.java
index 1d6ac2ede32..22880927c2c 100644
--- a/src/net/sf/freecol/client/gui/panel/colopedia/BuildingDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/colopedia/BuildingDetailPanel.java
@@ -167,7 +167,7 @@ public class BuildingDetailPanel
if (!buildingType.needsGoodsToBuild()) {
panel.add(Utility.localizedLabel("colopedia.buildings.autoBuilt"), "span");
} else {
- List<AbstractGoods> required = buildingType.getRequiredGoodsList();
+ List<AbstractGoods> required = buildingType.getRequiredGoods();
AbstractGoods goodsRequired = first(required);
if (required.size() > 1) {
panel.add(getGoodsButton(goodsRequired.getType(), goodsRequired.getAmount()),
diff --git a/src/net/sf/freecol/client/gui/panel/colopedia/UnitDetailPanel.java b/src/net/sf/freecol/client/gui/panel/colopedia/UnitDetailPanel.java
index 566a9d1b34a..a48b23ad856 100644
--- a/src/net/sf/freecol/client/gui/panel/colopedia/UnitDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/colopedia/UnitDetailPanel.java
@@ -207,7 +207,7 @@ public class UnitDetailPanel extends ColopediaGameObjectTypePanel<UnitType> {
if (type.needsGoodsToBuild()) {
panel.add(Utility.localizedLabel("colopedia.unit.goodsRequired"),
"newline 20");
- List<AbstractGoods> required = type.getRequiredGoodsList();
+ List<AbstractGoods> required = type.getRequiredGoods();
AbstractGoods goods = first(required);
if (required.size() > 1) {
panel.add(getGoodsButton(goods.getType(), goods.getAmount()),
diff --git a/src/net/sf/freecol/common/model/BuildQueue.java b/src/net/sf/freecol/common/model/BuildQueue.java
index b003844671e..4fb6e0248b5 100644
--- a/src/net/sf/freecol/common/model/BuildQueue.java
+++ b/src/net/sf/freecol/common/model/BuildQueue.java
@@ -168,7 +168,7 @@ public class BuildQueue<T extends BuildableType> implements Consumer {
final boolean overflow = this.colony.getSpecification()
.getBoolean(GameOptions.SAVE_PRODUCTION_OVERFLOW);
List<AbstractGoods> consumption = new ArrayList<>();
- for (AbstractGoods ag : current.getRequiredGoodsList()) {
+ for (AbstractGoods ag : current.getRequiredGoods()) {
AbstractGoods available = AbstractGoods.findByType(input, ag);
if (available != null
&& ag.getAmount() <= available.getAmount()) {
@@ -195,7 +195,7 @@ public class BuildQueue<T extends BuildableType> implements Consumer {
public List<AbstractGoods> getConsumedGoods() {
T current = getCurrentlyBuilding();
return (current == null) ? Collections.<AbstractGoods>emptyList()
- : current.getRequiredGoodsList();
+ : current.getRequiredGoods();
}

/**
diff --git a/src/net/sf/freecol/common/model/BuildableType.java b/src/net/sf/freecol/common/model/BuildableType.java
index 2d947d92bab..e263bdcbd55 100644
--- a/src/net/sf/freecol/common/model/BuildableType.java
+++ b/src/net/sf/freecol/common/model/BuildableType.java
@@ -24,7 +24,6 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.stream.Stream;

import javax.swing.JList;
import javax.xml.stream.XMLStreamException;
@@ -157,7 +156,7 @@ public abstract class BuildableType extends FreeColSpecObjectType {
*
* @return A deep copy of the list of required goods.
*/
- public List<AbstractGoods> getRequiredGoodsList() {
+ public List<AbstractGoods> getRequiredGoods() {
return (this.requiredGoods == null)
? Collections.<AbstractGoods>emptyList()
: transform(this.requiredGoods, alwaysTrue(),
@@ -165,17 +164,6 @@ public abstract class BuildableType extends FreeColSpecObjectType {
}

/**
- * Get the goods required to build an instance of this buildable
- * as a stream.
- *
- * @return A stream of the required goods.
- */
- public Stream<AbstractGoods> getRequiredGoods() {
- return (this.requiredGoods == null) ? Stream.<AbstractGoods>empty()
- : getRequiredGoodsList().stream();
- }
-
- /**
* Get the amount required of a given {@code GoodsType} to build
* an instance of this buildable.
*
@@ -183,7 +171,7 @@ public abstract class BuildableType extends FreeColSpecObjectType {
* @return The amount of goods required.
*/
public int getRequiredAmountOf(GoodsType type) {
- return AbstractGoods.getCount(type, getRequiredGoodsList());
+ return AbstractGoods.getCount(type, getRequiredGoods());
}

/**
@@ -302,7 +290,7 @@ public abstract class BuildableType extends FreeColSpecObjectType {
}
}

- for (AbstractGoods goods : getRequiredGoodsList()) {
+ for (AbstractGoods goods : getRequiredGoods()) {
xw.writeStartElement(REQUIRED_GOODS_TAG);

xw.writeAttribute(ID_ATTRIBUTE_TAG, goods.getType());
diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index 7cb6ad3559b..cd62183f987 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -989,7 +989,7 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*/
public int getTurnsToComplete(BuildableType buildable,
AbstractGoods needed) {
- final List<AbstractGoods> required = buildable.getRequiredGoodsList();
+ final List<AbstractGoods> required = buildable.getRequiredGoods();
int turns = 0, satisfied = 0, failing = 0, underway = 0;

ProductionInfo info = productionCache.getProductionInfo(buildQueue);
@@ -1183,7 +1183,7 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
if (buildable == null) return Collections.<AbstractGoods>emptyList();

List<AbstractGoods> required = new ArrayList<>();
- for (AbstractGoods ag : buildable.getRequiredGoodsList()) {
+ for (AbstractGoods ag : buildable.getRequiredGoods()) {
int amount = ag.getAmount();
GoodsType type = ag.getType();
while (type != null) {
@@ -2813,7 +2813,7 @@ loop: for (WorkLocation wl : getWorkLocationsForProducing(goodsType)) {

if (buildable != null) {
available -= AbstractGoods.getCount(goods.getType(),
- buildable.getRequiredGoodsList());
+ buildable.getRequiredGoods());
}

if (available < goods.getAmount()) return false;
diff --git a/src/net/sf/freecol/common/model/Role.java b/src/net/sf/freecol/common/model/Role.java
index 4eb33ed7e7b..fe67d564451 100644
--- a/src/net/sf/freecol/common/model/Role.java
+++ b/src/net/sf/freecol/common/model/Role.java
@@ -24,7 +24,6 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
-import java.util.stream.Stream;

import javax.xml.stream.XMLStreamException;

@@ -217,8 +216,8 @@ public class Role extends BuildableType {
* @param roleCount The role count.
* @return A list of required goods.
*/
- public List<AbstractGoods> getRequiredGoodsList(int roleCount) {
- List<AbstractGoods> result = getRequiredGoodsList();
+ public List<AbstractGoods> getRequiredGoods(int roleCount) {
+ List<AbstractGoods> result = getRequiredGoods();
if (roleCount > 1 && !result.isEmpty()) {
for (AbstractGoods ag : result) {
ag.setAmount(roleCount * ag.getAmount());
@@ -228,17 +227,6 @@ public class Role extends BuildableType {
}

/**
- * Get the required goods for this role, considering also the role count,
- * as a stream.
- *
- * @param roleCount The role count.
- * @return A stream of required goods.
- */
- public Stream<AbstractGoods> getRequiredGoods(int roleCount) {
- return getRequiredGoodsList(roleCount).stream();
- }
-
- /**
* Get the price of the required goods in a given market.
*
* @param market The {@code Market} to evaluate in.
@@ -356,8 +344,8 @@ public class Role extends BuildableType {
if (from != to && !(from == null && to.isDefaultRole())) {
List<AbstractGoods> fromGoods = (from == null)
? new ArrayList<AbstractGoods>()
- : from.getRequiredGoodsList(fromCount);
- List<AbstractGoods> toGoods = to.getRequiredGoodsList(toCount);
+ : from.getRequiredGoods(fromCount);
+ List<AbstractGoods> toGoods = to.getRequiredGoods(toCount);
for (AbstractGoods ag : toGoods) {
int amount = ag.getAmount()
- AbstractGoods.getCount(ag.getType(), fromGoods);
@@ -386,7 +374,7 @@ public class Role extends BuildableType {
int base = (requiresAbility(Ability.NATIVE)) ? 30
: (requiresAbility(Ability.REF_UNIT)) ? 20
: 10;
- return base - getRequiredGoodsList().size();
+ return base - getRequiredGoods().size();
}

/**
diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index 7aa3266f0fd..577341356f6 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -364,7 +364,7 @@ public class Unit extends GoodsLocation
} else {
// Other roles can be characterized by their goods.
List<AbstractGoods> requiredGoods
- = role.getRequiredGoodsList(getRoleCount());
+ = role.getRequiredGoods(getRoleCount());
boolean first = true;
extra = StringTemplate.label("");
for (AbstractGoods ag : requiredGoods) {
diff --git a/src/net/sf/freecol/server/ai/AIColony.java b/src/net/sf/freecol/server/ai/AIColony.java
index 9bc3eadd3e2..912b3bd2f40 100644
--- a/src/net/sf/freecol/server/ai/AIColony.java
+++ b/src/net/sf/freecol/server/ai/AIColony.java
@@ -1092,7 +1092,7 @@ public class AIColony extends AIObject implements PropertyChangeListener {
// Add building materials.
if (colony.getCurrentlyBuilding() != null) {
for (AbstractGoods ag : colony.getCurrentlyBuilding()
- .getRequiredGoodsList()) {
+ .getRequiredGoods()) {
if (colony.getAdjustedNetProductionOf(ag.getType()) <= 0) {
required.incrementCount(ag.getType(), ag.getAmount());
}
@@ -1103,7 +1103,7 @@ public class AIColony extends AIObject implements PropertyChangeListener {
for (TileImprovementPlan plan : tileImprovementPlans) {
Role role = plan.getType().getRequiredRole();
if (role == null) continue;
- for (AbstractGoods ag : role.getRequiredGoodsList()) {
+ for (AbstractGoods ag : role.getRequiredGoods()) {
required.incrementCount(ag.getType(), ag.getAmount());
}
}
@@ -1133,7 +1133,7 @@ public class AIColony extends AIObject implements PropertyChangeListener {
&& (u.hasDefaultRole()
|| Role.isCompatibleWith(role, u.getRole())));
if (any(colony.getTile().getUnits(), rolePred)) {
- for (AbstractGoods ag : role.getRequiredGoodsList()) {
+ for (AbstractGoods ag : role.getRequiredGoods()) {
required.incrementCount(ag.getType(), ag.getAmount());
}
}
diff --git a/src/net/sf/freecol/server/ai/ColonyPlan.java b/src/net/sf/freecol/server/ai/ColonyPlan.java
index 7e6b695ec39..91710509f97 100644
--- a/src/net/sf/freecol/server/ai/ColonyPlan.java
+++ b/src/net/sf/freecol/server/ai/ColonyPlan.java
@@ -1216,7 +1216,7 @@ public class ColonyPlan {
// Greedy assignment of other workers to plans.
List<AbstractGoods> buildGoods = new ArrayList<>();
BuildableType build = col.getCurrentlyBuilding();
- if (build != null) buildGoods.addAll(build.getRequiredGoodsList());
+ if (build != null) buildGoods.addAll(build.getRequiredGoods());
List<WorkLocationPlan> wlps;
WorkLocationPlan wlp;
boolean done = false;
diff --git a/src/net/sf/freecol/server/ai/mission/PioneeringMission.java b/src/net/sf/freecol/server/ai/mission/PioneeringMission.java
index 76cc5c6c8b7..6478fb294b3 100644
--- a/src/net/sf/freecol/server/ai/mission/PioneeringMission.java
+++ b/src/net/sf/freecol/server/ai/mission/PioneeringMission.java
@@ -395,7 +395,7 @@ public class PioneeringMission extends Mission {
return (reason != null)
? reason
: (!hasTools(aiUnit)
- && !colony.canProvideGoods(role.getRequiredGoodsList()))
+ && !colony.canProvideGoods(role.getRequiredGoods()))
? "colony-can-not-provide-equipment"
: null;
}
diff --git a/src/net/sf/freecol/server/model/ServerPlayer.java b/src/net/sf/freecol/server/model/ServerPlayer.java
index d2e1a23fb19..e49d8b2d602 100644
--- a/src/net/sf/freecol/server/model/ServerPlayer.java
+++ b/src/net/sf/freecol/server/model/ServerPlayer.java
@@ -3438,7 +3438,7 @@ outer: for (Effect effect : effects) {

// Autoequipment is not actually with the unit, it is stored
// in the settlement of the unit. Remove it from there.
- for (AbstractGoods ag : role.getRequiredGoodsList()) {
+ for (AbstractGoods ag : role.getRequiredGoods()) {
settlement.removeGoods(ag);
}

diff --git a/test/src/net/sf/freecol/common/model/CombatTest.java b/test/src/net/sf/freecol/common/model/CombatTest.java
index 26720c921e3..7c5858ccbea 100644
--- a/test/src/net/sf/freecol/common/model/CombatTest.java
+++ b/test/src/net/sf/freecol/common/model/CombatTest.java
@@ -302,7 +302,7 @@ public class CombatTest extends FreeColTestCase {

// Set up for auto-equip
dutch.addFather(spec().getFoundingFather("model.foundingFather.paulRevere"));
- for (AbstractGoods ag : soldierRole.getRequiredGoodsList()) {
+ for (AbstractGoods ag : soldierRole.getRequiredGoods()) {
colony.addGoods(ag);
}

@@ -339,7 +339,7 @@ public class CombatTest extends FreeColTestCase {
nativeDragoonRole);
Unit attacker = new ServerUnit(game, tile2, dutch, colonistType,
dragoonRole);
- for (AbstractGoods ag : nativeDragoonRole.getRequiredGoodsList()) {
+ for (AbstractGoods ag : nativeDragoonRole.getRequiredGoods()) {
is.addGoods(ag);
}

diff --git a/test/src/net/sf/freecol/common/model/SettlementTest.java b/test/src/net/sf/freecol/common/model/SettlementTest.java
index 5f28306d1ae..89722a9e30a 100644
--- a/test/src/net/sf/freecol/common/model/SettlementTest.java
+++ b/test/src/net/sf/freecol/common/model/SettlementTest.java
@@ -164,7 +164,7 @@ public class SettlementTest extends FreeColTestCase {

// Colony now has enough equipment
colony.addGoods(musketsType, 10);
- assertTrue(colony.canProvideGoods(soldierRole.getRequiredGoodsList()));
+ assertTrue(colony.canProvideGoods(soldierRole.getRequiredGoods()));
assertEquals(soldierRole,
colony.canImproveUnitMilitaryRole(colonist));

diff --git a/test/src/net/sf/freecol/common/model/SpecificationTest.java b/test/src/net/sf/freecol/common/model/SpecificationTest.java
index 3a525179896..c780916dad5 100644
--- a/test/src/net/sf/freecol/common/model/SpecificationTest.java
+++ b/test/src/net/sf/freecol/common/model/SpecificationTest.java
@@ -292,57 +292,57 @@ public final class SpecificationTest extends FreeColTestCase {
Role role;
role = spec.getRole("model.role.default");
assertNotNull(role);
- checkGoods(role.getId(), role.getRequiredGoodsList());
+ checkGoods(role.getId(), role.getRequiredGoods());

role = spec.getRole("model.role.scout");
assertNotNull(role);
- checkGoods(role.getId(), role.getRequiredGoodsList(),
+ checkGoods(role.getId(), role.getRequiredGoods(),
new AbstractGoods(horsesType, 50));

role = spec.getRole("model.role.soldier");
assertNotNull(role);
- checkGoods(role.getId(), role.getRequiredGoodsList(),
+ checkGoods(role.getId(), role.getRequiredGoods(),
new AbstractGoods(musketsType, 50));

role = spec.getRole("model.role.dragoon");
assertNotNull(role);
- checkGoods(role.getId(), role.getRequiredGoodsList(),
+ checkGoods(role.getId(), role.getRequiredGoods(),
new AbstractGoods(horsesType, 50),
new AbstractGoods(musketsType, 50));

role = spec.getRole("model.role.pioneer");
assertNotNull(role);
- checkGoods(role.getId(), role.getRequiredGoodsList(),
+ checkGoods(role.getId(), role.getRequiredGoods(),
new AbstractGoods(toolsType, 20));

role = spec.getRole("model.role.missionary");
assertNotNull(role);
- checkGoods(role.getId(), role.getRequiredGoodsList());
+ checkGoods(role.getId(), role.getRequiredGoods());

role = spec.getRole("model.role.infantry");
assertNotNull(role);
- checkGoods(role.getId(), role.getRequiredGoodsList(),
+ checkGoods(role.getId(), role.getRequiredGoods(),
new AbstractGoods(musketsType, 50));

role = spec.getRole("model.role.cavalry");
assertNotNull(role);
- checkGoods(role.getId(), role.getRequiredGoodsList(),
+ checkGoods(role.getId(), role.getRequiredGoods(),
new AbstractGoods(horsesType, 50),
new AbstractGoods(musketsType, 50));

role = spec.getRole("model.role.mountedBrave");
assertNotNull(role);
- checkGoods(role.getId(), role.getRequiredGoodsList(),
+ checkGoods(role.getId(), role.getRequiredGoods(),
new AbstractGoods(horsesType, 25));

role = spec.getRole("model.role.armedBrave");
assertNotNull(role);
- checkGoods(role.getId(), role.getRequiredGoodsList(),
+ checkGoods(role.getId(), role.getRequiredGoods(),
new AbstractGoods(musketsType, 25));

role = spec.getRole("model.role.nativeDragoon");
assertNotNull(role);
- checkGoods(role.getId(), role.getRequiredGoodsList(),
+ checkGoods(role.getId(), role.getRequiredGoods(),
new AbstractGoods(horsesType, 25),
new AbstractGoods(musketsType, 25));
}
diff --git a/test/src/net/sf/freecol/server/ai/StandardAIPlayerTest.java b/test/src/net/sf/freecol/server/ai/StandardAIPlayerTest.java
index 0036eb60b5c..ccbe48052ab 100644
--- a/test/src/net/sf/freecol/server/ai/StandardAIPlayerTest.java
+++ b/test/src/net/sf/freecol/server/ai/StandardAIPlayerTest.java
@@ -52,7 +52,7 @@ public class StandardAIPlayerTest extends FreeColTestCase {
}

private void setupNativeDragoons() {
- for (AbstractGoods ag : nativeDragoonRole.getRequiredGoodsList()) {
+ for (AbstractGoods ag : nativeDragoonRole.getRequiredGoods()) {
if (ag.getType() == horsesType) {
horsesReqPerUnit = ag.getAmount();
} else if (ag.getType() == musketsType) {
diff --git a/test/src/net/sf/freecol/server/ai/mission/PioneeringMissionTest.java b/test/src/net/sf/freecol/server/ai/mission/PioneeringMissionTest.java
index 9dfdde11024..2cf42cc3529 100644
--- a/test/src/net/sf/freecol/server/ai/mission/PioneeringMissionTest.java
+++ b/test/src/net/sf/freecol/server/ai/mission/PioneeringMissionTest.java
@@ -101,7 +101,7 @@ public class PioneeringMissionTest extends FreeColTestCase {
// Add some tools to the colony, mission should become viable.
colony.addGoods(toolsGoodsType, 100);
assertTrue("Colony can provide tools",
- colony.canProvideGoods(pioneerRole.getRequiredGoodsList()));
+ colony.canProvideGoods(pioneerRole.getRequiredGoods()));
assertEquals("Colony found", colony,
PioneeringMission.findTarget(aiUnit, 10, false));
assertNull("Pioneer has no mission",
diff --git a/test/src/net/sf/freecol/server/control/InGameControllerTest.java b/test/src/net/sf/freecol/server/control/InGameControllerTest.java
index 4804ec76ac6..0fdd03d45ad 100644
--- a/test/src/net/sf/freecol/server/control/InGameControllerTest.java
+++ b/test/src/net/sf/freecol/server/control/InGameControllerTest.java
@@ -961,7 +961,7 @@ public class InGameControllerTest extends FreeColTestCase {
dutch.addFather(spec()
.getFoundingFather("model.foundingFather.paulRevere"));
java.util.Map<GoodsType,Integer> goodsAdded = new HashMap<>();
- for (AbstractGoods goods : soldierRole.getRequiredGoodsList()) {
+ for (AbstractGoods goods : soldierRole.getRequiredGoods()) {
colony.addGoods(goods);
goodsAdded.put(goods.getType(), goods.getAmount());
}
@@ -978,7 +978,7 @@ public class InGameControllerTest extends FreeColTestCase {
colonist.isDisposed());
assertFalse("Colonist should not be captured",
colonist.getOwner() == attacker.getOwner());
- for (AbstractGoods goods : soldierRole.getRequiredGoodsList()) {
+ for (AbstractGoods goods : soldierRole.getRequiredGoods()) {
boolean goodsLost = colony.getGoodsCount(goods.getType())
< goodsAdded.get(goods.getType());
assertTrue("Colony should have lost " + goods.getType().toString(),
@@ -1736,7 +1736,7 @@ public class InGameControllerTest extends FreeColTestCase {
= new FreeColTestCase.IndianSettlementBuilder(game);
IndianSettlement camp = builder.build();
ServerPlayer indian = (ServerPlayer)camp.getOwner();
- List<AbstractGoods> required = nativeDragoonRole.getRequiredGoodsList();
+ List<AbstractGoods> required = nativeDragoonRole.getRequiredGoods();
int horsesReqPerUnit = AbstractGoods.getCount(horsesType, required);
int musketsReqPerUnit = AbstractGoods.getCount(musketsType, required);

@@ -1787,7 +1787,7 @@ public class InGameControllerTest extends FreeColTestCase {
= new FreeColTestCase.IndianSettlementBuilder(game);
IndianSettlement camp = builder.build();

- List<AbstractGoods> required = mountedBraveRole.getRequiredGoodsList();
+ List<AbstractGoods> required = mountedBraveRole.getRequiredGoods();
int horsesReq = AbstractGoods.getCount(horsesType, required);
int musketsReq = AbstractGoods.getCount(musketsType, required);

diff --git a/test/src/net/sf/freecol/server/model/ServerColonyTest.java b/test/src/net/sf/freecol/server/model/ServerColonyTest.java
index 699e6f89aff..2e89683576f 100644
--- a/test/src/net/sf/freecol/server/model/ServerColonyTest.java
+++ b/test/src/net/sf/freecol/server/model/ServerColonyTest.java
@@ -259,7 +259,7 @@ public class ServerColonyTest extends FreeColTestCase {
Unit unit = new ServerUnit(game, colony.getTile(), colony.getOwner(),
colonistType);
unit.setLocation(colony);
- for (AbstractGoods ag : lumberMillType.getRequiredGoodsList()) {
+ for (AbstractGoods ag : lumberMillType.getRequiredGoods()) {
GoodsType type = ag.getType();
int amount = ag.getAmount() + 1;
colony.addGoods(type, amount);
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:50 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Unit.java | 23 +++++++++++++----------
1 file changed, 13 insertions(+), 10 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index 577341356f6..0660ebe3ac4 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -98,14 +98,6 @@ public class Unit extends GoodsLocation
public static final Comparator<Unit> decreasingSkillComparator
= increasingSkillComparator.reversed();

- /**
- * Comparator to rank settlements by accessibility by sea to Europe.
- */
- private static final Comparator<Settlement> settlementStartComparator
- = cachingIntComparator(s ->
- (s == null || !s.getTile().isHighSeasConnected()) ? INFINITY
- : s.getTile().getHighSeasCount());
-
/** A state a Unit can have. */
public static enum UnitState {
ACTIVE,
@@ -2634,8 +2626,19 @@ public class Unit extends GoodsLocation
// Must be a land unit not on the map. May have a carrier.
// Get our nearest settlement to Europe, fallback to any other.
final Player owner = getOwner();
- Settlement sett = minimize(owner.getSettlements(),
- settlementStartComparator);
+ Settlement sett = null;
+ int sett_dist = INFINITY;
+ for (Settlement s : owner.getSettlements()) {
+ int hsc = s.getTile().getHighSeasCount();
+ int dist = (hsc < 0 ? INFINITY : hsc);
+
+ if ((sett == null) || (dist < sett_dist)) {
+ sett = s;
+ sett_dist = dist;
+ continue;
+ }
+ }
+
if (sett == null) sett = owner.getFirstSettlement();
if (sett != null) return sett;
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:13 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Unit.java | 51 +++++++++++++++++++++++--------
1 file changed, 38 insertions(+), 13 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Unit.java b/src/net/sf/freecol/common/model/Unit.java
index d49e7a004e6..ee066fffa0f 100644
--- a/src/net/sf/freecol/common/model/Unit.java
+++ b/src/net/sf/freecol/common/model/Unit.java
@@ -47,6 +47,7 @@ import net.sf.freecol.common.option.GameOptions;
import net.sf.freecol.common.networking.DOMMessage;
import static net.sf.freecol.common.util.CollectionUtils.*;
import static net.sf.freecol.common.util.StringUtils.*;
+import net.sf.freecol.common.model.Role.RoleChange;


/**
@@ -887,8 +888,10 @@ public class Unit extends GoodsLocation
* @return A military {@code Role}, or null if none found.
*/
public Role getMilitaryRole() {
- return first(transform(getSpecification().getMilitaryRoles(),
- r -> roleIsAvailable(r)));
+ for (Role r : getSpecification().getMilitaryRoles())
+ if (roleIsAvailable(r))
+ return r;
+ return null;
}

/**
@@ -1743,11 +1746,14 @@ public class Unit extends GoodsLocation
if (settlement == null) return null;

final Specification spec = getSpecification();
- return find(transform(flatten(getAbilities(Ability.AUTOMATIC_EQUIPMENT),
- Ability::getScopes),
- alwaysTrue(), s -> spec.getRole(s.getType())),
- r -> r != null
- && settlement.containsGoods(getGoodsDifference(r, 1)));
+ for (Ability a : getAbilities(Ability.AUTOMATIC_EQUIPMENT))
+ for (Scope s : a.getScopes()) {
+ Role r = spec.getRole(s.getType());
+ if (r != null && settlement.containsGoods(getGoodsDifference(r, 1)))
+ return r;
+ }
+
+ return null;
}

/**
@@ -1762,9 +1768,13 @@ public class Unit extends GoodsLocation
if (!hasAbility(Ability.CAPTURE_EQUIPMENT)) return null;
final Specification spec = getSpecification();
final Role oldRole = getRole();
- return find(getAvailableRoles(spec.getMilitaryRoles()),
- r -> any(r.getRoleChanges(), rc ->
- rc.getFrom(spec) == oldRole && rc.getCapture(spec) == role));
+
+ for (Role r : getAvailableRoles(spec.getMilitaryRoles()))
+ for (RoleChange rc : r.getRoleChanges())
+ if (rc.getFrom(spec) == oldRole && rc.getCapture(spec) == role)
+ return r;
+
+ return null;
}

/**
@@ -2663,9 +2673,15 @@ public class Unit extends GoodsLocation

// Desperately find the nearest land to the entry location.
Location loc = getFullEntryLocation();
- return (loc == null || loc.getTile() == null) ? null
- : find(loc.getTile().getSurroundingTiles(1, INFINITY),
- Tile::isLand);
+
+ if (loc != null && loc.getTile() != null)
+ return null;
+
+ for (Tile t : loc.getTile().getSurroundingTiles(1, INFINITY))
+ if (t.isLand())
+ return t;
+
+ return null;
}

/**
@@ -3283,6 +3299,15 @@ public class Unit extends GoodsLocation
}

/**
+ * Can this unit take more goods
+ *
+ * @return True if the unit can carry goods and has space
+ */
+ public final boolean canTakeGoods() {
+ return hasAbility(Ability.CARRY_GOODS) && hasSpaceLeft();
+ }
+
+ /**
* Could this unit carry some specified goods?
* This ignores the current load.
*
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:28 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/option/ListOption.java | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/net/sf/freecol/common/option/ListOption.java b/src/net/sf/freecol/common/option/ListOption.java
index feee2ccf689..6d303dbdead 100644
--- a/src/net/sf/freecol/common/option/ListOption.java
+++ b/src/net/sf/freecol/common/option/ListOption.java
@@ -137,7 +137,11 @@ public abstract class ListOption<T> extends AbstractOption<List<AbstractOption<T
* @return True if the option can be added.
*/
public boolean canAdd(AbstractOption<T> ao) {
- return (allowDuplicates) ? true : none(value, matchKey(ao));
+ if (!allowDuplicates)
+ for (AbstractOption<T> walk : value)
+ if (walk == ao)
+ return false;
+ return true;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:45 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Colony.java | 13 +++++++++----
src/net/sf/freecol/common/model/Tile.java | 8 ++++----
src/net/sf/freecol/common/model/TileImprovement.java | 7 +++----
src/net/sf/freecol/common/model/TileImprovementType.java | 12 ++++++------
src/net/sf/freecol/common/model/TileType.java | 12 ++++++------
5 files changed, 28 insertions(+), 24 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index cd62183f987..0fd5cfc0c2b 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -929,13 +929,18 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* colony. This list comprises all natural disasters that can
* strike the colony's tiles.
*
- * @return A stream of {@code Disaster}s.
+ * @param result List to fill results into {@code Disaster}s.
*/
- public Stream<RandomChoice<Disaster>> getDisasterChoices() {
- return flatten(getColonyTiles(),
- ct -> ct.getWorkTile().getDisasterChoices());
+ public void getDisasterChoices(List<RandomChoice<Disaster>> result) {
+ for (ColonyTile ct : getColonyTiles())
+ ct.getWorkTile().getDisasterChoices(result);
}

+ public List<RandomChoice<Disaster>> getDisasterChoices() {
+ List<RandomChoice<Disaster>> result = new ArrayList<>();
+ getDisasterChoices(result);
+ return result;
+ }

// What are we building? What can we build?

diff --git a/src/net/sf/freecol/common/model/Tile.java b/src/net/sf/freecol/common/model/Tile.java
index ecbef32a9a5..ed0957a15d0 100644
--- a/src/net/sf/freecol/common/model/Tile.java
+++ b/src/net/sf/freecol/common/model/Tile.java
@@ -1006,10 +1006,10 @@ public final class Tile extends UnitLocation implements Named, Ownable {
*
* @return A stream of {@code Disaster} choices.
*/
- public Stream<RandomChoice<Disaster>> getDisasterChoices() {
- return concat(type.getDisasterChoices(),
- flatten(getCompleteTileImprovements(),
- ti -> ti.getDisasterChoices()));
+ public void getDisasterChoices(List<RandomChoice<Disaster>> result) {
+ type.getDisasterChoices(result);
+ for (TileImprovement ti : getCompleteTileImprovements())
+ ti.getDisasterChoices(result);
}


diff --git a/src/net/sf/freecol/common/model/TileImprovement.java b/src/net/sf/freecol/common/model/TileImprovement.java
index 4093d939f73..e04804c782e 100644
--- a/src/net/sf/freecol/common/model/TileImprovement.java
+++ b/src/net/sf/freecol/common/model/TileImprovement.java
@@ -431,10 +431,9 @@ public class TileImprovement extends TileItem implements Named {
*
* @return A stream of {@code Disaster} choices.
*/
- public Stream<RandomChoice<Disaster>> getDisasterChoices() {
- return (this.type == null)
- ? Stream.<RandomChoice<Disaster>>empty()
- : this.type.getDisasterChoices();
+ public void getDisasterChoices(List<RandomChoice<Disaster>> result) {
+ if (this.type != null)
+ this.type.getDisasterChoices(result);
}


diff --git a/src/net/sf/freecol/common/model/TileImprovementType.java b/src/net/sf/freecol/common/model/TileImprovementType.java
index 50c18c4a689..85792d37afd 100644
--- a/src/net/sf/freecol/common/model/TileImprovementType.java
+++ b/src/net/sf/freecol/common/model/TileImprovementType.java
@@ -26,7 +26,6 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-import java.util.stream.Stream;

import javax.xml.stream.XMLStreamException;

@@ -178,10 +177,9 @@ public final class TileImprovementType extends FreeColSpecObjectType {
*
* @return A stream of {@code Disaster} choices.
*/
- public Stream<RandomChoice<Disaster>> getDisasterChoices() {
- return (disasters == null)
- ? Stream.<RandomChoice<Disaster>>empty()
- : disasters.stream();
+ public void getDisasterChoices(List<RandomChoice<Disaster>> result) {
+ if (disasters != null)
+ result.addAll(disasters);
}

/**
@@ -471,7 +469,9 @@ public final class TileImprovementType extends FreeColSpecObjectType {
}
}

- for (RandomChoice<Disaster> choice : iterable(getDisasterChoices())) {
+ List<RandomChoice<Disaster>> desasters = new ArrayList<>();
+ getDisasterChoices(desasters);
+ for (RandomChoice<Disaster> choice : desasters) {
xw.writeStartElement(DISASTER_TAG);

xw.writeAttribute(ID_ATTRIBUTE_TAG, choice.getObject().getId());
diff --git a/src/net/sf/freecol/common/model/TileType.java b/src/net/sf/freecol/common/model/TileType.java
index 860b36c4371..e0e50d35a5d 100644
--- a/src/net/sf/freecol/common/model/TileType.java
+++ b/src/net/sf/freecol/common/model/TileType.java
@@ -22,7 +22,6 @@ package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-import java.util.stream.Stream;

import javax.xml.stream.XMLStreamException;

@@ -262,10 +261,9 @@ public final class TileType extends FreeColSpecObjectType
*
* @return A stream of {@code Disaster} choices.
*/
- public Stream<RandomChoice<Disaster>> getDisasterChoices() {
- return (this.disasters == null)
- ? Stream.<RandomChoice<Disaster>>empty()
- : disasters.stream();
+ public void getDisasterChoices(List<RandomChoice<Disaster>> result) {
+ if (disasters != null)
+ result.addAll(disasters);
}

/**
@@ -474,7 +472,9 @@ public final class TileType extends FreeColSpecObjectType
xw.writeEndElement();
}

- for (RandomChoice<Disaster> choice : iterable(getDisasterChoices())) {
+ List<RandomChoice<Disaster>> desasters = new ArrayList<>();
+ getDisasterChoices(desasters);
+ for (RandomChoice<Disaster> choice : desasters) {
xw.writeStartElement(DISASTER_TAG);

xw.writeAttribute(ID_ATTRIBUTE_TAG, choice.getObject());
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:33 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
.../sf/freecol/common/util/CollectionUtils.java | 42 ++++------------------
1 file changed, 6 insertions(+), 36 deletions(-)

diff --git a/src/net/sf/freecol/common/util/CollectionUtils.java b/src/net/sf/freecol/common/util/CollectionUtils.java
index 03a7cf47c7f..f6a1e05bb11 100644
--- a/src/net/sf/freecol/common/util/CollectionUtils.java
+++ b/src/net/sf/freecol/common/util/CollectionUtils.java
@@ -19,6 +19,7 @@

package net.sf.freecol.common.util;

+import java.lang.Iterable;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
@@ -668,49 +669,18 @@ public class CollectionUtils {
}

/**
- * Dump an array to {@code System.err}.
- *
- * @param <T> The collection to dump
- * @param header Optional informational string to print first.
- * @param array The array to dump.
- */
- public static <T> void dump(String header, T[] array) {
- dump_internal(header, Arrays.stream(array));
- }
-
- /**
- * Dump a collection to {@code System.err}.
- *
- * @param header Optional informational string to print first.
- * @param c The {@code Collection} to print.
- */
- public static void dump(String header, Collection<?> c) {
- dump_internal(header, c.stream());
- }
-
- /**
- * Dump a stream to {@code System.err}.
- *
- * @param header Optional informational string to print first.
- * @param stream The {@code Stream} to print.
- */
- public static void dump(String header, Stream<?> stream) {
- dump_internal(header, stream);
- }
-
- /**
* Implement dump().
*
* @param header Optional informational string to print first.
* @param stream The {@code Stream} to print.
*/
- private static void dump_internal(String header, Stream<?> stream) {
+ private static <T> void dump(String header, Iterable<T> it) {
if (header != null) System.err.print(header);
System.err.print("[ ");
- forEach(stream, (v) -> {
+ for (T v : it) {
System.err.print(v);
System.err.print(' ');
- });
+ }
System.err.println(']');
}

@@ -723,12 +693,12 @@ public class CollectionUtils {
public static void dump(String header, Map<?,?> map) {
if (header != null) System.err.print(header);
System.err.print("[ ");
- forEachMapEntry(map, (e) -> {
+ for (Entry<?,?> e : map.entrySet()) {
System.err.print(e.getKey());
System.err.print(',');
System.err.print(e.getValue());
System.err.print(' ');
- });
+ }
System.err.println(']');
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:58 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/ProductionType.java | 17 +++++++++++------
1 file changed, 11 insertions(+), 6 deletions(-)

diff --git a/src/net/sf/freecol/common/model/ProductionType.java b/src/net/sf/freecol/common/model/ProductionType.java
index 58d1469f5db..0f7e8e8964f 100644
--- a/src/net/sf/freecol/common/model/ProductionType.java
+++ b/src/net/sf/freecol/common/model/ProductionType.java
@@ -257,12 +257,17 @@ public class ProductionType extends FreeColSpecObject {
* @return The {@code GoodsType} of the most productive output.
*/
public GoodsType getBestOutputType() {
- AbstractGoods goods;
- return (outputs == null
- || (goods = maximize(outputs,
- AbstractGoods.ascendingAmountComparator)) == null)
- ? null
- : goods.getType();
+ if (outputs == null) return null;
+ GoodsType best_type = null;
+ int best_amount = 0;
+ for (AbstractGoods ag : outputs) {
+ int amount = ag.getAmount();
+ if ((best_type == null) || (amount > best_amount)) {
+ best_amount = amount;
+ best_type = ag.getType();
+ }
+ }
+ return best_type;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:40 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/networking/Message.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/net/sf/freecol/common/networking/Message.java b/src/net/sf/freecol/common/networking/Message.java
index e9494420a92..611bc228251 100644
--- a/src/net/sf/freecol/common/networking/Message.java
+++ b/src/net/sf/freecol/common/networking/Message.java
@@ -182,8 +182,8 @@ public abstract class Message {
* @param attributes The map of key,value pairs to set.
*/
public void setStringAttributes(Map<String, String> attributes) {
- forEachMapEntry(attributes,
- e -> setStringAttribute(e.getKey(), e.getValue()));
+ for (Map.Entry<String, String> e : attributes.entrySet())
+ setStringAttribute(e.getKey(), e.getValue());
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:03 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Force.java | 22 ++++++++++++++++------
1 file changed, 16 insertions(+), 6 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Force.java b/src/net/sf/freecol/common/model/Force.java
index a4872c1c6fe..4550b896232 100644
--- a/src/net/sf/freecol/common/model/Force.java
+++ b/src/net/sf/freecol/common/model/Force.java
@@ -22,7 +22,6 @@ package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
-import java.util.function.Predicate;

import javax.xml.stream.XMLStreamException;

@@ -183,12 +182,16 @@ public class Force extends FreeColSpecObject {
final Specification spec = getSpecification();
final UnitType unitType = au.getType(spec);
final int n = au.getNumber();
- final Predicate<AbstractUnit> matchPred = a ->
- spec.getUnitType(a.getId()) == unitType
- && a.getRoleId().equals(au.getRoleId());

if (unitType.hasAbility(Ability.NAVAL_UNIT)) {
- AbstractUnit refUnit = find(this.navalUnits, matchPred);
+ AbstractUnit refUnit = null;
+ for (AbstractUnit a : this.navalUnits) {
+ if (spec.getUnitType(a.getId()) == unitType
+ && a.getRoleId().equals(au.getRoleId())) {
+ refUnit = a;
+ break;
+ }
+ }
if (refUnit != null) {
refUnit.setNumber(refUnit.getNumber() + n);
if (unitType.canCarryUnits()) {
@@ -198,7 +201,14 @@ public class Force extends FreeColSpecObject {
this.navalUnits.add(au);
}
} else {
- AbstractUnit refUnit = find(this.landUnits, matchPred);
+ AbstractUnit refUnit = null;
+ for (AbstractUnit a : this.landUnits) {
+ if (spec.getUnitType(a.getId()) == unitType
+ && a.getRoleId().equals(au.getRoleId())) {
+ refUnit = a;
+ break;
+ }
+ }
if (refUnit != null) {
refUnit.setNumber(refUnit.getNumber() + n);
this.spaceRequired += unitType.getSpaceTaken() * n;
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:01 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/DiplomaticTrade.java | 19 ++++++++++++-------
1 file changed, 12 insertions(+), 7 deletions(-)

diff --git a/src/net/sf/freecol/common/model/DiplomaticTrade.java b/src/net/sf/freecol/common/model/DiplomaticTrade.java
index ffb78d5805c..b8150676a4c 100644
--- a/src/net/sf/freecol/common/model/DiplomaticTrade.java
+++ b/src/net/sf/freecol/common/model/DiplomaticTrade.java
@@ -323,8 +323,10 @@ public class DiplomaticTrade extends FreeColGameObject {
* @return The {@code Stance} offered in this trade, or null if none.
*/
public Stance getStance() {
- TradeItem ti = find(this.items, i -> i instanceof StanceTradeItem);
- return (ti == null) ? null : ti.getStance();
+ for (TradeItem ti : this.items)
+ if (ti instanceof StanceTradeItem)
+ return ti.getStance();
+ return null;
}

/**
@@ -349,9 +351,10 @@ public class DiplomaticTrade extends FreeColGameObject {
* @return The gold offered in this trade.
*/
public int getGoldGivenBy(Player player) {
- TradeItem ti = find(this.items, i -> i instanceof GoldTradeItem
- && player == i.getSource());
- return (ti == null) ? -1 : ti.getGold();
+ for (TradeItem ti : this.items)
+ if ((ti instanceof GoldTradeItem) && (player == ti.getSource()))
+ return ti.getGold();
+ return -1;
}

/**
@@ -373,8 +376,10 @@ public class DiplomaticTrade extends FreeColGameObject {
* @return The {@code Player} to be incited against.
*/
public Player getVictim() {
- TradeItem ti = find(this.items, i -> i instanceof InciteTradeItem);
- return (ti == null) ? null : ti.getVictim();
+ for (TradeItem ti : this.items)
+ if (ti instanceof InciteTradeItem)
+ return ti.getVictim();
+ return null;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:31:59 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/AbstractGoods.java | 14 +++++---------
1 file changed, 5 insertions(+), 9 deletions(-)

diff --git a/src/net/sf/freecol/common/model/AbstractGoods.java b/src/net/sf/freecol/common/model/AbstractGoods.java
index 5d2e67ca790..6b264951ba9 100644
--- a/src/net/sf/freecol/common/model/AbstractGoods.java
+++ b/src/net/sf/freecol/common/model/AbstractGoods.java
@@ -249,25 +249,21 @@ public class AbstractGoods extends FreeColObject implements Named {
}

/**
- * find any in list by type
+ * find any in list with positive amount
*/
- public static AbstractGoods findByType(List<AbstractGoods> l, GoodsType gt) {
+ public static AbstractGoods findPositive(List<AbstractGoods> l) {
if (l != null)
for (AbstractGoods ag : l)
- if (ag.getType() == gt)
+ if (ag.amount > 0)
return ag;

- return false;
- }
-
- public static AbstractGoods findByType(List<AbstractGoods> l, AbstractGoods ag) {
- return findByType(l, ag.getType());
+ return null;
}

/**
* find any in list by type
*/
- public static AbstractGoods findByType(List<AbstractGoods> l, GoodsType gt) {
+ public static AbstractGoods findByType(List<? extends AbstractGoods> l, GoodsType gt) {
if (l != null)
for (AbstractGoods ag : l)
if (ag.getType() == gt)
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:00 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Colony.java | 58 +++++++++++++++++++----------
1 file changed, 39 insertions(+), 19 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index dcf6e936bd5..86107881814 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -237,7 +237,12 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return The corresponding {@code ColonyTile}, or null if not found.
*/
public ColonyTile getColonyTile(Tile tile) {
- return find(getColonyTiles(), matchKey(tile, ColonyTile::getWorkTile));
+ synchronized (this.colonyTiles) {
+ for (ColonyTile t : colonyTiles)
+ if (tile == t.getWorkTile())
+ return t;
+ }
+ return null;
}

/**
@@ -1876,9 +1881,11 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return {@code true} if this unit type could be added.
*/
public boolean canTrain(UnitType unitType) {
- return hasAbility(Ability.TEACH)
- && any(getBuildings(),
- b -> b.canTeach() && b.canAddType(unitType));
+ if (hasAbility(Ability.TEACH))
+ for (Building b : getBuildings())
+ if (b.canTeach() && b.canAddType(unitType))
+ return true;
+ return false;
}

/**
@@ -1904,11 +1911,13 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return A potential teacher, or null of none found.
*/
public Unit findTeacher(Unit student) {
- return (getSpecification().getBoolean(GameOptions.ALLOW_STUDENT_SELECTION))
- ? null // No automatic assignment
- : find(flatten(getBuildings(), Building::canTeach,
- Building::getUnits),
- u -> u.getStudent() == null);
+ if (!getSpecification().getBoolean(GameOptions.ALLOW_STUDENT_SELECTION))
+ for (Building b : getBuildings())
+ if (b.canTeach())
+ for (Unit u : b.getUnits())
+ if (u.getStudent() == null)
+ return u;
+ return null;
}

/**
@@ -2509,16 +2518,27 @@ loop: for (WorkLocation wl : getWorkLocationsForProducing(goodsType)) {
@SuppressWarnings("unchecked")
public <T extends FreeColObject> T getCorresponding(T fco) {
final String id = fco.getId();
- return (fco instanceof WorkLocation)
- ? (T)findWorkLocationById(id)
- : (fco instanceof Tile)
- ? (T)((getTile().getId().equals(id)) ? getTile()
- : find(map(getColonyTiles(), ColonyTile::getWorkTile),
- matchKeyEquals(id, Tile::getId)))
- : (fco instanceof Unit)
- ? (T)find(getAllUnits(),
- matchKeyEquals(id, Unit::getId))
- : null;
+
+ if (fco instanceof WorkLocation)
+ return (T)findWorkLocationById(id);
+ else if (fco instanceof Tile) {
+ Tile t = getTile();
+ if (t.getId().equals(id))
+ return (T)t;
+
+ for (ColonyTile ct : getColonyTiles()) {
+ t = ct.getWorkTile();
+ if (Utils.equals(id, t.getId()))
+ return (T)t;
+ }
+ }
+ else if (fco instanceof Unit) {
+ for (Unit u : getAllUnits())
+ if (Utils.equals(id, u.getId()))
+ return (T)u;
+ }
+
+ return null;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:38 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

The current implementation of thee disposable list generation goes a long
detour, building up a long chain of (mostly single-item) streams. IOW:
at lot of allocations and a long linked-list. Finally that's then serialized
into an plain list anyways.

So, just turn it around: let the getDisposable() methods fill in their
items into a given list and forget about streams at all.
---
src/net/sf/freecol/common/model/Colony.java | 14 ++++++++++----
.../sf/freecol/common/model/FreeColGameObject.java | 13 ++++++++-----
src/net/sf/freecol/common/model/GoodsLocation.java | 10 +++++-----
src/net/sf/freecol/common/model/UnitLocation.java | 8 ++++----
src/net/sf/freecol/common/networking/ChangeSet.java | 21 ++++++++++++++-------
5 files changed, 41 insertions(+), 25 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index 67f1a307dad..83491089da1 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -2557,10 +2557,16 @@ loop: for (WorkLocation wl : getWorkLocationsForProducing(goodsType)) {
* {@inheritDoc}
*/
@Override
- public Stream<FreeColGameObject> getDisposables() {
- return concat(flatten(getAllWorkLocations(),
- WorkLocation::getDisposables),
- super.getDisposables());
+ public void getDisposables(List<FreeColGameObject> list) {
+ synchronized (this.colonyTiles) {
+ for (ColonyTile walk : this.colonyTiles)
+ walk.getDisposables(list);
+ }
+ synchronized (this.buildingMap) {
+ for (Building walk : this.buildingMap.values())
+ walk.getDisposables(list);
+ }
+ super.getDisposables(list);
}


diff --git a/src/net/sf/freecol/common/model/FreeColGameObject.java b/src/net/sf/freecol/common/model/FreeColGameObject.java
index e7626cb6bad..f6ebdce1afa 100644
--- a/src/net/sf/freecol/common/model/FreeColGameObject.java
+++ b/src/net/sf/freecol/common/model/FreeColGameObject.java
@@ -21,7 +21,8 @@ package net.sf.freecol.common.model;

import java.util.logging.Level;
import java.util.logging.Logger;
-import java.util.stream.Stream;
+import java.util.ArrayList;
+import java.util.List;

import javax.xml.stream.XMLStreamException;

@@ -174,7 +175,9 @@ public abstract class FreeColGameObject extends FreeColObject {
if (this.disposed) return;
LogBuilder lb = new LogBuilder(64);
lb.add("Destroying:");
- for (FreeColGameObject fcgo : toList(getDisposables())) {
+ List<FreeColGameObject> dl = new ArrayList<>();
+ getDisposables(dl);
+ for (FreeColGameObject fcgo : dl) {
lb.add(" ", fcgo.getId());
fcgo.disposeResources();
}
@@ -212,10 +215,10 @@ public abstract class FreeColGameObject extends FreeColObject {
* Overriding routines should call upwards towards this routine,
* arranging that the object itself is last.
*
- * @return A stream of {@code FreeColGameObject}s to dispose of.
+ * @param dl target list to fill elements into
*/
- public Stream<FreeColGameObject> getDisposables() {
- return Stream.of(this);
+ public void getDisposables(List<FreeColGameObject> dl) {
+ dl.add(this);
}

/**
diff --git a/src/net/sf/freecol/common/model/GoodsLocation.java b/src/net/sf/freecol/common/model/GoodsLocation.java
index cc9917784e1..13a8e9e89f1 100644
--- a/src/net/sf/freecol/common/model/GoodsLocation.java
+++ b/src/net/sf/freecol/common/model/GoodsLocation.java
@@ -22,7 +22,6 @@ package net.sf.freecol.common.model;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
-import java.util.stream.Stream;

import javax.xml.stream.XMLStreamException;

@@ -303,10 +302,11 @@ public abstract class GoodsLocation extends UnitLocation {
* {@inheritDoc}
*/
@Override
- public Stream<FreeColGameObject> getDisposables() {
- Stream<FreeColGameObject> up = super.getDisposables();
- return (this.goodsContainer == null) ? up
- : concat(this.goodsContainer.getDisposables(), up);
+ public void getDisposables(List<FreeColGameObject> dl) {
+ if (this.goodsContainer != null)
+ this.goodsContainer.getDisposables(dl);
+
+ super.getDisposables(dl);
}


diff --git a/src/net/sf/freecol/common/model/UnitLocation.java b/src/net/sf/freecol/common/model/UnitLocation.java
index 7bbbf03f480..a50758b38f1 100644
--- a/src/net/sf/freecol/common/model/UnitLocation.java
+++ b/src/net/sf/freecol/common/model/UnitLocation.java
@@ -23,7 +23,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
-import java.util.stream.Stream;

import javax.xml.stream.XMLStreamException;

@@ -263,11 +262,12 @@ public abstract class UnitLocation extends FreeColGameObject implements Location
* {@inheritDoc}
*/
@Override
- public Stream<FreeColGameObject> getDisposables() {
+ public void getDisposables(List<FreeColGameObject> dl) {
synchronized (this.units) {
- return concat(flatten(this.units, Unit::getDisposables),
- super.getDisposables());
+ for (Unit u : this.units)
+ u.getDisposables(dl);
}
+ super.getDisposables(dl);
}

/**
diff --git a/src/net/sf/freecol/common/networking/ChangeSet.java b/src/net/sf/freecol/common/networking/ChangeSet.java
index 48bef9f74cb..35234ff1536 100644
--- a/src/net/sf/freecol/common/networking/ChangeSet.java
+++ b/src/net/sf/freecol/common/networking/ChangeSet.java
@@ -24,7 +24,6 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
-import java.util.stream.Stream;

import net.sf.freecol.common.model.Ability;
import net.sf.freecol.common.model.Feature;
@@ -724,9 +723,11 @@ public class ChangeSet {
public List<Change> consequences(ServerPlayer serverPlayer) {
if (seeOld(serverPlayer) && !seeNew(serverPlayer)
&& !unit.isDisposed()) {
+ List<Unit> ul = new ArrayList<>();
+ ul.add(unit);
List<Change> changes = new ArrayList<>();
changes.add(new RemoveChange(See.only(serverPlayer),
- unit.getLocation(), Stream.of(unit)));
+ unit.getLocation(), ul));
return changes;
}
return Collections.<Change>emptyList();
@@ -1032,10 +1033,10 @@ public class ChangeSet {
* @param objects The {@code FreeColGameObject}s to remove.
*/
public RemoveChange(See see, Location loc,
- Stream<? extends FreeColGameObject> objects) {
+ List<? extends FreeColGameObject> objects) {
super(see);
this.tile = (loc instanceof Tile) ? (Tile)loc : null;
- this.contents = toList(objects);
+ this.contents = objects;
this.fcgo = this.contents.remove(this.contents.size() - 1);
}

@@ -1535,8 +1536,10 @@ public class ChangeSet {
*/
public ChangeSet addDisappear(ServerPlayer owner, Tile tile,
FreeColGameObject fcgo) {
+ List<FreeColGameObject> fl = new ArrayList<>();
+ fl.add(fcgo);
changes.add(new RemoveChange(See.perhaps().except(owner), tile,
- Stream.of(fcgo)));
+ fl));
changes.add(new ObjectChange(See.perhaps().except(owner), tile));
return this;
}
@@ -1716,7 +1719,9 @@ public class ChangeSet {
* @return The updated {@code ChangeSet}.
*/
public ChangeSet addRemove(See see, Location loc, FreeColGameObject obj) {
- changes.add(new RemoveChange(see, loc, obj.getDisposables()));//-vis
+ List<FreeColGameObject> dl = new ArrayList<>();
+ obj.getDisposables(dl);
+ changes.add(new RemoveChange(see, loc, dl));//-vis
return this;
}

@@ -1731,7 +1736,9 @@ public class ChangeSet {
public ChangeSet addRemoves(See see, Location loc,
List<? extends FreeColGameObject> objects) {
for (FreeColGameObject fcgo : objects) {
- changes.add(new RemoveChange(see, loc, fcgo.getDisposables()));
+ List<FreeColGameObject> dl = new ArrayList<>();
+ fcgo.getDisposables(dl);
+ changes.add(new RemoveChange(see, loc, dl));
}
return this;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:41 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/networking/ReceivingThread.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/net/sf/freecol/common/networking/ReceivingThread.java b/src/net/sf/freecol/common/networking/ReceivingThread.java
index 055b7d9ce01..d0d110aa2a1 100644
--- a/src/net/sf/freecol/common/networking/ReceivingThread.java
+++ b/src/net/sf/freecol/common/networking/ReceivingThread.java
@@ -272,7 +272,7 @@ final class ReceivingThread extends Thread {
}
}

- private Thread query(DOMMessage msg, final int replyId) {
+ private Thread query(final DOMMessage msg, final int replyId) {
return new Thread(this.connection.getName() + "-query-" + replyId + "-"
+ msg.getType()) {
@Override
@@ -291,7 +291,7 @@ final class ReceivingThread extends Thread {
};
}

- private Thread update(DOMMessage msg) {
+ private Thread update(final DOMMessage msg) {
return new Thread(this.connection.getName() + "-update-"
+ msg.getType()) {
@Override
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:36 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/i18n/DefaultNumberRule.java | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/src/net/sf/freecol/common/i18n/DefaultNumberRule.java b/src/net/sf/freecol/common/i18n/DefaultNumberRule.java
index 17e13859b14..be863ad44b4 100644
--- a/src/net/sf/freecol/common/i18n/DefaultNumberRule.java
+++ b/src/net/sf/freecol/common/i18n/DefaultNumberRule.java
@@ -77,8 +77,9 @@ public class DefaultNumberRule extends Number {
*/
@Override
public Category getCategory(double input) {
- return find(Category.values(),
- category -> rules.containsKey(category)
- && rules.get(category).matches(input), Category.other);
+ for (Category c : Category.values())
+ if (rules.containsKey(c) && rules.get(c).matches(input))
+ return c;
+ return Category.other;
}
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:43 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

[javac] /home/nekrad/src/packaging/pkg/freecol.git/src/net/sf/freecol/common/util/RandomUtils.java:148: error: incompatible types: Object cannot be converted to T
[javac] return (stream == null) ? null
[javac] ^
[javac] where T is a type-variable:
[javac] T extends Object declared in method <T>getRandomMember(Logger,String,Stream<T>,Random)
---
src/net/sf/freecol/common/util/RandomUtils.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/net/sf/freecol/common/util/RandomUtils.java b/src/net/sf/freecol/common/util/RandomUtils.java
index 58fcc584010..80be2d8bab8 100644
--- a/src/net/sf/freecol/common/util/RandomUtils.java
+++ b/src/net/sf/freecol/common/util/RandomUtils.java
@@ -147,7 +147,7 @@ public class RandomUtils {
Stream<T> stream, Random random) {
return (stream == null) ? null
: getRandomMember(logger, logMe,
- stream.collect(Collectors.toList()), random);
+ stream.collect(Collectors.<T>toList()), random);
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:08 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/SettlementType.java | 9 ++++++---
1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/src/net/sf/freecol/common/model/SettlementType.java b/src/net/sf/freecol/common/model/SettlementType.java
index 65e8adb2d0e..26a4778e7b6 100644
--- a/src/net/sf/freecol/common/model/SettlementType.java
+++ b/src/net/sf/freecol/common/model/SettlementType.java
@@ -216,9 +216,12 @@ public class SettlementType extends FreeColSpecObjectType {
* @return The plunder range, or null if none applicable.
*/
public final RandomRange getPlunderRange(Unit unit) {
- if (this.plunder == null) return null;
- PlunderType pt = find(plunder, p -> p.appliesTo(unit));
- return (pt == null) ? null : pt.getPlunder();
+ if (this.plunder != null)
+ for (PlunderType p : this.plunder)
+ if ((p != null) && p.appliesTo(unit))
+ return p.getPlunder();
+
+ return null;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:50 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/server/model/ServerGame.java | 32 ++++++++++++++++++-------
1 file changed, 23 insertions(+), 9 deletions(-)

diff --git a/src/net/sf/freecol/server/model/ServerGame.java b/src/net/sf/freecol/server/model/ServerGame.java
index a7bc9d8bb31..d2aed2cd7b0 100644
--- a/src/net/sf/freecol/server/model/ServerGame.java
+++ b/src/net/sf/freecol/server/model/ServerGame.java
@@ -255,19 +255,33 @@ public class ServerGame extends Game implements ServerModelObject {
public Player checkForWinner() {
final Specification spec = getSpecification();
if (spec.getBoolean(GameOptions.VICTORY_DEFEAT_REF)) {
- Player winner = find(getLiveEuropeanPlayers(),
- p -> p.getPlayerType() == Player.PlayerType.INDEPENDENT);
- if (winner != null) return winner;
+ for (Player winner : getLiveEuropeanPlayers())
+ if (winner.getPlayerType() == Player.PlayerType.INDEPENDENT)
+ return winner;
}
+
if (spec.getBoolean(GameOptions.VICTORY_DEFEAT_EUROPEANS)) {
- List<Player> winners = transform(getLiveEuropeanPlayers(),
- p -> !p.isREF());
- if (winners.size() == 1) return winners.get(0);
+ Player winner = null;
+ int count = 0;
+ for (Player p : getLiveEuropeanPlayers()) {
+ if (!p.isREF()) {
+ if (winner == null) winner = p;
+ count++;
+ }
+ }
+ if (count == 1) return winner;
}
+
if (spec.getBoolean(GameOptions.VICTORY_DEFEAT_HUMANS)) {
- List<Player> winners = transform(getLiveEuropeanPlayers(),
- p -> !p.isAI());
- if (winners.size() == 1) return winners.get(0);
+ Player winner = null;
+ int count = 0;
+ for (Player p : getLiveEuropeanPlayers()) {
+ if (!p.isAI()) {
+ if (winner == null) winner = p;
+ count++;
+ }
+ }
+ if (count == 1) return winner;
}
return null;
}
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:11 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/model/Tile.java | 27 +++++++++++++++++----------
1 file changed, 17 insertions(+), 10 deletions(-)

diff --git a/src/net/sf/freecol/common/model/Tile.java b/src/net/sf/freecol/common/model/Tile.java
index d524ed49f88..897fcc70acb 100644
--- a/src/net/sf/freecol/common/model/Tile.java
+++ b/src/net/sf/freecol/common/model/Tile.java
@@ -1408,8 +1408,10 @@ public final class Tile extends UnitLocation implements Named, Ownable {
* @return The most defensible adjacent land {@code Tile}.
*/
public Tile getBestDisembarkTile(Player player) {
- return find(getSafestSurroundingLandTiles(player),
- Tile::isHighSeasConnected);
+ for (Tile t : getSafestSurroundingLandTiles(player))
+ if (t.isHighSeasConnected())
+ return t;
+ return null;
}

/**
@@ -1809,10 +1811,12 @@ public final class Tile extends UnitLocation implements Named, Ownable {
* Update production after a change to this tile.
*/
private void updateColonyTiles() {
- WorkLocation wl = find(flatten(getGame().getAllColonies(null),
- Colony::getAvailableWorkLocations),
- matchKey(this, WorkLocation::getWorkTile));
- if (wl != null) wl.updateProductionType();
+ for (Colony c : getGame().getAllColonies(null))
+ for (WorkLocation wl : c.getAvailableWorkLocations())
+ if (wl.getWorkTile() == this) {
+ wl.updateProductionType();
+ break;
+ }
}

/**
@@ -2094,10 +2098,13 @@ public final class Tile extends UnitLocation implements Named, Ownable {
if (getOwningSettlement() != null) {
owner = getOwningSettlement().getOwner();
}
- return (owner != null && unit != null && unit.getOwner() != owner
- && unit.getOwner().atWarWith(owner))
- ? find(getUnits(), Unit::isOffensiveUnit)
- : null;
+
+ if (owner != null && unit != null && unit.getOwner() != owner
+ && unit.getOwner().atWarWith(owner))
+ for (Unit u : getUnits())
+ if (u.isOffensiveUnit()) return u;
+
+ return null;
}

/**
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:44 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/common/debug/DebugUtils.java | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/src/net/sf/freecol/common/debug/DebugUtils.java b/src/net/sf/freecol/common/debug/DebugUtils.java
index ed574b14554..01c82e8bbcc 100644
--- a/src/net/sf/freecol/common/debug/DebugUtils.java
+++ b/src/net/sf/freecol/common/debug/DebugUtils.java
@@ -23,6 +23,7 @@ import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
@@ -588,8 +589,14 @@ public class DebugUtils {
LogBuilder lb = new LogBuilder(256);
lb.add("Desynchronization detected\n");
lb.mark();
- sMap.forEachTile(t -> sPlayer.canSee(t),
- t -> checkDesyncTile(cGame, sPlayer, t, lb));
+
+ Iterator<Tile> iterator = cGame.getMap().getWholeMapIterator();
+ while (iterator.hasNext()) {
+ Tile t = iterator.next();
+ if (sPlayer.canSee(t))
+ checkDesyncTile(cGame, sPlayer, t, lb);
+ }
+
boolean problemDetected = lb.grew();
// Do not check goods amount, the server only sends changes to
// the client when the *price* changes.
--
2.11.0.rc0.7.gbe5a750
e***@gr13.net
2017-01-19 02:32:46 UTC
Permalink
From: "Enrico Weigelt, metux IT consult" <***@gr13.net>

---
src/net/sf/freecol/server/model/ServerPlayer.java | 26 +++++++++++++----------
1 file changed, 15 insertions(+), 11 deletions(-)

diff --git a/src/net/sf/freecol/server/model/ServerPlayer.java b/src/net/sf/freecol/server/model/ServerPlayer.java
index 836bdcf29d0..0eb01fca07d 100644
--- a/src/net/sf/freecol/server/model/ServerPlayer.java
+++ b/src/net/sf/freecol/server/model/ServerPlayer.java
@@ -31,7 +31,6 @@ import java.util.Random;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
-import java.util.function.ToIntFunction;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
@@ -543,15 +542,15 @@ public class ServerPlayer extends Player implements ServerModelObject {

// It is necessary to still have a carrier.
final Europe europe = getEurope();
- final ToIntFunction<UnitType> unitPricer = ut -> {
- int p = europe.getUnitPrice(ut);
- return (p == UNDEFINED) ? Integer.MAX_VALUE : p;
- };
int goldNeeded = 0;
if (!hasCarrier) {
- int price = (europe == null) ? Integer.MAX_VALUE
- : min(spec.getUnitTypesWithAbility(Ability.NAVAL_UNIT),
- unitPricer);
+ int price = Integer.MAX_VALUE;
+ if (europe != null)
+ for (UnitType ut : spec.getUnitTypesWithAbility(Ability.NAVAL_UNIT)) {
+ int p = europe.getUnitPrice(ut);
+ if ((p != UNDEFINED) && (p < price))
+ price = p;
+ }
if (price == Integer.MAX_VALUE || !checkGold(price)) {
logger.info(getName() + " dead, can not buy carrier.");
return IS_DEAD;
@@ -567,10 +566,15 @@ public class ServerPlayer extends Player implements ServerModelObject {
logger.info(getName() + " dead, can not recruit.");
return IS_DEAD;
}
+
UnitType unitType = null;
- int price = Math.min(europe.getRecruitPrice(),
- min(spec.getUnitTypesWithAbility(Ability.FOUND_COLONY),
- unitPricer));
+ int price = europe.getRecruitPrice();
+ for (UnitType ut : spec.getUnitTypesWithAbility(Ability.FOUND_COLONY)) {
+ int p = europe.getUnitPrice(ut);
+ if ((p != UNDEFINED) && (p < price))
+ price = p;
+ }
+
goldNeeded += price;
if (checkGold(goldNeeded)) {
logger.info(getName() + " alive, can buy colonist.");
--
2.11.0.rc0.7.gbe5a750
Loading...